context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal static class EXPRExtensions
{
public static EXPR Map(this EXPR expr, ExprFactory factory, Func<EXPR, EXPR> f)
{
Debug.Assert(f != null);
Debug.Assert(factory != null);
if (expr == null)
return f(expr);
EXPR result = null;
EXPR tail = null;
foreach (EXPR item in expr.ToEnumerable())
{
EXPR mappedItem = f(item);
factory.AppendItemToList(mappedItem, ref result, ref tail);
}
return result;
}
public static IEnumerable<EXPR> ToEnumerable(this EXPR expr)
{
EXPR exprCur = expr;
while (exprCur != null)
{
if (exprCur.isLIST())
{
yield return exprCur.asLIST().GetOptionalElement();
exprCur = exprCur.asLIST().GetOptionalNextListNode();
}
else
{
yield return exprCur;
yield break;
}
}
}
public static bool isSTMT(this EXPR expr)
{
return (expr == null) ? false : expr.kind < ExpressionKind.EK_StmtLim;
}
public static EXPRSTMT asSTMT(this EXPR expr)
{
Debug.Assert(expr == null || expr.kind < ExpressionKind.EK_StmtLim);
return (EXPRSTMT)expr;
}
public static bool isBIN(this EXPR expr)
{
return (expr == null) ? false : (expr.kind >= ExpressionKind.EK_TypeLim) &&
(0 != (expr.flags & EXPRFLAG.EXF_BINOP));
}
public static bool isUnaryOperator(this EXPR expr)
{
if (expr != null)
{
switch (expr.kind)
{
case ExpressionKind.EK_UNARYOP:
case ExpressionKind.EK_TRUE:
case ExpressionKind.EK_FALSE:
case ExpressionKind.EK_INC:
case ExpressionKind.EK_DEC:
case ExpressionKind.EK_LOGNOT:
case ExpressionKind.EK_NEG:
case ExpressionKind.EK_UPLUS:
case ExpressionKind.EK_BITNOT:
case ExpressionKind.EK_ADDR:
case ExpressionKind.EK_DECIMALNEG:
case ExpressionKind.EK_DECIMALINC:
case ExpressionKind.EK_DECIMALDEC:
return true;
default:
break;
}
}
return false;
}
public static bool isLvalue(this EXPR expr)
{
return (expr == null) ? false : 0 != (expr.flags & EXPRFLAG.EXF_LVALUE);
}
public static bool isChecked(this EXPR expr)
{
return (expr == null) ? false : 0 != (expr.flags & EXPRFLAG.EXF_CHECKOVERFLOW);
}
public static EXPRBINOP asBIN(this EXPR expr)
{
Debug.Assert(expr == null || 0 != (expr.flags & EXPRFLAG.EXF_BINOP));
return (EXPRBINOP)expr;
}
public static EXPRUNARYOP asUnaryOperator(this EXPR expr)
{
Debug.Assert(expr == null || expr.isUnaryOperator());
return (EXPRUNARYOP)expr;
}
public static bool isANYLOCAL(this EXPR expr)
{
return (expr == null) ? false : expr.kind == ExpressionKind.EK_LOCAL || expr.kind == ExpressionKind.EK_THISPOINTER;
}
public static EXPRLOCAL asANYLOCAL(this EXPR expr)
{
Debug.Assert(expr == null || expr.isANYLOCAL());
return (EXPRLOCAL)expr;
}
public static bool isANYLOCAL_OK(this EXPR expr)
{
return expr.isANYLOCAL() && expr.isOK();
}
public static bool isNull(this EXPR expr)
{
return expr.isCONSTANT_OK() && (expr.type.fundType() == FUNDTYPE.FT_REF) && expr.asCONSTANT().Val.IsNullRef();
}
public static bool isZero(this EXPR expr)
{
return (expr.isCONSTANT_OK()) && (expr.asCONSTANT().isZero());
}
private static EXPR GetSeqVal(this EXPR expr)
{
// Scan through EK_SEQUENCE and EK_SEQREV exprs to get the real value.
if (expr == null)
return null;
EXPR exprVal = expr;
for (; ;)
{
switch (exprVal.kind)
{
default:
return exprVal;
case ExpressionKind.EK_SEQUENCE:
exprVal = exprVal.asBIN().GetOptionalRightChild();
break;
case ExpressionKind.EK_SEQREV:
exprVal = exprVal.asBIN().GetOptionalLeftChild();
break;
}
}
}
/***************************************************************************************************
Determine whether this expr has a constant value (EK_CONSTANT or EK_ZEROINIT), possibly with
side effects (via EK_SEQUENCE or EK_SEQREV). Returns NULL if not, or the constant expr if so.
The returned EXPR will always be an EK_CONSTANT or EK_ZEROINIT.
***************************************************************************************************/
public static EXPR GetConst(this EXPR expr)
{
EXPR exprVal = expr.GetSeqVal();
if (null == exprVal || !exprVal.isCONSTANT_OK() && exprVal.kind != ExpressionKind.EK_ZEROINIT)
return null;
return exprVal;
}
private static void RETAILVERIFY(bool f)
{
if (!f)
Debug.Assert(false, "Panic!");
}
public static EXPRRETURN asRETURN(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_RETURN); return (EXPRRETURN)expr; }
public static EXPRBINOP asBINOP(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_BINOP); return (EXPRBINOP)expr; }
public static EXPRLIST asLIST(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_LIST); return (EXPRLIST)expr; }
public static EXPRARRAYINDEX asARRAYINDEX(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_ARRAYINDEX); return (EXPRARRAYINDEX)expr; }
public static EXPRCALL asCALL(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_CALL); return (EXPRCALL)expr; }
public static EXPREVENT asEVENT(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_EVENT); return (EXPREVENT)expr; }
public static EXPRFIELD asFIELD(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_FIELD); return (EXPRFIELD)expr; }
public static EXPRCONSTANT asCONSTANT(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_CONSTANT); return (EXPRCONSTANT)expr; }
public static EXPRFUNCPTR asFUNCPTR(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_FUNCPTR); return (EXPRFUNCPTR)expr; }
public static EXPRPROP asPROP(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_PROP); return (EXPRPROP)expr; }
public static EXPRWRAP asWRAP(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_WRAP); return (EXPRWRAP)expr; }
public static EXPRARRINIT asARRINIT(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_ARRINIT); return (EXPRARRINIT)expr; }
public static EXPRCAST asCAST(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_CAST); return (EXPRCAST)expr; }
public static EXPRUSERDEFINEDCONVERSION asUSERDEFINEDCONVERSION(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_USERDEFINEDCONVERSION); return (EXPRUSERDEFINEDCONVERSION)expr; }
public static EXPRTYPEOF asTYPEOF(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_TYPEOF); return (EXPRTYPEOF)expr; }
public static EXPRZEROINIT asZEROINIT(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_ZEROINIT); return (EXPRZEROINIT)expr; }
public static EXPRUSERLOGOP asUSERLOGOP(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_USERLOGOP); return (EXPRUSERLOGOP)expr; }
public static EXPRMEMGRP asMEMGRP(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_MEMGRP); return (EXPRMEMGRP)expr; }
public static EXPRFIELDINFO asFIELDINFO(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_FIELDINFO); return (EXPRFIELDINFO)expr; }
public static EXPRMETHODINFO asMETHODINFO(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_METHODINFO); return (EXPRMETHODINFO)expr; }
public static EXPRPropertyInfo asPropertyInfo(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_PROPERTYINFO); return (EXPRPropertyInfo)expr; }
public static EXPRNamedArgumentSpecification asNamedArgumentSpecification(this EXPR expr) { RETAILVERIFY(expr == null || expr.kind == ExpressionKind.EK_NamedArgumentSpecification); return (EXPRNamedArgumentSpecification)expr; }
public static bool isCONSTANT_OK(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_CONSTANT && expr.isOK()); }
public static bool isRETURN(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_RETURN); }
public static bool isLIST(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_LIST); }
public static bool isARRAYINDEX(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_ARRAYINDEX); }
public static bool isCALL(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_CALL); }
public static bool isFIELD(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_FIELD); }
public static bool isCONSTANT(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_CONSTANT); }
public static bool isCLASS(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_CLASS); }
public static bool isPROP(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_PROP); }
public static bool isWRAP(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_WRAP); }
public static bool isARRINIT(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_ARRINIT); }
public static bool isCAST(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_CAST); }
public static bool isUSERDEFINEDCONVERSION(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_USERDEFINEDCONVERSION); }
public static bool isTYPEOF(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_TYPEOF); }
public static bool isZEROINIT(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_ZEROINIT); }
public static bool isMEMGRP(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_MEMGRP); }
public static bool isBOUNDLAMBDA(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_BOUNDLAMBDA); }
public static bool isUNBOUNDLAMBDA(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_UNBOUNDLAMBDA); }
public static bool isMETHODINFO(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_METHODINFO); }
public static bool isNamedArgumentSpecification(this EXPR expr) { return (expr == null) ? false : (expr.kind == ExpressionKind.EK_NamedArgumentSpecification); }
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.PowerShell;
using Dbg = System.Diagnostics.Debug;
using System.Management.Automation.Language;
namespace System.Management.Automation
{
/// <summary>
/// This class represents the compiled metadata for a parameter set.
/// </summary>
public sealed class ParameterSetMetadata
{
#region Private Data
private bool _isMandatory;
private int _position;
private bool _valueFromPipeline;
private bool _valueFromPipelineByPropertyName;
private bool _valueFromRemainingArguments;
private string _helpMessage;
private string _helpMessageBaseName;
private string _helpMessageResourceId;
#endregion
#region Constructor
/// <summary>
///
/// </summary>
/// <param name="psMD"></param>
internal ParameterSetMetadata(ParameterSetSpecificMetadata psMD)
{
Dbg.Assert(null != psMD, "ParameterSetSpecificMetadata cannot be null");
Initialize(psMD);
}
/// <summary>
/// A copy constructor that creates a deep copy of the <paramref name="other"/> ParameterSetMetadata object.
/// </summary>
/// <param name="other">object to copy</param>
internal ParameterSetMetadata(ParameterSetMetadata other)
{
if (other == null)
{
throw PSTraceSource.NewArgumentNullException("other");
}
_helpMessage = other._helpMessage;
_helpMessageBaseName = other._helpMessageBaseName;
_helpMessageResourceId = other._helpMessageResourceId;
_isMandatory = other._isMandatory;
_position = other._position;
_valueFromPipeline = other._valueFromPipeline;
_valueFromPipelineByPropertyName = other._valueFromPipelineByPropertyName;
_valueFromRemainingArguments = other._valueFromRemainingArguments;
}
#endregion
#region Public Properties
/// <summary>
/// Returns true if the parameter is mandatory for this parameterset, false otherwise.
/// </summary>
/// <value></value>
public bool IsMandatory
{
get
{
return _isMandatory;
}
set
{
_isMandatory = value;
}
}
/// <summary>
/// If the parameter is allowed to be positional for this parameter set, this returns
/// the position it is allowed to be in. If it is not positional, this returns int.MinValue.
/// </summary>
/// <value></value>
public int Position
{
get
{
return _position;
}
set
{
_position = value;
}
}
/// <summary>
/// Specifies that this parameter can take values from the incoming pipeline object.
/// </summary>
public bool ValueFromPipeline
{
get
{
return _valueFromPipeline;
}
set
{
_valueFromPipeline = value;
}
}
/// <summary>
/// Specifies that this parameter can take values from a property from the incoming
/// pipeline object with the same name as the parameter.
/// </summary>
public bool ValueFromPipelineByPropertyName
{
get
{
return _valueFromPipelineByPropertyName;
}
set
{
_valueFromPipelineByPropertyName = value;
}
}
/// <summary>
/// Specifies if this parameter takes all the remaining unbound
/// arguments that were specified
/// </summary>
/// <value></value>
public bool ValueFromRemainingArguments
{
get
{
return _valueFromRemainingArguments;
}
set
{
_valueFromRemainingArguments = value;
}
}
/// <summary>
/// A short description for this parameter, suitable for presentation as a tool tip.
/// </summary>
public string HelpMessage
{
get
{
return _helpMessage;
}
set
{
_helpMessage = value;
}
}
/// <summary>
/// The base name of the resource for a help message.
/// </summary>
public string HelpMessageBaseName
{
get
{
return _helpMessageBaseName;
}
set
{
_helpMessageBaseName = value;
}
}
/// <summary>
/// The Id of the resource for a help message.
/// </summary>
public string HelpMessageResourceId
{
get
{
return _helpMessageResourceId;
}
set
{
_helpMessageResourceId = value;
}
}
#endregion
#region Private / Internal Methods & Properties
/// <summary>
///
/// </summary>
/// <param name="psMD"></param>
internal void Initialize(ParameterSetSpecificMetadata psMD)
{
_isMandatory = psMD.IsMandatory;
_position = psMD.Position;
_valueFromPipeline = psMD.ValueFromPipeline;
_valueFromPipelineByPropertyName = psMD.ValueFromPipelineByPropertyName;
_valueFromRemainingArguments = psMD.ValueFromRemainingArguments;
_helpMessage = psMD.HelpMessage;
_helpMessageBaseName = psMD.HelpMessageBaseName;
_helpMessageResourceId = psMD.HelpMessageResourceId;
}
/// <summary>
/// Compares this instance with the supplied <paramref name="second"/>.
/// </summary>
/// <param name="second">
/// An object to compare this instance with
/// </param>
/// <returns>
/// true if the metadata is same. false otherwise.
/// </returns>
internal bool Equals(ParameterSetMetadata second)
{
if ((_isMandatory != second._isMandatory) ||
(_position != second._position) ||
(_valueFromPipeline != second._valueFromPipeline) ||
(_valueFromPipelineByPropertyName != second._valueFromPipelineByPropertyName) ||
(_valueFromRemainingArguments != second._valueFromRemainingArguments) ||
(_helpMessage != second._helpMessage) ||
(_helpMessageBaseName != second._helpMessageBaseName) ||
(_helpMessageResourceId != second._helpMessageResourceId))
{
return false;
}
return true;
}
#endregion
#region Efficient serialization + rehydration logic
[Flags]
internal enum ParameterFlags : uint
{
Mandatory = 0x01,
ValueFromPipeline = 0x02,
ValueFromPipelineByPropertyName = 0x04,
ValueFromRemainingArguments = 0x08,
}
internal ParameterFlags Flags
{
get
{
ParameterFlags flags = 0;
if (IsMandatory) { flags = flags | ParameterFlags.Mandatory; }
if (ValueFromPipeline) { flags = flags | ParameterFlags.ValueFromPipeline; }
if (ValueFromPipelineByPropertyName) { flags = flags | ParameterFlags.ValueFromPipelineByPropertyName; }
if (ValueFromRemainingArguments) { flags = flags | ParameterFlags.ValueFromRemainingArguments; }
return flags;
}
set
{
this.IsMandatory = (ParameterFlags.Mandatory == (value & ParameterFlags.Mandatory));
this.ValueFromPipeline = (ParameterFlags.ValueFromPipeline == (value & ParameterFlags.ValueFromPipeline));
this.ValueFromPipelineByPropertyName = (ParameterFlags.ValueFromPipelineByPropertyName == (value & ParameterFlags.ValueFromPipelineByPropertyName));
this.ValueFromRemainingArguments = (ParameterFlags.ValueFromRemainingArguments == (value & ParameterFlags.ValueFromRemainingArguments));
}
}
/// <summary>
/// Constructor used by rehydration
/// </summary>
internal ParameterSetMetadata(
int position,
ParameterFlags flags,
string helpMessage)
{
this.Position = position;
this.Flags = flags;
this.HelpMessage = helpMessage;
}
#endregion
#region Proxy Parameter Generation
private const string MandatoryFormat = @"{0}Mandatory=$true";
private const string PositionFormat = @"{0}Position={1}";
private const string ValueFromPipelineFormat = @"{0}ValueFromPipeline=$true";
private const string ValueFromPipelineByPropertyNameFormat = @"{0}ValueFromPipelineByPropertyName=$true";
private const string ValueFromRemainingArgumentsFormat = @"{0}ValueFromRemainingArguments=$true";
private const string HelpMessageFormat = @"{0}HelpMessage='{1}'";
/// <summary>
///
/// </summary>
/// <returns></returns>
internal string GetProxyParameterData()
{
Text.StringBuilder result = new System.Text.StringBuilder();
string prefix = "";
if (_isMandatory)
{
result.AppendFormat(CultureInfo.InvariantCulture, MandatoryFormat, prefix);
prefix = ", ";
}
if (_position != Int32.MinValue)
{
result.AppendFormat(CultureInfo.InvariantCulture, PositionFormat, prefix, _position);
prefix = ", ";
}
if (_valueFromPipeline)
{
result.AppendFormat(CultureInfo.InvariantCulture, ValueFromPipelineFormat, prefix);
prefix = ", ";
}
if (_valueFromPipelineByPropertyName)
{
result.AppendFormat(CultureInfo.InvariantCulture, ValueFromPipelineByPropertyNameFormat, prefix);
prefix = ", ";
}
if (_valueFromRemainingArguments)
{
result.AppendFormat(CultureInfo.InvariantCulture, ValueFromRemainingArgumentsFormat, prefix);
prefix = ", ";
}
if (!string.IsNullOrEmpty(_helpMessage))
{
result.AppendFormat(
CultureInfo.InvariantCulture,
HelpMessageFormat,
prefix,
CodeGeneration.EscapeSingleQuotedStringContent(_helpMessage));
prefix = ", ";
}
return result.ToString();
}
#endregion
}
/// <summary>
/// This class represents the compiled metadata for a parameter.
/// </summary>
public sealed class ParameterMetadata
{
#region Private Data
private string _name;
private Type _parameterType;
private bool _isDynamic;
private Dictionary<string, ParameterSetMetadata> _parameterSets;
private Collection<string> _aliases;
private Collection<Attribute> _attributes;
#endregion
#region Constructor
/// <summary>
/// Constructs a ParameterMetadata instance.
/// </summary>
/// <param name="name">
/// Name of the parameter.
/// </param>
/// <exception cref="ArgumentNullException">
/// name is null.
/// </exception>
public ParameterMetadata(string name)
: this(name, null)
{
}
/// <summary>
/// Constructs a ParameterMetadata instance.
/// </summary>
/// <param name="name">
/// Name of the parameter.
/// </param>
/// <param name="parameterType">
/// Type of the parameter.
/// </param>
/// <exception cref="ArgumentNullException">
/// name is null.
/// </exception>
public ParameterMetadata(string name, Type parameterType)
{
if (string.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentNullException("name");
}
_name = name;
_parameterType = parameterType;
_attributes = new Collection<Attribute>();
_aliases = new Collection<string>();
_parameterSets = new Dictionary<string, ParameterSetMetadata>();
}
/// <summary>
/// A copy constructor that creates a deep copy of the <paramref name="other"/> ParameterMetadata object.
/// Instances of Attribute and Type classes are copied by reference.
/// </summary>
/// <param name="other">object to copy</param>
public ParameterMetadata(ParameterMetadata other)
{
if (other == null)
{
throw PSTraceSource.NewArgumentNullException("other");
}
_isDynamic = other._isDynamic;
_name = other._name;
_parameterType = other._parameterType;
// deep copy
_aliases = new Collection<string>(new List<string>(other._aliases.Count));
foreach (string alias in other._aliases)
{
_aliases.Add(alias);
}
// deep copy of the collection, collection items (Attributes) copied by reference
if (other._attributes == null)
{
_attributes = null;
}
else
{
_attributes = new Collection<Attribute>(new List<Attribute>(other._attributes.Count));
foreach (Attribute attribute in other._attributes)
{
_attributes.Add(attribute);
}
}
// deep copy
_parameterSets = null;
if (other._parameterSets == null)
{
_parameterSets = null;
}
else
{
_parameterSets = new Dictionary<string, ParameterSetMetadata>(other._parameterSets.Count);
foreach (KeyValuePair<string, ParameterSetMetadata> entry in other._parameterSets)
{
_parameterSets.Add(entry.Key, new ParameterSetMetadata(entry.Value));
}
}
}
/// <summary>
/// An internal constructor which constructs a ParameterMetadata object
/// from compiled commmand parameter metadata. ParameterMetadata
/// is a proxy written on top of CompiledCommandParameter
/// </summary>
/// <param name="cmdParameterMD">
/// Internal CompiledCommandParameter metadata
/// </param>
internal ParameterMetadata(CompiledCommandParameter cmdParameterMD)
{
Dbg.Assert(null != cmdParameterMD,
"CompiledCommandParameter cannot be null");
Initialize(cmdParameterMD);
}
/// <summary>
/// Constructor used by implicit remoting
/// </summary>
internal ParameterMetadata(
Collection<string> aliases,
bool isDynamic,
string name,
Dictionary<string, ParameterSetMetadata> parameterSets,
Type parameterType)
{
_aliases = aliases;
_isDynamic = isDynamic;
_name = name;
_parameterSets = parameterSets;
_parameterType = parameterType;
_attributes = new Collection<Attribute>();
}
#endregion
#region Public Methods/Properties
/// <summary>
/// Gets the name of the parameter
/// </summary>
///
public String Name
{
get
{
return _name;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw PSTraceSource.NewArgumentNullException("Name");
}
_name = value;
}
}
/// <summary>
/// Gets the Type information of the Parameter.
/// </summary>
public Type ParameterType
{
get
{
return _parameterType;
}
set
{
_parameterType = value;
}
}
/// <summary>
/// Gets the ParameterSets metadata that this parameter belongs to.
/// </summary>
public Dictionary<string, ParameterSetMetadata> ParameterSets
{
get
{
return _parameterSets;
}
}
/// <summary>
/// Specifies if the parameter is Dynamic
/// </summary>
public bool IsDynamic
{
get { return _isDynamic; }
set { _isDynamic = value; }
}
/// <summary>
/// Specifies the alias names for this parameter
/// </summary>
public Collection<string> Aliases
{
get
{
return _aliases;
}
}
/// <summary>
/// A collection of the attributes found on the member.
/// </summary>
public Collection<Attribute> Attributes
{
get
{
return _attributes;
}
}
/// <summary>
/// Specifies if the parameter is a SwitchParameter
/// </summary>
public bool SwitchParameter
{
get
{
if (_parameterType != null)
{
return _parameterType.Equals(typeof(SwitchParameter));
}
return false;
}
}
/// <summary>
/// Gets a dictionary of parameter metadata for the supplied <paramref name="type"/>.
/// </summary>
/// <param name="type">
/// CLR Type for which the parameter metadata is constructed.
/// </param>
/// <returns>
/// A Dictionary of ParameterMetadata keyed by parameter name.
/// null if no parameter metadata is found.
/// </returns>
/// <exception cref="ArgumentNullException">
/// type is null.
/// </exception>
public static Dictionary<string, ParameterMetadata> GetParameterMetadata(Type type)
{
if (null == type)
{
throw PSTraceSource.NewArgumentNullException("type");
}
CommandMetadata cmdMetaData = new CommandMetadata(type);
Dictionary<string, ParameterMetadata> result = cmdMetaData.Parameters;
// early GC.
cmdMetaData = null;
return result;
}
#endregion
#region Internal Methods/Properties
/// <summary>
///
/// </summary>
/// <param name="compiledParameterMD"></param>
internal void Initialize(CompiledCommandParameter compiledParameterMD)
{
_name = compiledParameterMD.Name;
_parameterType = compiledParameterMD.Type;
_isDynamic = compiledParameterMD.IsDynamic;
// Create parameter set metadata
_parameterSets = new Dictionary<string, ParameterSetMetadata>(StringComparer.OrdinalIgnoreCase);
foreach (string key in compiledParameterMD.ParameterSetData.Keys)
{
ParameterSetSpecificMetadata pMD = compiledParameterMD.ParameterSetData[key];
_parameterSets.Add(key, new ParameterSetMetadata(pMD));
}
// Create aliases for this parameter
_aliases = new Collection<string>();
foreach (string alias in compiledParameterMD.Aliases)
{
_aliases.Add(alias);
}
// Create attributes for this parameter
_attributes = new Collection<Attribute>();
foreach (var attrib in compiledParameterMD.CompiledAttributes)
{
_attributes.Add(attrib);
}
}
/// <summary>
///
/// </summary>
/// <param name="cmdParameterMetadata"></param>
/// <returns></returns>
internal static Dictionary<string, ParameterMetadata> GetParameterMetadata(MergedCommandParameterMetadata
cmdParameterMetadata)
{
Dbg.Assert(null != cmdParameterMetadata, "cmdParameterMetadata cannot be null");
Dictionary<string, ParameterMetadata> result = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase);
foreach (var keyValuePair in cmdParameterMetadata.BindableParameters)
{
var key = keyValuePair.Key;
var mergedCompiledPMD = keyValuePair.Value;
ParameterMetadata parameterMetaData = new ParameterMetadata(mergedCompiledPMD.Parameter);
result.Add(key, parameterMetaData);
}
return result;
}
internal bool IsMatchingType(PSTypeName psTypeName)
{
Type dotNetType = psTypeName.Type;
if (dotNetType != null)
{
// ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion.
bool parameterAcceptsObjects =
((int)(LanguagePrimitives.FigureConversion(typeof(object), this.ParameterType).Rank)) >=
(int)(ConversionRank.AssignableS2A);
if (dotNetType.Equals(typeof(object)))
{
return parameterAcceptsObjects;
}
if (parameterAcceptsObjects)
{
return (psTypeName.Type != null) && (psTypeName.Type.Equals(typeof(object)));
}
// ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion.
var convertionData = LanguagePrimitives.FigureConversion(dotNetType, this.ParameterType);
if (convertionData != null)
{
if ((int)(convertionData.Rank) >= (int)(ConversionRank.NumericImplicitS2A))
{
return true;
}
}
return false;
}
var wildcardPattern = WildcardPattern.Get(
"*" + (psTypeName.Name ?? ""),
WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
if (wildcardPattern.IsMatch(this.ParameterType.FullName))
{
return true;
}
if (this.ParameterType.IsArray && wildcardPattern.IsMatch((this.ParameterType.GetElementType().FullName)))
{
return true;
}
if (this.Attributes != null)
{
PSTypeNameAttribute typeNameAttribute = this.Attributes.OfType<PSTypeNameAttribute>().FirstOrDefault();
if (typeNameAttribute != null && wildcardPattern.IsMatch(typeNameAttribute.PSTypeName))
{
return true;
}
}
return false;
}
#endregion
#region Proxy Parameter generation
// The formats are prefixed with {0} to enable easy formatting.
private const string ParameterNameFormat = @"{0}${{{1}}}";
private const string ParameterTypeFormat = @"{0}[{1}]";
private const string ParameterSetNameFormat = "ParameterSetName='{0}'";
private const string AliasesFormat = @"{0}[Alias({1})]";
private const string ValidateLengthFormat = @"{0}[ValidateLength({1}, {2})]";
private const string ValidateRangeFloatFormat = @"{0}[ValidateRange({1:R}, {2:R})]";
private const string ValidateRangeFormat = @"{0}[ValidateRange({1}, {2})]";
private const string ValidatePatternFormat = "{0}[ValidatePattern('{1}')]";
private const string ValidateScriptFormat = @"{0}[ValidateScript({{ {1} }})]";
private const string ValidateCountFormat = @"{0}[ValidateCount({1}, {2})]";
private const string ValidateSetFormat = @"{0}[ValidateSet({1})]";
private const string ValidateNotNullFormat = @"{0}[ValidateNotNull()]";
private const string ValidateNotNullOrEmptyFormat = @"{0}[ValidateNotNullOrEmpty()]";
private const string AllowNullFormat = @"{0}[AllowNull()]";
private const string AllowEmptyStringFormat = @"{0}[AllowEmptyString()]";
private const string AllowEmptyCollectionFormat = @"{0}[AllowEmptyCollection()]";
private const string PSTypeNameFormat = @"{0}[PSTypeName('{1}')]";
private const string ObsoleteFormat = @"{0}[Obsolete({1})]";
private const string CredentialAttributeFormat = @"{0}[System.Management.Automation.CredentialAttribute()]";
/// <summary>
///
/// </summary>
/// <param name="prefix">
/// prefix that is added to every new-line. Used for tabbing content.
/// </param>
/// <param name="paramNameOverride">
/// The paramNameOverride is used as the parameter name if it is not null or empty.
/// </param>
/// <param name="isProxyForCmdlet">
/// The parameter is for a cmdlet and requires a Parameter attribute.
/// </param>
/// <returns></returns>
internal string GetProxyParameterData(string prefix, string paramNameOverride, bool isProxyForCmdlet)
{
Text.StringBuilder result = new System.Text.StringBuilder();
if (_parameterSets != null && isProxyForCmdlet)
{
foreach (var pair in _parameterSets)
{
string parameterSetName = pair.Key;
ParameterSetMetadata parameterSet = pair.Value;
string paramSetData = parameterSet.GetProxyParameterData();
if (!string.IsNullOrEmpty(paramSetData) || !parameterSetName.Equals(ParameterAttribute.AllParameterSets))
{
string separator = "";
result.Append(prefix);
result.Append("[Parameter(");
if (!parameterSetName.Equals(ParameterAttribute.AllParameterSets))
{
result.AppendFormat(
CultureInfo.InvariantCulture,
ParameterSetNameFormat,
CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName));
separator = ", ";
}
if (!string.IsNullOrEmpty(paramSetData))
{
result.Append(separator);
result.Append(paramSetData);
}
result.Append(")]");
}
}
}
if ((_aliases != null) && (_aliases.Count > 0))
{
Text.StringBuilder aliasesData = new System.Text.StringBuilder();
string comma = ""; // comma is not need for the first element
foreach (string alias in _aliases)
{
aliasesData.AppendFormat(
CultureInfo.InvariantCulture,
"{0}'{1}'",
comma,
CodeGeneration.EscapeSingleQuotedStringContent(alias));
comma = ",";
}
result.AppendFormat(CultureInfo.InvariantCulture, AliasesFormat, prefix, aliasesData.ToString());
}
if ((_attributes != null) && (_attributes.Count > 0))
{
foreach (Attribute attrib in _attributes)
{
string attribData = GetProxyAttributeData(attrib, prefix);
if (!string.IsNullOrEmpty(attribData))
{
result.Append(attribData);
}
}
}
if (SwitchParameter)
{
result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, "switch");
}
else if (_parameterType != null)
{
result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, ToStringCodeMethods.Type(_parameterType));
}
/* 1. CredentialAttribute needs to go after the type
* 2. To avoid risk, I don't want to move other attributes to go here / after the type */
CredentialAttribute credentialAttrib = _attributes.OfType<CredentialAttribute>().FirstOrDefault();
if (credentialAttrib != null)
{
string attribData = string.Format(CultureInfo.InvariantCulture, CredentialAttributeFormat, prefix);
if (!string.IsNullOrEmpty(attribData))
{
result.Append(attribData);
}
}
result.AppendFormat(
CultureInfo.InvariantCulture,
ParameterNameFormat,
prefix,
CodeGeneration.EscapeVariableName(string.IsNullOrEmpty(paramNameOverride) ? _name : paramNameOverride));
return result.ToString();
}
/// <summary>
/// Generates proxy data for attributes like ValidateLength, ValidateRange etc.
/// </summary>
/// <param name="attrib">
/// Attribute to process.
/// </param>
/// <param name="prefix">
/// Prefix string to add.
/// </param>
/// <returns>
/// Attribute's proxy string.
/// </returns>
private string GetProxyAttributeData(Attribute attrib, string prefix)
{
string result;
ValidateLengthAttribute validLengthAttrib = attrib as ValidateLengthAttribute;
if (validLengthAttrib != null)
{
result = string.Format(CultureInfo.InvariantCulture,
ValidateLengthFormat, prefix,
validLengthAttrib.MinLength, validLengthAttrib.MaxLength);
return result;
}
ValidateRangeAttribute validRangeAttrib = attrib as ValidateRangeAttribute;
if (validRangeAttrib != null)
{
Type rangeType = validRangeAttrib.MinRange.GetType();
string format;
if (rangeType == typeof(float) || rangeType == typeof(double))
{
format = ValidateRangeFloatFormat;
}
else
{
format = ValidateRangeFormat;
}
result = string.Format(CultureInfo.InvariantCulture,
format, prefix,
validRangeAttrib.MinRange, validRangeAttrib.MaxRange);
return result;
}
AllowNullAttribute allowNullAttrib = attrib as AllowNullAttribute;
if (allowNullAttrib != null)
{
result = string.Format(CultureInfo.InvariantCulture,
AllowNullFormat, prefix);
return result;
}
AllowEmptyStringAttribute allowEmptyStringAttrib = attrib as AllowEmptyStringAttribute;
if (allowEmptyStringAttrib != null)
{
result = string.Format(CultureInfo.InvariantCulture,
AllowEmptyStringFormat, prefix);
return result;
}
AllowEmptyCollectionAttribute allowEmptyColAttrib = attrib as AllowEmptyCollectionAttribute;
if (allowEmptyColAttrib != null)
{
result = string.Format(CultureInfo.InvariantCulture,
AllowEmptyCollectionFormat, prefix);
return result;
}
ValidatePatternAttribute patternAttrib = attrib as ValidatePatternAttribute;
if (patternAttrib != null)
{
/* TODO: Validate Pattern dont support Options in ScriptCmdletText.
StringBuilder regexOps = new System.Text.StringBuilder();
string or = "";
string[] regexOptionEnumValues = Enum.GetNames(typeof(System.Text.RegularExpressions.RegexOptions));
foreach(string regexOption in regexOptionEnumValues)
{
System.Text.RegularExpressions.RegexOptions option = (System.Text.RegularExpressions.RegexOptions) Enum.Parse(
typeof(System.Text.RegularExpressions.RegexOptions),
regexOption, true);
if ((option & patternAttrib.Options) == option)
{
tracer.WriteLine("Regex option {0} found", regexOption);
regexOps.AppendFormat(CultureInfo.InvariantCulture,
"{0}[System.Text.RegularExpressions.RegexOptions]::{1}", or,
option.ToString()
);
or = "|";
}
}*/
result = string.Format(CultureInfo.InvariantCulture,
ValidatePatternFormat, prefix,
CodeGeneration.EscapeSingleQuotedStringContent(patternAttrib.RegexPattern)
/*,regexOps.ToString()*/);
return result;
}
ValidateCountAttribute countAttrib = attrib as ValidateCountAttribute;
if (countAttrib != null)
{
result = string.Format(CultureInfo.InvariantCulture,
ValidateCountFormat, prefix, countAttrib.MinLength, countAttrib.MaxLength);
return result;
}
ValidateNotNullAttribute notNullAttrib = attrib as ValidateNotNullAttribute;
if (notNullAttrib != null)
{
result = string.Format(CultureInfo.InvariantCulture,
ValidateNotNullFormat, prefix);
return result;
}
ValidateNotNullOrEmptyAttribute notNullEmptyAttrib = attrib as ValidateNotNullOrEmptyAttribute;
if (notNullEmptyAttrib != null)
{
result = string.Format(CultureInfo.InvariantCulture,
ValidateNotNullOrEmptyFormat, prefix);
return result;
}
ValidateSetAttribute setAttrib = attrib as ValidateSetAttribute;
if (setAttrib != null)
{
Text.StringBuilder values = new System.Text.StringBuilder();
string comma = "";
foreach (string validValue in setAttrib.ValidValues)
{
values.AppendFormat(
CultureInfo.InvariantCulture,
"{0}'{1}'",
comma,
CodeGeneration.EscapeSingleQuotedStringContent(validValue));
comma = ",";
}
result = string.Format(CultureInfo.InvariantCulture,
ValidateSetFormat, prefix, values.ToString()/*, setAttrib.IgnoreCase*/);
return result;
}
ValidateScriptAttribute scriptAttrib = attrib as ValidateScriptAttribute;
if (scriptAttrib != null)
{
// Talked with others and I think it is okay to use *unescaped* value from sb.ToString()
// 1. implicit remoting is not bringing validation scripts across
// 2. other places in code also assume that contents of a script block can be parsed
// without escaping
result = string.Format(CultureInfo.InvariantCulture,
ValidateScriptFormat, prefix, scriptAttrib.ScriptBlock.ToString());
return result;
}
PSTypeNameAttribute psTypeNameAttrib = attrib as PSTypeNameAttribute;
if (psTypeNameAttrib != null)
{
result = string.Format(
CultureInfo.InvariantCulture,
PSTypeNameFormat,
prefix,
CodeGeneration.EscapeSingleQuotedStringContent(psTypeNameAttrib.PSTypeName));
return result;
}
ObsoleteAttribute obsoleteAttrib = attrib as ObsoleteAttribute;
if (obsoleteAttrib != null)
{
string parameters = string.Empty;
if (obsoleteAttrib.IsError)
{
string message = "'" + CodeGeneration.EscapeSingleQuotedStringContent(obsoleteAttrib.Message) + "'";
parameters = message + ", $true";
}
else if (obsoleteAttrib.Message != null)
{
parameters = "'" + CodeGeneration.EscapeSingleQuotedStringContent(obsoleteAttrib.Message) + "'";
}
result = string.Format(
CultureInfo.InvariantCulture,
ObsoleteFormat,
prefix,
parameters);
return result;
}
return null;
}
#endregion
}
/// <summary>
/// The metadata associated with a bindable type
/// </summary>
///
internal class InternalParameterMetadata
{
#region ctor
/// <summary>
/// Gets or constructs an instance of the InternalParameterMetadata for the specified runtime-defined parameters.
/// </summary>
///
/// <param name="runtimeDefinedParameters">
/// The runtime-defined parameter collection that describes the parameters and their metadata.
/// </param>
///
/// <param name="processingDynamicParameters">
/// True if dynamic parameters are being processed, or false otherwise.
/// </param>
///
/// <param name="checkNames">
/// Check for reserved parameter names.
/// </param>
///
/// <returns>
/// An instance of the TypeMetdata for the specified runtime-defined parameters. The metadata
/// is always constructed on demand and never cached.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="runtimeDefinedParameters"/> is null.
/// </exception>
///
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
///
internal static InternalParameterMetadata Get(RuntimeDefinedParameterDictionary runtimeDefinedParameters,
bool processingDynamicParameters,
bool checkNames)
{
if (runtimeDefinedParameters == null)
{
throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter");
}
return new InternalParameterMetadata(runtimeDefinedParameters, processingDynamicParameters, checkNames);
}
/// <summary>
/// Gets or constructs an instance of the InternalParameterMetadata for the specified type.
/// </summary>
///
/// <param name="type">
/// The type to get the metadata for.
/// </param>
///
/// <param name="context">
/// The current engine context.
/// </param>
///
/// <param name="processingDynamicParameters">
/// True if dynamic parameters are being processed, or false otherwise.
/// </param>
///
/// <returns>
/// An instance of the TypeMetdata for the specified type. The metadata may get
/// constructed on-demand or may be retrieved from the cache.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="type"/> is null.
/// </exception>
///
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
///
internal static InternalParameterMetadata Get(Type type, ExecutionContext context, bool processingDynamicParameters)
{
if (type == null)
{
throw PSTraceSource.NewArgumentNullException("type");
}
InternalParameterMetadata result;
if (context == null || !s_parameterMetadataCache.TryGetValue(type.AssemblyQualifiedName, out result))
{
result = new InternalParameterMetadata(type, processingDynamicParameters);
if (context != null)
{
s_parameterMetadataCache.TryAdd(type.AssemblyQualifiedName, result);
}
}
return result;
} // GetMetadata
//
/// <summary>
/// Constructs an instance of the InternalParameterMetadata using the metadata in the
/// runtime-defined parameter collection.
/// </summary>
///
/// <param name="runtimeDefinedParameters">
/// The collection of runtime-defined parameters that declare the parameters and their
/// metadata.
/// </param>
///
/// <param name="processingDynamicParameters">
/// True if dynamic parameters are being processed, or false otherwise.
/// </param>
///
/// <param name="checkNames">
/// Check if the parameter name has been reserved.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="runtimeDefinedParameters"/> is null.
/// </exception>
///
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
///
internal InternalParameterMetadata(RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames)
{
if (runtimeDefinedParameters == null)
{
throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameters");
}
ConstructCompiledParametersUsingRuntimeDefinedParameters(runtimeDefinedParameters, processingDynamicParameters, checkNames);
}
//
/// <summary>
/// Constructs an instance of the InternalParameterMetadata using the reflection information retrieved
/// from the enclosing bindable object type.
/// </summary>
///
/// <param name="type">
/// The type information for the bindable object
/// </param>
///
/// <param name="processingDynamicParameters">
/// True if dynamic parameters are being processed, or false otherwise.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="type"/> is null.
/// </exception>
///
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
///
internal InternalParameterMetadata(Type type, bool processingDynamicParameters)
{
if (type == null)
{
throw PSTraceSource.NewArgumentNullException("type");
}
_type = type;
TypeName = type.Name;
ConstructCompiledParametersUsingReflection(processingDynamicParameters);
}
#endregion ctor
/// <summary>
/// Gets the type name of the bindable type
/// </summary>
///
internal string TypeName { get; } = String.Empty;
/// <summary>
/// Gets a dictionary of the compiled parameter metadata for this Type.
/// The dictionary keys are the names of the parameters (or aliases) and
/// the values are the compiled parameter metdata.
/// </summary>
///
internal Dictionary<string, CompiledCommandParameter> BindableParameters { get; }
= new Dictionary<string, CompiledCommandParameter>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets a dictionary of the parameters that have been aliased to other names. The key is
/// the alias name and the value is the CompiledCommandParameter metadata.
/// </summary>
///
internal Dictionary<string, CompiledCommandParameter> AliasedParameters { get; }
= new Dictionary<string, CompiledCommandParameter>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The type information for the class that implements the bindable object.
/// This member is null in all cases except when constructed with using reflection
/// against the Type.
/// </summary>
private Type _type;
/// <summary>
/// The flags used when reflecting against the object to create the metadata
/// </summary>
internal static readonly BindingFlags metaDataBindingFlags = (BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
#region helper methods
/// <summary>
/// Fills in the data for an instance of this class using the specified runtime-defined parameters
/// </summary>
///
/// <param name="runtimeDefinedParameters">
/// A description of the parameters and their metadata.
/// </param>
///
/// <param name="processingDynamicParameters">
/// True if dynamic parameters are being processed, or false otherwise.
/// </param>
///
/// <param name="checkNames">
/// Check if the parameter name has been reserved.
/// </param>
///
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
///
private void ConstructCompiledParametersUsingRuntimeDefinedParameters(
RuntimeDefinedParameterDictionary runtimeDefinedParameters,
bool processingDynamicParameters,
bool checkNames)
{
Diagnostics.Assert(
runtimeDefinedParameters != null,
"This method should only be called when constructed with a valid runtime-defined parameter collection");
foreach (RuntimeDefinedParameter parameterDefinition in runtimeDefinedParameters.Values)
{
// Create the compiled parameter and add it to the bindable parameters collection
// NTRAID#Windows Out Of Band Releases-926374-2005/12/22-JonN
if (null == parameterDefinition)
continue;
CompiledCommandParameter parameter = new CompiledCommandParameter(parameterDefinition, processingDynamicParameters);
AddParameter(parameter, checkNames);
}
} // ConstructCompiledParametersUsingRuntimeDefinedParameters
/// <summary>
/// Compiles the parameter using reflection against the CLR type.
/// </summary>
///
/// <param name="processingDynamicParameters">
/// True if dynamic parameters are being processed, or false otherwise.
/// </param>
///
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
///
private void ConstructCompiledParametersUsingReflection(bool processingDynamicParameters)
{
Diagnostics.Assert(
_type != null,
"This method should only be called when constructed with the Type");
// Get the property and field info
PropertyInfo[] properties = _type.GetProperties(metaDataBindingFlags);
FieldInfo[] fields = _type.GetFields(metaDataBindingFlags);
foreach (PropertyInfo property in properties)
{
// Check whether the property is a parameter
if (!IsMemberAParameter(property))
{
continue;
}
AddParameter(property, processingDynamicParameters);
}
foreach (FieldInfo field in fields)
{
// Check whether the field is a parameter
if (!IsMemberAParameter(field))
{
continue;
}
AddParameter(field, processingDynamicParameters);
}
} // ConstructCompiledParametersUsingReflection
private void CheckForReservedParameter(string name)
{
if (name.Equals("SelectProperty", StringComparison.OrdinalIgnoreCase)
||
name.Equals("SelectObject", StringComparison.OrdinalIgnoreCase))
{
throw new MetadataException(
"ReservedParameterName",
null,
DiscoveryExceptions.ReservedParameterName,
name);
}
}
// NTRAID#Windows Out Of Band Releases-906345-2005/06/30-JeffJon
// This call verifies that the parameter is unique or
// can be deemed unique. If not, an exception is thrown.
// If it is unique (or deemed unique), then it is added
// to the bindableParameters collection
//
private void AddParameter(MemberInfo member, bool processingDynamicParameters)
{
bool error = false;
bool useExisting = false;
CheckForReservedParameter(member.Name);
do // false loop
{
CompiledCommandParameter existingParameter;
if (!BindableParameters.TryGetValue(member.Name, out existingParameter))
{
break;
}
Type existingParamDeclaringType = existingParameter.DeclaringType;
if (existingParamDeclaringType == null)
{
error = true;
break;
}
if (existingParamDeclaringType.IsSubclassOf(member.DeclaringType))
{
useExisting = true;
break;
}
if (member.DeclaringType.IsSubclassOf(existingParamDeclaringType))
{
// Need to swap out the new member for the parameter definition
// that is already defined.
RemoveParameter(existingParameter);
break;
}
error = true;
} while (false);
if (error)
{
// A duplicate parameter was found and could not be deemed unique
// through inheritance.
throw new MetadataException(
"DuplicateParameterDefinition",
null,
ParameterBinderStrings.DuplicateParameterDefinition,
member.Name);
}
if (!useExisting)
{
CompiledCommandParameter parameter = new CompiledCommandParameter(member, processingDynamicParameters);
AddParameter(parameter, true);
}
}
private void AddParameter(CompiledCommandParameter parameter, bool checkNames)
{
if (checkNames)
{
CheckForReservedParameter(parameter.Name);
}
BindableParameters.Add(parameter.Name, parameter);
// Now add entries in the parameter aliases collection for any aliases.
foreach (string alias in parameter.Aliases)
{
// NTRAID#Windows Out Of Band Releases-917356-JonN
if (AliasedParameters.ContainsKey(alias))
{
throw new MetadataException(
"AliasDeclaredMultipleTimes",
null,
DiscoveryExceptions.AliasDeclaredMultipleTimes,
alias);
}
AliasedParameters.Add(alias, parameter);
}
}
private void RemoveParameter(CompiledCommandParameter parameter)
{
BindableParameters.Remove(parameter.Name);
// Now add entries in the parameter aliases collection for any aliases.
foreach (string alias in parameter.Aliases)
{
AliasedParameters.Remove(alias);
}
}
/// <summary>
/// Determines if the specified member represents a parameter based on its attributes
/// </summary>
///
/// <param name="member">
/// The member to check to see if it is a parameter.
/// </param>
///
/// <returns>
/// True if at least one ParameterAttribute is declared on the member, or false otherwise.
/// </returns>
///
/// <exception cref="MetadataException">
/// If GetCustomAttributes fails on <paramref name="member"/>.
/// </exception>
///
private static bool IsMemberAParameter(MemberInfo member)
{
bool result = false;
try
{
// MemberInfo.GetCustomAttributes returns IEnumerable<Attribute> in CoreCLR
var attributes = member.GetCustomAttributes(typeof(ParameterAttribute), false);
if (attributes.Any())
{
result = true;
}
}
catch (MetadataException metadataException)
{
throw new MetadataException(
"GetCustomAttributesMetadataException",
metadataException,
Metadata.MetadataMemberInitialization,
member.Name,
metadataException.Message);
}
catch (ArgumentException argumentException)
{
throw new MetadataException(
"GetCustomAttributesArgumentException",
argumentException,
Metadata.MetadataMemberInitialization,
member.Name,
argumentException.Message);
}
return result;
} // IsMemberAParameter
#endregion helper methods
#region Metadata cache
/// <summary>
/// The cache of the type metadata. The key for the cache is the Type.FullName.
/// Note, this is a case-sensitive dictionary because Type names are case sensitive.
/// </summary>
private static System.Collections.Concurrent.ConcurrentDictionary<string, InternalParameterMetadata> s_parameterMetadataCache =
new System.Collections.Concurrent.ConcurrentDictionary<string, InternalParameterMetadata>(StringComparer.Ordinal);
#endregion Metadata cache
} // CompiledCommandParameter
}
| |
using UnityEngine;
using System.Linq;
using UnityEditor;
namespace PrefabEvolution
{
static class PEModificationsExt
{
private class PropertyCouple
{
public SerializedProperty prefabProperty;
public SerializedProperty objectProperty;
}
static internal void GetProperties(this PEModifications.PropertyData _this, out SerializedProperty prefabProperty, out SerializedProperty objectProperty, PEPrefabScript script)
{
var couple = _this.UserData as PropertyCouple;
if (couple == null)
{
couple = new PropertyCouple();
if (couple.objectProperty == null)
{
var so = new SerializedObject(_this.Object);
if (so != null)
couple.objectProperty = so.FindProperty(_this.PropertyPath);
if (couple.objectProperty == null)
{
if (PEPrefs.DebugLevel > 0)
Debug.Log(string.Format("Property {0} not found on Object {1}", _this.PropertyPath, _this.Object));
}
}
if (couple.prefabProperty == null)
{
var prefabObject = script.Links.GetPrefabObject(script.GetDiffWith().gameObject, _this.Object);
if (prefabObject != null)
{
var so = new SerializedObject(prefabObject);
if (so != null)
couple.prefabProperty = so.FindProperty(_this.PropertyPath);
}
else
{
Debug.LogWarning("Prefab object for prefab property modifications is not found");
}
}
}
prefabProperty = couple.prefabProperty;
objectProperty = couple.objectProperty;
_this.UserData = couple;
}
static private bool CheckChild(SerializedProperty property)
{
var types = new [] {
SerializedPropertyType.String,
SerializedPropertyType.Color,
SerializedPropertyType.Vector2,
SerializedPropertyType.Vector3,
SerializedPropertyType.Quaternion,
SerializedPropertyType.ObjectReference,
};
return !types.Contains(property.propertyType);
}
static internal void CalculateModifications(this PEModifications _this, PEPrefabScript prefab, PEPrefabScript instance)
{
instance.Modifications.Modificated.RemoveAll(m => m.Mode == PEModifications.PropertyData.PropertyMode.Default);
var counter = 0;
foreach (var link in instance.Links.Links)
{
if (link == null || link.InstanceTarget == null || link.InstanceTarget == instance || link.InstanceTarget is PEPrefabScript)
continue;
var so = new SerializedObject(link.InstanceTarget);
var property = so.GetIterator();
var prefabObjectLink = prefab.Links[link];
if (prefabObjectLink == null)
continue;
var prefabObject = prefabObjectLink.InstanceTarget;
if (prefabObject == null)
continue;
var prefabSerializedObject = new SerializedObject(prefabObject);
while (property.Next(CheckChild(property)))
{
counter++;
if (PEUtils.PropertyFilter(property))
{
continue;
}
var prefabProperty = prefabSerializedObject.FindProperty(property.propertyPath);
var isArray = property.propertyPath.Contains(".Array.data[");
var isInherited = link.InstanceTarget.GetType().IsSubclassOf(prefabObject.GetType());
if (prefabProperty == null && !isArray && !isInherited)
{
if (PEPrefs.DebugLevel > 0)
Debug.Log("Property not found(Some times its happens) " + property.propertyPath);
continue;
}
var instanceValue = property.GetPropertyValue();
var prefabValue = prefabProperty == null ? null : prefabProperty.GetPropertyValue();
var isChanged = !object.Equals(instanceValue, prefabValue);
if (isChanged)
{
if (property.propertyType == SerializedPropertyType.ObjectReference)
{
var instanceLink = instance.Links[instanceValue as Object];
var prefabLink = prefab.Links[prefabValue as Object];
if (prefabLink != null && instanceLink != null)
isChanged = prefabLink.LIIF != instanceLink.LIIF;
}
else
{
var animationCurve = instanceValue as AnimationCurve;
if (animationCurve != null)
{
isChanged = !PEUtils.Compare(animationCurve, prefabValue as AnimationCurve);
}
}
}
if (!isChanged)
continue;
instance.Modifications.AddModification(new PEModifications.PropertyData {
Object = link.InstanceTarget,
PropertyPath = property.propertyPath,
ObjeckLink = link.LIIF,
});
}
}
instance.Modifications.CalculateStructureDiff(prefab, instance);
}
static private void AddModification(this PEModifications _this, PEModifications.PropertyData data)
{
foreach (var mod in _this.Modificated)
if (mod.PropertyPath == data.PropertyPath && mod.Object == data.Object && mod.ObjeckLink == data.ObjeckLink)
return;
_this.Modificated.Add(data);
}
static private void CalculateStructureDiff(this PEModifications _this, PEPrefabScript prefab, PEPrefabScript instance)
{
_this.NonPrefabObjects.Clear();
var hierarchy = EditorUtility.CollectDeepHierarchy(new[] { instance });
foreach (var transform in hierarchy.OfType<Transform>())
{
if (transform.parent == null)
continue;
var link = prefab.Links[instance.Links[transform]];
if (link != null)
continue;
_this.NonPrefabObjects.Add(new PEModifications.HierarchyData {
child = transform,
parent = transform.parent
});
}
_this.NonPrefabComponents.Clear();
foreach (var component in hierarchy.Where(obj => !(obj is Transform)).OfType<Component>())
{
var link = prefab.Links[instance.Links[component]];
if (link != null || prefab.Links[instance.Links[component.gameObject.transform]] == null)
continue;
_this.NonPrefabComponents.Add(new PEModifications.ComponentsData {
child = component,
parent = component.gameObject
});
}
_this.RemovedObjects.Clear();
foreach (var link in prefab.Links.Links)
{
if (link.InstanceTarget is Transform)
continue;
if (instance.Links[link] == null || instance.Links[link].InstanceTarget == null)
_this.RemovedObjects.Add(link.LIIF);
}
_this.TransformParentChanges.Clear();
foreach (var link in instance.Links.Links)
{
var transform = link.InstanceTarget as Transform;
if (transform == null)
continue;
var currentTransform = transform;
if (currentTransform == instance.transform)
continue;
var currentTransformParent = currentTransform.parent;
if (prefab.Links[link] == null)
continue;
var otherTransform = prefab.Links[link].InstanceTarget as Transform;
var otherTransformParent = otherTransform.parent;
if (prefab.Links[otherTransformParent] == null || instance.Links[currentTransformParent] == null
|| prefab.Links[otherTransformParent].LIIF
!= instance.Links[currentTransformParent].LIIF)
_this.TransformParentChanges.Add(new PEModifications.HierarchyData {
child = currentTransform,
parent = currentTransformParent
});
}
}
}
}
| |
/********************************************************************/
/* Office 2007 Renderer Project */
/* */
/* Use the Office2007Renderer class as a custom renderer by */
/* providing it to the ToolStripManager.Renderer property. Then */
/* all tool strips, menu strips, status strips etc will be drawn */
/* using the Office 2007 style renderer in your application. */
/* */
/* Author: Phil Wright */
/* Website: www.componentfactory.com */
/* Contact: phil.wright@componentfactory.com */
/********************************************************************/
using System.Drawing;
using System.Drawing.Text;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Diagnostics;
namespace BSE.Windows.Forms
{
/// <summary>
/// Draw ToolStrips using the Office 2007 themed appearance.
/// </summary>
public class Office2007Renderer : ToolStripProfessionalRenderer
{
#region FieldsPrivate
private static int MarginInset;
private static Blend StatusStripBlend;
#endregion
#region MethodsPublic
static Office2007Renderer()
{
MarginInset = 2;
// One time creation of the blend for the status strip gradient brush
StatusStripBlend = new Blend();
StatusStripBlend.Positions = new float[] { 0.0F, 0.2F, 0.3F, 0.4F, 0.8F, 1.0F };
StatusStripBlend.Factors = new float[] { 0.3F, 0.4F, 0.5F, 1.0F, 0.8F, 0.7F };
}
/// <summary>
/// Initialize a new instance of the Office2007Renderer class.
/// </summary>
public Office2007Renderer()
: base(new BSE.Windows.Forms.Office2007BlueColorTable())
{
this.ColorTable.UseSystemColors = false;
}
/// <summary>
/// Initializes a new instance of the Office2007Renderer class.
/// </summary>
/// <param name="professionalColorTable">A <see cref="ProfessionalColorTable"/> to be used for painting.</param>
public Office2007Renderer(ProfessionalColorTable professionalColorTable)
: base(professionalColorTable)
{
}
#endregion
#region MethodsProtected
/// <summary>
/// Raises the RenderArrow event.
/// </summary>
/// <param name="e">A ToolStripArrowRenderEventArgs that contains the event data.</param>
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
if (ColorTable.UseSystemColors == false)
{
ProfessionalColorTable colorTable = ColorTable as BSE.Windows.Forms.ProfessionalColorTable;
if (colorTable != null)
{
if ((e.Item.Owner.GetType() == typeof(MenuStrip)) && (e.Item.Selected == false) && e.Item.Pressed == false)
{
if (colorTable.MenuItemText != Color.Empty)
{
e.ArrowColor = colorTable.MenuItemText;
}
}
if ((e.Item.Owner.GetType() == typeof(StatusStrip)) && (e.Item.Selected == false) && e.Item.Pressed == false)
{
if (colorTable.StatusStripText != Color.Empty)
{
e.ArrowColor = colorTable.StatusStripText;
}
}
}
}
base.OnRenderArrow(e);
}
/// <summary>
/// Raises the RenderItemText event.
/// </summary>
/// <param name="e">A ToolStripItemTextRenderEventArgs that contains the event data.</param>
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
if (ColorTable.UseSystemColors == false)
{
ProfessionalColorTable colorTable = ColorTable as BSE.Windows.Forms.ProfessionalColorTable;
if (colorTable != null)
{
if ((e.ToolStrip is MenuStrip) && (e.Item.Selected == false) && e.Item.Pressed == false)
{
if (colorTable.MenuItemText != Color.Empty)
{
e.TextColor = colorTable.MenuItemText;
}
}
if ((e.ToolStrip is StatusStrip) && (e.Item.Selected == false) && e.Item.Pressed == false)
{
if (colorTable.StatusStripText != Color.Empty)
{
e.TextColor = colorTable.StatusStripText;
}
}
}
}
base.OnRenderItemText(e);
}
/// <summary>
/// Raises the RenderToolStripContentPanelBackground event.
/// </summary>
/// <param name="e">An ToolStripContentPanelRenderEventArgs containing the event data.</param>
protected override void OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e)
{
// Must call base class, otherwise the subsequent drawing does not appear!
base.OnRenderToolStripContentPanelBackground(e);
if (ColorTable.UseSystemColors == false)
{
// Cannot paint a zero sized area
if ((e.ToolStripContentPanel.Width > 0) &&
(e.ToolStripContentPanel.Height > 0))
{
using (LinearGradientBrush backBrush = new LinearGradientBrush(e.ToolStripContentPanel.ClientRectangle,
ColorTable.ToolStripContentPanelGradientBegin,
ColorTable.ToolStripContentPanelGradientEnd,
LinearGradientMode.Vertical))
{
e.Graphics.FillRectangle(backBrush, e.ToolStripContentPanel.ClientRectangle);
}
}
}
}
/// <summary>
/// Raises the RenderSeparator event.
/// </summary>
/// <param name="e">An ToolStripSeparatorRenderEventArgs containing the event data.</param>
protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e)
{
if (ColorTable.UseSystemColors == false)
{
e.Item.ForeColor = ColorTable.RaftingContainerGradientBegin;
}
base.OnRenderSeparator(e);
}
/// <summary>
/// Raises the RenderToolStripBackground event.
/// </summary>
/// <param name="e">An ToolStripRenderEventArgs containing the event data.</param>
protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e)
{
if (ColorTable.UseSystemColors == true)
{
base.OnRenderToolStripBackground(e);
}
else
{
if (e.ToolStrip is StatusStrip)
{
// We do not paint the top two pixel lines, so are drawn by the status strip border render method
//RectangleF backRectangle = new RectangleF(0, 1.5f, e.ToolStrip.Width, e.ToolStrip.Height - 2);
RectangleF backRectangle = new RectangleF(0, 0, e.ToolStrip.Width, e.ToolStrip.Height);
// Cannot paint a zero sized area
if ((backRectangle.Width > 0) && (backRectangle.Height > 0))
{
using (LinearGradientBrush backBrush = new LinearGradientBrush(backRectangle,
ColorTable.StatusStripGradientBegin,
ColorTable.StatusStripGradientEnd,
LinearGradientMode.Vertical))
{
backBrush.Blend = StatusStripBlend;
e.Graphics.FillRectangle(backBrush, backRectangle);
}
}
}
else
{
base.OnRenderToolStripBackground(e);
}
}
}
/// <summary>
/// Raises the RenderImageMargin event.
/// </summary>
/// <param name="e">An ToolStripRenderEventArgs containing the event data.</param>
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
if (ColorTable.UseSystemColors == true)
{
base.OnRenderToolStripBackground(e);
}
else
{
if ((e.ToolStrip is ContextMenuStrip) ||
(e.ToolStrip is ToolStripDropDownMenu))
{
// Start with the total margin area
Rectangle marginRectangle = e.AffectedBounds;
// Do we need to draw with separator on the opposite edge?
bool bIsRightToLeft = (e.ToolStrip.RightToLeft == RightToLeft.Yes);
marginRectangle.Y += MarginInset;
marginRectangle.Height -= MarginInset * 2;
// Reduce so it is inside the border
if (bIsRightToLeft == false)
{
marginRectangle.X += MarginInset;
}
else
{
marginRectangle.X += MarginInset / 2;
}
// Draw the entire margine area in a solid color
using (SolidBrush backBrush = new SolidBrush(
ColorTable.ImageMarginGradientBegin))
e.Graphics.FillRectangle(backBrush, marginRectangle);
}
else
{
base.OnRenderImageMargin(e);
}
}
}
#endregion
#region MethodsPrivate
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.CodeGeneration;
using Orleans.Configuration;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions.Compatibility;
using Orleans.Serialization;
namespace Orleans.Runtime
{
internal class Dispatcher
{
internal ISiloMessageCenter Transport { get; }
private readonly OrleansTaskScheduler scheduler;
private readonly Catalog catalog;
private readonly ILogger logger;
private readonly SiloMessagingOptions messagingOptions;
private readonly PlacementDirectorsManager placementDirectorsManager;
private readonly ILocalGrainDirectory localGrainDirectory;
private readonly ActivationCollector activationCollector;
private readonly MessageFactory messageFactory;
private readonly SerializationManager serializationManager;
private readonly CompatibilityDirectorManager compatibilityDirectorManager;
private readonly SchedulingOptions schedulingOptions;
private readonly ILogger invokeWorkItemLogger;
internal Dispatcher(
OrleansTaskScheduler scheduler,
ISiloMessageCenter transport,
Catalog catalog,
IOptions<SiloMessagingOptions> messagingOptions,
PlacementDirectorsManager placementDirectorsManager,
ILocalGrainDirectory localGrainDirectory,
ActivationCollector activationCollector,
MessageFactory messageFactory,
SerializationManager serializationManager,
CompatibilityDirectorManager compatibilityDirectorManager,
ILoggerFactory loggerFactory,
IOptions<SchedulingOptions> schedulerOptions)
{
this.scheduler = scheduler;
this.catalog = catalog;
Transport = transport;
this.messagingOptions = messagingOptions.Value;
this.invokeWorkItemLogger = loggerFactory.CreateLogger<InvokeWorkItem>();
this.placementDirectorsManager = placementDirectorsManager;
this.localGrainDirectory = localGrainDirectory;
this.activationCollector = activationCollector;
this.messageFactory = messageFactory;
this.serializationManager = serializationManager;
this.compatibilityDirectorManager = compatibilityDirectorManager;
this.schedulingOptions = schedulerOptions.Value;
logger = loggerFactory.CreateLogger<Dispatcher>();
}
public ISiloRuntimeClient RuntimeClient => this.catalog.RuntimeClient;
/// <summary>
/// Receive a new message:
/// - validate order constraints, queue (or possibly redirect) if out of order
/// - validate transactions constraints
/// - invoke handler if ready, otherwise enqueue for later invocation
/// </summary>
/// <param name="message"></param>
public void ReceiveMessage(Message message)
{
MessagingProcessingStatisticsGroup.OnDispatcherMessageReceive(message);
// Don't process messages that have already timed out
if (message.IsExpired)
{
logger.Warn(ErrorCode.Dispatcher_DroppingExpiredMessage, "Dropping an expired message: {0}", message);
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Expired");
message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Dispatch);
return;
}
// check if its targeted at a new activation
if (message.TargetGrain.IsSystemTarget)
{
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ReceiveMessage on system target.");
throw new InvalidOperationException("Dispatcher was called ReceiveMessage on system target for " + message);
}
try
{
Task ignore;
ActivationData target = catalog.GetOrCreateActivation(
message.TargetAddress,
message.IsNewPlacement,
message.NewGrainType,
String.IsNullOrEmpty(message.GenericGrainType) ? null : message.GenericGrainType,
message.RequestContextData,
out ignore);
if (ignore != null)
{
ignore.Ignore();
}
if (message.Direction == Message.Directions.Response)
{
ReceiveResponse(message, target);
}
else // Request or OneWay
{
if (target.State == ActivationState.Valid)
{
this.activationCollector.TryRescheduleCollection(target);
}
// Silo is always capable to accept a new request. It's up to the activation to handle its internal state.
// If activation is shutting down, it will queue and later forward this request.
ReceiveRequest(message, target);
}
}
catch (Exception ex)
{
try
{
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Non-existent activation");
var nea = ex as Catalog.NonExistentActivationException;
if (nea == null)
{
var str = $"Error creating activation for {message.NewGrainType}. Message {message}";
logger.Error(ErrorCode.Dispatcher_ErrorCreatingActivation, str, ex);
throw new OrleansException(str, ex);
}
if (nea.IsStatelessWorker)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation,
$"Intermediate StatelessWorker NonExistentActivation for message {message}, Exception {ex}");
}
else
{
logger.Info(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation,
$"Intermediate NonExistentActivation for message {message}, with Exception {ex}");
}
ActivationAddress nonExistentActivation = nea.NonExistentActivation;
if (message.Direction != Message.Directions.Response)
{
// Un-register the target activation so we don't keep getting spurious messages.
// The time delay (one minute, as of this writing) is to handle the unlikely but possible race where
// this request snuck ahead of another request, with new placement requested, for the same activation.
// If the activation registration request from the new placement somehow sneaks ahead of this un-registration,
// we want to make sure that we don't un-register the activation we just created.
// We would add a counter here, except that there's already a counter for this in the Catalog.
// Note that this has to run in a non-null scheduler context, so we always queue it to the catalog's context
var origin = message.SendingSilo;
scheduler.QueueWorkItem(new ClosureWorkItem(
// don't use message.TargetAddress, cause it may have been removed from the headers by this time!
async () =>
{
try
{
await this.localGrainDirectory.UnregisterAfterNonexistingActivation(
nonExistentActivation, origin);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Dispatcher_FailedToUnregisterNonExistingAct,
$"Failed to un-register NonExistentActivation {nonExistentActivation}", exc);
}
},
"LocalGrainDirectory.UnregisterAfterNonexistingActivation"),
catalog.SchedulingContext);
ProcessRequestToInvalidActivation(message, nonExistentActivation, null, "Non-existent activation");
}
else
{
logger.Warn(
ErrorCode.Dispatcher_NoTargetActivation,
nonExistentActivation.Silo.IsClient
? "No target client {0} for response message: {1}. It's likely that the client recently disconnected."
: "No target activation {0} for response message: {1}",
nonExistentActivation,
message);
this.localGrainDirectory.InvalidateCacheEntry(nonExistentActivation);
}
}
catch (Exception exc)
{
// Unable to create activation for this request - reject message
RejectMessage(message, Message.RejectionTypes.Transient, exc);
}
}
}
public void RejectMessage(
Message message,
Message.RejectionTypes rejectType,
Exception exc,
string rejectInfo = null)
{
if (message.Direction == Message.Directions.Request
|| (message.Direction == Message.Directions.OneWay && message.HasCacheInvalidationHeader))
{
var str = String.Format("{0} {1}", rejectInfo ?? "", exc == null ? "" : exc.ToString());
MessagingStatisticsGroup.OnRejectedMessage(message);
Message rejection = this.messageFactory.CreateRejectionResponse(message, rejectType, str, exc);
SendRejectionMessage(rejection);
}
else
{
logger.Warn(ErrorCode.Messaging_Dispatcher_DiscardRejection,
"Discarding {0} rejection for message {1}. Exc = {2}",
Enum.GetName(typeof(Message.Directions), message.Direction), message, exc == null ? "" : exc.Message);
}
}
internal void SendRejectionMessage(Message rejection)
{
if (rejection.Result == Message.ResponseTypes.Rejection)
{
Transport.SendMessage(rejection);
rejection.ReleaseBodyAndHeaderBuffers();
}
else
{
throw new InvalidOperationException(
"Attempt to invoke Dispatcher.SendRejectionMessage() for a message that isn't a rejection.");
}
}
private void ReceiveResponse(Message message, ActivationData targetActivation)
{
lock (targetActivation)
{
if (targetActivation.State == ActivationState.Invalid)
{
logger.Warn(ErrorCode.Dispatcher_Receive_InvalidActivation,
"Response received for invalid activation {0}", message);
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Invalid");
return;
}
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message);
if (Transport.TryDeliverToProxy(message)) return;
this.catalog.RuntimeClient.ReceiveResponse(message);
}
}
/// <summary>
/// Check if we can locally accept this message.
/// Redirects if it can't be accepted.
/// </summary>
/// <param name="message"></param>
/// <param name="targetActivation"></param>
private void ReceiveRequest(Message message, ActivationData targetActivation)
{
lock (targetActivation)
{
if (targetActivation.State == ActivationState.Invalid)
{
ProcessRequestToInvalidActivation(
message,
targetActivation.Address,
targetActivation.ForwardingAddress,
"ReceiveRequest");
}
else if (!ActivationMayAcceptRequest(targetActivation, message))
{
// Check for deadlock before Enqueueing.
if (schedulingOptions.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget)
{
try
{
CheckDeadlock(message);
}
catch (DeadlockException exc)
{
// Record that this message is no longer flowing through the system
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Deadlock");
logger.Warn(ErrorCode.Dispatcher_DetectedDeadlock,
"Detected Application Deadlock: {0}", exc.Message);
// We want to send DeadlockException back as an application exception, rather than as a system rejection.
SendResponse(message, Response.ExceptionResponse(exc));
return;
}
}
EnqueueRequest(message, targetActivation);
}
else
{
HandleIncomingRequest(message, targetActivation);
}
}
}
/// <summary>
/// Determine if the activation is able to currently accept the given message
/// - always accept responses
/// For other messages, require that:
/// - activation is properly initialized
/// - the message would not cause a reentrancy conflict
/// </summary>
/// <param name="targetActivation"></param>
/// <param name="incoming"></param>
/// <returns></returns>
private bool ActivationMayAcceptRequest(ActivationData targetActivation, Message incoming)
{
if (targetActivation.State != ActivationState.Valid) return false;
if (!targetActivation.IsCurrentlyExecuting) return true;
return CanInterleave(targetActivation, incoming);
}
/// <summary>
/// Whether an incoming message can interleave
/// </summary>
/// <param name="targetActivation"></param>
/// <param name="incoming"></param>
/// <returns></returns>
public bool CanInterleave(ActivationData targetActivation, Message incoming)
{
bool canInterleave =
incoming.IsAlwaysInterleave
|| targetActivation.Blocking == null
|| (targetActivation.Blocking.IsReadOnly && incoming.IsReadOnly)
|| (schedulingOptions.AllowCallChainReentrancy && targetActivation.ActivationId.Equals(incoming.SendingActivation))
|| catalog.CanInterleave(targetActivation.ActivationId, incoming);
return canInterleave;
}
/// <summary>
/// https://github.com/dotnet/orleans/issues/3184
/// Checks whether reentrancy is allowed for calls to grains that are already part of the call chain.
/// Covers following case: grain A calls grain B, and while executing the invoked method B calls back to A.
/// Design: Senders collection `RunningRequestsSenders` contains sending grains references
/// during duration of request processing. If target of outgoing request is found in that collection -
/// such request will be marked as interleaving in order to prevent deadlocks.
/// </summary>
private void MarkSameCallChainMessageAsInterleaving(ActivationData sendingActivation, Message outgoing)
{
if (!schedulingOptions.AllowCallChainReentrancy)
{
return;
}
if (sendingActivation?.RunningRequestsSenders.Contains(outgoing.TargetActivation) == true)
{
outgoing.IsAlwaysInterleave = true;
}
}
/// <summary>
/// Check if the current message will cause deadlock.
/// Throw DeadlockException if yes.
/// </summary>
/// <param name="message">Message to analyze</param>
private void CheckDeadlock(Message message)
{
var requestContext = message.RequestContextData;
object obj;
if (requestContext == null ||
!requestContext.TryGetValue(RequestContext.CALL_CHAIN_REQUEST_CONTEXT_HEADER, out obj) ||
obj == null) return; // first call in a chain
var prevChain = ((IList)obj);
ActivationId nextActivationId = message.TargetActivation;
// check if the target activation already appears in the call chain.
foreach (object invocationObj in prevChain)
{
var prevId = ((RequestInvocationHistory)invocationObj).ActivationId;
if (!prevId.Equals(nextActivationId) || catalog.CanInterleave(nextActivationId, message)) continue;
var newChain = new List<RequestInvocationHistory>();
newChain.AddRange(prevChain.Cast<RequestInvocationHistory>());
newChain.Add(new RequestInvocationHistory(message.TargetGrain, message.TargetActivation, message.DebugContext));
throw new DeadlockException(
String.Format(
"Deadlock Exception for grain call chain {0}.",
Utils.EnumerableToString(
newChain,
elem => String.Format("{0}.{1}", elem.GrainId, elem.DebugContext))),
newChain.Select(req => new Tuple<GrainId, string>(req.GrainId, req.DebugContext)).ToList());
}
}
/// <summary>
/// Handle an incoming message and queue/invoke appropriate handler
/// </summary>
/// <param name="message"></param>
/// <param name="targetActivation"></param>
public void HandleIncomingRequest(Message message, ActivationData targetActivation)
{
lock (targetActivation)
{
if (targetActivation.Grain.IsGrain && message.IsUsingInterfaceVersions)
{
var request = ((InvokeMethodRequest)message.GetDeserializedBody(this.serializationManager));
var compatibilityDirector = compatibilityDirectorManager.GetDirector(request.InterfaceId);
var currentVersion = catalog.GrainTypeManager.GetLocalSupportedVersion(request.InterfaceId);
if (!compatibilityDirector.IsCompatible(request.InterfaceVersion, currentVersion))
catalog.DeactivateActivationOnIdle(targetActivation);
}
if (targetActivation.State == ActivationState.Invalid || targetActivation.State == ActivationState.Deactivating)
{
ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "HandleIncomingRequest");
return;
}
// Now we can actually scheduler processing of this request
targetActivation.RecordRunning(message, message.IsAlwaysInterleave);
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message);
scheduler.QueueWorkItem(new InvokeWorkItem(targetActivation, message, this, this.invokeWorkItemLogger), targetActivation.SchedulingContext);
}
}
/// <summary>
/// Enqueue message for local handling after transaction completes
/// </summary>
/// <param name="message"></param>
/// <param name="targetActivation"></param>
private void EnqueueRequest(Message message, ActivationData targetActivation)
{
var overloadException = targetActivation.CheckOverloaded(logger);
if (overloadException != null)
{
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Overload2");
RejectMessage(message, Message.RejectionTypes.Overloaded, overloadException, "Target activation is overloaded " + targetActivation);
return;
}
switch (targetActivation.EnqueueMessage(message))
{
case ActivationData.EnqueueMessageResult.Success:
// Great, nothing to do
break;
case ActivationData.EnqueueMessageResult.ErrorInvalidActivation:
ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest");
break;
case ActivationData.EnqueueMessageResult.ErrorStuckActivation:
// Avoid any new call to this activation
catalog.DeactivateStuckActivation(targetActivation);
ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest - blocked grain");
break;
default:
throw new ArgumentOutOfRangeException();
}
// Dont count this as end of processing. The message will come back after queueing via HandleIncomingRequest.
#if DEBUG
// This is a hot code path, so using #if to remove diags from Release version
// Note: Caller already holds lock on activation
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.Dispatcher_EnqueueMessage,
"EnqueueMessage for {0}: targetActivation={1}", message.TargetActivation, targetActivation.DumpStatus());
#endif
}
internal void ProcessRequestToInvalidActivation(
Message message,
ActivationAddress oldAddress,
ActivationAddress forwardingAddress,
string failedOperation,
Exception exc = null)
{
// Just use this opportunity to invalidate local Cache Entry as well.
if (oldAddress != null)
{
this.localGrainDirectory.InvalidateCacheEntry(oldAddress);
}
// IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already.
scheduler.QueueWorkItem(new ClosureWorkItem(
() => TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc)),
catalog.SchedulingContext);
}
internal void ProcessRequestsToInvalidActivation(
List<Message> messages,
ActivationAddress oldAddress,
ActivationAddress forwardingAddress,
string failedOperation,
Exception exc = null,
bool rejectMessages = false)
{
// Just use this opportunity to invalidate local Cache Entry as well.
if (oldAddress != null)
{
this.localGrainDirectory.InvalidateCacheEntry(oldAddress);
}
if (logger.IsEnabled(LogLevel.Information))
{
logger.Info(ErrorCode.Messaging_Dispatcher_ForwardingRequests,
$"Forwarding {messages.Count} requests destined for address {oldAddress} to address {forwardingAddress} after {failedOperation}.");
}
// IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already.
scheduler.QueueWorkItem(new ClosureWorkItem(
() =>
{
foreach (var message in messages)
{
if (rejectMessages)
{
RejectMessage(message, Message.RejectionTypes.Transient, exc, failedOperation);
}
else
{
TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc);
}
}
}
), catalog.SchedulingContext);
}
internal void TryForwardRequest(Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null)
{
bool forwardingSucceded = true;
try
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
(int)ErrorCode.Messaging_Dispatcher_TryForward,
"Trying to forward after {FailedOperation}, ForwardCount = {ForwardCount}. OldAddress = {OldAddress}, ForwardingAddress = {ForwardingAddress}, Message {Message}, Exception: {Exception}.",
failedOperation,
message.ForwardCount,
oldAddress,
forwardingAddress,
message,
exc);
}
// if this message is from a different cluster and hit a non-existing activation
// in this cluster (which can happen due to stale cache or directory states)
// we forward it back to the original silo it came from in the original cluster,
// and target it to a fictional activation that is guaranteed to not exist.
// This ensures that the GSI protocol creates a new instance there instead of here.
if (forwardingAddress == null
&& message.TargetSilo != message.SendingSilo
&& !this.localGrainDirectory.IsSiloInCluster(message.SendingSilo))
{
message.IsReturnedFromRemoteCluster = true; // marks message to force invalidation of stale directory entry
forwardingAddress = ActivationAddress.NewActivationAddress(message.SendingSilo, message.TargetGrain);
logger.Info(ErrorCode.Messaging_Dispatcher_ReturnToOriginCluster, $"Forwarding back to origin cluster, to fictional activation {message}");
}
MessagingProcessingStatisticsGroup.OnDispatcherMessageReRouted(message);
if (oldAddress != null)
{
message.AddToCacheInvalidationHeader(oldAddress);
}
forwardingSucceded = this.TryForwardMessage(message, forwardingAddress);
}
catch (Exception exc2)
{
forwardingSucceded = false;
exc = exc2;
}
finally
{
var sentRejection = false;
// If the message was a one-way message, send a cache invalidation response even if the message was successfully forwarded.
if (message.Direction == Message.Directions.OneWay)
{
this.RejectMessage(
message,
Message.RejectionTypes.CacheInvalidation,
exc,
"OneWay message sent to invalid activation");
sentRejection = true;
}
if (!forwardingSucceded)
{
var str = $"Forwarding failed: tried to forward message {message} for {message.ForwardCount} times after {failedOperation} to invalid activation. Rejecting now.";
logger.Warn(ErrorCode.Messaging_Dispatcher_TryForwardFailed, str, exc);
if (!sentRejection) RejectMessage(message, Message.RejectionTypes.Transient, exc, str);
}
}
}
/// <summary>
/// Reroute a message coming in through a gateway
/// </summary>
/// <param name="message"></param>
internal void RerouteMessage(Message message)
{
ResendMessageImpl(message);
}
internal bool TryResendMessage(Message message)
{
if (!message.MayResend(this.messagingOptions.MaxResendCount)) return false;
message.ResendCount = message.ResendCount + 1;
MessagingProcessingStatisticsGroup.OnIgcMessageResend(message);
ResendMessageImpl(message);
return true;
}
internal bool TryForwardMessage(Message message, ActivationAddress forwardingAddress)
{
if (!MayForward(message, this.messagingOptions)) return false;
message.ForwardCount = message.ForwardCount + 1;
MessagingProcessingStatisticsGroup.OnIgcMessageForwared(message);
ResendMessageImpl(message, forwardingAddress);
return true;
}
private void ResendMessageImpl(Message message, ActivationAddress forwardingAddress = null)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Resend {0}", message);
message.TargetHistory = message.GetTargetHistory();
if (message.TargetGrain.IsSystemTarget)
{
this.SendSystemTargetMessage(message);
}
else if (forwardingAddress != null)
{
message.TargetAddress = forwardingAddress;
message.IsNewPlacement = false;
this.Transport.SendMessage(message);
}
else
{
message.TargetActivation = null;
message.TargetSilo = null;
message.ClearTargetAddress();
this.SendMessage(message);
}
}
// Forwarding is used by the receiver, usually when it cannot process the message and forwards it to another silo to perform the processing
// (got here due to duplicate activation, outdated cache, silo is shutting down/overloaded, ...).
private static bool MayForward(Message message, SiloMessagingOptions messagingOptions)
{
return message.ForwardCount < messagingOptions.MaxForwardCount
// allow one more forward hop for multi-cluster case
+ (message.IsReturnedFromRemoteCluster ? 1 : 0)
;
}
/// <summary>
/// Send an outgoing message, may complete synchronously
/// - may buffer for transaction completion / commit if it ends a transaction
/// - choose target placement address, maintaining send order
/// - add ordering info and maintain send order
///
/// </summary>
/// <param name="message"></param>
/// <param name="sendingActivation"></param>
public Task AsyncSendMessage(Message message, ActivationData sendingActivation = null)
{
Action<Exception> onAddressingFailure = ex =>
{
if (ShouldLogError(ex))
{
logger.Error(ErrorCode.Dispatcher_SelectTarget_Failed, $"SelectTarget failed with {ex.Message}", ex);
}
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "SelectTarget failed");
RejectMessage(message, Message.RejectionTypes.Unrecoverable, ex);
};
Func<Task, Task> transportMessageAfterAddressing = async addressMessageTask =>
{
try
{
await addressMessageTask;
}
catch (Exception ex)
{
onAddressingFailure(ex);
return;
}
TransportMessage(message, sendingActivation);
};
try
{
var messageAddressingTask = AddressMessage(message);
if (messageAddressingTask.Status == TaskStatus.RanToCompletion)
{
TransportMessage(message, sendingActivation);
}
else
{
return transportMessageAfterAddressing(messageAddressingTask);
}
}
catch (Exception ex)
{
onAddressingFailure(ex);
}
return Task.CompletedTask;
}
private bool ShouldLogError(Exception ex)
{
return !(ex.GetBaseException() is KeyNotFoundException) &&
!(ex.GetBaseException() is ClientNotAvailableException);
}
// this is a compatibility method for portions of the code base that don't use
// async/await yet, which is almost everything. there's no liability to discarding the
// Task returned by AsyncSendMessage()
internal void SendMessage(Message message, ActivationData sendingActivation = null)
{
AsyncSendMessage(message, sendingActivation).Ignore();
}
/// <summary>
/// Resolve target address for a message
/// - use transaction info
/// - check ordering info in message and sending activation
/// - use sender's placement strategy
/// </summary>
/// <param name="message"></param>
/// <returns>Resolve when message is addressed (modifies message fields)</returns>
private Task AddressMessage(Message message)
{
var targetAddress = message.TargetAddress;
if (targetAddress.IsComplete) return Task.CompletedTask;
// placement strategy is determined by searching for a specification. first, we check for a strategy associated with the grain reference,
// second, we check for a strategy associated with the target's interface. third, we check for a strategy associated with the activation sending the
// message.
var strategy = targetAddress.Grain.IsGrain ? catalog.GetGrainPlacementStrategy(targetAddress.Grain) : null;
var request = message.IsUsingInterfaceVersions
? message.GetDeserializedBody(this.serializationManager) as InvokeMethodRequest
: null;
var target = new PlacementTarget(
message.TargetGrain,
message.RequestContextData,
request?.InterfaceId ?? 0,
request?.InterfaceVersion ?? 0);
PlacementResult placementResult;
if (placementDirectorsManager.TrySelectActivationSynchronously(
message.SendingAddress, target, this.catalog, strategy, out placementResult) && placementResult != null)
{
SetMessageTargetPlacement(message, placementResult, targetAddress);
return Task.CompletedTask;
}
return AddressMessageAsync(message, target, strategy, targetAddress);
}
private async Task AddressMessageAsync(Message message, PlacementTarget target, PlacementStrategy strategy, ActivationAddress targetAddress)
{
var placementResult = await placementDirectorsManager.SelectOrAddActivation(
message.SendingAddress, target, this.catalog, strategy);
SetMessageTargetPlacement(message, placementResult, targetAddress);
}
private void SetMessageTargetPlacement(Message message, PlacementResult placementResult, ActivationAddress targetAddress)
{
if (placementResult.IsNewPlacement && targetAddress.Grain.IsClient)
{
logger.Error(ErrorCode.Dispatcher_AddressMsg_UnregisteredClient, $"AddressMessage could not find target for client pseudo-grain {message}");
throw new KeyNotFoundException($"Attempting to send a message {message} to an unregistered client pseudo-grain {targetAddress.Grain}");
}
message.SetTargetPlacement(placementResult);
if (placementResult.IsNewPlacement)
{
CounterStatistic.FindOrCreate(StatisticNames.DISPATCHER_NEW_PLACEMENT).Increment();
}
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.Dispatcher_AddressMsg_SelectTarget, "AddressMessage Placement SelectTarget {0}", message);
}
internal void SendResponse(Message request, Response response)
{
// create the response
var message = this.messageFactory.CreateResponseMessage(request);
message.BodyObject = response;
if (message.TargetGrain.IsSystemTarget)
{
SendSystemTargetMessage(message);
}
else
{
TransportMessage(message);
}
}
internal void SendSystemTargetMessage(Message message)
{
message.Category = message.TargetGrain.Equals(Constants.MembershipOracleId) ?
Message.Categories.Ping : Message.Categories.System;
if (message.TargetSilo == null)
{
message.TargetSilo = Transport.MyAddress;
}
if (message.TargetActivation == null)
{
message.TargetActivation = ActivationId.GetSystemActivation(message.TargetGrain, message.TargetSilo);
}
TransportMessage(message);
}
/// <summary>
/// Directly send a message to the transport without processing
/// </summary>
/// <param name="message"></param>
/// <param name="sendingActivation"></param>
public void TransportMessage(Message message, ActivationData sendingActivation = null)
{
MarkSameCallChainMessageAsInterleaving(sendingActivation, message);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.Dispatcher_Send_AddressedMessage, "Addressed message {0}", message);
Transport.SendMessage(message);
}
/// <summary>
/// Invoked when an activation has finished a transaction and may be ready for additional transactions
/// </summary>
/// <param name="activation">The activation that has just completed processing this message</param>
/// <param name="message">The message that has just completed processing.
/// This will be <c>null</c> for the case of completion of Activate/Deactivate calls.</param>
internal void OnActivationCompletedRequest(ActivationData activation, Message message)
{
lock (activation)
{
#if DEBUG
// This is a hot code path, so using #if to remove diags from Release version
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace(ErrorCode.Dispatcher_OnActivationCompletedRequest_Waiting,
"OnActivationCompletedRequest {0}: Activation={1}", activation.ActivationId, activation.DumpStatus());
}
#endif
activation.ResetRunning(message);
// ensure inactive callbacks get run even with transactions disabled
if (!activation.IsCurrentlyExecuting)
activation.RunOnInactive();
// Run message pump to see if there is a new request arrived to be processed
RunMessagePump(activation);
}
}
internal void RunMessagePump(ActivationData activation)
{
// Note: this method must be called while holding lock (activation)
#if DEBUG
// This is a hot code path, so using #if to remove diags from Release version
// Note: Caller already holds lock on activation
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace(ErrorCode.Dispatcher_ActivationEndedTurn_Waiting,
"RunMessagePump {0}: Activation={1}", activation.ActivationId, activation.DumpStatus());
}
#endif
// don't run any messages if activation is not ready or deactivating
if (activation.State != ActivationState.Valid) return;
bool runLoop;
do
{
runLoop = false;
var nextMessage = activation.PeekNextWaitingMessage();
if (nextMessage == null) continue;
if (!ActivationMayAcceptRequest(activation, nextMessage)) continue;
activation.DequeueNextWaitingMessage();
// we might be over-writing an already running read only request.
HandleIncomingRequest(nextMessage, activation);
runLoop = true;
}
while (runLoop);
}
}
}
| |
/*
* Copyright (c) 2009, Stefan Simek
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
namespace TriAxis.RunSharp
{
using Operands;
interface ICodeGenContext : IMemberInfo, ISignatureGen, IDelayedDefinition, IDelayedCompletion
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Typical implementation invokes XxxBuilder.GetILGenerator() which is a method as well.")]
ILGenerator GetILGenerator();
Type OwnerType { get; }
bool SupportsScopes { get; }
}
public partial class CodeGen
{
ILGenerator il;
ICodeGenContext context;
ConstructorGen cg;
bool chainCalled = false;
bool reachable = true;
bool hasRetVar = false, hasRetLabel = false;
LocalBuilder retVar = null;
Label retLabel;
Stack<Block> blocks = new Stack<Block>();
Dictionary<string, Label> Labels = new Dictionary<string, Label>();
Dictionary<string, Operand> NamedLocals = new Dictionary<string, Operand>();
internal ILGenerator IL { get { return il; } }
internal ICodeGenContext Context { get { return context; } }
internal CodeGen(ICodeGenContext context)
{
this.context = context;
this.cg = context as ConstructorGen;
if (cg != null && cg.IsStatic)
// #14 - cg is relevant for instance constructors - it wreaks havoc in a static constructor
cg = null;
il = context.GetILGenerator();
}
/*public static CodeGen CreateDynamicMethod(string name, Type returnType, params Type[] parameterTypes, Type owner, bool skipVisibility)
{
DynamicMethod dm = new DynamicMethod(name, returnType, parameterTypes, owner, skipVisibility);
return new CodeGen(method.GetILGenerator(), defaultType, method.ReturnType, method.IsStatic, parameterTypes);
}
public static CodeGen FromMethodBuilder(MethodBuilder builder, params Type[] parameterTypes)
{
return new CodeGen(builder.GetILGenerator(), builder.DeclaringType, builder.ReturnType, builder.IsStatic, parameterTypes);
}
public static CodeGen FromConstructorBuilder(ConstructorBuilder builder, params Type[] parameterTypes)
{
return new CodeGen(builder.GetILGenerator(), builder.DeclaringType, builder.ReturnType, builder.IsStatic, parameterTypes);
}*/
#region Arguments
public Operand This()
{
if (context.IsStatic)
throw new InvalidOperationException(Properties.Messages.ErrCodeStaticThis);
return new _Arg(0, context.OwnerType);
}
public Operand Base()
{
if (context.IsStatic)
return new _StaticTarget(context.OwnerType.BaseType);
else
return new _Base(context.OwnerType.BaseType);
}
int _ThisOffset { get { return context.IsStatic ? 0 : 1; } }
public Operand PropertyValue()
{
Type[] parameterTypes = context.ParameterTypes;
return new _Arg(_ThisOffset + parameterTypes.Length - 1, parameterTypes[parameterTypes.Length - 1]);
}
public Operand Arg(string name)
{
ParameterGen param = context.GetParameterByName(name);
return new _Arg(_ThisOffset + param.Position - 1, param.Type);
}
#endregion
#region Locals
public Operand Local()
{
return new _Local(this);
}
public Operand Local(Operand init)
{
Operand var = Local();
Assign(var, init);
return var;
}
public Operand Local(Type type)
{
return new _Local(this, type);
}
public Operand Local(Type type, Operand init)
{
Operand var = Local(type);
Assign(var, init);
return var;
}
#endregion
bool HasReturnValue
{
get
{
Type returnType = context.ReturnType;
return returnType != null && returnType != typeof(void);
}
}
void EnsureReturnVariable()
{
if (hasRetVar)
return;
retLabel = il.DefineLabel();
if (HasReturnValue)
retVar = il.DeclareLocal(context.ReturnType);
hasRetVar = true;
}
public bool IsCompleted
{
get
{
return blocks.Count == 0 && !reachable && hasRetVar == hasRetLabel;
}
}
internal void Complete()
{
if (blocks.Count > 0)
throw new InvalidOperationException(Properties.Messages.ErrOpenBlocksRemaining);
if (reachable)
{
if (HasReturnValue)
throw new InvalidOperationException(string.Format(null, Properties.Messages.ErrMethodMustReturnValue, context));
else
Return();
}
if (hasRetVar && !hasRetLabel)
{
il.MarkLabel(retLabel);
if (retVar != null)
il.Emit(OpCodes.Ldloc, retVar);
il.Emit(OpCodes.Ret);
hasRetLabel = true;
}
}
class _Base : _Arg
{
public _Base(Type type) : base(0, type) { }
internal override bool SuppressVirtual
{
get
{
return true;
}
}
}
class _Arg : Operand
{
ushort index;
Type type;
public _Arg(int index, Type type)
{
this.index = checked((ushort)index);
this.type = type;
}
internal override void EmitGet(CodeGen g)
{
g.EmitLdargHelper(index);
if (IsReference)
g.EmitLdindHelper(Type);
}
internal override void EmitSet(CodeGen g, Operand value, bool allowExplicitConversion)
{
if (IsReference)
{
g.EmitLdargHelper(index);
g.EmitStindHelper(Type, value, allowExplicitConversion);
}
else
{
g.EmitGetHelper(value, Type, allowExplicitConversion);
g.EmitStargHelper(index);
}
}
internal override void EmitAddressOf(CodeGen g)
{
if (IsReference)
{
g.EmitLdargHelper(index);
}
else
{
if (index <= byte.MaxValue)
g.il.Emit(OpCodes.Ldarga_S, (byte)index);
else
g.il.Emit(OpCodes.Ldarga, index);
}
}
bool IsReference { get { return type.IsByRef; } }
public override Type Type
{
get
{
return IsReference ? type.GetElementType() : type;
}
}
internal override bool TrivialAccess
{
get
{
return true;
}
}
}
internal class _Local : Operand
{
CodeGen owner;
LocalBuilder var;
Block scope;
Type t, tHint;
public _Local(CodeGen owner)
{
this.owner = owner;
scope = owner.GetBlockForVariable();
}
public _Local(CodeGen owner, Type t)
{
this.owner = owner; this.t = t;
scope = owner.GetBlockForVariable();
}
public _Local(CodeGen owner, LocalBuilder var)
{
this.owner = owner;
this.var = var;
this.t = var.LocalType;
}
void CheckScope(CodeGen g)
{
if (g != owner)
throw new InvalidOperationException(Properties.Messages.ErrInvalidVariableContext);
if (scope != null && !owner.blocks.Contains(scope))
throw new InvalidOperationException(Properties.Messages.ErrInvalidVariableScope);
}
internal override void EmitGet(CodeGen g)
{
CheckScope(g);
if (var == null)
throw new InvalidOperationException(Properties.Messages.ErrUninitializedVarAccess);
g.il.Emit(OpCodes.Ldloc, var);
}
internal override void EmitSet(CodeGen g, Operand value, bool allowExplicitConversion)
{
CheckScope(g);
if (t == null)
t = value.Type;
if (var == null)
var = g.il.DeclareLocal(t);
g.EmitGetHelper(value, t, allowExplicitConversion);
g.il.Emit(OpCodes.Stloc, var);
}
internal override void EmitAddressOf(CodeGen g)
{
CheckScope(g);
if (var == null)
{
RequireType();
var = g.il.DeclareLocal(t);
}
g.il.Emit(OpCodes.Ldloca, var);
}
public override Type Type
{
get
{
RequireType();
return t;
}
}
void RequireType()
{
if (t == null)
{
if (tHint != null)
t = tHint;
else
throw new InvalidOperationException(Properties.Messages.ErrUntypedVarAccess);
}
}
internal override bool TrivialAccess
{
get
{
return true;
}
}
internal override void AssignmentHint(Operand op)
{
if (tHint == null)
tHint = Operand.GetType(op);
}
}
class _StaticTarget : Operand
{
Type t;
public _StaticTarget(Type t) { this.t = t; }
public override Type Type
{
get
{
return t;
}
}
internal override bool IsStaticTarget
{
get
{
return true;
}
}
}
public Operand this[string localName] // Named locals support.
{
get
{
Operand target;
if (!NamedLocals.TryGetValue(localName, out target))
throw new InvalidOperationException(Properties.Messages.ErrUninitializedVarAccess);
return target;
}
set
{
Operand target;
if (NamedLocals.TryGetValue(localName, out target))
// run in statement form; C# left-to-right evaluation semantics "just work"
Assign(target, value);
else
NamedLocals.Add(localName, Local(value));
}
}
public void Label(string labelName)
{
Label label;
if (!Labels.TryGetValue(labelName, out label))
Labels.Add(labelName, label = IL.DefineLabel());
IL.MarkLabel(label);
}
public void Goto(string labelName)
{
Label label;
if (!Labels.TryGetValue(labelName, out label))
Labels.Add(labelName, label = IL.DefineLabel());
IL.Emit(OpCodes.Br, label);
}
}
}
| |
using System;
using SharedKernel;
using Xunit;
namespace SharedKernelTest
{
public class ValueObjectTest
{
private const string Value1 = "test1";
private const string Value2 = "test2";
private const string Value3 = "test3";
private const string Value4 = "test4";
private const string Value5 = "test5";
private const string Value6 = "test6";
private class TestValueObject : ValueObject<TestValueObject>
{
[Identity]
private string test1;
[Identity]
public string test2;
public TestValueObject(string test1, string test2)
{
this.test1 = test1;
this.test2 = test2;
}
}
private class ExpandedTestValueObject : TestValueObject
{
[Identity]
public readonly string test3;
public ExpandedTestValueObject(string test1, string test2, string test3)
: base(test1, test2)
{
this.test3 = test3;
}
}
[Fact]
public void Equals_Null_False()
{
var test = new TestValueObject(Value1, Value2);
Assert.False(test.Equals(null));
}
[Fact]
public void Equals_IdenticalTestObjects_True()
{
TestValueObject address = new TestValueObject(Value1, Value2);
TestValueObject address2 = new TestValueObject(Value1, Value2);
Assert.True(address.Equals(address2));
}
[Fact]
public void Equals_FirstArgumentDifferent_False()
{
TestValueObject address = new TestValueObject(Value1, Value2);
TestValueObject address2 = new TestValueObject(Value3, Value2);
Assert.False(address.Equals(address2));
}
[Fact]
public void Equals_FirstArgumentIsNull_False()
{
TestValueObject address = new TestValueObject(null, Value2);
TestValueObject address2 = new TestValueObject(Value1, Value2);
Assert.False(address.Equals(address2));
}
[Fact]
public void Equals_SecondArgumentInSecondTestObjectIsNull_False()
{
TestValueObject address = new TestValueObject(Value1, Value2);
TestValueObject address2 = new TestValueObject(Value1, null);
Assert.False(address.Equals(address2));
}
[Fact]
public void Equals_TheSameObject_True()
{
TestValueObject address = new TestValueObject(Value1, Value2);
Assert.True(address.Equals(address));
}
[Fact]
public void EqualsChecksIfSymmetic_DifferentObjects_False()
{
TestValueObject address = new TestValueObject(Value1, Value2);
TestValueObject address2 = new TestValueObject(Value3, Value2);
Assert.False(address.Equals(address2));
Assert.False(address2.Equals(address));
}
[Fact]
public void EqualsChecksIfTransitive_IdenticalObjects_True()
{
TestValueObject address = new TestValueObject(Value1, Value2);
TestValueObject address2 = new TestValueObject(Value1, Value2);
TestValueObject address3 = new TestValueObject(Value1, Value2);
Assert.True(address.Equals(address2));
Assert.True(address2.Equals(address3));
Assert.True(address.Equals(address3));
}
[Fact]
public void EqualityOperators_IdenticalAndDifferentObjects_True()
{
TestValueObject address = new TestValueObject(Value1, Value2);
TestValueObject address2 = new TestValueObject(Value1, Value2);
TestValueObject address3 = new TestValueObject(Value3, Value2);
Assert.True(address == address2);
Assert.True(address2 != address3);
}
[Fact]
public void EqualityOperators_OneObjectIsNull_False()
{
TestValueObject address = new TestValueObject(Value1, Value2);
Assert.False(address == null);
Assert.False(null == address);
}
[Fact]
public void EqualityOperators_OneObjectIsNull_True()
{
TestValueObject address = new TestValueObject(Value1, Value2);
Assert.True(null != address);
Assert.True(address != null);
}
[Fact]
public void EqualityOperators_BaseAndDerivedType_False()
{
TestValueObject address = new TestValueObject(Value1, Value2);
ExpandedTestValueObject address2 = new ExpandedTestValueObject(Value1, Value2, Value3);
Assert.False(address.Equals(address2));
Assert.False(address == address2);
}
[Fact]
public void GetHashCode_TheSameObjects_TheSameHashCodes()
{
TestValueObject address = new TestValueObject(Value1, Value2);
TestValueObject address2 = new TestValueObject(Value1, Value2);
Assert.Equal(address.GetHashCode(), address2.GetHashCode());
}
[Fact]
public void GetHashCode_DifferentObjectsWithNulls_DifferentHashCodes()
{
TestValueObject address = new TestValueObject(null, Value2);
TestValueObject address2 = new TestValueObject(Value1, null);
Assert.NotEqual(address.GetHashCode(), address2.GetHashCode());
}
[Fact]
public void GetHashCode_DifferentObjects_DifferentHashCodes()
{
TestValueObject address = new TestValueObject(Value1, Value2);
TestValueObject address2 = new TestValueObject(Value3, Value4);
Assert.NotEqual(address.GetHashCode(), address2.GetHashCode());
}
[Fact]
public void GetHashCode_DifferentDerivedTypes_DifferentHashCodes()
{
ExpandedTestValueObject address = new ExpandedTestValueObject(Value1, Value2, Value3);
ExpandedTestValueObject address2 = new ExpandedTestValueObject(Value4, Value5, Value6);
Assert.NotEqual(address.GetHashCode(), address2.GetHashCode());
}
[Fact]
public void Equals_DerivedTypesWithFirstArgumentDifferent_False()
{
var address = new ExpandedTestValueObject(Value1, Value2, Value3);
var address2 = new ExpandedTestValueObject(Value4, Value2, Value3);
Assert.False(address.Equals(address2));
}
[Fact]
public void Equals_DerivedTypesWithSecondArgumentDifferent_False()
{
var address = new ExpandedTestValueObject(Value1, Value2, Value3);
var address2 = new ExpandedTestValueObject(Value1, Value4, Value3);
Assert.False(address.Equals(address2));
}
[Fact]
public void Equals_DerivedTypesWithThirdArgumentDifferent_False()
{
var address = new ExpandedTestValueObject(Value1, Value2, Value3);
var address2 = new ExpandedTestValueObject(Value1, Value4, Value3);
Assert.False(address.Equals(address2));
}
[Fact]
public void Equals_TheSameDerivedTypes_True()
{
var address = new ExpandedTestValueObject(Value1, Value2, Value3);
var address2 = new ExpandedTestValueObject(Value1, Value2, Value3);
Assert.True(address.Equals(address2));
}
}
}
| |
using System;
using System.Diagnostics;
using FieldInfos = YAF.Lucene.Net.Index.FieldInfos;
using IndexFormatTooNewException = YAF.Lucene.Net.Index.IndexFormatTooNewException;
using IndexFormatTooOldException = YAF.Lucene.Net.Index.IndexFormatTooOldException;
namespace YAF.Lucene.Net.Codecs.Lucene3x
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IndexInput = YAF.Lucene.Net.Store.IndexInput;
using Term = YAF.Lucene.Net.Index.Term;
/// <summary>
/// @lucene.experimental
/// </summary>
[Obsolete("(4.0) No longer used with flex indexing, except for reading old segments")]
internal sealed class SegmentTermEnum : IDisposable
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
private IndexInput input;
internal FieldInfos fieldInfos;
internal long size;
internal long position = -1;
// Changed strings to true utf8 with length-in-bytes not
// length-in-chars
public const int FORMAT_VERSION_UTF8_LENGTH_IN_BYTES = -4;
// NOTE: always change this if you switch to a new format!
// whenever you add a new format, make it 1 smaller (negative version logic)!
public const int FORMAT_CURRENT = FORMAT_VERSION_UTF8_LENGTH_IN_BYTES;
// when removing support for old versions, leave the last supported version here
public const int FORMAT_MINIMUM = FORMAT_VERSION_UTF8_LENGTH_IN_BYTES;
private TermBuffer termBuffer = new TermBuffer();
private TermBuffer prevBuffer = new TermBuffer();
private TermBuffer scanBuffer = new TermBuffer(); // used for scanning
internal TermInfo termInfo = new TermInfo();
private int format;
private bool isIndex = false;
internal long indexPointer = 0;
internal int indexInterval; // LUCENENET NOTE: Changed from public field to internal (class is internal anyway)
internal int skipInterval;
internal int newSuffixStart;
internal int maxSkipLevels;
private bool first = true;
public SegmentTermEnum(IndexInput i, FieldInfos fis, bool isi)
{
input = i;
fieldInfos = fis;
isIndex = isi;
maxSkipLevels = 1; // use single-level skip lists for formats > -3
int firstInt = input.ReadInt32();
if (firstInt >= 0)
{
// original-format file, without explicit format version number
format = 0;
size = firstInt;
// back-compatible settings
indexInterval = 128;
skipInterval = int.MaxValue; // switch off skipTo optimization
}
else
{
// we have a format version number
format = firstInt;
// check that it is a format we can understand
if (format > FORMAT_MINIMUM)
{
throw new IndexFormatTooOldException(input, format, FORMAT_MINIMUM, FORMAT_CURRENT);
}
if (format < FORMAT_CURRENT)
{
throw new IndexFormatTooNewException(input, format, FORMAT_MINIMUM, FORMAT_CURRENT);
}
size = input.ReadInt64(); // read the size
indexInterval = input.ReadInt32();
skipInterval = input.ReadInt32();
maxSkipLevels = input.ReadInt32();
Debug.Assert(indexInterval > 0, "indexInterval=" + indexInterval + " is negative; must be > 0");
Debug.Assert(skipInterval > 0, "skipInterval=" + skipInterval + " is negative; must be > 0");
}
}
public object Clone()
{
SegmentTermEnum clone = null;
try
{
clone = (SegmentTermEnum)base.MemberwiseClone();
}
#pragma warning disable 168
catch (InvalidOperationException e)
#pragma warning restore 168
{
}
clone.input = (IndexInput)input.Clone();
clone.termInfo = new TermInfo(termInfo);
clone.termBuffer = (TermBuffer)termBuffer.Clone();
clone.prevBuffer = (TermBuffer)prevBuffer.Clone();
clone.scanBuffer = new TermBuffer();
return clone;
}
internal void Seek(long pointer, long p, Term t, TermInfo ti)
{
input.Seek(pointer);
position = p;
termBuffer.Set(t);
prevBuffer.Reset();
//System.out.println(" ste doSeek prev=" + prevBuffer.toTerm() + " this=" + this);
termInfo.Set(ti);
first = p == -1;
}
/// <summary>
/// Increments the enumeration to the next element. True if one exists. </summary>
public bool Next()
{
prevBuffer.Set(termBuffer);
//System.out.println(" ste setPrev=" + prev() + " this=" + this);
if (position++ >= size - 1)
{
termBuffer.Reset();
//System.out.println(" EOF");
return false;
}
termBuffer.Read(input, fieldInfos);
newSuffixStart = termBuffer.newSuffixStart;
termInfo.DocFreq = input.ReadVInt32(); // read doc freq
termInfo.FreqPointer += input.ReadVInt64(); // read freq pointer
termInfo.ProxPointer += input.ReadVInt64(); // read prox pointer
if (termInfo.DocFreq >= skipInterval)
{
termInfo.SkipOffset = input.ReadVInt32();
}
if (isIndex)
{
indexPointer += input.ReadVInt64(); // read index pointer
}
//System.out.println(" ste ret term=" + term());
return true;
}
/* Optimized scan, without allocating new terms.
* Return number of invocations to next().
*
* NOTE: LUCENE-3183: if you pass Term("", "") here then this
* will incorrectly return before positioning the enum,
* and position will be -1; caller must detect this. */
internal int ScanTo(Term term)
{
scanBuffer.Set(term);
int count = 0;
if (first)
{
// Always force initial next() in case term is
// Term("", "")
Next();
first = false;
count++;
}
while (scanBuffer.CompareTo(termBuffer) > 0 && Next())
{
count++;
}
return count;
}
/// <summary>
/// Returns the current Term in the enumeration.
/// Initially invalid, valid after <see cref="Next()"/> called for the first time.
/// </summary>
public Term Term()
{
return termBuffer.ToTerm();
}
/// <summary>
/// Returns the previous Term enumerated. Initially <c>null</c>. </summary>
internal Term Prev()
{
return prevBuffer.ToTerm();
}
/// <summary>
/// Returns the current <see cref="Lucene3x.TermInfo"/> in the enumeration.
/// Initially invalid, valid after <see cref="Next()"/> called for the first time.
/// </summary>
internal TermInfo TermInfo()
{
return new TermInfo(termInfo);
}
/// <summary>
/// Sets the argument to the current <see cref="Lucene3x.TermInfo"/> in the enumeration.
/// Initially invalid, valid after <see cref="Next()"/> called for the first time.
/// </summary>
internal void TermInfo(TermInfo ti)
{
ti.Set(termInfo);
}
/// <summary>
/// Returns the docFreq from the current <see cref="Lucene3x.TermInfo"/> in the enumeration.
/// Initially invalid, valid after <see cref="Next()"/> called for the first time.
/// </summary>
public int DocFreq
{
get { return termInfo.DocFreq; }
}
/// <summary>
/// Returns the freqPointer from the current <see cref="Lucene3x.TermInfo"/> in the enumeration.
/// Initially invalid, valid after<see cref="Next()"/> called for the first time.
/// </summary>
internal long FreqPointer
{
get { return termInfo.FreqPointer; }
}
/// <summary>
/// Returns the proxPointer from the current <see cref="Lucene3x.TermInfo"/> in the enumeration.
/// Initially invalid, valid after<see cref="Next()"/> called for the first time.
/// </summary>
internal long ProxPointer
{
get { return termInfo.ProxPointer; }
}
/// <summary>
/// Closes the enumeration to further activity, freeing resources. </summary>
public void Dispose()
{
input.Dispose();
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by Microsoft.VSDesigner, Version 4.0.30319.1.
//
#pragma warning disable 1591
namespace WebsitePanel.Updater.Services {
using System;
using System.Web.Services;
using System.Diagnostics;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Data;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="InstallerServiceSoap", Namespace="http://websitepanel.net/services")]
public partial class InstallerService : System.Web.Services.Protocols.SoapHttpClientProtocol {
private System.Threading.SendOrPostCallback GetAvailableComponentsOperationCompleted;
private System.Threading.SendOrPostCallback GetFileChunkOperationCompleted;
private System.Threading.SendOrPostCallback GetFileSizeOperationCompleted;
private bool useDefaultCredentialsSetExplicitly;
/// <remarks/>
public InstallerService() {
this.Url = "http://localhost/WebsitePanelSite/Services/InstallerService-2.1.asmx";
if ((this.IsLocalFileSystemWebService(this.Url) == true)) {
this.UseDefaultCredentials = true;
this.useDefaultCredentialsSetExplicitly = false;
}
else {
this.useDefaultCredentialsSetExplicitly = true;
}
}
public new string Url {
get {
return base.Url;
}
set {
if ((((this.IsLocalFileSystemWebService(base.Url) == true)
&& (this.useDefaultCredentialsSetExplicitly == false))
&& (this.IsLocalFileSystemWebService(value) == false))) {
base.UseDefaultCredentials = false;
}
base.Url = value;
}
}
public new bool UseDefaultCredentials {
get {
return base.UseDefaultCredentials;
}
set {
base.UseDefaultCredentials = value;
this.useDefaultCredentialsSetExplicitly = true;
}
}
/// <remarks/>
public event GetAvailableComponentsCompletedEventHandler GetAvailableComponentsCompleted;
/// <remarks/>
public event GetFileChunkCompletedEventHandler GetFileChunkCompleted;
/// <remarks/>
public event GetFileSizeCompletedEventHandler GetFileSizeCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://websitepanel.net/services/GetAvailableComponents", RequestNamespace="http://websitepanel.net/services", ResponseNamespace="http://websitepanel.net/services", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public System.Data.DataSet GetAvailableComponents() {
object[] results = this.Invoke("GetAvailableComponents", new object[0]);
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public void GetAvailableComponentsAsync() {
this.GetAvailableComponentsAsync(null);
}
/// <remarks/>
public void GetAvailableComponentsAsync(object userState) {
if ((this.GetAvailableComponentsOperationCompleted == null)) {
this.GetAvailableComponentsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetAvailableComponentsOperationCompleted);
}
this.InvokeAsync("GetAvailableComponents", new object[0], this.GetAvailableComponentsOperationCompleted, userState);
}
private void OnGetAvailableComponentsOperationCompleted(object arg) {
if ((this.GetAvailableComponentsCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetAvailableComponentsCompleted(this, new GetAvailableComponentsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://websitepanel.net/services/GetFileChunk", RequestNamespace="http://websitepanel.net/services", ResponseNamespace="http://websitepanel.net/services", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")]
public byte[] GetFileChunk(string fileName, int offset, int size) {
object[] results = this.Invoke("GetFileChunk", new object[] {
fileName,
offset,
size});
return ((byte[])(results[0]));
}
/// <remarks/>
public void GetFileChunkAsync(string fileName, int offset, int size) {
this.GetFileChunkAsync(fileName, offset, size, null);
}
/// <remarks/>
public void GetFileChunkAsync(string fileName, int offset, int size, object userState) {
if ((this.GetFileChunkOperationCompleted == null)) {
this.GetFileChunkOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetFileChunkOperationCompleted);
}
this.InvokeAsync("GetFileChunk", new object[] {
fileName,
offset,
size}, this.GetFileChunkOperationCompleted, userState);
}
private void OnGetFileChunkOperationCompleted(object arg) {
if ((this.GetFileChunkCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetFileChunkCompleted(this, new GetFileChunkCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://websitepanel.net/services/GetFileSize", RequestNamespace="http://websitepanel.net/services", ResponseNamespace="http://websitepanel.net/services", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public long GetFileSize(string fileName) {
object[] results = this.Invoke("GetFileSize", new object[] {
fileName});
return ((long)(results[0]));
}
/// <remarks/>
public void GetFileSizeAsync(string fileName) {
this.GetFileSizeAsync(fileName, null);
}
/// <remarks/>
public void GetFileSizeAsync(string fileName, object userState) {
if ((this.GetFileSizeOperationCompleted == null)) {
this.GetFileSizeOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetFileSizeOperationCompleted);
}
this.InvokeAsync("GetFileSize", new object[] {
fileName}, this.GetFileSizeOperationCompleted, userState);
}
private void OnGetFileSizeOperationCompleted(object arg) {
if ((this.GetFileSizeCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetFileSizeCompleted(this, new GetFileSizeCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
private bool IsLocalFileSystemWebService(string url) {
if (((url == null)
|| (url == string.Empty))) {
return false;
}
System.Uri wsUri = new System.Uri(url);
if (((wsUri.Port >= 1024)
&& (string.Compare(wsUri.Host, "localHost", System.StringComparison.OrdinalIgnoreCase) == 0))) {
return true;
}
return false;
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")]
public delegate void GetAvailableComponentsCompletedEventHandler(object sender, GetAvailableComponentsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetAvailableComponentsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetAvailableComponentsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public System.Data.DataSet Result {
get {
this.RaiseExceptionIfNecessary();
return ((System.Data.DataSet)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")]
public delegate void GetFileChunkCompletedEventHandler(object sender, GetFileChunkCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetFileChunkCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetFileChunkCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public byte[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((byte[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")]
public delegate void GetFileSizeCompletedEventHandler(object sender, GetFileSizeCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetFileSizeCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetFileSizeCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public long Result {
get {
this.RaiseExceptionIfNecessary();
return ((long)(this.results[0]));
}
}
}
}
#pragma warning restore 1591
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace RemoteWindowsAgent
{
//remaining strings are internal use only - no I18n needed
[Serializable]
public class ReturnValues {
List<ReturnValue> values = new List<ReturnValue>();
private static Object lockObj = new Object();
private static XmlReaderSettings settings = null;
public ReturnValues(ReturnValue rv)
{
values.Add(rv);
}
public ReturnValues() {
}
public ReturnValues(String xml)
{
parse(xml);
}
public ReturnValues Clone()
{
ReturnValues ReturnValuesCopy = new ReturnValues();
ReturnValuesCopy.values = new List<ReturnValue>();
List<ReturnValue>.Enumerator ienum = values.GetEnumerator();
while (ienum.MoveNext())
ReturnValuesCopy.values.Add(ienum.Current);
return ReturnValuesCopy;
}
public static ReturnValues GetSimpleSuccessReturnValues(String val) {
ReturnValues rvs = new ReturnValues();
ReturnValue rv = new ReturnValue(ReturnCodes.SUCCESS);
rv.SetValue(val);
rvs.AddReturnValue(rv);
return rvs;
}
public static ReturnValues GetSimpleReturnValues(int code, String text) {
ReturnValues rvs = new ReturnValues();
ReturnValue rv = new ReturnValue(code);
rv.SetText(text);
rvs.AddReturnValue(rv);
return rvs;
}
public static ReturnValues GetSimpleReturnValues(int code, String text, String value) {
ReturnValues rvs = new ReturnValues();
ReturnValue rv = new ReturnValue(code);
rv.SetText(text);
rv.SetValue(value);
rvs.AddReturnValue(rv);
return rvs;
}
public void AddReturnValue(ReturnValue rv) {
values.Add(rv);
}
//Does an Add if the value does not exist
public void ReplaceReturnValue(ReturnValue rv)
{
String name = rv.GetName();
bool done = false;
IEnumerator ienum = this.values.GetEnumerator();
while (ienum.MoveNext())
{
ReturnValue rv2 = (ReturnValue)ienum.Current;
if (name==rv2.GetName())
{
rv2.SetValue(rv.GetStringValue());
rv2.SetText(rv.GetText());
rv2.SetCode(rv.GetCode());
done = true;
break;
}
}
if (!done)
{
AddReturnValue(rv);
}
}
//returns null if not found
public ReturnValue GetReturnValue(String name)
{
IEnumerator ienum = this.values.GetEnumerator();
while (ienum.MoveNext())
{
ReturnValue rv2 = (ReturnValue)ienum.Current;
if (name==rv2.GetName())
{
return rv2;
}
}
return null;
}
public void Validate(
object sender,
ValidationEventArgs e
) {
}
//convenience method
public bool IsSuccessful() {
//bool allowDebug = LogFile.AllowDebug;
if (values.Count == 0)
{
//if (allowDebug) LogFile.Debug("ReturnValues.IsSuccessful(): Returning true (by default) for an empty ReturnValues object");
return true;
}
IEnumerator e = values.GetEnumerator();
while (e.MoveNext()) {
ReturnValue rv = (ReturnValue)(e.Current);
int code = rv.GetCode();
if (code<0) return false;
}
return true;
}
/// <summary>
/// Returns true if all errors (if there are any) in the object
/// are retryable.
/// </summary>
/// <param name="rvs"></param>
/// <returns>false if there is at least one error that is not
/// retryable. Returns true otherwise.</returns>
public bool AllErrorsAreRetryable()
{
// look at each rv in rvs. If anything is NOT retryable, return false
List<ReturnValue> returnValues = GetAllReturnValues();
foreach (ReturnValue returnValue in returnValues)
{
int code = returnValue.GetCode();
if (ReturnCodes.IsError(code))
{
// we found an error. See if it is retryable.
if (!ReturnCodes.IsRetryableError(code))
{
return false;
}
}
}
// If we made it here, then there are no permanent errors
return true;
}
public bool IsSuccessfulOrNotSupported()
{
IEnumerator e = values.GetEnumerator();
while (e.MoveNext())
{
ReturnValue rv = (ReturnValue)(e.Current);
int code = rv.GetCode();
if ((code < 0) && (code != ReturnCodes.OPERATION_NOT_SUPPORTED))
{
return false;
}
}
return true;
}
public bool IsFirstValueSuccessful()
{
if (values.Count==0) return true;
ReturnValue rv = (ReturnValue)values[0];
return rv.GetCode()>=0;
}
//warnings in this case are considered non-success
public bool IsStrictSuccessful() {
IEnumerator e = values.GetEnumerator();
while (e.MoveNext()) {
ReturnValue rv = (ReturnValue)(e.Current);
int code = rv.GetCode();
if (code!=0) return false;
}
return true;
}
public bool IsNoSuchUser() {
IEnumerator e = values.GetEnumerator();
while (e.MoveNext()) {
ReturnValue rv = (ReturnValue)(e.Current);
if (rv.GetCode()!=ReturnCodes.NO_SUCH_USER) return false;
}
return true;
}
public String GetSuccessString() {
IEnumerator e = values.GetEnumerator();
while (e.MoveNext()) {
ReturnValue rv = (ReturnValue)(e.Current);
int code = rv.GetCode();
if (code==0) {
return rv.GetStringValue();
}
}
return null;
}
//An enumeration of ReturnValue objects
public List<ReturnValue>.Enumerator GetEnumerator() {
return values.GetEnumerator();
}
public static XmlElement buildReturnValueElement(ReturnValue rv, XmlDocument doc) {
XmlElement e = doc.CreateElement("","returnvalue","");
String name = rv.GetName();
if (name!=null) {
e.SetAttribute("name","",name);
}
String code = rv.GetCode().ToString();
e.SetAttribute("code","",code);
//some fields such as color are ignored because we don't need to send to the agent
String type = rv.GetStringType();
if (type!=null) {
e.SetAttribute("type","",type);
}
bool isList = rv.IsList();
e.SetAttribute("list","",isList.ToString());
if (isList) {
IList list = rv.GetOriginalList();
IEnumerator ienum = list.GetEnumerator();
while (ienum.MoveNext()) {
String val = ienum.Current.ToString();
XmlElement valueElement = doc.CreateElement("", "value", "");
if (ienum.Current is ReturnValueField)
{
valueElement.SetAttribute("field",
((ReturnValueField) ienum.Current).GetFieldName());
}
valueElement.AppendChild(doc.CreateTextNode(val));
e.AppendChild(valueElement);
}
}
else {
String val2 = rv.GetStringValue();
if (val2!=null) {
XmlElement valueElement = doc.CreateElement("","value","");
valueElement.AppendChild(doc.CreateTextNode(val2));
e.AppendChild(valueElement);
}
}
String text = rv.GetText();
if (text!=null) {
XmlElement textElement = doc.CreateElement("","text","");
textElement.AppendChild(doc.CreateTextNode(text));
e.AppendChild(textElement);
}
return e;
}
public String toXML() {
try {
// Code to demonstrate creating of XmlDocument programmatically
XmlDocument xmlDom = new XmlDocument( );
xmlDom.AppendChild(xmlDom.CreateElement("", "returnvalues", ""));
XmlElement xmlRoot = xmlDom.DocumentElement;
IEnumerator ienum = values.GetEnumerator();
while (ienum.MoveNext()) {
ReturnValue rv = (ReturnValue)(ienum.Current);
XmlElement e = buildReturnValueElement(rv,xmlDom);
xmlRoot.AppendChild(e);
}
return xmlDom.InnerXml;
}
catch (Exception) {
return null;
}
}
//Not sure this is going to meet our needs. It is a port from the Java side.
//the Java side could tell all fields as strings, but I'm not sure that applies here.
public Hashtable GetHashtable() {
Hashtable table = new Hashtable();
IEnumerator ienum = values.GetEnumerator();
while (ienum.MoveNext()) {
ReturnValue rv = (ReturnValue)(ienum.Current);
String name = rv.GetName();
ReturnValueTypes type = rv.GetValueType();
bool isList = rv.IsList();
if (!isList) {
table[name]=rv.GetStringValue();
}
else {
table[name]=rv.GetList();
}
}
return table;
}
public Hashtable GetReturnValueHashtable()
{
Hashtable table = new Hashtable();
IEnumerator ienum = values.GetEnumerator();
while (ienum.MoveNext())
{
ReturnValue rv = (ReturnValue)(ienum.Current);
String name = rv.GetName();
if (name!=null) //This was thrown in due to crashes occuring when Solaris was timing out.
{
table[name]=rv;
}
}
return table;
}
public void LoadFromReturnValueHashtable(Hashtable ht)
{
IDictionaryEnumerator ienum = ht.GetEnumerator();
while (ienum.MoveNext())
{
ReturnValue rv = (ReturnValue)(ienum.Value);
this.ReplaceReturnValue(rv);
}
}
public void LoadFromHashtable(Hashtable ht)
{
IDictionaryEnumerator ienum = ht.GetEnumerator();
while (ienum.MoveNext())
{
ReturnValue rv = new ReturnValue(0);
rv.SetName((String)(ienum.Key));
Object val = ienum.Value;
if (val is IList)
{
rv.SetList((IList)val);
}
else
{
rv.SetValue((String)val);
}
this.ReplaceReturnValue(rv);
}
}
public bool IsEmpty()
{
return (values==null) || (values.Count==0);
}
public void AddReturnValues(ReturnValues rvs)
{
values.AddRange(rvs.values);
}
public ReturnValue GetFirstReturnValue()
{
List<ReturnValue>.Enumerator rvsEnum = values.GetEnumerator();
if (rvsEnum.MoveNext())
{
return rvsEnum.Current;
}
return null;
}
public List<ReturnValue> GetAllReturnValues()
{
if (values == null)
{
return new List<ReturnValue>();
}
else
{
return values;
}
}
public void SetAllNames(String name)
{
IEnumerator e = values.GetEnumerator();
while (e.MoveNext())
{
ReturnValue rv = (ReturnValue)(e.Current);
rv.SetName(name);
}
}
private void parse(String xml)
{
try
{
XmlReader r = XmlReader.Create(new StringReader(xml));
XmlDocument doc = new XmlDocument();
doc.Load(r);
//XmlDocument doc = new XmlDocument();
//doc.LoadXml(xml);
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = doc.GetElementsByTagName("returnvalues");
XmlNode node = nodes.Item(0);
XmlNodeList rvs = node.SelectNodes("returnvalue");
if (rvs == null)
{
}
for (int i = 0; i < rvs.Count; i++)
{
XmlNode child = rvs.Item(i);
ReturnValue srv = new ReturnValue(child);
values.Add(srv);
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
throw new XmlException(e.Message, e);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedFile.CreateNew.
/// </summary>
public class MemoryMappedFileTests_CreateNew : MemoryMappedFilesTestBase
{
/// <summary>
/// Tests invalid arguments to the CreateNew mapName parameter.
/// </summary>
[Fact]
public void InvalidArguments_MapName()
{
// Empty string is an invalid map name
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateNew(string.Empty, 4096));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateNew(string.Empty, 4096, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateNew(string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None));
}
/// <summary>
/// Tests invalid arguments to the CreateNew capacity parameter.
/// </summary>
[Theory]
[InlineData(0)] // default size is invalid with CreateNew as there's nothing to expand to match
[InlineData(-100)] // negative values don't make sense
public void InvalidArguments_Capacity(int capacity)
{
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, capacity));
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, capacity, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None));
}
/// <summary>
/// Tests invalid arguments to the CreateNew access parameter.
/// </summary>
[Theory]
[InlineData((MemoryMappedFileAccess)42)]
[InlineData((MemoryMappedFileAccess)(-2))]
public void InvalidArguments_Access(MemoryMappedFileAccess access)
{
// Out of range values
Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateNew(null, 4096, access));
Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateNew(null, 4096, access, MemoryMappedFileOptions.None, HandleInheritability.None));
}
/// <summary>
/// Tests invalid arguments to the CreateNew access parameter, specifically MemoryMappedFileAccess.Write.
/// </summary>
[Fact]
public void InvalidArguments_WriteAccess()
{
// Write-only access isn't allowed, as it'd be useless
Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Write));
}
/// <summary>
/// Tests invalid arguments to the CreateNew options parameter.
/// </summary>
[Theory]
[InlineData((MemoryMappedFileOptions)42)]
[InlineData((MemoryMappedFileOptions)(-2))]
public void InvalidArguments_Options(MemoryMappedFileOptions options)
{
Assert.Throws<ArgumentOutOfRangeException>("options", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Read, options, HandleInheritability.None));
}
/// <summary>
/// Tests invalid arguments to the CreateNew inheritability parameter.
/// </summary>
[Theory]
[InlineData((HandleInheritability)42)]
[InlineData((HandleInheritability)(-2))]
public void InvalidArguments_Inheritability(HandleInheritability inheritability)
{
Assert.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Read, MemoryMappedFileOptions.None, inheritability));
}
/// <summary>
/// Test the exceptional behavior when attempting to create a map so large it's not supported.
/// </summary>
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void TooLargeCapacity_Windows()
{
if (IntPtr.Size == 4)
{
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, 1 + (long)uint.MaxValue));
}
else
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateNew(null, long.MaxValue));
}
}
/// <summary>
/// Test the exceptional behavior when attempting to create a map so large it's not supported.
/// </summary>
[PlatformSpecific(PlatformID.AnyUnix & ~PlatformID.OSX)] // Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately)
[Fact]
public void TooLargeCapacity_Unix()
{
// On Windows we fail with too large a capacity as part of the CreateNew call.
// On Unix that exception may happen a bit later, as part of creating the view,
// due to differences in OS behaviors and Unix not actually having a notion of
// a view separate from a map. It could also come from CreateNew, depending
// on what backing store is being used.
Assert.Throws<IOException>(() =>
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, long.MaxValue))
{
mmf.CreateViewAccessor().Dispose();
}
});
}
/// <summary>
/// Test to verify that map names are left unsupported on Unix.
/// </summary>
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void MapNamesNotSupported_Unix(string mapName)
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateNew(mapName, 4096));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateNew(mapName, 4096, MemoryMappedFileAccess.Read));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateNew(mapName, 4096, MemoryMappedFileAccess.Read, MemoryMappedFileOptions.None, HandleInheritability.None));
}
/// <summary>
/// Test to verify a variety of map names work correctly on Windows.
/// </summary>
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[MemberData(nameof(CreateValidMapNames))]
[InlineData(null)]
public void ValidMapNames_Windows(string name)
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096))
{
ValidateMemoryMappedFile(mmf, 4096);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096, MemoryMappedFileAccess.Read))
{
ValidateMemoryMappedFile(mmf, 4096, MemoryMappedFileAccess.Read);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096, MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileOptions.DelayAllocatePages, HandleInheritability.Inheritable))
{
ValidateMemoryMappedFile(mmf, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.Inheritable);
}
}
/// <summary>
/// Test to verify map names are handled appropriately, causing a conflict when they're active but
/// reusable in a sequential manner.
/// </summary>
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void ReusingNames_Windows(string name)
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096))
{
ValidateMemoryMappedFile(mmf, 4096);
Assert.Throws<IOException>(() => MemoryMappedFile.CreateNew(name, 4096));
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096))
{
ValidateMemoryMappedFile(mmf, 4096, MemoryMappedFileAccess.ReadWrite);
}
}
/// <summary>
/// Test various combinations of arguments to CreateNew, validating the created maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinations),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.CopyOnWrite },
new MemoryMappedFileOptions[] { MemoryMappedFileOptions.None, MemoryMappedFileOptions.DelayAllocatePages },
new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable })]
public void ValidArgumentCombinations(
string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability)
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access))
{
ValidateMemoryMappedFile(mmf, capacity, access);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinations tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">The accesses to yield</param>
/// <param name="options">The options to yield.</param>
/// <param name="inheritabilities">The inheritabilities to yield.</param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinations(
string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, MemoryMappedFileOptions[] options, HandleInheritability[] inheritabilities)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
string mapName = tmpMapName == "CreateUniqueMapName()" ?
CreateUniqueMapName() :
tmpMapName;
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ?
s_pageSize.Value :
tmpCapacity;
foreach (MemoryMappedFileAccess access in accesses)
{
foreach (MemoryMappedFileOptions option in options)
{
foreach (HandleInheritability inheritability in inheritabilities)
{
yield return new object[] { mapName, capacity, access, option, inheritability };
}
}
}
}
}
}
/// <summary>
/// Test to verify that two unrelated maps don't share data.
/// </summary>
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[MemberData(nameof(CreateValidMapNames))]
[InlineData(null)]
public void DataNotPersistedBetweenMaps_Windows(string name)
{
// Write some data to a map newly created with the specified name
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096))
using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor())
{
accessor.Write(0, 42);
}
// After it's closed, open a map with the same name again and verify the data's gone
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096))
using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor())
{
// Data written to previous map should not be here
Assert.Equal(0, accessor.ReadByte(0));
}
}
/// <summary>
/// Test to verify that two unrelated maps don't share data.
/// </summary>
[Fact]
public void DataNotPersistedBetweenMaps_Unix()
{
// same as the Windows test, but for Unix we only validate null, as other names aren't allowed
DataNotPersistedBetweenMaps_Windows(null);
}
/// <summary>
/// Test to verify that we can have many maps open at the same time.
/// </summary>
[Fact]
public void ManyConcurrentMaps()
{
const int NumMaps = 100, Capacity = 4096;
var mmfs = new List<MemoryMappedFile>(Enumerable.Range(0, NumMaps).Select(_ => MemoryMappedFile.CreateNew(null, Capacity)));
try
{
mmfs.ForEach(mmf => ValidateMemoryMappedFile(mmf, Capacity));
}
finally
{
mmfs.ForEach(mmf => mmf.Dispose());
}
}
/// <summary>
/// Test to verify expected capacity with regards to page size and automatically rounding up to the nearest.
/// </summary>
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void RoundedUpCapacity_Windows()
{
// On both Windows and Unix, capacity is rounded up to the nearest page size. However,
// the amount of capacity actually usable by the developer is supposed to be limited
// to that specified. That's not currently the case with the MMF APIs on Windows;
// it is the case on Unix.
const int CapacityLessThanPageSize = 1;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, CapacityLessThanPageSize))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor())
{
Assert.Equal(s_pageSize.Value, acc.Capacity);
}
}
/// <summary>
/// Test to verify expected capacity with regards to page size and automatically rounding up to the nearest.
/// </summary>
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public void RoundedUpCapacity_Unix()
{
// The capacity of the view should match the capacity specified when creating the map,
// even though under the covers the map's capacity is rounded up to the nearest page size.
const int CapacityLessThanPageSize = 1;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, CapacityLessThanPageSize))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor())
{
Assert.Equal(CapacityLessThanPageSize, acc.Capacity);
}
}
/// <summary>
/// Test to verify we can dispose of a map multiple times.
/// </summary>
[Fact]
public void DoubleDispose()
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096);
mmf.Dispose();
mmf.Dispose();
}
/// <summary>
/// Test to verify we can't create new views after the map has been disposed.
/// </summary>
[Fact]
public void UnusableAfterDispose()
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096);
SafeMemoryMappedFileHandle handle = mmf.SafeMemoryMappedFileHandle;
Assert.False(handle.IsClosed);
mmf.Dispose();
Assert.True(handle.IsClosed);
Assert.Throws<ObjectDisposedException>(() => mmf.CreateViewAccessor());
Assert.Throws<ObjectDisposedException>(() => mmf.CreateViewStream());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Anlab.Core.Data;
using Anlab.Core.Domain;
using AnlabMvc.Controllers;
using AnlabMvc.Models.Roles;
using AnlabMvc.Models.User;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Moq;
using Shouldly;
using Test.Helpers;
using TestHelpers.Helpers;
using Xunit;
using Xunit.Abstractions;
namespace Test.TestsController
{
[Trait("Category", "ControllerTests")]
public class AdminControllerTests
{
public Mock<ApplicationDbContext> MockDbContext { get; set; }
public Mock<HttpContext> MockHttpContext { get; set; }
public Mock<FakeUserManager> MockUserManager { get; set; }
public Mock<FakeRoleManager> MockRolemanager { get; set; }
public Mock<ClaimsPrincipal> MockClaimsPrincipal { get; set; }
//Setup Data
public List<User> UserData { get; set; }
//Controller
public AdminController Controller { get; set; }
public AdminControllerTests()
{
MockDbContext = new Mock<ApplicationDbContext>();
MockHttpContext = new Mock<HttpContext>();
MockUserManager = new Mock<FakeUserManager>();
MockRolemanager = new Mock<FakeRoleManager>();
MockClaimsPrincipal = new Mock<ClaimsPrincipal>();
var mockDataProvider = new Mock<SessionStateTempDataProvider>();
//Default Data
UserData = new List<User>();
for (int i = 0; i < 5; i++)
{
var user = CreateValidEntities.User(i + 1, true);
UserData.Add(user);
}
var userIdent = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, UserData[2].Id),
}));
//Setups
MockDbContext.Setup(a => a.Users).Returns(UserData.AsQueryable().MockAsyncDbSet().Object);
MockClaimsPrincipal.Setup(a => a.Claims).Returns(userIdent.Claims);
MockClaimsPrincipal.Setup(a => a.IsInRole(RoleCodes.Admin)).Returns(false);
MockClaimsPrincipal.Setup(a => a.FindFirst(It.IsAny<string>())).Returns(new Claim(ClaimTypes.NameIdentifier, UserData[3].Id));
MockHttpContext.Setup(m => m.User).Returns(MockClaimsPrincipal.Object);
Controller = new AdminController(MockDbContext.Object, MockUserManager.Object, MockRolemanager.Object)
{
ControllerContext = new ControllerContext
{
HttpContext = MockHttpContext.Object
},
TempData = new TempDataDictionary(MockHttpContext.Object, mockDataProvider.Object)
};
}
#region Index
[Fact]
public async Task TestIndexReturnsViewWithExpectedResults1()
{
// Arrange
var adminUsers = new List<User>();
adminUsers.Add(UserData[1]);
adminUsers.Add(UserData[3]);
var labUsers = new List<User>();
labUsers.Add(UserData[1]);
labUsers.Add(UserData[2]);
var reportUsers = new List<User>();
reportUsers.Add(UserData[1]);
reportUsers.Add(UserData[4]);
MockUserManager.Setup(a => a.GetUsersInRoleAsync(RoleCodes.Admin)).ReturnsAsync(adminUsers);
MockUserManager.Setup(a => a.GetUsersInRoleAsync(RoleCodes.LabUser)).ReturnsAsync(labUsers);
MockUserManager.Setup(a => a.GetUsersInRoleAsync(RoleCodes.Reports)).ReturnsAsync(reportUsers);
// Act
var controllerResult = await Controller.Index();
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<List<UserRolesModel>>(viewResult.Model);
modelResult.ShouldNotBeNull();
modelResult.Count.ShouldBe(4);
var user = modelResult.SingleOrDefault(a => a.User.Id == UserData[1].Id);
user.ShouldNotBeNull();
user.IsAdmin.ShouldBeTrue();
user.IsLabUser.ShouldBeTrue();
user.IsReports.ShouldBeTrue();
user = modelResult.SingleOrDefault(a => a.User.Id == UserData[2].Id);
user.ShouldNotBeNull();
user.IsAdmin.ShouldBeFalse();
user.IsLabUser.ShouldBeTrue();
user.IsReports.ShouldBeFalse();
user = modelResult.SingleOrDefault(a => a.User.Id == UserData[3].Id);
user.ShouldNotBeNull();
user.IsAdmin.ShouldBeTrue();
user.IsLabUser.ShouldBeFalse();
user.IsReports.ShouldBeFalse();
user = modelResult.SingleOrDefault(a => a.User.Id == UserData[4].Id);
user.ShouldNotBeNull();
user.IsAdmin.ShouldBeFalse();
user.IsLabUser.ShouldBeFalse();
user.IsReports.ShouldBeTrue();
}
[Fact]
public async Task TestIndexReturnsViewWithExpectedResults2()
{
// Arrange
var adminUsers = new List<User>();
var labUsers = new List<User>();
labUsers.Add(UserData[2]);
var reportUsers = new List<User>();
reportUsers.Add(UserData[4]);
MockUserManager.Setup(a => a.GetUsersInRoleAsync(RoleCodes.Admin)).ReturnsAsync(adminUsers);
MockUserManager.Setup(a => a.GetUsersInRoleAsync(RoleCodes.LabUser)).ReturnsAsync(labUsers);
MockUserManager.Setup(a => a.GetUsersInRoleAsync(RoleCodes.Reports)).ReturnsAsync(reportUsers);
// Act
var controllerResult = await Controller.Index();
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<List<UserRolesModel>>(viewResult.Model);
modelResult.ShouldNotBeNull();
modelResult.Count.ShouldBe(2);
var user = modelResult.SingleOrDefault(a => a.User.Id == UserData[1].Id);
user.ShouldBeNull();
user = modelResult.SingleOrDefault(a => a.User.Id == UserData[2].Id);
user.ShouldNotBeNull();
user.IsAdmin.ShouldBeFalse();
user.IsLabUser.ShouldBeTrue();
user.IsReports.ShouldBeFalse();
user = modelResult.SingleOrDefault(a => a.User.Id == UserData[3].Id);
user.ShouldBeNull();
user = modelResult.SingleOrDefault(a => a.User.Id == UserData[4].Id);
user.ShouldNotBeNull();
user.IsAdmin.ShouldBeFalse();
user.IsLabUser.ShouldBeFalse();
user.IsReports.ShouldBeTrue();
}
#endregion Index
#region SearchAdminUser
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task TestSearchAdminUserRedirectsToIndex1(string value)
{
// Arrange
// Act
var controllerResult = await Controller.SearchAdminUser(value);
// Assert
var redirectResult = Assert.IsType<RedirectToActionResult>(controllerResult);
redirectResult.ActionName.ShouldBe("Index");
redirectResult.ControllerName.ShouldBeNull();
Controller.ErrorMessage.ShouldBe("Nothing entered to search.");
}
[Fact]
public async Task TestSearchAdminUserRedirectsToIndex2()
{
// Arrange
// Act
var controllerResult = await Controller.SearchAdminUser("xxx");
// Assert
var redirectResult = Assert.IsType<RedirectToActionResult>(controllerResult);
redirectResult.ActionName.ShouldBe("Index");
redirectResult.ControllerName.ShouldBeNull();
Controller.ErrorMessage.ShouldBe("Email xxx not found.");
}
[Theory]
[InlineData("xxx@xx.com")]
[InlineData("XXX@XX.COM")]
[InlineData(" XXX@XX.COM ")]
public async Task TestSearchAdminUserRedirectsToEditAdmin(string value)
{
// Arrange
UserData[1].NormalizedUserName = "XXX@XX.COM";
// Act
var controllerResult = await Controller.SearchAdminUser(value);
// Assert
var redirectResult = Assert.IsType<RedirectToActionResult>(controllerResult);
redirectResult.ActionName.ShouldBe("EditAdmin");
redirectResult.ControllerName.ShouldBeNull();
redirectResult.RouteValues["id"].ShouldBe(UserData[1].Id);
Controller.ErrorMessage.ShouldBeNull();
}
[Fact]
public async Task TestSearchAdminUserThrowsExceptionIfDuplicate()
{
// Arrange
UserData[1].NormalizedUserName = "XXX@XX.COM";
UserData[2].NormalizedUserName = "XXX@XX.COM"; //Should never happen...
// Act
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await Controller.SearchAdminUser("xxx@xx.com"));
// Assert
ex.ShouldNotBeNull();
ex.Message.ShouldBe("Sequence contains more than one matching element");
}
#endregion SearchAdminUser
#region EditAdmin
[Fact]
public async Task TestEditAdminReturnsNotFound()
{
// Arrange
// Act
var controllerResult = await Controller.EditAdmin("XXX");
// Assert
Assert.IsType<NotFoundResult>(controllerResult);
}
[Fact]
public async Task TestEditAdminReturnsExpectedResults()
{
// Arrange
MockUserManager.Setup(a => a.IsInRoleAsync(UserData[1], RoleCodes.LabUser)).ReturnsAsync(true);
// Act
var controllerResult = await Controller.EditAdmin(UserData[1].Id);
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<UserRolesModel>(viewResult.Model);
modelResult.User.Id.ShouldBe(UserData[1].Id);
modelResult.IsLabUser.ShouldBeTrue();
modelResult.IsAdmin.ShouldBeFalse();
modelResult.IsReports.ShouldBeFalse();
MockUserManager.Verify(a => a.IsInRoleAsync(UserData[1], It.IsAny<string>()), Times.Exactly(3));
}
#endregion EditAdmin
#region ListClients
[Fact]
public async Task TestListClientsReturnsView()
{
// Arrange
// Act
var controllerResult = await Controller.ListClients();
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<List<User>>(viewResult.Model);
modelResult.ShouldNotBeNull();
modelResult.Count.ShouldBe(5);
}
#endregion Description
#region EditUser
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("xxx")]
public async Task TestEditUserGetRedirectsWhenUserNotFound(string value)
{
// Arrange
// Act
var controllerResult = await Controller.EditUser(value);
// Assert
var redrectResult = Assert.IsType<RedirectToActionResult>(controllerResult);
redrectResult.ActionName.ShouldBe("ListClients");
redrectResult.ControllerName.ShouldBeNull();
Controller.ErrorMessage.ShouldBe("User Not Found.");
}
[Fact]
public async Task TestEditUserGetReturnsView()
{
// Arrange
// Act
var controllerResult = await Controller.EditUser(UserData[1].Id);
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<User>(viewResult.Model);
modelResult.ShouldNotBeNull();
modelResult.Id.ShouldBe(UserData[1].Id);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("xxx")]
public async Task TestEditUserPostRedirectsWhenUserNotFound(string value)
{
// Arrange
// Act
var controllerResult = await Controller.EditUser(value, CreateValidEntities.User(7));
// Assert
var redrectResult = Assert.IsType<RedirectToActionResult>(controllerResult);
redrectResult.ActionName.ShouldBe("ListClients");
redrectResult.ControllerName.ShouldBeNull();
Controller.ErrorMessage.ShouldBe("User Not Found.");
MockDbContext.Verify(a => a.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Never);
MockDbContext.Verify(a => a.Update(It.IsAny<User>()), Times.Never);
}
[Fact]
public async Task TestEditUserPostThrowsExceptionIfIdDoesNotMatch()
{
// Arrange
var model = CreateValidEntities.User(7);
//model.Id = UserData[1].Id;
Controller.ModelState.AddModelError("Fake", "Fake Error");
// Act
var ex = await Assert.ThrowsAsync<Exception>(async () => await Controller.EditUser(UserData[1].Id, model));
// Assert
ex.ShouldNotBeNull();
ex.Message.ShouldBe("User id did not match passed value.");
}
[Fact]
public async Task TestEditUserPostReturnsViewIfModelStateInvalid()
{
// Arrange
var model = CreateValidEntities.User(7);
model.Id = UserData[1].Id;
Controller.ModelState.AddModelError("Fake", "Fake Error");
// Act
var controllerResult = await Controller.EditUser(UserData[1].Id, model);
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<User>(viewResult.Model);
modelResult.ShouldNotBeNull();
modelResult.Id.ShouldBe(UserData[1].Id);
Controller.ErrorMessage.ShouldBe("The user had invalid data.");
MockDbContext.Verify(a => a.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Never);
MockDbContext.Verify(a => a.Update(It.IsAny<User>()), Times.Never);
}
[Fact]
public async Task TestEditUserPostSavesExpectedFields()
{
// Arrange
var model = CreateValidEntities.User(7, true);
model.Id = UserData[1].Id;
// Act
var controllerResult = await Controller.EditUser(UserData[1].Id, model);
// Assert
var redirectResult = Assert.IsType<RedirectToActionResult>(controllerResult);
redirectResult.ShouldNotBeNull();
redirectResult.ActionName.ShouldBe("ListClients");
redirectResult.ControllerName.ShouldBeNull();
Controller.ErrorMessage.ShouldBeNull();
Controller.Message.ShouldBe("User Updated.");
MockDbContext.Verify(a => a.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
MockDbContext.Verify(a => a.Update(UserData[1]), Times.Once);
//Fields
UserData[1].FirstName.ShouldBe("FirstName7");
UserData[1].LastName.ShouldBe("LastName7");
UserData[1].Name.ShouldBe("FirstName7 LastName7");
UserData[1].Phone.ShouldBe("Phone7");
UserData[1].Account.ShouldBe("ACCOUNT7");
UserData[1].ClientId.ShouldBe("CLIENTID7");
UserData[1].CompanyName.ShouldBe("CompanyName7");
UserData[1].BillingContactName.ShouldBe("BillingContactName7");
UserData[1].BillingContactAddress.ShouldBe("BillingContactAddress7");
UserData[1].BillingContactEmail.ShouldBe("BillingContactEmail7@test.com");
UserData[1].BillingContactPhone.ShouldBe("BillingContactPhone7");
UserData[1].NormalizedUserName.ShouldBe("NormalizedUserName2"); //Unchanged
}
#endregion EditUser
#region AddUserToRole
[Theory]
[InlineData(RoleCodes.Admin, true)]
[InlineData(RoleCodes.Admin, false)]
[InlineData(RoleCodes.LabUser, true)]
[InlineData(RoleCodes.LabUser, false)]
[InlineData(RoleCodes.Reports, true)]
[InlineData(RoleCodes.Reports, false)]
public async Task TestAddUserToRoleThrowsExceptionWhenUserNotFound(string role, bool add)
{
// Arrange
// Act
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await Controller.AddUserToRole("xxx", role, add));
// Assert
ex.ShouldNotBeNull();
ex.Message.ShouldBe("Sequence contains no matching element");
MockUserManager.Verify(a => a.AddToRoleAsync(It.IsAny<User>(), It.IsAny<string>()), Times.Never);
MockUserManager.Verify(a => a.RemoveFromRoleAsync(It.IsAny<User>(), It.IsAny<string>()), Times.Never);
}
[Theory]
[InlineData(RoleCodes.Admin)]
[InlineData(RoleCodes.LabUser)]
[InlineData(RoleCodes.Reports)]
public async Task TestAddUserToRoleWhenAdd(string role)
{
// Arrange
// Act
var controllerResult = await Controller.AddUserToRole(UserData[1].Id, role, true);
// Assert
var redirectResult = Assert.IsType<RedirectToActionResult>(controllerResult);
redirectResult.ShouldNotBeNull();
redirectResult.ActionName.ShouldBe("EditAdmin");
redirectResult.ControllerName.ShouldBeNull();
redirectResult.RouteValues["id"].ShouldBe(UserData[1].Id);
MockUserManager.Verify(a => a.AddToRoleAsync(UserData[1], role), Times.Once);
MockUserManager.Verify(a => a.RemoveFromRoleAsync(It.IsAny<User>(), It.IsAny<string>()), Times.Never);
Controller.ErrorMessage.ShouldBeNull();
}
[Theory]
[InlineData(RoleCodes.Admin)]
[InlineData(RoleCodes.LabUser)]
[InlineData(RoleCodes.Reports)]
public async Task TestAddUserToRoleWhenRemoveOwnRole(string role)
{
// Arrange
//UserData[3] is configured above to be the CurrentUser
// Act
var controllerResult = await Controller.AddUserToRole(UserData[3].Id, role, false);
// Assert
var redirectResult = Assert.IsType<RedirectToActionResult>(controllerResult);
redirectResult.ShouldNotBeNull();
redirectResult.ActionName.ShouldBe("Index");
redirectResult.ControllerName.ShouldBeNull();
Controller.ErrorMessage.ShouldBe("Can't remove your own permissions.");
MockUserManager.Verify(a => a.AddToRoleAsync(It.IsAny<User>(), It.IsAny<string>()), Times.Never);
MockUserManager.Verify(a => a.RemoveFromRoleAsync(It.IsAny<User>(), It.IsAny<string>()), Times.Never);
}
[Theory]
[InlineData(RoleCodes.Admin)]
[InlineData(RoleCodes.LabUser)]
[InlineData(RoleCodes.Reports)]
public async Task TestAddUserToRoleWhenRemoveOtherRole(string role)
{
// Arrange
//UserData[3] is configured above to be the CurrentUser
// Act
var controllerResult = await Controller.AddUserToRole(UserData[2].Id, role, false);
// Assert
var redirectResult = Assert.IsType<RedirectToActionResult>(controllerResult);
redirectResult.ShouldNotBeNull();
redirectResult.ActionName.ShouldBe("EditAdmin");
redirectResult.ControllerName.ShouldBeNull();
redirectResult.RouteValues["id"].ShouldBe(UserData[2].Id);
Controller.ErrorMessage.ShouldBeNull();
MockUserManager.Verify(a => a.AddToRoleAsync(It.IsAny<User>(), It.IsAny<string>()), Times.Never);
MockUserManager.Verify(a => a.RemoveFromRoleAsync(UserData[2], role), Times.Once);
}
#endregion AddUserToRole
#region MailQueue
[Fact]
public async Task TestMailQueueReturnsView1()
{
// Arrange
var mail = new List<MailMessage>();
for (int i = 0; i < 10; i++)
{
var mm = CreateValidEntities.MailMessage(i + 1);
mm.Order = CreateValidEntities.Order(i + 1);
mm.User = UserData[i % 2];
mail.Add(mm);
}
MockDbContext.Setup(a => a.MailMessages).Returns(mail.AsQueryable().MockAsyncDbSet().Object);
for (int i = 0; i < 3; i++)
{
mail[i].Order = CreateValidEntities.Order(2);
}
// Act
var controllerResult = await Controller.MailQueue(mail[0].Order.Id);
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<List<MailMessage>>(viewResult.Model);
modelResult.ShouldNotBeNull();
modelResult.Count.ShouldBe(3);
modelResult[0].Id.ShouldBe(1);
modelResult[0].Order.Id.ShouldBe(2);
}
[Fact]
public async Task TestMailQueueReturnsView2()
{
// Arrange
var mail = new List<MailMessage>();
for (int i = 0; i < 10; i++)
{
var mm = CreateValidEntities.MailMessage(i + 1);
mm.Order = CreateValidEntities.Order(i + 1);
mm.User = UserData[i % 2];
mm.Sent = null;
mm.SentAt = DateTime.UtcNow.AddDays(-35);
mail.Add(mm);
}
MockDbContext.Setup(a => a.MailMessages).Returns(mail.AsQueryable().MockAsyncDbSet().Object);
// Act
var controllerResult = await Controller.MailQueue();
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<List<MailMessage>>(viewResult.Model);
modelResult.ShouldNotBeNull();
modelResult.Count.ShouldBe(10);
}
[Fact]
public async Task TestMailQueueReturnsView3()
{
// Arrange
var mail = new List<MailMessage>();
for (int i = 0; i < 10; i++)
{
var mm = CreateValidEntities.MailMessage(i + 1);
mm.Order = CreateValidEntities.Order(i + 1);
mm.User = UserData[i % 2];
mm.Sent = false;
mm.SentAt = DateTime.UtcNow.AddDays(-35);
mail.Add(mm);
}
MockDbContext.Setup(a => a.MailMessages).Returns(mail.AsQueryable().MockAsyncDbSet().Object);
// Act
var controllerResult = await Controller.MailQueue();
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<List<MailMessage>>(viewResult.Model);
modelResult.ShouldNotBeNull();
modelResult.Count.ShouldBe(10);
}
[Fact]
public async Task TestMailQueueReturnsView4()
{
// Arrange
var mail = new List<MailMessage>();
for (int i = 0; i < 10; i++)
{
var mm = CreateValidEntities.MailMessage(i + 1);
mm.Order = CreateValidEntities.Order(i + 1);
mm.User = UserData[i % 2];
mm.Sent = true;
mm.SentAt = DateTime.UtcNow.AddDays(-35);
mail.Add(mm);
}
mail[1].SentAt = DateTime.UtcNow.AddDays(-28);
MockDbContext.Setup(a => a.MailMessages).Returns(mail.AsQueryable().MockAsyncDbSet().Object);
// Act
var controllerResult = await Controller.MailQueue();
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<List<MailMessage>>(viewResult.Model);
modelResult.ShouldNotBeNull();
modelResult.Count.ShouldBe(1);
}
#endregion MailQueue
#region ViewMessage
[Fact]
public async Task TestViewMessageReturnsNotFound()
{
// Arrange
var mail = new List<MailMessage>();
for (int i = 0; i < 5; i++)
{
var mm = CreateValidEntities.MailMessage(i + 1);
mm.Order = CreateValidEntities.Order(i + 1);
mm.User = UserData[i % 2];
mm.Sent = null;
mm.SentAt = DateTime.UtcNow.AddDays(-35);
mail.Add(mm);
}
MockDbContext.Setup(a => a.MailMessages).Returns(mail.AsQueryable().MockAsyncDbSet().Object);
// Act
var controllerResult = await Controller.ViewMessage(9);
// Assert
Assert.IsType<NotFoundResult>(controllerResult);
}
[Fact]
public async Task TestViewMessageReturnsView()
{
// Arrange
var mail = new List<MailMessage>();
for (int i = 0; i < 5; i++)
{
var mm = CreateValidEntities.MailMessage(i + 1);
mm.Order = CreateValidEntities.Order(i + 1);
mm.User = UserData[i % 2];
mm.Sent = null;
mm.SentAt = DateTime.UtcNow.AddDays(-35);
mail.Add(mm);
}
MockDbContext.Setup(a => a.MailMessages).Returns(mail.AsQueryable().MockAsyncDbSet().Object);
// Act
var controllerResult = await Controller.ViewMessage(3);
// Assert
var viewResult = Assert.IsType<ViewResult>(controllerResult);
var modelResult = Assert.IsType<MailMessage>(viewResult.Model);
modelResult.ShouldNotBeNull();
modelResult.Id.ShouldBe(3);
}
#endregion ViewMessage
}
[Trait("Category", "Controller Reflection")]
public class AdminControllerReflectionTests
{
private readonly ITestOutputHelper output;
public ControllerReflection ControllerReflection;
public AdminControllerReflectionTests(ITestOutputHelper output)
{
this.output = output;
ControllerReflection = new ControllerReflection(this.output, typeof(AdminController));
}
[Fact]
public void TestControllerClassAttributes()
{
ControllerReflection.ControllerInherits("ApplicationController");
var authAttribute = ControllerReflection.ClassExpectedAttribute<AuthorizeAttribute>(3);
authAttribute.ElementAt(0).Roles.ShouldBe($"{RoleCodes.Admin},{RoleCodes.LabUser}");
ControllerReflection.ClassExpectedAttribute<AutoValidateAntiforgeryTokenAttribute>(3);
ControllerReflection.ClassExpectedAttribute<ControllerAttribute>(3);
}
[Fact]
public void TestControllerMethodCount()
{
ControllerReflection.ControllerPublicMethods(11);
}
[Fact]
public void TestControllerMethodAttributes()
{
#if DEBUG
var countAdjustment = 1;
#else
var countAdjustment = 0;
#endif
//1
var indexAuth = ControllerReflection.MethodExpectedAttribute<AuthorizeAttribute>("Index", 2 + countAdjustment, "Index-1", false, showListOfAttributes: false);
indexAuth.ElementAt(0).Roles.ShouldBe(RoleCodes.Admin);
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("Index", 2 + countAdjustment, "Index-1", false, showListOfAttributes: false);
//2
var searchAdminUserAuth = ControllerReflection.MethodExpectedAttribute<AuthorizeAttribute>("SearchAdminUser", 3 + countAdjustment, "SearchAdminUser-1", false, showListOfAttributes: false);
searchAdminUserAuth.ElementAt(0).Roles.ShouldBe(RoleCodes.Admin);
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("SearchAdminUser", 3 + countAdjustment, "SearchAdminUser-2", false, showListOfAttributes: false);
ControllerReflection.MethodExpectedAttribute<HttpGetAttribute>("SearchAdminUser", 3 + countAdjustment, "SearchAdminUser-3", false, showListOfAttributes: false);
//3
var editAdminAminUserAuth = ControllerReflection.MethodExpectedAttribute<AuthorizeAttribute>("EditAdmin", 3 + countAdjustment, "EditAdmin-1", false, showListOfAttributes: false);
editAdminAminUserAuth.ElementAt(0).Roles.ShouldBe(RoleCodes.Admin);
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("SearchAdminUser", 3 + countAdjustment, "EditAdmin-2", false, showListOfAttributes: false);
ControllerReflection.MethodExpectedAttribute<HttpGetAttribute>("EditAdmin", 3 + countAdjustment, "EditAdmin-3", false, showListOfAttributes: false);
//4
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("ListClients", 1 + countAdjustment, "ListClients-1", false, showListOfAttributes: false);
//5 & 6
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("EditUser", 1 + countAdjustment, "EditUserGet-1", false, showListOfAttributes: false);
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("EditUser", 2 + countAdjustment, "EditUserPost-1", true, showListOfAttributes: false);
ControllerReflection.MethodExpectedAttribute<HttpPostAttribute>("EditUser", 2 + countAdjustment, "EditUserPost-2", true, showListOfAttributes: false);
//7
var addUserToRoleAuth = ControllerReflection.MethodExpectedAttribute<AuthorizeAttribute>("AddUserToRole", 3 + countAdjustment, "AddUserToRole-1", false, showListOfAttributes: false);
addUserToRoleAuth.ElementAt(0).Roles.ShouldBe(RoleCodes.Admin);
ControllerReflection.MethodExpectedAttribute<HttpPostAttribute>("AddUserToRole", 3 + countAdjustment, "AddUserToRole-2", false, showListOfAttributes: false);
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("AddUserToRole", 3 + countAdjustment, "AddUserToRole-3", false, showListOfAttributes: false);
//8
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("MailQueue", 1 + countAdjustment, "MailQueue-1", false, showListOfAttributes: false);
//9
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("ViewMessage", 1 + countAdjustment, "ViewMessage-1", false, showListOfAttributes: false);
//10 & 11
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("FixEmail", 3 + countAdjustment, "FixEmailGet-1", false, showListOfAttributes: false);
ControllerReflection.MethodExpectedAttribute<HttpGetAttribute>("FixEmail", 3 + countAdjustment, "FixEmailGet-2", false, showListOfAttributes: false);
var fixEmailUserAuth = ControllerReflection.MethodExpectedAttribute<AuthorizeAttribute>("FixEmail", 3 + countAdjustment, "FixEmail-1", false, showListOfAttributes: false);
fixEmailUserAuth.ElementAt(0).Roles.ShouldBe(RoleCodes.Admin);
ControllerReflection.MethodExpectedAttribute<AsyncStateMachineAttribute>("FixEmail", 3 + countAdjustment, "FixEmailPost-1", true, showListOfAttributes: false);
ControllerReflection.MethodExpectedAttribute<HttpPostAttribute>("FixEmail", 3 + countAdjustment, "FixEmailPost-2", true, showListOfAttributes: false);
var fixEmailUserAuthPost = ControllerReflection.MethodExpectedAttribute<AuthorizeAttribute>("FixEmail", 3 + countAdjustment, "FixEmail-1", true, showListOfAttributes: false);
fixEmailUserAuthPost.ElementAt(0).Roles.ShouldBe(RoleCodes.Admin);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview
{
public class PreviewWorkspaceTests
{
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationDefault()
{
using (var previewWorkspace = new PreviewWorkspace())
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationWithExplicitHostServices()
{
var assembly = typeof(ISolutionCrawlerRegistrationService).Assembly;
using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly))))
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationWithSolution()
{
using (var custom = new AdhocWorkspace())
using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution))
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewAddRemoveProject()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
Assert.True(previewWorkspace.TryApplyChanges(project.Solution));
var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id);
Assert.True(previewWorkspace.TryApplyChanges(newSolution));
Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewProjectChanges()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
Assert.True(previewWorkspace.TryApplyChanges(project.Solution));
var addedSolution = previewWorkspace.CurrentSolution.Projects.First()
.AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib)
.AddDocument("document", "").Project.Solution;
Assert.True(previewWorkspace.TryApplyChanges(addedSolution));
Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count);
Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count);
var text = "class C {}";
var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution;
Assert.True(previewWorkspace.TryApplyChanges(changedSolution));
Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text);
var removedSolution = previewWorkspace.CurrentSolution.Projects.First()
.RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0])
.RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution;
Assert.True(previewWorkspace.TryApplyChanges(removedSolution));
Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count);
Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count);
}
}
[WorkItem(923121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923121")]
[WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewOpenCloseFile()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
var document = project.AddDocument("document", "");
Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution));
previewWorkspace.OpenDocument(document.Id);
Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count());
Assert.True(previewWorkspace.IsDocumentOpen(document.Id));
previewWorkspace.CloseDocument(document.Id);
Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count());
Assert.False(previewWorkspace.IsDocumentOpen(document.Id));
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewServices()
{
using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider())))
{
var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>();
Assert.True(service is PreviewSolutionCrawlerRegistrationService);
var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>();
Assert.NotNull(persistentService);
var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution);
Assert.True(storage is NoOpPersistentStorage);
}
}
[WorkItem(923196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923196")]
[WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewDiagnostic()
{
var diagnosticService = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource;
var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>();
diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a);
using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider())))
{
var solution = previewWorkspace.CurrentSolution
.AddProject("project", "project.dll", LanguageNames.CSharp)
.AddDocument("document", "class { }")
.Project
.Solution;
Assert.True(previewWorkspace.TryApplyChanges(solution));
previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]);
previewWorkspace.EnableDiagnostic();
// wait 20 seconds
taskSource.Task.Wait(20000);
if (!taskSource.Task.IsCompleted)
{
// something is wrong
FatalError.Report(new System.Exception("not finished after 20 seconds"));
}
var args = taskSource.Task.Result;
Assert.True(args.Diagnostics.Length > 0);
}
}
[WpfFact]
public async Task TestPreviewDiagnosticTagger()
{
using (var workspace = await TestWorkspace.CreateCSharpAsync("class { }"))
using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution))
{
//// preview workspace and owner of the solution now share solution and its underlying text buffer
var hostDocument = workspace.Projects.First().Documents.First();
//// enable preview diagnostics
previewWorkspace.EnableDiagnostic();
var diagnosticsAndErrorsSpans = await SquiggleUtilities.GetDiagnosticsAndErrorSpans(workspace);
const string AnalzyerCount = "Analyzer Count: ";
Assert.Equal(AnalzyerCount + 1, AnalzyerCount + diagnosticsAndErrorsSpans.Item1.Length);
const string SquigglesCount = "Squiggles Count: ";
Assert.Equal(SquigglesCount + 1, SquigglesCount + diagnosticsAndErrorsSpans.Item2.Count);
}
}
[WpfFact]
public async Task TestPreviewDiagnosticTaggerInPreviewPane()
{
using (var workspace = await TestWorkspace.CreateCSharpAsync("class { }"))
{
// set up listener to wait until diagnostic finish running
var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService;
// no easy way to setup waiter. kind of hacky way to setup waiter
var source = new CancellationTokenSource();
var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>();
diagnosticService.DiagnosticsUpdated += (s, a) =>
{
source.Cancel();
source = new CancellationTokenSource();
var cancellationToken = source.Token;
Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current);
};
var hostDocument = workspace.Projects.First().Documents.First();
// make a change to remove squiggle
var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id);
var oldText = oldDocument.GetTextAsync().Result;
var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }")));
// create a diff view
WpfTestCase.RequireWpfFact($"{nameof(TestPreviewDiagnosticTaggerInPreviewPane)} creates a {nameof(IWpfDifferenceViewer)}");
var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>();
var diffView = (IWpfDifferenceViewer)(await previewFactoryService.CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, CancellationToken.None));
var foregroundService = workspace.GetService<IForegroundNotificationService>();
var optionsService = workspace.Services.GetService<IOptionService>();
var waiter = new ErrorSquiggleWaiter();
var listeners = AsynchronousOperationListener.CreateListeners(FeatureAttribute.ErrorSquiggles, waiter);
// set up tagger for both buffers
var leftBuffer = diffView.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First();
var leftProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners);
var leftTagger = leftProvider.CreateTagger<IErrorTag>(leftBuffer);
using (var leftDisposable = leftTagger as IDisposable)
{
var rightBuffer = diffView.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First();
var rightProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners);
var rightTagger = rightProvider.CreateTagger<IErrorTag>(rightBuffer);
using (var rightDisposable = rightTagger as IDisposable)
{
// wait up to 20 seconds for diagnostics
taskSource.Task.Wait(20000);
if (!taskSource.Task.IsCompleted)
{
// something is wrong
FatalError.Report(new System.Exception("not finished after 20 seconds"));
}
// wait taggers
await waiter.CreateWaitTask();
// check left buffer
var leftSnapshot = leftBuffer.CurrentSnapshot;
var leftSpans = leftTagger.GetTags(leftSnapshot.GetSnapshotSpanCollection()).ToList();
Assert.Equal(1, leftSpans.Count);
// check right buffer
var rightSnapshot = rightBuffer.CurrentSnapshot;
var rightSpans = rightTagger.GetTags(rightSnapshot.GetSnapshotSpanCollection()).ToList();
Assert.Equal(0, rightSpans.Count);
}
}
}
}
private class ErrorSquiggleWaiter : AsynchronousOperationListener { }
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Unadus.Audio.Data;
using Unadus.Core.Extensions;
using Unadus.Core.Objects;
using Unadus.Core.Services;
using Unadus.Data;
namespace Unadus.Audio
{
public sealed class AudioService : UnadusServiceBase, IShutdownable
{
private readonly ConcurrentDictionary<ulong, AudioPlayer> _audioInstances;
private readonly ConcurrentDictionary<ulong, IMessageChannel> _notificationChannel;
private readonly ConcurrentDictionary<ulong, IUserMessage> _lastNotification;
public AudioService(DiscordSocketClient client, LoggingService logging, LocalizationService localizationService)
: base(client, logging, localizationService)
{
this._audioInstances = new ConcurrentDictionary<ulong, AudioPlayer>();
this._notificationChannel = new ConcurrentDictionary<ulong, IMessageChannel>();
this._lastNotification = new ConcurrentDictionary<ulong, IUserMessage>();
}
public bool TryGetAudioInstance(IGuild guild, out AudioPlayer player)
{
player = _audioInstances.FirstOrDefault(x => x.Key == guild.Id).Value;
return player != null;
}
public bool TryCreateAudioInstance(IGuild guild, decimal volume, IVoiceChannel channel, IMessageChannel notificationChannel)
{
if (_audioInstances.ContainsKey(guild.Id))
return false;
if (volume > 1)
volume = volume / 100;
var audioInstance = new AudioPlayer(guild, channel, volume);
_audioInstances.TryAdd(guild.Id, audioInstance);
_notificationChannel.TryAdd(guild.Id, notificationChannel);
audioInstance.Log += HandleLogAsync;
audioInstance.LogException += LoggingService.LogAudioExceptionAsync;
audioInstance.Exited += HandleInstanceExitedAsync;
audioInstance.QueueNext += HandleQueueNextAsync;
audioInstance.Notification += ShowNotificationAsync;
return true;
}
public void SetNotificationChannel(IGuild guild, IMessageChannel channel)
{
if (!_notificationChannel.TryGetValue(guild.Id, out _))
return;
_notificationChannel.AddOrUpdate(guild.Id, channel, (g, m) => channel);
}
public bool TryDestroyAudioInstance(IGuild guild)
{
if (!_audioInstances.TryRemove(guild.Id, out AudioPlayer instance))
return false;
instance.Dispose();
return true;
}
public Task QuitAsync()
{
foreach (var guildId in this._audioInstances.Select(x => x.Key).ToList())
{
if (_audioInstances.TryRemove(guildId, out AudioPlayer instance))
instance.Dispose();
}
return Task.CompletedTask;
}
private async Task HandleLogAsync(IGuild guild, Severity logSeverity, string localizationKey)
{
Localization loc = null;
using (var context = new GuildConfigurationContext(guild.Id))
{
loc = await LocalizationService.GetLocalizationAsync(context.Culture);
}
await LoggingService.LogAudioAsync(guild, logSeverity, loc.GetLocalizedString(localizationKey));
}
private async Task HandleInstanceExitedAsync(IGuild guild, AudioPlayer instance)
{
_audioInstances.TryRemove(guild.Id, out _);
instance.Exited -= HandleInstanceExitedAsync;
instance.Log -= HandleLogAsync;
instance.LogException -= LoggingService.LogAudioExceptionAsync;
instance.QueueNext -= HandleQueueNextAsync;
instance.Notification -= ShowNotificationAsync;
if (!_lastNotification.TryRemove(guild.Id, out IUserMessage notification))
return;
try
{
await notification.DeleteAsync();
}
catch {}
}
private async Task ShowNotificationAsync(ISongInfo song, IGuild guild)
{
if (!_notificationChannel.TryGetValue(guild.Id, out IMessageChannel channel)) return;
var notifEmbed = await CreateNotificationEmbedAsync(song, guild);
if (!_lastNotification.TryGetValue(guild.Id, out IUserMessage oldMessage))
{
var message = await channel.SendMessageAsync("", embed: notifEmbed);
_lastNotification.AddOrUpdate(guild.Id, message, (key, old) => message);
return;
}
if (oldMessage.Channel.Id != channel.Id)
{
try
{
await oldMessage.DeleteAsync();
}
catch {}
var message = await channel.SendMessageAsync("", embed: notifEmbed);
_lastNotification.AddOrUpdate(guild.Id, message, (key, old) => message);
return;
}
var messagesAfter = await channel.GetMessagesAsync(oldMessage, Direction.After, 6).Flatten();
if (messagesAfter.Count() >= 5)
{
try
{
await oldMessage.DeleteAsync();
}
catch{}
var message = await channel.SendMessageAsync("", embed: notifEmbed);
_lastNotification.AddOrUpdate(guild.Id, message, (key, old) => message);
return;
}
try
{
await oldMessage.ModifyAsync(x => x.Embed = notifEmbed);
}
catch
{
var message = await channel.SendMessageAsync("", embed: notifEmbed);
_lastNotification.AddOrUpdate(guild.Id, message, (key, old) => message);
}
}
private async Task<Embed> CreateNotificationEmbedAsync(ISongInfo info, IGuild guild)
{
Color embedColor = Color.Default;
Localization localization = null;
using (var context = new GuildConfigurationContext(guild.Id))
{
embedColor = context.EmbedColor;
localization = await LocalizationService.GetLocalizationAsync(context.Culture);
}
EmbedBuilder embed = new EmbedBuilder();
embed.Color = embedColor;
embed.Title = localization.GetLocalizedString("audio.notification.nowPlaying");
embed.Description = $"[{Format.Sanitize(info.Title)}]({info.Url})";
embed.ThumbnailUrl = info.ThumbnailUrl;
embed.Footer = new EmbedFooterBuilder().WithText($"{localization.GetLocalizedString("audio.by")} {info.User.Username} | {info.Duration.ToProperTime()}");
return embed.Build();
}
private async Task<Song> HandleQueueNextAsync(IGuild guild)
{
Localization localization = null;
using (var context = new GuildConfigurationContext(guild.Id))
{
localization = await LocalizationService.GetLocalizationAsync(context.Culture);
}
using (var context = new AutoplaylistContext(guild.Id))
{
context.Database.EnsureCreated();
var songModel = context.Playlists.Where(x => x.IsSelected)?.SelectMany(x => x.Songs)?.Random();
if (songModel is null) return null;
var res = await Song.TryCreateSongAsync(songModel.Url, Client.CurrentUser, (ulong)DateTimeOffset.Now.Ticks, localization);
if (!res.Success)
songModel.TryRemove();
return res.Song;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Nancy.Helpers;
namespace Nancy.ViewEngines.Razor
{
public class TagBuilder
{
private static string _idAttributeDotReplacement;
private string _innerHtml;
public static string IdAttributeDotReplacement
{
get
{
if (String.IsNullOrEmpty(_idAttributeDotReplacement))
{
_idAttributeDotReplacement = "_";
}
return _idAttributeDotReplacement;
}
set { _idAttributeDotReplacement = value; }
}
public TagBuilder(string tagName)
{
if (String.IsNullOrEmpty(tagName))
{
throw new ArgumentException("Argument_Cannot_Be_Null_Or_Empty", "tagName");
}
TagName = tagName;
Attributes = new SortedDictionary<string, string>(StringComparer.Ordinal);
}
public IDictionary<string, string> Attributes { get; private set; }
public string InnerHtml
{
get { return _innerHtml ?? String.Empty; }
set { _innerHtml = value; }
}
public string TagName { get; private set; }
public void AddCssClass(string value)
{
string currentValue;
if (Attributes.TryGetValue("class", out currentValue))
{
Attributes["class"] = value + " " + currentValue;
}
else
{
Attributes["class"] = value;
}
}
public static string CreateSanitizedId(string originalId)
{
return CreateSanitizedId(originalId, IdAttributeDotReplacement);
}
public static string CreateSanitizedId(string originalId, string invalidCharReplacement)
{
if (String.IsNullOrEmpty(originalId))
{
return null;
}
if (invalidCharReplacement == null)
{
throw new ArgumentNullException("invalidCharReplacement");
}
char firstChar = originalId[0];
if (!Html401IdUtil.IsLetter(firstChar))
{
// the first character must be a letter
return null;
}
var sb = new StringBuilder(originalId.Length);
sb.Append(firstChar);
for (var i = 1; i < originalId.Length; i++)
{
var thisChar = originalId[i];
if (Html401IdUtil.IsValidIdCharacter(thisChar))
{
sb.Append(thisChar);
}
else
{
sb.Append(invalidCharReplacement);
}
}
return sb.ToString();
}
public void GenerateId(string name)
{
if (Attributes.ContainsKey("id"))
{
return;
}
var sanitizedId = CreateSanitizedId(name, IdAttributeDotReplacement);
if (String.IsNullOrEmpty(sanitizedId))
{
return;
}
Attributes["id"] = sanitizedId;
}
private void AppendAttributes(StringBuilder sb)
{
foreach (var attribute in Attributes)
{
var key = attribute.Key;
if (String.Equals(key, "id", StringComparison.Ordinal /* case-sensitive */) && String.IsNullOrEmpty(attribute.Value))
{
continue; // DevDiv Bugs #227595: don't output empty IDs
}
var value = HttpUtility.HtmlAttributeEncode(attribute.Value);
sb.Append(' ').Append(key).Append("=\"").Append(value).Append('"');
}
}
public void MergeAttribute(string key, string value)
{
MergeAttribute(key, value, false);
}
public void MergeAttribute(string key, string value, bool replaceExisting)
{
if (String.IsNullOrEmpty(key))
{
throw new ArgumentException("Argument_Cannot_Be_Null_Or_Empty", "key");
}
if (replaceExisting || !Attributes.ContainsKey(key))
{
Attributes[key] = value;
}
}
public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes)
{
MergeAttributes(attributes, false);
}
public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes, bool replaceExisting)
{
if (attributes == null) return;
foreach (var entry in attributes)
{
var key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
var value = Convert.ToString(entry.Value, CultureInfo.InvariantCulture);
MergeAttribute(key, value, replaceExisting);
}
}
public void SetInnerText(string innerText)
{
InnerHtml = HttpUtility.HtmlEncode(innerText);
}
internal HtmlString ToHtmlString(TagRenderMode renderMode)
{
return new HtmlString(ToString(renderMode));
}
public override string ToString()
{
return ToString(TagRenderMode.Normal);
}
public string ToString(TagRenderMode renderMode)
{
var sb = new StringBuilder();
switch (renderMode)
{
case TagRenderMode.StartTag:
sb.Append('<')
.Append(TagName);
AppendAttributes(sb);
sb.Append('>');
break;
case TagRenderMode.EndTag:
sb.Append("</")
.Append(TagName)
.Append('>');
break;
case TagRenderMode.SelfClosing:
sb.Append('<')
.Append(TagName);
AppendAttributes(sb);
sb.Append(" />");
break;
default:
sb.Append('<')
.Append(TagName);
AppendAttributes(sb);
sb.Append('>')
.Append(InnerHtml)
.Append("</")
.Append(TagName)
.Append('>');
break;
}
return sb.ToString();
}
// Valid IDs are defined in http://www.w3.org/TR/html401/types.html#type-id
private static class Html401IdUtil
{
private static bool IsAllowableSpecialCharacter(char c)
{
switch (c)
{
case '-':
case '_':
case ':':
// note that we're specifically excluding the '.' character
return true;
default:
return false;
}
}
private static bool IsDigit(char c)
{
return ('0' <= c && c <= '9');
}
public static bool IsLetter(char c)
{
return (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'));
}
public static bool IsValidIdCharacter(char c)
{
return (IsLetter(c) || IsDigit(c) || IsAllowableSpecialCharacter(c));
}
}
}
public enum TagRenderMode
{
Normal,
StartTag,
EndTag,
SelfClosing,
}
}
| |
/*
* 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 OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System.Text;
using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags;
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsModule")]
public class GroupsModule : ISharedRegionModule, IGroupsModule
{
/// <summary>
/// ; To use this module, you must specify the following in your OpenSim.ini
/// [GROUPS]
/// Enabled = true
///
/// Module = GroupsModule
/// NoticesEnabled = true
/// DebugEnabled = true
///
/// GroupsServicesConnectorModule = XmlRpcGroupsServicesConnector
/// XmlRpcServiceURL = http://osflotsam.org/xmlrpc.php
/// XmlRpcServiceReadKey = 1234
/// XmlRpcServiceWriteKey = 1234
///
/// MessagingModule = GroupsMessagingModule
/// MessagingEnabled = true
///
/// ; Disables HTTP Keep-Alive for Groups Module HTTP Requests, work around for
/// ; a problem discovered on some Windows based region servers. Only disable
/// ; if you see a large number (dozens) of the following Exceptions:
/// ; System.Net.WebException: The request was aborted: The request was canceled.
///
/// XmlRpcDisableKeepAlive = false
/// </summary>
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_sceneList = new List<Scene>();
private IMessageTransferModule m_msgTransferModule;
private IGroupsMessagingModule m_groupsMessagingModule;
private IGroupsServicesConnector m_groupData;
// Configuration settings
private bool m_groupsEnabled = false;
private bool m_groupNoticesEnabled = true;
private bool m_debugEnabled = false;
private int m_levelGroupCreate = 0;
#region Region Module interfaceBase Members
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
m_groupsEnabled = groupsConfig.GetBoolean("Enabled", false);
if (!m_groupsEnabled)
{
return;
}
if (groupsConfig.GetString("Module", "Default") != Name)
{
m_groupsEnabled = false;
return;
}
m_log.InfoFormat("[GROUPS]: Initializing {0}", this.Name);
m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true);
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false);
m_levelGroupCreate = groupsConfig.GetInt("LevelGroupCreate", 0);
}
}
public void AddRegion(Scene scene)
{
if (m_groupsEnabled)
{
scene.RegisterModuleInterface<IGroupsModule>(this);
scene.AddCommand(
"Debug",
this,
"debug groups verbose",
"debug groups verbose <true|false>",
"This setting turns on very verbose groups debugging",
HandleDebugGroupsVerbose);
}
}
private void HandleDebugGroupsVerbose(object modules, string[] args)
{
if (args.Length < 4)
{
MainConsole.Instance.Output("Usage: debug groups verbose <true|false>");
return;
}
bool verbose = false;
if (!bool.TryParse(args[3], out verbose))
{
MainConsole.Instance.Output("Usage: debug groups verbose <true|false>");
return;
}
m_debugEnabled = verbose;
MainConsole.Instance.OutputFormat("{0} verbose logging set to {1}", Name, m_debugEnabled);
}
public void RegionLoaded(Scene scene)
{
if (!m_groupsEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
if (m_groupData == null)
{
m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>();
// No Groups Service Connector, then nothing works...
if (m_groupData == null)
{
m_groupsEnabled = false;
m_log.Error("[GROUPS]: Could not get IGroupsServicesConnector");
Close();
return;
}
}
if (m_msgTransferModule == null)
{
m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
// No message transfer module, no notices, group invites, rejects, ejects, etc
if (m_msgTransferModule == null)
{
m_groupsEnabled = false;
m_log.Warn("[GROUPS]: Could not get IMessageTransferModule");
}
}
if (m_groupsMessagingModule == null)
{
m_groupsMessagingModule = scene.RequestModuleInterface<IGroupsMessagingModule>();
// No message transfer module, no notices, group invites, rejects, ejects, etc
if (m_groupsMessagingModule == null)
m_log.Warn("[GROUPS]: Could not get IGroupsMessagingModule");
}
lock (m_sceneList)
{
m_sceneList.Add(scene);
}
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnMakeRootAgent += OnMakeRoot;
scene.EventManager.OnMakeChildAgent += OnMakeChild;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
scene.EventManager.OnClientClosed += OnClientClosed;
}
public void RemoveRegion(Scene scene)
{
if (!m_groupsEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnMakeRootAgent -= OnMakeRoot;
scene.EventManager.OnMakeChildAgent -= OnMakeChild;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
scene.EventManager.OnClientClosed -= OnClientClosed;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
lock (m_sceneList)
{
m_sceneList.Remove(scene);
}
}
public void Close()
{
if (!m_groupsEnabled)
return;
if (m_debugEnabled) m_log.Debug("[GROUPS]: Shutting down Groups module.");
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "GroupsModule"; }
}
#endregion
#region ISharedRegionModule Members
public void PostInitialise()
{
// NoOp
}
#endregion
#region EventHandlers
private void OnMakeRoot(ScenePresence sp)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
sp.ControllingClient.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest;
// Used for Notices and Group Invites/Accept/Reject
sp.ControllingClient.OnInstantMessage += OnInstantMessage;
// comented out because some viewers no longer suport it
// sp.ControllingClient.AddGenericPacketHandler("avatargroupsrequest", AvatarGroupsRequest);
// Send out group data update for compatibility.
// There might be some problem with the thread we're generating this on but not
// doing the update at this time causes problems (Mantis #7920 and #7915)
// TODO: move sending this update to a later time in the rootification of the client.
if(!sp.haveGroupInformation)
SendAgentGroupDataUpdate(sp.ControllingClient, false);
}
private void OnMakeChild(ScenePresence sp)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
sp.ControllingClient.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest;
sp.ControllingClient.OnInstantMessage -= OnInstantMessage;
}
private void OnNewClient(IClientAPI client)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest;
client.OnRequestAvatarProperties += OnRequestAvatarProperties;
}
/* this should be the right message to ask for other avatars groups
private void AvatarGroupsRequest(Object sender, string method, List<String> args)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID avatarID;
UUID.TryParse(args[0], out avatarID);
if (avatarID != UUID.Zero)
{
GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID);
remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups);
}
}
*/
// this should not be used to send groups memberships, but some viewers do expect it
// it does send unnecessary memberships, when viewers just want other properties information
private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID);
remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups);
}
private void OnClientClosed(UUID AgentId, Scene scene)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
if (scene == null)
return;
ScenePresence sp = scene.GetScenePresence(AgentId);
IClientAPI client = sp.ControllingClient;
if (client != null)
{
client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest;
client.OnRequestAvatarProperties -= OnRequestAvatarProperties;
// make child possible not called?
client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest;
client.OnInstantMessage -= OnInstantMessage;
}
/*
lock (m_ActiveClients)
{
if (m_ActiveClients.ContainsKey(AgentId))
{
IClientAPI client = m_ActiveClients[AgentId];
client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest;
client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest;
client.OnDirFindQuery -= OnDirFindQuery;
client.OnInstantMessage -= OnInstantMessage;
m_ActiveClients.Remove(AgentId);
}
else
{
if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Client closed that wasn't registered here.");
}
}
*/
}
private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID dataForAgentID, UUID sessionID)
{
// this a private message for own agent only
if (dataForAgentID != GetRequestingAgentID(remoteClient))
return;
SendAgentGroupDataUpdate(remoteClient, false);
// its a info request not a change, so nothing is sent to others
// they do get the group title with the avatar object update on arrivel to a region
}
private void HandleUUIDGroupNameRequest(UUID GroupID, IClientAPI remoteClient)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
string GroupName;
GroupRecord group = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null);
if (group != null)
{
GroupName = group.GroupName;
}
else
{
GroupName = "Unknown";
}
remoteClient.SendGroupNameReply(GroupID, GroupName);
}
private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
{
if (m_debugEnabled)
m_log.DebugFormat(
"[GROUPS]: {0} called for {1}, message type {2}",
System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name, (InstantMessageDialog)im.dialog);
// Group invitations
if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline))
{
UUID inviteID = new UUID(im.imSessionID);
GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID);
if (inviteInfo == null)
{
if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Received an Invite IM for an invite that does not exist {0}.", inviteID);
return;
}
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Invite is for Agent {0} to Group {1}.", inviteInfo.AgentID, inviteInfo.GroupID);
UUID fromAgentID = new UUID(im.fromAgentID);
if ((inviteInfo != null) && (fromAgentID == inviteInfo.AgentID))
{
// Accept
if (im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received an accept invite notice.");
// and the sessionid is the role
m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID, inviteInfo.RoleID);
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = UUID.Zero.Guid;
msg.fromAgentID = UUID.Zero.Guid;
msg.toAgentID = inviteInfo.AgentID.Guid;
msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.fromAgentName = "Groups";
msg.message = string.Format("You have been added to the group.");
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageBox;
msg.fromGroup = false;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = UUID.Zero.Guid;
msg.binaryBucket = new byte[0];
OutgoingInstantMessage(msg, inviteInfo.AgentID);
IClientAPI inviteeClient = GetActiveRootClient(inviteInfo.AgentID);
if(inviteeClient !=null)
{
SendAgentGroupDataUpdate(inviteeClient,true);
}
m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID);
}
// Reject
if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received a reject invite notice.");
m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID);
}
}
}
// Group notices
if ((im.dialog == (byte)InstantMessageDialog.GroupNotice))
{
if (!m_groupNoticesEnabled)
{
return;
}
UUID GroupID = new UUID(im.toAgentID);
if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null) != null)
{
UUID NoticeID = UUID.Random();
string Subject = im.message.Substring(0, im.message.IndexOf('|'));
string Message = im.message.Substring(Subject.Length + 1);
InventoryItemBase item = null;
bool hasAttachment = false;
UUID itemID = UUID.Zero; //Assignment to quiet compiler
UUID ownerID = UUID.Zero; //Assignment to quiet compiler
byte[] bucket;
if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0)
{
string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket);
binBucket = binBucket.Remove(0, 14).Trim();
OSDMap binBucketOSD = (OSDMap)OSDParser.DeserializeLLSDXml(binBucket);
if (binBucketOSD is OSD)
{
OSDMap binBucketMap = (OSDMap)binBucketOSD;
itemID = binBucketMap["item_id"].AsUUID();
ownerID = binBucketMap["owner_id"].AsUUID();
//Attempt to get the details of the attached item.
//If sender doesn't own the attachment, the item
//variable will be set to null and attachment will
//not be included with the group notice.
Scene scene = (Scene)remoteClient.Scene;
item = scene.InventoryService.GetItem(ownerID, itemID);
if (item != null)
{
//Got item details so include the attachment.
hasAttachment = true;
}
}
else
{
m_log.DebugFormat("[Groups]: Received OSD with unexpected type: {0}", binBucketOSD.GetType());
}
}
if (hasAttachment)
{
//Bucket contains information about attachment.
//
//Byte offset and description of bucket data:
//0: 1 byte indicating if attachment is present
//1: 1 byte indicating the type of attachment
//2: 16 bytes - Group UUID
//18: 16 bytes - UUID of the attachment owner
//34: 16 bytes - UUID of the attachment
//50: variable - Name of the attachment
//??: NUL byte to terminate the attachment name
byte[] name = Encoding.UTF8.GetBytes(item.Name);
bucket = new byte[51 + name.Length];//3 bytes, 3 UUIDs, and name
bucket[0] = 1; //Has attachment flag
bucket[1] = (byte)item.InvType; //Type of Attachment
GroupID.ToBytes(bucket, 2);
ownerID.ToBytes(bucket, 18);
itemID.ToBytes(bucket, 34);
name.CopyTo(bucket, 50);
}
else
{
bucket = new byte[19];
bucket[0] = 0; //Has attachment flag
bucket[1] = 0; //Type of attachment
GroupID.ToBytes(bucket, 2);
bucket[18] = 0; //NUL terminate name of attachment
}
m_groupData.AddGroupNotice(GetRequestingAgentID(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message, bucket);
if (OnNewGroupNotice != null)
{
OnNewGroupNotice(GroupID, NoticeID);
}
if (m_debugEnabled)
{
foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), GroupID))
{
if (m_debugEnabled)
{
UserAccount targetUser
= m_sceneList[0].UserAccountService.GetUserAccount(
remoteClient.Scene.RegionInfo.ScopeID, member.AgentID);
if (targetUser != null)
{
m_log.DebugFormat(
"[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})",
NoticeID, targetUser.FirstName + " " + targetUser.LastName, member.AcceptNotices);
}
else
{
m_log.DebugFormat(
"[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})",
NoticeID, member.AgentID, member.AcceptNotices);
}
}
}
}
GridInstantMessage msg
= CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice);
if (m_groupsMessagingModule != null)
m_groupsMessagingModule.SendMessageToGroup(
msg, GroupID, remoteClient.AgentId, gmd => gmd.AcceptNotices);
}
}
if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryAccepted)
{
//Is bucket large enough to hold UUID of the attachment?
if (im.binaryBucket.Length < 16)
return;
UUID noticeID = new UUID(im.imSessionID);
if (m_debugEnabled)
m_log.DebugFormat("[GROUPS]: Requesting notice {0} for {1}", noticeID, remoteClient.AgentId);
GroupNoticeInfo notice = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), noticeID);
if (notice != null)
{
UUID giver = new UUID(notice.BinaryBucket, 18);
UUID attachmentUUID = new UUID(notice.BinaryBucket, 34);
if (m_debugEnabled)
m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId);
string message;
InventoryItemBase itemCopy = ((Scene)(remoteClient.Scene)).GiveInventoryItem(remoteClient.AgentId,
giver, attachmentUUID, out message);
if (itemCopy == null)
{
remoteClient.SendAgentAlertMessage(message, false);
return;
}
remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0);
}
else
{
if (m_debugEnabled)
m_log.DebugFormat(
"[GROUPS]: Could not find notice {0} for {1} on GroupNoticeInventoryAccepted.",
noticeID, remoteClient.AgentId);
}
}
// Interop, received special 210 code for ejecting a group member
// this only works within the comms servers domain, and won't work hypergrid
// TODO:FIXME: Use a presence server of some kind to find out where the
// client actually is, and try contacting that region directly to notify them,
// or provide the notification via xmlrpc update queue
if ((im.dialog == 210))
{
// This is sent from the region that the ejectee was ejected from
// if it's being delivered here, then the ejectee is here
// so we need to send local updates to the agent.
UUID ejecteeID = new UUID(im.toAgentID);
im.imSessionID = UUID.Zero.Guid;
im.dialog = (byte)InstantMessageDialog.MessageFromAgent;
OutgoingInstantMessage(im, ejecteeID);
IClientAPI ejectee = GetActiveRootClient(ejecteeID);
if (ejectee != null)
{
UUID groupID = new UUID(im.imSessionID);
ejectee.SendAgentDropGroup(groupID);
SendAgentGroupDataUpdate(ejectee,true);
}
}
}
private void OnGridInstantMessage(GridInstantMessage msg)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Trigger the above event handler
OnInstantMessage(null, msg);
// If a message from a group arrives here, it may need to be forwarded to a local client
if (msg.fromGroup == true)
{
switch (msg.dialog)
{
case (byte)InstantMessageDialog.GroupInvitation:
case (byte)InstantMessageDialog.GroupNotice:
UUID toAgentID = new UUID(msg.toAgentID);
IClientAPI localClient = GetActiveRootClient(toAgentID);
if (localClient != null)
{
localClient.SendInstantMessage(msg);
}
break;
}
}
}
#endregion
#region IGroupsModule Members
public event NewGroupNotice OnNewGroupNotice;
public GroupRecord GetGroupRecord(UUID GroupID)
{
return m_groupData.GetGroupRecord(UUID.Zero, GroupID, null);
}
public GroupRecord GetGroupRecord(string name)
{
return m_groupData.GetGroupRecord(UUID.Zero, UUID.Zero, name);
}
public void ActivateGroup(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
UUID agentID = GetRequestingAgentID(remoteClient);
m_groupData.SetAgentActiveGroup(agentID, agentID, groupID);
// llClientView does this
SendAgentGroupDataUpdate(remoteClient, true);
}
/// <summary>
/// Get the Role Titles for an Agent, for a specific group
/// </summary>
public List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
List<GroupTitlesData> titles = new List<GroupTitlesData>();
foreach (GroupRolesData role in agentRoles)
{
GroupTitlesData title = new GroupTitlesData();
title.Name = role.Name;
if (agentMembership != null)
{
title.Selected = agentMembership.ActiveRole == role.RoleID;
}
title.UUID = role.RoleID;
titles.Add(title);
}
return titles;
}
public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled)
m_log.DebugFormat(
"[GROUPS]: GroupMembersRequest called for {0} from client {1}", groupID, remoteClient.Name);
List<GroupMembersData> data = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID);
if (m_debugEnabled)
{
foreach (GroupMembersData member in data)
{
m_log.DebugFormat("[GROUPS]: Member({0}) - IsOwner({1})", member.AgentID, member.IsOwner);
}
}
return data;
}
public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRolesData> data = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID);
return data;
}
public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetRequestingAgentID(remoteClient), groupID);
if (m_debugEnabled)
{
foreach (GroupRoleMembersData member in data)
{
m_log.DebugFormat("[GROUPS]: Member({0}) - Role({1})", member.MemberID, member.RoleID);
}
}
return data;
}
public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupProfileData profile = new GroupProfileData();
GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null);
if (groupInfo != null)
{
profile.AllowPublish = groupInfo.AllowPublish;
profile.Charter = groupInfo.Charter;
profile.FounderID = groupInfo.FounderID;
profile.GroupID = groupID;
profile.GroupMembershipCount = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID).Count;
profile.GroupRolesCount = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID).Count;
profile.InsigniaID = groupInfo.GroupPicture;
profile.MaturePublish = groupInfo.MaturePublish;
profile.MembershipFee = groupInfo.MembershipFee;
profile.Money = 0; // TODO: Get this from the currency server?
profile.Name = groupInfo.GroupName;
profile.OpenEnrollment = groupInfo.OpenEnrollment;
profile.OwnerRole = groupInfo.OwnerRoleID;
profile.ShowInList = groupInfo.ShowInList;
}
GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
if (memberInfo != null)
{
profile.MemberTitle = memberInfo.GroupTitle;
profile.PowersMask = memberInfo.GroupPowers;
}
/*
this should save xmlrpc calls, but seems to return wrong GroupMembershipCount and GroupRolesCount
UUID agent = GetRequestingAgentID(remoteClient);
GroupProfileData profile = m_groupData.GetMemberGroupProfile(agent, groupID, agent);
*/
return profile;
}
public GroupMembershipData[] GetMembershipData(UUID agentID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
return m_groupData.GetAgentGroupMemberships(UUID.Zero, agentID).ToArray();
}
public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID)
{
if (m_debugEnabled)
m_log.DebugFormat(
"[GROUPS]: {0} called with groupID={1}, agentID={2}",
System.Reflection.MethodBase.GetCurrentMethod().Name, groupID, agentID);
return m_groupData.GetAgentGroupMembership(UUID.Zero, agentID, groupID);
}
public GroupMembershipData GetActiveMembershipData(UUID agentID)
{
return m_groupData.GetAgentActiveMembership(agentID, agentID);
}
public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Note: Permissions checking for modification rights is handled by the Groups Server/Service
m_groupData.UpdateGroup(GetRequestingAgentID(remoteClient), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish);
}
public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile)
{
// Note: Permissions checking for modification rights is handled by the Groups Server/Service
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.SetAgentGroupInfo(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, acceptNotices, listInProfile);
}
public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupRecord groupRecord = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), UUID.Zero, name);
if (groupRecord != null)
{
remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists.");
return UUID.Zero;
}
// check user level
ScenePresence avatar = null;
Scene scene = (Scene)remoteClient.Scene;
scene.TryGetScenePresence(remoteClient.AgentId, out avatar);
if (avatar != null)
{
if (avatar.GodController.UserLevel < m_levelGroupCreate)
{
remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have insufficient permissions to create a group.");
return UUID.Zero;
}
}
// check funds
// is there a money module present ?
IMoneyModule money = scene.RequestModuleInterface<IMoneyModule>();
if (money != null && money.GroupCreationCharge > 0)
{
// do the transaction, that is if the agent has sufficient funds
if (!money.AmountCovered(remoteClient.AgentId, money.GroupCreationCharge)) {
remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have insufficient funds to create a group.");
return UUID.Zero;
}
money.ApplyCharge(GetRequestingAgentID(remoteClient), money.GroupCreationCharge, MoneyTransactionType.GroupCreate, name);
}
UUID groupID = m_groupData.CreateGroup(GetRequestingAgentID(remoteClient), name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, GetRequestingAgentID(remoteClient));
remoteClient.SendCreateGroupReply(groupID, true, "Group created successfully");
// Update the founder with new group information.
SendAgentGroupDataUpdate(remoteClient, false);
return groupID;
}
public GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// ToDo: check if agent is a member of group and is allowed to see notices?
return m_groupData.GetGroupNotices(GetRequestingAgentID(remoteClient), groupID).ToArray();
}
/// <summary>
/// Get the title of the agent's current role.
/// </summary>
public string GetGroupTitle(UUID avatarID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupMembershipData membership = m_groupData.GetAgentActiveMembership(UUID.Zero, avatarID);
if (membership != null)
{
return membership.GroupTitle;
}
return string.Empty;
}
/// <summary>
/// Change the current Active Group Role for Agent
/// </summary>
public void GroupTitleUpdate(IClientAPI remoteClient, UUID groupID, UUID titleRoleID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.SetAgentActiveGroupRole(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, titleRoleID);
// TODO: Not sure what all is needed here, but if the active group role change is for the group
// the client currently has set active, then we need to do a scene presence update too
// if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID)
SendDataUpdate(remoteClient, true);
}
public void GroupRoleUpdate(IClientAPI remoteClient, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, byte updateType)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Security Checks are handled in the Groups Service.
switch ((OpenMetaverse.GroupRoleUpdate)updateType)
{
case OpenMetaverse.GroupRoleUpdate.Create:
m_groupData.AddGroupRole(GetRequestingAgentID(remoteClient), groupID, UUID.Random(), name, description, title, powers);
break;
case OpenMetaverse.GroupRoleUpdate.Delete:
m_groupData.RemoveGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID);
break;
case OpenMetaverse.GroupRoleUpdate.UpdateAll:
case OpenMetaverse.GroupRoleUpdate.UpdateData:
case OpenMetaverse.GroupRoleUpdate.UpdatePowers:
if (m_debugEnabled)
{
GroupPowers gp = (GroupPowers)powers;
m_log.DebugFormat("[GROUPS]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString());
}
m_groupData.UpdateGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID, name, description, title, powers);
break;
case OpenMetaverse.GroupRoleUpdate.NoUpdate:
default:
// No Op
break;
}
// TODO: This update really should send out updates for everyone in the role that just got changed.
SendAgentGroupDataUpdate(remoteClient, false);
}
public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Todo: Security check
switch (changes)
{
case 0:
// Add
m_groupData.AddAgentToGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID);
break;
case 1:
// Remove
m_groupData.RemoveAgentFromGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID);
break;
default:
m_log.ErrorFormat("[GROUPS]: {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes);
break;
}
// TODO: This update really should send out updates for everyone in the role that just got changed.
SendAgentGroupDataUpdate(remoteClient, false);
}
public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupNoticeInfo data = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), groupNoticeID);
if (data != null)
{
GridInstantMessage msg = CreateGroupNoticeIM(remoteClient.AgentId, groupNoticeID, (byte)InstantMessageDialog.GroupNoticeRequested);
OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient));
}
}
public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID, byte dialog)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GridInstantMessage msg = new GridInstantMessage();
byte[] bucket;
msg.imSessionID = groupNoticeID.Guid;
msg.toAgentID = agentID.Guid;
msg.dialog = dialog;
msg.fromGroup = true;
msg.offline = (byte)1; // Allow this message to be stored for offline use
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = UUID.Zero.Guid;
GroupNoticeInfo info = m_groupData.GetGroupNotice(agentID, groupNoticeID);
if (info != null)
{
msg.fromAgentID = info.GroupID.Guid;
msg.timestamp = info.noticeData.Timestamp;
msg.fromAgentName = info.noticeData.FromName;
msg.message = info.noticeData.Subject + "|" + info.Message;
if (info.BinaryBucket[0] > 0)
{
//32 is due to not needing space for two of the UUIDs.
//(Don't need UUID of attachment or its owner in IM)
//50 offset gets us to start of attachment name.
//We are skipping the attachment flag, type, and
//the three UUID fields at the start of the bucket.
bucket = new byte[info.BinaryBucket.Length-32];
bucket[0] = 1; //Has attachment
bucket[1] = info.BinaryBucket[1];
Array.Copy(info.BinaryBucket, 50,
bucket, 18, info.BinaryBucket.Length-50);
}
else
{
bucket = new byte[19];
bucket[0] = 0; //No attachment
bucket[1] = 0; //Attachment type
bucket[18] = 0; //NUL terminate name
}
info.GroupID.ToBytes(bucket, 2);
msg.binaryBucket = bucket;
}
else
{
if (m_debugEnabled)
m_log.DebugFormat("[GROUPS]: Group Notice {0} not found, composing empty message.", groupNoticeID);
msg.fromAgentID = UUID.Zero.Guid;
msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.fromAgentName = string.Empty;
msg.message = string.Empty;
msg.binaryBucket = new byte[0];
}
return msg;
}
public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Should check to see if OpenEnrollment, or if there's an outstanding invitation
m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, UUID.Zero);
// check funds
// is there a money module present ?
GroupRecord groupRecord = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null);
IMoneyModule money = remoteClient.Scene.RequestModuleInterface<IMoneyModule>();
if (money != null && groupRecord.MembershipFee > 0)
{
// do the transaction, that is if the agent has sufficient funds
if (!money.AmountCovered(GetRequestingAgentID(remoteClient), groupRecord.MembershipFee)) {
remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have insufficient funds to join the group.");
return;
}
money.ApplyCharge(GetRequestingAgentID(remoteClient), groupRecord.MembershipFee, MoneyTransactionType.GroupJoin, groupRecord.GroupName);
}
remoteClient.SendJoinGroupReply(groupID, true);
SendAgentGroupDataUpdate(remoteClient, true);
}
public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.RemoveAgentFromGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
remoteClient.SendLeaveGroupReply(groupID, true);
remoteClient.SendAgentDropGroup(groupID);
// SL sends out notifcations to the group messaging session that the person has left
// Should this also update everyone who is in the group?
SendAgentGroupDataUpdate(remoteClient, true);
}
public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID)
{
EjectGroupMember(remoteClient, GetRequestingAgentID(remoteClient), groupID, ejecteeID);
}
public void EjectGroupMember(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID ejecteeID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Todo: Security check?
m_groupData.RemoveAgentFromGroup(agentID, ejecteeID, groupID);
string agentName;
RegionInfo regionInfo;
// remoteClient provided or just agentID?
if (remoteClient != null)
{
agentName = remoteClient.Name;
regionInfo = remoteClient.Scene.RegionInfo;
remoteClient.SendEjectGroupMemberReply(agentID, groupID, true);
}
else
{
IClientAPI client = GetActiveClient(agentID);
if (client != null)
{
agentName = client.Name;
regionInfo = client.Scene.RegionInfo;
client.SendEjectGroupMemberReply(agentID, groupID, true);
}
else
{
regionInfo = m_sceneList[0].RegionInfo;
UserAccount acc = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID);
if (acc != null)
{
agentName = acc.FirstName + " " + acc.LastName;
}
else
{
agentName = "Unknown member";
}
}
}
GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID, groupID, null);
if (groupInfo == null)
return;
IClientAPI ejecteeClient = GetActiveRootClient(ejecteeID);
// Send Message to Ejectee
GridInstantMessage msg = new GridInstantMessage();
string ejecteeName = "Unknown member";
// if local send a normal message
if(ejecteeClient != null)
{
msg.imSessionID = UUID.Zero.Guid;
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent;
// also execute and send update
ejecteeClient.SendAgentDropGroup(groupID);
SendAgentGroupDataUpdate(ejecteeClient,true);
ejecteeName = ejecteeClient.Name;
}
else // send
{
// Interop, received special 210 code for ejecting a group member
// this only works within the comms servers domain, and won't work hypergrid
// TODO:FIXME: Use a presence server of some kind to find out where the
// client actually is, and try contacting that region directly to notify them,
// or provide the notification via xmlrpc update queue
msg.imSessionID = groupInfo.GroupID.Guid;
msg.dialog = (byte)210; //interop
UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, ejecteeID);
if (account != null)
ejecteeName = account.FirstName + " " + account.LastName;
}
msg.fromAgentID = agentID.Guid;
// msg.fromAgentID = info.GroupID;
msg.toAgentID = ejecteeID.Guid;
//msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.timestamp = 0;
msg.fromAgentName = agentName;
msg.message = string.Format("You have been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName);
//
msg.fromGroup = false;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = regionInfo.RegionID.Guid;
msg.binaryBucket = new byte[0];
OutgoingInstantMessage(msg, ejecteeID);
// Message to ejector
msg = new GridInstantMessage();
msg.imSessionID = UUID.Zero.Guid;
msg.fromAgentID = agentID.Guid;
msg.toAgentID = agentID.Guid;
msg.timestamp = 0;
msg.fromAgentName = agentName;
msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, ejecteeName);
// msg.dialog = (byte)210; //interop
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent;
msg.fromGroup = false;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = regionInfo.RegionID.Guid;
msg.binaryBucket = new byte[0];
OutgoingInstantMessage(msg, agentID);
}
public void InviteGroupRequest(IClientAPI remoteClient, UUID groupID, UUID invitedAgentID, UUID roleID)
{
InviteGroup(remoteClient, GetRequestingAgentID(remoteClient), groupID, invitedAgentID, roleID);
}
public void InviteGroup(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID invitedAgentID, UUID roleID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
string agentName;
RegionInfo regionInfo;
// remoteClient provided or just agentID?
if (remoteClient != null)
{
agentName = remoteClient.Name;
regionInfo = remoteClient.Scene.RegionInfo;
}
else
{
IClientAPI client = GetActiveClient(agentID);
if (client != null)
{
agentName = client.Name;
regionInfo = client.Scene.RegionInfo;
}
else
{
regionInfo = m_sceneList[0].RegionInfo;
UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID);
if (account != null)
{
agentName = account.FirstName + " " + account.LastName;
}
else
{
agentName = "Unknown member";
}
}
}
// Todo: Security check, probably also want to send some kind of notification
UUID InviteID = UUID.Random();
m_groupData.AddAgentToGroupInvite(agentID, InviteID, groupID, roleID, invitedAgentID);
// Check to see if the invite went through, if it did not then it's possible
// the remoteClient did not validate or did not have permission to invite.
GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(agentID, InviteID);
if (inviteInfo != null)
{
if (m_msgTransferModule != null)
{
Guid inviteUUID = InviteID.Guid;
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = inviteUUID;
// msg.fromAgentID = agentID.Guid;
msg.fromAgentID = groupID.Guid;
msg.toAgentID = invitedAgentID.Guid;
//msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.timestamp = 0;
msg.fromAgentName = agentName;
msg.message = string.Format("{0} has invited you to join a group. There is no cost to join this group.", agentName);
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation;
msg.fromGroup = true;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = regionInfo.RegionID.Guid;
msg.binaryBucket = new byte[20];
OutgoingInstantMessage(msg, invitedAgentID);
}
}
}
public List<DirGroupsReplyData> FindGroups(IClientAPI remoteClient, string query)
{
return m_groupData.FindGroups(GetRequestingAgentID(remoteClient), query);
}
#endregion
#region Client/Update Tools
private IClientAPI GetActiveRootClient(UUID agentID)
{
foreach (Scene scene in m_sceneList)
{
ScenePresence sp = scene.GetScenePresence(agentID);
if (sp != null && !sp.IsChildAgent && !sp.IsDeleted)
{
return sp.ControllingClient;
}
}
return null;
}
/// <summary>
/// Try to find an active IClientAPI reference for agentID giving preference to root connections
/// </summary>
private IClientAPI GetActiveClient(UUID agentID)
{
IClientAPI child = null;
// Try root avatar first
foreach (Scene scene in m_sceneList)
{
ScenePresence sp = scene.GetScenePresence(agentID);
if (sp != null && !sp.IsDeleted)
{
if (!sp.IsChildAgent)
{
return sp.ControllingClient;
}
else
{
child = sp.ControllingClient;
}
}
}
// If we didn't find a root, then just return whichever child we found, or null if none
return child;
}
private void SendScenePresenceUpdate(UUID AgentID, string Title)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Updating scene title for {0} with title: {1}", AgentID, Title);
ScenePresence presence = null;
foreach (Scene scene in m_sceneList)
{
presence = scene.GetScenePresence(AgentID);
if (presence != null)
{
if (presence.Grouptitle != Title)
{
presence.Grouptitle = Title;
if (! presence.IsChildAgent)
presence.SendAvatarDataToAllAgents();
}
}
}
}
public void SendAgentGroupDataUpdate(IClientAPI remoteClient)
{
SendAgentGroupDataUpdate(remoteClient, true);
}
/// <summary>
/// Tell remoteClient about its agent groups, and optionally send title to others
/// </summary>
private void SendAgentGroupDataUpdate(IClientAPI remoteClient, bool tellOthers)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called for {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name);
// NPCs currently don't have a CAPs structure or event queues. There is a strong argument for conveying this information
// to them anyway since it makes writing server-side bots a lot easier, but for now we don't do anything.
if (remoteClient.SceneAgent.PresenceType == PresenceType.Npc)
return;
// TODO: All the client update functions need to be reexamined because most do too much and send too much stuff
UUID agentID = GetRequestingAgentID(remoteClient);
SendDataUpdate(remoteClient, tellOthers);
GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, agentID);
remoteClient.UpdateGroupMembership(membershipArray);
remoteClient.SendAgentGroupDataUpdate(agentID, membershipArray);
}
/// <summary>
/// Get a list of groups memberships for the agent that are marked "ListInProfile"
/// (unless that agent has a godLike aspect, in which case get all groups)
/// </summary>
/// <param name="dataForAgentID"></param>
/// <returns></returns>
private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID)
{
List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(requestingClient.AgentId, dataForAgentID);
GroupMembershipData[] membershipArray;
// cScene and property accessor 'isGod' are in support of the opertions to bypass 'hidden' group attributes for
// those with a GodLike aspect.
Scene cScene = (Scene)requestingClient.Scene;
bool isGod = cScene.Permissions.IsGod(requestingClient.AgentId);
if (isGod)
{
membershipArray = membershipData.ToArray();
}
else
{
if (requestingClient.AgentId != dataForAgentID)
{
Predicate<GroupMembershipData> showInProfile = delegate(GroupMembershipData membership)
{
return membership.ListInProfile;
};
membershipArray = membershipData.FindAll(showInProfile).ToArray();
}
else
{
membershipArray = membershipData.ToArray();
}
}
if (m_debugEnabled)
{
m_log.InfoFormat("[GROUPS]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId);
foreach (GroupMembershipData membership in membershipArray)
{
m_log.InfoFormat("[GROUPS]: {0} :: {1} - {2} - {3}", dataForAgentID, membership.GroupName, membership.GroupTitle, membership.GroupPowers);
}
}
return membershipArray;
}
//tell remoteClient about its agent group info, and optionally send title to others
private void SendDataUpdate(IClientAPI remoteClient, bool tellOthers)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
UUID activeGroupID = UUID.Zero;
string activeGroupTitle = string.Empty;
string activeGroupName = string.Empty;
ulong activeGroupPowers = (ulong)GroupPowers.None;
UUID agentID = GetRequestingAgentID(remoteClient);
GroupMembershipData membership = m_groupData.GetAgentActiveMembership(agentID, agentID);
if (membership != null)
{
activeGroupID = membership.GroupID;
activeGroupTitle = membership.GroupTitle;
activeGroupPowers = membership.GroupPowers;
activeGroupName = membership.GroupName;
}
UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, agentID);
string firstname, lastname;
if (account != null)
{
firstname = account.FirstName;
lastname = account.LastName;
}
else
{
firstname = "Unknown";
lastname = "Unknown";
}
remoteClient.SendAgentDataUpdate(agentID, activeGroupID, firstname,
lastname, activeGroupPowers, activeGroupName,
activeGroupTitle);
if (tellOthers)
SendScenePresenceUpdate(agentID, activeGroupTitle);
ScenePresence sp = (ScenePresence)remoteClient.SceneAgent;
if (sp != null)
sp.Grouptitle = activeGroupTitle;
}
#endregion
#region IM Backed Processes
private void OutgoingInstantMessage(GridInstantMessage msg, UUID msgTo)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
IClientAPI localClient = GetActiveRootClient(msgTo);
if (localClient != null)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is local, delivering directly", localClient.Name);
localClient.SendInstantMessage(msg);
}
else if (m_msgTransferModule != null)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is not local, delivering via TransferModule", msgTo);
m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Message Sent: {0}", success?"Succeeded":"Failed"); });
}
}
public void NotifyChange(UUID groupID)
{
// Notify all group members of a chnge in group roles and/or
// permissions
//
}
#endregion
private UUID GetRequestingAgentID(IClientAPI client)
{
UUID requestingAgentID = UUID.Zero;
if (client != null)
{
requestingAgentID = client.AgentId;
}
return requestingAgentID;
}
}
public class GroupNoticeInfo
{
public GroupNoticeData noticeData = new GroupNoticeData();
public UUID GroupID = UUID.Zero;
public string Message = string.Empty;
public byte[] BinaryBucket = new byte[0];
}
}
| |
using System;
using System.Collections.Generic;
using BEPUphysics.BroadPhaseEntries;
using BEPUphysics.BroadPhaseSystems;
using BEPUphysics.BroadPhaseEntries.MobileCollidables;
using BEPUphysics.CollisionRuleManagement;
using BEPUphysics.Entities;
using BEPUutilities;
using BEPUutilities.ResourceManagement;
using BEPUutilities.Threading;
namespace BEPUphysics.UpdateableSystems
{
/// <summary>
/// Volume in which physically simulated objects have a buoyancy force applied to them based on their density and volume.
/// </summary>
public class FluidVolume : Updateable, IDuringForcesUpdateable, ICollisionRulesOwner
{
//TODO: The current FluidVolume implementation is awfully awful.
//It would be really nice if it was a bit more flexible and less clunktastic.
//(A mesh volume, maybe?)
private RigidTransform surfaceTransform;
private Matrix3x3 toSurfaceRotationMatrix;
Vector3 upVector;
///<summary>
/// Gets or sets the up vector of the fluid volume.
///</summary>
public Vector3 UpVector
{
get
{
return upVector;
}
set
{
value.Normalize();
upVector = value;
RecalculateBoundingBox();
}
}
/// <summary>
/// Gets or sets the dictionary storing density multipliers for the fluid volume. If a value is specified for an entity, the density of the object is effectively scaled to match.
/// Higher values make entities sink more, lower values make entities float more.
/// </summary>
public Dictionary<Entity, float> DensityMultipliers { get; set; }
BoundingBox boundingBox;
/// <summary>
/// Bounding box surrounding the surface triangles and entire depth of the object.
/// </summary>
public BoundingBox BoundingBox
{
get
{
return boundingBox;
}
}
float maxDepth;
/// <summary>
/// Maximum depth of the fluid from the surface.
/// </summary>
public float MaxDepth
{
get
{
return maxDepth;
}
set
{
maxDepth = value;
RecalculateBoundingBox();
}
}
/// <summary>
/// Density of the fluid represented in the volume.
/// </summary>
public float Density { get; set; }
int samplePointsPerDimension = 8;
/// <summary>
/// Number of locations along each of the horizontal axes from which to sample the shape.
/// Defaults to 8.
/// </summary>
public int SamplePointsPerDimension
{
get
{
return samplePointsPerDimension;
}
set
{
samplePointsPerDimension = value;
}
}
/// <summary>
/// Fraction by which to reduce the linear momentum of floating objects each update.
/// </summary>
public float LinearDamping { get; set; }
/// <summary>
/// Fraction by which to reduce the angular momentum of floating objects each update.
/// </summary>
public float AngularDamping { get; set; }
private Vector3 flowDirection;
/// <summary>
/// Direction in which to exert force on objects within the fluid.
/// flowForce and maxFlowSpeed must have valid values as well for the flow to work.
/// </summary>
public Vector3 FlowDirection
{
get
{
return flowDirection;
}
set
{
float length = value.Length();
if (length > 0)
{
flowDirection = value / length;
}
else
flowDirection = Vector3.Zero;
//TODO: Activate bodies in water
}
}
private float flowForce;
/// <summary>
/// Magnitude of the flow's force, in units of flow direction.
/// flowDirection and maxFlowSpeed must have valid values as well for the flow to work.
/// </summary>
public float FlowForce
{
get
{
return flowForce;
}
set
{
flowForce = value;
//TODO: Activate bodies in water
}
}
float maxFlowSpeed;
/// <summary>
/// Maximum speed of the flow; objects will not be accelerated by the flow force beyond this speed.
/// flowForce and flowDirection must have valid values as well for the flow to work.
/// </summary>
public float MaxFlowSpeed
{
get
{
return maxFlowSpeed;
}
set
{
maxFlowSpeed = value;
}
}
IQueryAccelerator QueryAccelerator { get; set; }
///<summary>
/// Gets or sets the parallel loop provider used by the fluid volume.
///</summary>
public IParallelLooper ParallelLooper { get; set; }
private List<Vector3[]> surfaceTriangles;
/// <summary>
/// List of coplanar triangles composing the surface of the fluid.
/// </summary>
public List<Vector3[]> SurfaceTriangles
{
get
{
return surfaceTriangles;
}
set
{
surfaceTriangles = value;
RecalculateBoundingBox();
}
}
float gravity;
///<summary>
/// Gets or sets the gravity used by the fluid volume.
///</summary>
public float Gravity
{
get
{
return gravity;
}
set
{
gravity = value;
}
}
/// <summary>
/// Creates a fluid volume.
/// </summary>
/// <param name="upVector">Up vector of the fluid volume.</param>
/// <param name="gravity">Strength of gravity for the purposes of the fluid volume.</param>
/// <param name="surfaceTriangles">List of triangles composing the surface of the fluid. Set up as a list of length 3 arrays of Vector3's.</param>
/// <param name="depth">Depth of the fluid back along the surface normal.</param>
/// <param name="fluidDensity">Density of the fluid represented in the volume.</param>
/// <param name="linearDamping">Fraction by which to reduce the linear momentum of floating objects each update, in addition to any of the body's own damping.</param>
/// <param name="angularDamping">Fraction by which to reduce the angular momentum of floating objects each update, in addition to any of the body's own damping.</param>
public FluidVolume(Vector3 upVector, float gravity, List<Vector3[]> surfaceTriangles, float depth, float fluidDensity, float linearDamping, float angularDamping)
{
Gravity = gravity;
SurfaceTriangles = surfaceTriangles;
MaxDepth = depth;
Density = fluidDensity;
LinearDamping = linearDamping;
AngularDamping = angularDamping;
UpVector = upVector;
analyzeCollisionEntryDelegate = AnalyzeEntry;
DensityMultipliers = new Dictionary<Entity, float>();
}
/// <summary>
/// Recalculates the bounding box of the fluid based on its depth, surface normal, and surface triangles.
/// </summary>
public void RecalculateBoundingBox()
{
var points = CommonResources.GetVectorList();
foreach (var tri in SurfaceTriangles)
{
points.Add(tri[0]);
points.Add(tri[1]);
points.Add(tri[2]);
points.Add(tri[0] - upVector * MaxDepth);
points.Add(tri[1] - upVector * MaxDepth);
points.Add(tri[2] - upVector * MaxDepth);
}
boundingBox = BoundingBox.CreateFromPoints(points);
CommonResources.GiveBack(points);
//Compute the transforms used to pull objects into fluid local space.
Quaternion.GetQuaternionBetweenNormalizedVectors(ref Toolbox.UpVector, ref upVector, out surfaceTransform.Orientation);
Matrix3x3.CreateFromQuaternion(ref surfaceTransform.Orientation, out toSurfaceRotationMatrix);
surfaceTransform.Position = surfaceTriangles[0][0];
}
List<BroadPhaseEntry> broadPhaseEntries = new List<BroadPhaseEntry>();
/// <summary>
/// Applies buoyancy forces to appropriate objects.
/// Called automatically when needed by the owning Space.
/// </summary>
/// <param name="dt">Time since last frame in physical logic.</param>
void IDuringForcesUpdateable.Update(float dt)
{
QueryAccelerator.GetEntries(boundingBox, broadPhaseEntries);
//TODO: Could integrate the entire thing into the collision detection pipeline. Applying forces
//in the collision detection pipeline isn't allowed, so there'd still need to be an Updateable involved.
//However, the broadphase query would be eliminated and the raycasting work would be automatically multithreaded.
this.dt = dt;
//Don't always multithread. For small numbers of objects, the overhead of using multithreading isn't worth it.
//Could tune this value depending on platform for better performance.
if (broadPhaseEntries.Count > 30 && ParallelLooper != null && ParallelLooper.ThreadCount > 1)
ParallelLooper.ForLoop(0, broadPhaseEntries.Count, analyzeCollisionEntryDelegate);
else
for (int i = 0; i < broadPhaseEntries.Count; i++)
{
AnalyzeEntry(i);
}
broadPhaseEntries.Clear();
}
float dt;
Action<int> analyzeCollisionEntryDelegate;
void AnalyzeEntry(int i)
{
var entityCollidable = broadPhaseEntries[i] as EntityCollidable;
if (entityCollidable != null && entityCollidable.IsActive && entityCollidable.entity.isDynamic && CollisionRules.collisionRuleCalculator(this, entityCollidable) <= CollisionRule.Normal)
{
bool keepGoing = false;
foreach (var tri in surfaceTriangles)
{
//Don't need to do anything if the entity is outside of the water.
if (Toolbox.IsPointInsideTriangle(ref tri[0], ref tri[1], ref tri[2], ref entityCollidable.worldTransform.Position))
{
keepGoing = true;
break;
}
}
if (!keepGoing)
return;
//The entity is submerged, apply buoyancy forces.
float submergedVolume;
Vector3 submergedCenter;
GetBuoyancyInformation(entityCollidable, out submergedVolume, out submergedCenter);
if (submergedVolume > 0)
{
//The approximation can sometimes output a volume greater than the shape itself. Don't let that error seep into usage.
float fractionSubmerged = Math.Min(1, submergedVolume / entityCollidable.entity.CollisionInformation.Shape.Volume);
//Divide the volume by the density multiplier if present.
float densityMultiplier;
if (DensityMultipliers.TryGetValue(entityCollidable.entity, out densityMultiplier))
{
submergedVolume /= densityMultiplier;
}
Vector3 force;
Vector3.Multiply(ref upVector, -gravity * Density * dt * submergedVolume, out force);
entityCollidable.entity.ApplyImpulseWithoutActivating(ref submergedCenter, ref force);
//Flow
if (FlowForce != 0)
{
float dot = Math.Max(Vector3.Dot(entityCollidable.entity.linearVelocity, flowDirection), 0);
if (dot < MaxFlowSpeed)
{
force = Math.Min(FlowForce, (MaxFlowSpeed - dot) * entityCollidable.entity.mass) * dt * fractionSubmerged * FlowDirection;
entityCollidable.entity.ApplyLinearImpulse(ref force);
}
}
//Damping
entityCollidable.entity.ModifyLinearDamping(fractionSubmerged * LinearDamping);
entityCollidable.entity.ModifyAngularDamping(fractionSubmerged * AngularDamping);
}
}
}
void GetBuoyancyInformation(EntityCollidable collidable, out float submergedVolume, out Vector3 submergedCenter)
{
BoundingBox entityBoundingBox;
RigidTransform localTransform;
RigidTransform.MultiplyByInverse(ref collidable.worldTransform, ref surfaceTransform, out localTransform);
collidable.Shape.GetBoundingBox(ref localTransform, out entityBoundingBox);
if (entityBoundingBox.Min.Y > 0)
{
//Fish out of the water. Don't need to do raycast tests on objects not at the boundary.
submergedVolume = 0;
submergedCenter = collidable.worldTransform.Position;
return;
}
if (entityBoundingBox.Max.Y < 0)
{
submergedVolume = collidable.entity.CollisionInformation.Shape.Volume;
submergedCenter = collidable.worldTransform.Position;
return;
}
Vector3 origin, xSpacing, zSpacing;
float perColumnArea;
GetSamplingOrigin(ref entityBoundingBox, out xSpacing, out zSpacing, out perColumnArea, out origin);
float boundingBoxHeight = entityBoundingBox.Max.Y - entityBoundingBox.Min.Y;
float maxLength = -entityBoundingBox.Min.Y;
submergedCenter = new Vector3();
submergedVolume = 0;
for (int i = 0; i < samplePointsPerDimension; i++)
{
for (int j = 0; j < samplePointsPerDimension; j++)
{
Vector3 columnVolumeCenter;
float submergedHeight;
if ((submergedHeight = GetSubmergedHeight(collidable, maxLength, boundingBoxHeight, ref origin, ref xSpacing, ref zSpacing, i, j, out columnVolumeCenter)) > 0)
{
float columnVolume = submergedHeight * perColumnArea;
Vector3.Multiply(ref columnVolumeCenter, columnVolume, out columnVolumeCenter);
Vector3.Add(ref columnVolumeCenter, ref submergedCenter, out submergedCenter);
submergedVolume += columnVolume;
}
}
}
Vector3.Divide(ref submergedCenter, submergedVolume, out submergedCenter);
//Pull the submerged center into world space before applying the force.
RigidTransform.Transform(ref submergedCenter, ref surfaceTransform, out submergedCenter);
}
void GetSamplingOrigin(ref BoundingBox entityBoundingBox, out Vector3 xSpacing, out Vector3 zSpacing, out float perColumnArea, out Vector3 origin)
{
//Compute spacing and increment informaiton.
float widthIncrement = (entityBoundingBox.Max.X - entityBoundingBox.Min.X) / samplePointsPerDimension;
float lengthIncrement = (entityBoundingBox.Max.Z - entityBoundingBox.Min.Z) / samplePointsPerDimension;
xSpacing = new Vector3(widthIncrement, 0, 0);
zSpacing = new Vector3(0, 0, lengthIncrement);
Quaternion.Transform(ref xSpacing, ref surfaceTransform.Orientation, out xSpacing);
Quaternion.Transform(ref zSpacing, ref surfaceTransform.Orientation, out zSpacing);
perColumnArea = widthIncrement * lengthIncrement;
//Compute the origin.
Vector3 minimum;
RigidTransform.Transform(ref entityBoundingBox.Min, ref surfaceTransform, out minimum);
//Matrix3X3.TransformTranspose(ref entityBoundingBox.Min, ref surfaceOrientationTranspose, out minimum);
Vector3 offset;
Vector3.Multiply(ref xSpacing, .5f, out offset);
Vector3.Add(ref minimum, ref offset, out origin);
Vector3.Multiply(ref zSpacing, .5f, out offset);
Vector3.Add(ref origin, ref offset, out origin);
//TODO: Could adjust the grid origin such that a ray always hits the deepest point.
//The below code is a prototype of the idea, but has bugs.
//var convexInfo = collidable as ConvexCollisionInformation;
//if (convexInfo != null)
//{
// Vector3 dir;
// Vector3.Negate(ref upVector, out dir);
// Vector3 extremePoint;
// convexInfo.Shape.GetExtremePoint(dir, ref convexInfo.worldTransform, out extremePoint);
// //Use extreme point to snap to grid.
// Vector3.Subtract(ref extremePoint, ref origin, out offset);
// float offsetX, offsetZ;
// Vector3.Dot(ref offset, ref right, out offsetX);
// Vector3.Dot(ref offset, ref backward, out offsetZ);
// offsetX %= widthIncrement;
// offsetZ %= lengthIncrement;
// if (offsetX > .5f * widthIncrement)
// {
// Vector3.Multiply(ref right, 1 - offsetX, out offset);
// }
// else
// {
// Vector3.Multiply(ref right, -offsetX, out offset);
// }
// if (offsetZ > .5f * lengthIncrement)
// {
// Vector3 temp;
// Vector3.Multiply(ref right, 1 - offsetZ, out temp);
// Vector3.Add(ref temp, ref offset, out offset);
// }
// else
// {
// Vector3 temp;
// Vector3.Multiply(ref right, -offsetZ, out temp);
// Vector3.Add(ref temp, ref offset, out offset);
// }
// Vector3.Add(ref origin, ref offset, out origin);
//}
}
float GetSubmergedHeight(EntityCollidable collidable, float maxLength, float boundingBoxHeight, ref Vector3 rayOrigin, ref Vector3 xSpacing, ref Vector3 zSpacing, int i, int j, out Vector3 volumeCenter)
{
Ray ray;
Vector3.Multiply(ref xSpacing, i, out ray.Position);
Vector3.Multiply(ref zSpacing, j, out ray.Direction);
Vector3.Add(ref ray.Position, ref ray.Direction, out ray.Position);
Vector3.Add(ref ray.Position, ref rayOrigin, out ray.Position);
ray.Direction = upVector;
//do a bottom-up raycast.
RayHit rayHit;
//Only go up to maxLength. If it's further away than maxLength, then it's above the water and it doesn't contribute anything.
if (collidable.RayCast(ray, maxLength, out rayHit))
{
//Position the ray to point from the other side.
Vector3.Multiply(ref ray.Direction, boundingBoxHeight, out ray.Direction);
Vector3.Add(ref ray.Position, ref ray.Direction, out ray.Position);
Vector3.Negate(ref upVector, out ray.Direction);
//Transform the hit into local space.
RigidTransform.TransformByInverse(ref rayHit.Location, ref surfaceTransform, out rayHit.Location);
float bottomY = rayHit.Location.Y;
float bottom = rayHit.T;
Vector3 bottomPosition = rayHit.Location;
if (collidable.RayCast(ray, boundingBoxHeight - rayHit.T, out rayHit))
{
//Transform the hit into local space.
RigidTransform.TransformByInverse(ref rayHit.Location, ref surfaceTransform, out rayHit.Location);
Vector3.Add(ref rayHit.Location, ref bottomPosition, out volumeCenter);
Vector3.Multiply(ref volumeCenter, .5f, out volumeCenter);
return Math.Min(-bottomY, boundingBoxHeight - rayHit.T - bottom);
}
//This inner raycast should always hit, but just in case it doesn't due to some numerical problem, give it a graceful way out.
volumeCenter = Vector3.Zero;
return 0;
}
volumeCenter = Vector3.Zero;
return 0;
}
public override void OnAdditionToSpace(Space newSpace)
{
base.OnAdditionToSpace(newSpace);
ParallelLooper = newSpace.ParallelLooper;
QueryAccelerator = newSpace.BroadPhase.QueryAccelerator;
}
public override void OnRemovalFromSpace(Space oldSpace)
{
base.OnRemovalFromSpace(oldSpace);
ParallelLooper = null;
QueryAccelerator = null;
}
private CollisionRules collisionRules = new CollisionRules();
/// <summary>
/// Gets or sets the collision rules associated with the fluid volume.
/// </summary>
public CollisionRules CollisionRules
{
get
{
return collisionRules;
}
set
{
collisionRules = value;
}
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using OpenSim.ScriptEngine.Shared;
namespace OpenSim.ScriptEngine.Components.DotNetEngine.Scheduler
{
public class BaseClassFactory
{
public static void MakeBaseClass(ScriptStructure script)
{
string asmName = "ScriptAssemblies";
string ModuleID = asmName;
string ClassID = "Script";
string moveToDir = "ScriptEngines";
string asmFileName = ModuleID + "_" + ClassID + ".dll";
if (!Directory.Exists(moveToDir))
Directory.CreateDirectory(moveToDir);
ILGenerator ilgen;
AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName(asmName), AssemblyBuilderAccess.RunAndSave);
// The module builder
ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule(ModuleID, asmFileName);
// The class builder
TypeBuilder classBuilder = modBuilder.DefineType(ClassID, TypeAttributes.Class | TypeAttributes.Public);
// The default constructor
//ConstructorBuilder ctorBuilder = classBuilder.DefineDefaultConstructor(MethodAttributes.Public);
Type[] paramsTypeArray = new Type[] {typeof (System.ParamArrayAttribute)};
Type[] executeFunctionTypeArray = new Type[] {typeof (string), typeof (System.ParamArrayAttribute)};
foreach (IScriptCommandProvider cp in script.RegionInfo.CommandProviders.Values)
{
Type t = cp.GetType();
foreach (MethodInfo mi in t.GetMethods())
{
MethodBuilder methodBuilder = classBuilder.DefineMethod(mi.Name, mi.Attributes, mi.GetType(), Type.EmptyTypes);
methodBuilder.SetParameters(paramsTypeArray);
//ParameterBuilder paramBuilder = methodBuilder.DefineParameter(1, ParameterAttributes.None, "args");
ilgen = methodBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Nop);
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldc_I4_0);
//ilgen.Emit(OpCodes.Ldelem_Ref);
//ilgen.MarkSequencePoint(doc, 6, 1, 6, 100);
//MethodInfo ExecuteFunction = typeof(ScriptAssemblies.IScript).GetMethod(
// "ExecuteFunction",
// executeFunctionTypeArray);
ilgen.DeclareLocal(typeof(string));
ilgen.Emit(OpCodes.Nop);
ilgen.Emit(OpCodes.Ldstr, mi.Name);
ilgen.Emit(OpCodes.Stloc_0);
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Ldloc_0);
ilgen.Emit(OpCodes.Ldarg_1);
// FieldInfo testInfo = classBuilder.
//BindingFlags.NonPublic | BindingFlags.Instance);
//ilgen.Emit(OpCodes.Ldfld, testInfo);
//ilgen.EmitCall(OpCodes.Call, ExecuteFunction, executeFunctionTypeArray);
ilgen.EmitCall(OpCodes.Call, typeof(System.Console).GetMethod("WriteLine"), executeFunctionTypeArray);
// // string.Format("Hello, {0} World!", toWhom)
// //
// ilgen.Emit(OpCodes.Ldstr, "Hello, {0} World!");
// ilgen.Emit(OpCodes.Ldarg_1);
// ilgen.Emit(OpCodes.Call, typeof(string).GetMethod
//("Format", new Type[] { typeof(string), typeof(object) }));
// // m_log.Debug("Hello, World!");
// //
// ilgen.Emit(OpCodes.Call, typeof(Console).GetMethod
// ("WriteLine", new Type[] { typeof(string) }));
ilgen.Emit(OpCodes.Ret);
//Label eom = ilgen.DefineLabel();
//ilgen.Emit(OpCodes.Br_S, eom);
//ilgen.MarkLabel(eom);
//ilgen.Emit(OpCodes.Ret);
//Type test = methodBuilder.SetParameters();
//methodBuilder.SetParameters(typeof (object[]));
}
}
//// Two fields: m_firstname, m_lastname
//FieldBuilder fBuilderFirstName = classBuilder.DefineField("m_firstname", typeof(string), FieldAttributes.Private);
//FieldBuilder fBuilderLastName = classBuilder.DefineField("m_lastname", typeof(string), FieldAttributes.Private);
//// Two properties for this object: FirstName, LastName
//PropertyBuilder pBuilderFirstName = classBuilder.DefineProperty("FirstName", System.Reflection.PropertyAttributes.HasDefault, typeof(string), null);
//PropertyBuilder pBuilderLastName = classBuilder.DefineProperty("LastName", System.Reflection.PropertyAttributes.HasDefault, typeof(string), null);
//// Custom attributes for get, set accessors
//MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName;
//// get,set accessors for FirstName
//MethodBuilder mGetFirstNameBuilder = classBuilder.DefineMethod("get_FirstName", getSetAttr, typeof(string), Type.EmptyTypes);
//// Code generation
//ilgen = mGetFirstNameBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldfld, fBuilderFirstName); // returning the firstname field
//ilgen.Emit(OpCodes.Ret);
//MethodBuilder mSetFirstNameBuilder = classBuilder.DefineMethod("set_FirstName", getSetAttr, null, new Type[] { typeof(string) });
//// Code generation
//ilgen = mSetFirstNameBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldarg_1);
//ilgen.Emit(OpCodes.Stfld, fBuilderFirstName); // setting the firstname field from the first argument (1)
//ilgen.Emit(OpCodes.Ret);
//// get,set accessors for LastName
//MethodBuilder mGetLastNameBuilder = classBuilder.DefineMethod("get_LastName", getSetAttr, typeof(string), Type.EmptyTypes);
//// Code generation
//ilgen = mGetLastNameBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldfld, fBuilderLastName); // returning the firstname field
//ilgen.Emit(OpCodes.Ret);
//MethodBuilder mSetLastNameBuilder = classBuilder.DefineMethod("set_LastName", getSetAttr, null, new Type[] { typeof(string) });
//// Code generation
//ilgen = mSetLastNameBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldarg_1);
//ilgen.Emit(OpCodes.Stfld, fBuilderLastName); // setting the firstname field from the first argument (1)
//ilgen.Emit(OpCodes.Ret);
//// Assigning get/set accessors
//pBuilderFirstName.SetGetMethod(mGetFirstNameBuilder);
//pBuilderFirstName.SetSetMethod(mSetFirstNameBuilder);
//pBuilderLastName.SetGetMethod(mGetLastNameBuilder);
//pBuilderLastName.SetSetMethod(mSetLastNameBuilder);
//// Now, a custom method named GetFullName that concatenates FirstName and LastName properties
//MethodBuilder mGetFullNameBuilder = classBuilder.DefineMethod("GetFullName", MethodAttributes.Public, typeof(string), Type.EmptyTypes);
//// Code generation
//ilgen = mGetFullNameBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Call, mGetFirstNameBuilder); // getting the firstname
//ilgen.Emit(OpCodes.Ldstr, " "); // an space
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Call, mGetLastNameBuilder); // getting the lastname
//// We need the 'Concat' method from string type
//MethodInfo concatMethod = typeof(String).GetMethod("Concat", new Type[] { typeof(string), typeof(string), typeof(string) });
//ilgen.Emit(OpCodes.Call, concatMethod); // calling concat and returning the result
//ilgen.Emit(OpCodes.Ret);
//// Another constructor that initializes firstname and lastname
//ConstructorBuilder ctorBuilder2 = classBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string), typeof(string) });
//ctorBuilder2.DefineParameter(1, ParameterAttributes.In, "firstname");
//ctorBuilder2.DefineParameter(2, ParameterAttributes.In, "lastname");
//// Code generation
//ilgen = ctorBuilder2.GetILGenerator();
//// First of all, we need to call the base constructor,
//// the Object's constructor in this sample
//Type objType = Type.GetType("System.Object");
//ConstructorInfo objCtor = objType.GetConstructor(Type.EmptyTypes);
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Call, objCtor); // calling the Object's constructor
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldarg_1);
//ilgen.Emit(OpCodes.Call, mSetFirstNameBuilder); // setting the firstname field from the first argument (1)
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldarg_2);
//ilgen.Emit(OpCodes.Call, mSetLastNameBuilder); // setting the lastname field from the second argument (2)
//ilgen.Emit(OpCodes.Ret);
// Finally, create the type and save the assembly
classBuilder.CreateType();
asmBuilder.Save(asmFileName);
string toFile = Path.Combine(moveToDir, asmFileName);
if (File.Exists(toFile))
File.Delete(toFile);
File.Move(asmFileName, toFile);
//string a = "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Globalization
{
public static class __ThaiBuddhistCalendar
{
public static IObservable<System.DateTime> AddMonths(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.DateTime> time, IObservable<System.Int32> months)
{
return Observable.Zip(ThaiBuddhistCalendarValue, time, months,
(ThaiBuddhistCalendarValueLambda, timeLambda, monthsLambda) =>
ThaiBuddhistCalendarValueLambda.AddMonths(timeLambda, monthsLambda));
}
public static IObservable<System.DateTime> AddYears(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.DateTime> time, IObservable<System.Int32> years)
{
return Observable.Zip(ThaiBuddhistCalendarValue, time, years,
(ThaiBuddhistCalendarValueLambda, timeLambda, yearsLambda) =>
ThaiBuddhistCalendarValueLambda.AddYears(timeLambda, yearsLambda));
}
public static IObservable<System.Int32> GetDaysInMonth(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> era)
{
return Observable.Zip(ThaiBuddhistCalendarValue, year, month, era,
(ThaiBuddhistCalendarValueLambda, yearLambda, monthLambda, eraLambda) =>
ThaiBuddhistCalendarValueLambda.GetDaysInMonth(yearLambda, monthLambda, eraLambda));
}
public static IObservable<System.Int32> GetDaysInYear(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> era)
{
return Observable.Zip(ThaiBuddhistCalendarValue, year, era,
(ThaiBuddhistCalendarValueLambda, yearLambda, eraLambda) =>
ThaiBuddhistCalendarValueLambda.GetDaysInYear(yearLambda, eraLambda));
}
public static IObservable<System.Int32> GetDayOfMonth(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(ThaiBuddhistCalendarValue, time,
(ThaiBuddhistCalendarValueLambda, timeLambda) =>
ThaiBuddhistCalendarValueLambda.GetDayOfMonth(timeLambda));
}
public static IObservable<System.DayOfWeek> GetDayOfWeek(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(ThaiBuddhistCalendarValue, time,
(ThaiBuddhistCalendarValueLambda, timeLambda) =>
ThaiBuddhistCalendarValueLambda.GetDayOfWeek(timeLambda));
}
public static IObservable<System.Int32> GetDayOfYear(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(ThaiBuddhistCalendarValue, time,
(ThaiBuddhistCalendarValueLambda, timeLambda) =>
ThaiBuddhistCalendarValueLambda.GetDayOfYear(timeLambda));
}
public static IObservable<System.Int32> GetMonthsInYear(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> era)
{
return Observable.Zip(ThaiBuddhistCalendarValue, year, era,
(ThaiBuddhistCalendarValueLambda, yearLambda, eraLambda) =>
ThaiBuddhistCalendarValueLambda.GetMonthsInYear(yearLambda, eraLambda));
}
public static IObservable<System.Int32> GetWeekOfYear(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.DateTime> time, IObservable<System.Globalization.CalendarWeekRule> rule,
IObservable<System.DayOfWeek> firstDayOfWeek)
{
return Observable.Zip(ThaiBuddhistCalendarValue, time, rule, firstDayOfWeek,
(ThaiBuddhistCalendarValueLambda, timeLambda, ruleLambda, firstDayOfWeekLambda) =>
ThaiBuddhistCalendarValueLambda.GetWeekOfYear(timeLambda, ruleLambda, firstDayOfWeekLambda));
}
public static IObservable<System.Int32> GetEra(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(ThaiBuddhistCalendarValue, time,
(ThaiBuddhistCalendarValueLambda, timeLambda) => ThaiBuddhistCalendarValueLambda.GetEra(timeLambda));
}
public static IObservable<System.Int32> GetMonth(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(ThaiBuddhistCalendarValue, time,
(ThaiBuddhistCalendarValueLambda, timeLambda) => ThaiBuddhistCalendarValueLambda.GetMonth(timeLambda));
}
public static IObservable<System.Int32> GetYear(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(ThaiBuddhistCalendarValue, time,
(ThaiBuddhistCalendarValueLambda, timeLambda) => ThaiBuddhistCalendarValueLambda.GetYear(timeLambda));
}
public static IObservable<System.Boolean> IsLeapDay(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> day,
IObservable<System.Int32> era)
{
return Observable.Zip(ThaiBuddhistCalendarValue, year, month, day, era,
(ThaiBuddhistCalendarValueLambda, yearLambda, monthLambda, dayLambda, eraLambda) =>
ThaiBuddhistCalendarValueLambda.IsLeapDay(yearLambda, monthLambda, dayLambda, eraLambda));
}
public static IObservable<System.Boolean> IsLeapYear(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> era)
{
return Observable.Zip(ThaiBuddhistCalendarValue, year, era,
(ThaiBuddhistCalendarValueLambda, yearLambda, eraLambda) =>
ThaiBuddhistCalendarValueLambda.IsLeapYear(yearLambda, eraLambda));
}
public static IObservable<System.Int32> GetLeapMonth(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> era)
{
return Observable.Zip(ThaiBuddhistCalendarValue, year, era,
(ThaiBuddhistCalendarValueLambda, yearLambda, eraLambda) =>
ThaiBuddhistCalendarValueLambda.GetLeapMonth(yearLambda, eraLambda));
}
public static IObservable<System.Boolean> IsLeapMonth(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> era)
{
return Observable.Zip(ThaiBuddhistCalendarValue, year, month, era,
(ThaiBuddhistCalendarValueLambda, yearLambda, monthLambda, eraLambda) =>
ThaiBuddhistCalendarValueLambda.IsLeapMonth(yearLambda, monthLambda, eraLambda));
}
public static IObservable<System.DateTime> ToDateTime(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> day,
IObservable<System.Int32> hour, IObservable<System.Int32> minute, IObservable<System.Int32> second,
IObservable<System.Int32> millisecond, IObservable<System.Int32> era)
{
return Observable.Zip(ThaiBuddhistCalendarValue, year, month, day, hour, minute, second, millisecond, era,
(ThaiBuddhistCalendarValueLambda, yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda,
secondLambda, millisecondLambda, eraLambda) =>
ThaiBuddhistCalendarValueLambda.ToDateTime(yearLambda, monthLambda, dayLambda, hourLambda,
minuteLambda, secondLambda, millisecondLambda, eraLambda));
}
public static IObservable<System.Int32> ToFourDigitYear(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.Int32> year)
{
return Observable.Zip(ThaiBuddhistCalendarValue, year,
(ThaiBuddhistCalendarValueLambda, yearLambda) =>
ThaiBuddhistCalendarValueLambda.ToFourDigitYear(yearLambda));
}
public static IObservable<System.DateTime> get_MinSupportedDateTime(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue)
{
return Observable.Select(ThaiBuddhistCalendarValue,
(ThaiBuddhistCalendarValueLambda) => ThaiBuddhistCalendarValueLambda.MinSupportedDateTime);
}
public static IObservable<System.DateTime> get_MaxSupportedDateTime(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue)
{
return Observable.Select(ThaiBuddhistCalendarValue,
(ThaiBuddhistCalendarValueLambda) => ThaiBuddhistCalendarValueLambda.MaxSupportedDateTime);
}
public static IObservable<System.Globalization.CalendarAlgorithmType> get_AlgorithmType(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue)
{
return Observable.Select(ThaiBuddhistCalendarValue,
(ThaiBuddhistCalendarValueLambda) => ThaiBuddhistCalendarValueLambda.AlgorithmType);
}
public static IObservable<System.Int32[]> get_Eras(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue)
{
return Observable.Select(ThaiBuddhistCalendarValue,
(ThaiBuddhistCalendarValueLambda) => ThaiBuddhistCalendarValueLambda.Eras);
}
public static IObservable<System.Int32> get_TwoDigitYearMax(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue)
{
return Observable.Select(ThaiBuddhistCalendarValue,
(ThaiBuddhistCalendarValueLambda) => ThaiBuddhistCalendarValueLambda.TwoDigitYearMax);
}
public static IObservable<System.Reactive.Unit> set_TwoDigitYearMax(
this IObservable<System.Globalization.ThaiBuddhistCalendar> ThaiBuddhistCalendarValue,
IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(ThaiBuddhistCalendarValue, value,
(ThaiBuddhistCalendarValueLambda, valueLambda) =>
ThaiBuddhistCalendarValueLambda.TwoDigitYearMax = valueLambda);
}
}
}
| |
/// QAS Pro Web > (c) Experian > www.edq.com
/// Web > Verification > VerifyBase
/// Provide common functionality and value transfer
namespace Experian.Qas.Prowebintegration
{
using System;
using System.Text;
using System.Web;
using Experian.Qas.Proweb;
/// <summary>
/// Web > Verification > VerifyBase
/// This is the base class for the pages of the scenario
/// It provides common functionality and simple inter-page value passing.
/// </summary>
public class VerifyBase : System.Web.UI.Page
{
private IAddressLookup addressLookup = null;
private string[] m_asInputAddress;
// Page filenames
private const string PAGE_REFINE = "VerifyRefine.aspx";
/** Methods **/
/// <summary>
/// Gets a new QAS service, connected to the configured server
/// </summary>
protected IAddressLookup AddressLookup
{
get
{
if (addressLookup == null)
{
// Create QAS search object
addressLookup = QAS.GetSearchService();
}
return addressLookup;
}
}
/// <summary>
/// Get the layout from the config
/// </summary>
/// <returns>string</returns>
protected string GetLayout()
{
string sLayout = string.Empty;
string sDataID = Request[Constants.FIELD_DATA_ID];
if (sDataID != null && sDataID != string.Empty)
{
// Look for a layout specific to this datamap
sLayout = System.Configuration.ConfigurationManager.AppSettings[Constants.KEY_LAYOUT + "." + sDataID];
if (sLayout == null || sLayout == string.Empty)
{
// No layout found specific to this datamap - try the default
sLayout = System.Configuration.ConfigurationManager.AppSettings[Constants.KEY_LAYOUT];
}
}
return sLayout;
}
/// <summary>
/// Transfer out of the scenario to display the formatted address
/// </summary>
/// <param name="sMoniker">string</param>
protected void GoFinalPage(string sMoniker)
{
FormatAddress(sMoniker);
Server.Transfer(Constants.PAGE_FINAL_ADDRESS);
}
/// <summary>
/// Transfer out of the scenario to the original input screen
/// </summary>
protected void GoInputPage()
{
Server.Transfer(Constants.PAGE_VERIFY_INPUT);
}
/// <summary>
/// Transfer out of the scenario to display the found address
/// </summary>
protected void GoFinalPage()
{
Server.Transfer(Constants.PAGE_FINAL_ADDRESS);
}
/// <summary>
/// Transfer out of the scenario to display the input address, after exception thrown
/// </summary>
/// <param name="x">Exception</param>
protected void GoErrorPage(Exception x)
{
// Copy input lines through to output
SetAddressResult(GetInputAddress);
SetAddressInfo("address verification " + Constants.Routes.Failed + ", so the entered address has been used");
SetErrorInfo(x.Message);
Server.Transfer(Constants.PAGE_FINAL_ADDRESS);
}
/// <summary>
/// Transfer out of the scenario to display the input address, after verification failed
/// </summary>
/// <param name="route">Constants.Routes</param>
/// <param name="sReason">string</param>
protected void GoErrorPage(Constants.Routes route, string sReason)
{
// Copy input lines through to output
SetAddressResult(GetInputAddress);
SetAddressInfo("address verification " + route + ", so the entered address has been used");
SetErrorInfo(sReason);
Server.Transfer(Constants.PAGE_FINAL_ADDRESS);
}
/// <summary>
/// Retrieve a final formatted address from the moniker, which came from the picklist.
/// </summary>
/// <param name="sMoniker">Search Point Moniker of address to retrieve.</param>
protected void FormatAddress(string sMoniker)
{
try
{
if (!string.IsNullOrEmpty(sMoniker))
{
// Format the address
FormattedAddress tAddressResult = AddressLookup.GetFormattedAddress(sMoniker, GetLayout());
SetAddressResult(tAddressResult);
}
else
{
SetAddressResult(GetInputAddress);
SetAddressInfo("Address verification is not available, so the entered address has been used");
}
}
catch (Exception x)
{
SetAddressResult(GetInputAddress);
SetAddressInfo("Address verification is not available, so the entered address has been used");
SetErrorInfo(x.Message);
}
}
// Stored properties **/
/// <summary>
/// Write out the address result - into the Request as cookies (server side only)
/// </summary>
/// <param name="tAddressResult">FormattedAddress</param>
protected void SetAddressResult(FormattedAddress tAddressResult)
{
Request.Cookies.Remove(Constants.FIELD_ADDRESS_LINES);
foreach (AddressLine tLine in tAddressResult.AddressLines)
{
Request.Cookies.Add(new HttpCookie(Constants.FIELD_ADDRESS_LINES, tLine.Line));
}
AddAddressWarnings(tAddressResult);
}
/// <summary>
/// Write out the address result - into the Request as cookies (server side only)
/// </summary>
/// <param name="asAddress">string[]</param>
protected void SetAddressResult(string[] asAddress)
{
Request.Cookies.Remove(Constants.FIELD_ADDRESS_LINES);
foreach (string sLine in asAddress)
{
Request.Cookies.Add(new HttpCookie(Constants.FIELD_ADDRESS_LINES, sLine));
}
}
/// <summary>
/// Gets the display name of the Country in use (i.e. Australia)
/// </summary>
/// <returns>string</returns>
protected string GetCountry()
{
return Request[Constants.FIELD_COUNTRY_NAME];
}
/// <summary>
/// Country display name (i.e. Australia)
/// </summary>
/// <param name="sCountry">string</param>
protected void SetCountry(string sCountry)
{
Request.Cookies.Set(new HttpCookie(Constants.FIELD_COUNTRY_NAME, sCountry));
}
/// <summary>
/// Error information returned through the exception
/// </summary>
/// <param name="sErrorInfo">string</param>
protected void SetErrorInfo(string sErrorInfo)
{
Request.Cookies.Set(new HttpCookie(Constants.FIELD_ERROR_INFO, sErrorInfo));
}
/// <summary>
/// Gets entered address to check
/// </summary>
protected string GetSearch
{
get
{
string[] values = Request.Form.GetValues(Constants.FIELD_INPUT_LINES);
if (values != null)
{
StringBuilder search = new StringBuilder();
foreach (string line in values)
{
search.Append(line);
search.Append(',');
}
return search.ToString();
}
else
{
return string.Empty;
}
}
}
protected string[] GetInputAddress
{
get
{
if (m_asInputAddress == null)
{
m_asInputAddress = Request.Form.GetValues(Constants.FIELD_INPUT_LINES);
}
return m_asInputAddress;
}
}
/// <summary>
/// Gets moniker of the final address
/// </summary>
/// <returns>string</returns>
protected string GetMoniker()
{
return Request[Constants.FIELD_MONIKER];
}
/// <summary>
/// Get the state of the verification searching
/// </summary>
/// <returns>string</returns>
protected string GetAddressInfo()
{
return Request[Constants.FIELD_ADDRESS_INFO];
}
/// <summary>
/// Get the address information, HTML transformed
/// </summary>
/// <returns>string</returns>
protected string GetAddressInfoHTML()
{
return GetAddressInfo().Replace("\n", "<br />");
}
/// <summary>
/// Set the state of the verification searching
/// </summary>
/// <param name="sAddressInfo">string</param>
protected void SetAddressInfo(string sAddressInfo)
{
Request.Cookies.Set(new HttpCookie(Constants.FIELD_ADDRESS_INFO, sAddressInfo));
}
/// <summary>
/// Add formatted address warnings to the address info
/// </summary>
/// <param name="tAddressResult">FormattedAddress</param>
protected void AddAddressWarnings(FormattedAddress tAddressResult)
{
if (tAddressResult.IsOverflow)
{
SetAddressInfo(GetAddressInfo() + "\nWarning: Address has overflowed the layout – elements lost");
}
if (tAddressResult.IsTruncated)
{
SetAddressInfo(GetAddressInfo() + "\nWarning: Address elements have been truncated");
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnTrzPre class.
/// </summary>
[Serializable]
public partial class PnTrzPreCollection : ActiveList<PnTrzPre, PnTrzPreCollection>
{
public PnTrzPreCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnTrzPreCollection</returns>
public PnTrzPreCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnTrzPre o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_trz_pres table.
/// </summary>
[Serializable]
public partial class PnTrzPre : ActiveRecord<PnTrzPre>, IActiveRecord
{
#region .ctors and Default Settings
public PnTrzPre()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnTrzPre(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnTrzPre(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnTrzPre(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_trz_pres", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdTrzPres = new TableSchema.TableColumn(schema);
colvarIdTrzPres.ColumnName = "id_trz_pres";
colvarIdTrzPres.DataType = DbType.Int32;
colvarIdTrzPres.MaxLength = 0;
colvarIdTrzPres.AutoIncrement = true;
colvarIdTrzPres.IsNullable = false;
colvarIdTrzPres.IsPrimaryKey = true;
colvarIdTrzPres.IsForeignKey = false;
colvarIdTrzPres.IsReadOnly = false;
colvarIdTrzPres.DefaultSetting = @"";
colvarIdTrzPres.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTrzPres);
TableSchema.TableColumn colvarTextoBoton = new TableSchema.TableColumn(schema);
colvarTextoBoton.ColumnName = "texto_boton";
colvarTextoBoton.DataType = DbType.AnsiString;
colvarTextoBoton.MaxLength = -1;
colvarTextoBoton.AutoIncrement = false;
colvarTextoBoton.IsNullable = false;
colvarTextoBoton.IsPrimaryKey = false;
colvarTextoBoton.IsForeignKey = false;
colvarTextoBoton.IsReadOnly = false;
colvarTextoBoton.DefaultSetting = @"";
colvarTextoBoton.ForeignKeyTableName = "";
schema.Columns.Add(colvarTextoBoton);
TableSchema.TableColumn colvarTrzVincula = new TableSchema.TableColumn(schema);
colvarTrzVincula.ColumnName = "trz_vincula";
colvarTrzVincula.DataType = DbType.AnsiString;
colvarTrzVincula.MaxLength = -1;
colvarTrzVincula.AutoIncrement = false;
colvarTrzVincula.IsNullable = false;
colvarTrzVincula.IsPrimaryKey = false;
colvarTrzVincula.IsForeignKey = false;
colvarTrzVincula.IsReadOnly = false;
colvarTrzVincula.DefaultSetting = @"";
colvarTrzVincula.ForeignKeyTableName = "";
schema.Columns.Add(colvarTrzVincula);
TableSchema.TableColumn colvarPaginaDestino = new TableSchema.TableColumn(schema);
colvarPaginaDestino.ColumnName = "pagina_destino";
colvarPaginaDestino.DataType = DbType.AnsiString;
colvarPaginaDestino.MaxLength = -1;
colvarPaginaDestino.AutoIncrement = false;
colvarPaginaDestino.IsNullable = false;
colvarPaginaDestino.IsPrimaryKey = false;
colvarPaginaDestino.IsForeignKey = false;
colvarPaginaDestino.IsReadOnly = false;
colvarPaginaDestino.DefaultSetting = @"";
colvarPaginaDestino.ForeignKeyTableName = "";
schema.Columns.Add(colvarPaginaDestino);
TableSchema.TableColumn colvarParamPaginaDestino = new TableSchema.TableColumn(schema);
colvarParamPaginaDestino.ColumnName = "param_pagina_destino";
colvarParamPaginaDestino.DataType = DbType.AnsiString;
colvarParamPaginaDestino.MaxLength = -1;
colvarParamPaginaDestino.AutoIncrement = false;
colvarParamPaginaDestino.IsNullable = false;
colvarParamPaginaDestino.IsPrimaryKey = false;
colvarParamPaginaDestino.IsForeignKey = false;
colvarParamPaginaDestino.IsReadOnly = false;
colvarParamPaginaDestino.DefaultSetting = @"";
colvarParamPaginaDestino.ForeignKeyTableName = "";
schema.Columns.Add(colvarParamPaginaDestino);
TableSchema.TableColumn colvarObligaEfector = new TableSchema.TableColumn(schema);
colvarObligaEfector.ColumnName = "obliga_efector";
colvarObligaEfector.DataType = DbType.AnsiStringFixedLength;
colvarObligaEfector.MaxLength = 1;
colvarObligaEfector.AutoIncrement = false;
colvarObligaEfector.IsNullable = false;
colvarObligaEfector.IsPrimaryKey = false;
colvarObligaEfector.IsForeignKey = false;
colvarObligaEfector.IsReadOnly = false;
colvarObligaEfector.DefaultSetting = @"";
colvarObligaEfector.ForeignKeyTableName = "";
schema.Columns.Add(colvarObligaEfector);
TableSchema.TableColumn colvarPracticaVincula = new TableSchema.TableColumn(schema);
colvarPracticaVincula.ColumnName = "practica_vincula";
colvarPracticaVincula.DataType = DbType.AnsiStringFixedLength;
colvarPracticaVincula.MaxLength = 5;
colvarPracticaVincula.AutoIncrement = false;
colvarPracticaVincula.IsNullable = true;
colvarPracticaVincula.IsPrimaryKey = false;
colvarPracticaVincula.IsForeignKey = false;
colvarPracticaVincula.IsReadOnly = false;
colvarPracticaVincula.DefaultSetting = @"";
colvarPracticaVincula.ForeignKeyTableName = "";
schema.Columns.Add(colvarPracticaVincula);
TableSchema.TableColumn colvarObjPrestacionVincula = new TableSchema.TableColumn(schema);
colvarObjPrestacionVincula.ColumnName = "obj_prestacion_vincula";
colvarObjPrestacionVincula.DataType = DbType.AnsiStringFixedLength;
colvarObjPrestacionVincula.MaxLength = 5;
colvarObjPrestacionVincula.AutoIncrement = false;
colvarObjPrestacionVincula.IsNullable = false;
colvarObjPrestacionVincula.IsPrimaryKey = false;
colvarObjPrestacionVincula.IsForeignKey = false;
colvarObjPrestacionVincula.IsReadOnly = false;
colvarObjPrestacionVincula.DefaultSetting = @"";
colvarObjPrestacionVincula.ForeignKeyTableName = "";
schema.Columns.Add(colvarObjPrestacionVincula);
TableSchema.TableColumn colvarDiagnostico = new TableSchema.TableColumn(schema);
colvarDiagnostico.ColumnName = "diagnostico";
colvarDiagnostico.DataType = DbType.AnsiStringFixedLength;
colvarDiagnostico.MaxLength = 5;
colvarDiagnostico.AutoIncrement = false;
colvarDiagnostico.IsNullable = true;
colvarDiagnostico.IsPrimaryKey = false;
colvarDiagnostico.IsForeignKey = false;
colvarDiagnostico.IsReadOnly = false;
colvarDiagnostico.DefaultSetting = @"";
colvarDiagnostico.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiagnostico);
TableSchema.TableColumn colvarGrupoEtareo = new TableSchema.TableColumn(schema);
colvarGrupoEtareo.ColumnName = "grupo_etareo";
colvarGrupoEtareo.DataType = DbType.AnsiString;
colvarGrupoEtareo.MaxLength = -1;
colvarGrupoEtareo.AutoIncrement = false;
colvarGrupoEtareo.IsNullable = false;
colvarGrupoEtareo.IsPrimaryKey = false;
colvarGrupoEtareo.IsForeignKey = false;
colvarGrupoEtareo.IsReadOnly = false;
colvarGrupoEtareo.DefaultSetting = @"";
colvarGrupoEtareo.ForeignKeyTableName = "";
schema.Columns.Add(colvarGrupoEtareo);
TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema);
colvarSexo.ColumnName = "sexo";
colvarSexo.DataType = DbType.AnsiStringFixedLength;
colvarSexo.MaxLength = 1;
colvarSexo.AutoIncrement = false;
colvarSexo.IsNullable = false;
colvarSexo.IsPrimaryKey = false;
colvarSexo.IsForeignKey = false;
colvarSexo.IsReadOnly = false;
colvarSexo.DefaultSetting = @"";
colvarSexo.ForeignKeyTableName = "";
schema.Columns.Add(colvarSexo);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_trz_pres",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdTrzPres")]
[Bindable(true)]
public int IdTrzPres
{
get { return GetColumnValue<int>(Columns.IdTrzPres); }
set { SetColumnValue(Columns.IdTrzPres, value); }
}
[XmlAttribute("TextoBoton")]
[Bindable(true)]
public string TextoBoton
{
get { return GetColumnValue<string>(Columns.TextoBoton); }
set { SetColumnValue(Columns.TextoBoton, value); }
}
[XmlAttribute("TrzVincula")]
[Bindable(true)]
public string TrzVincula
{
get { return GetColumnValue<string>(Columns.TrzVincula); }
set { SetColumnValue(Columns.TrzVincula, value); }
}
[XmlAttribute("PaginaDestino")]
[Bindable(true)]
public string PaginaDestino
{
get { return GetColumnValue<string>(Columns.PaginaDestino); }
set { SetColumnValue(Columns.PaginaDestino, value); }
}
[XmlAttribute("ParamPaginaDestino")]
[Bindable(true)]
public string ParamPaginaDestino
{
get { return GetColumnValue<string>(Columns.ParamPaginaDestino); }
set { SetColumnValue(Columns.ParamPaginaDestino, value); }
}
[XmlAttribute("ObligaEfector")]
[Bindable(true)]
public string ObligaEfector
{
get { return GetColumnValue<string>(Columns.ObligaEfector); }
set { SetColumnValue(Columns.ObligaEfector, value); }
}
[XmlAttribute("PracticaVincula")]
[Bindable(true)]
public string PracticaVincula
{
get { return GetColumnValue<string>(Columns.PracticaVincula); }
set { SetColumnValue(Columns.PracticaVincula, value); }
}
[XmlAttribute("ObjPrestacionVincula")]
[Bindable(true)]
public string ObjPrestacionVincula
{
get { return GetColumnValue<string>(Columns.ObjPrestacionVincula); }
set { SetColumnValue(Columns.ObjPrestacionVincula, value); }
}
[XmlAttribute("Diagnostico")]
[Bindable(true)]
public string Diagnostico
{
get { return GetColumnValue<string>(Columns.Diagnostico); }
set { SetColumnValue(Columns.Diagnostico, value); }
}
[XmlAttribute("GrupoEtareo")]
[Bindable(true)]
public string GrupoEtareo
{
get { return GetColumnValue<string>(Columns.GrupoEtareo); }
set { SetColumnValue(Columns.GrupoEtareo, value); }
}
[XmlAttribute("Sexo")]
[Bindable(true)]
public string Sexo
{
get { return GetColumnValue<string>(Columns.Sexo); }
set { SetColumnValue(Columns.Sexo, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varTextoBoton,string varTrzVincula,string varPaginaDestino,string varParamPaginaDestino,string varObligaEfector,string varPracticaVincula,string varObjPrestacionVincula,string varDiagnostico,string varGrupoEtareo,string varSexo)
{
PnTrzPre item = new PnTrzPre();
item.TextoBoton = varTextoBoton;
item.TrzVincula = varTrzVincula;
item.PaginaDestino = varPaginaDestino;
item.ParamPaginaDestino = varParamPaginaDestino;
item.ObligaEfector = varObligaEfector;
item.PracticaVincula = varPracticaVincula;
item.ObjPrestacionVincula = varObjPrestacionVincula;
item.Diagnostico = varDiagnostico;
item.GrupoEtareo = varGrupoEtareo;
item.Sexo = varSexo;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdTrzPres,string varTextoBoton,string varTrzVincula,string varPaginaDestino,string varParamPaginaDestino,string varObligaEfector,string varPracticaVincula,string varObjPrestacionVincula,string varDiagnostico,string varGrupoEtareo,string varSexo)
{
PnTrzPre item = new PnTrzPre();
item.IdTrzPres = varIdTrzPres;
item.TextoBoton = varTextoBoton;
item.TrzVincula = varTrzVincula;
item.PaginaDestino = varPaginaDestino;
item.ParamPaginaDestino = varParamPaginaDestino;
item.ObligaEfector = varObligaEfector;
item.PracticaVincula = varPracticaVincula;
item.ObjPrestacionVincula = varObjPrestacionVincula;
item.Diagnostico = varDiagnostico;
item.GrupoEtareo = varGrupoEtareo;
item.Sexo = varSexo;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdTrzPresColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn TextoBotonColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn TrzVinculaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn PaginaDestinoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn ParamPaginaDestinoColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ObligaEfectorColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn PracticaVinculaColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn ObjPrestacionVinculaColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn DiagnosticoColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn GrupoEtareoColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn SexoColumn
{
get { return Schema.Columns[10]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdTrzPres = @"id_trz_pres";
public static string TextoBoton = @"texto_boton";
public static string TrzVincula = @"trz_vincula";
public static string PaginaDestino = @"pagina_destino";
public static string ParamPaginaDestino = @"param_pagina_destino";
public static string ObligaEfector = @"obliga_efector";
public static string PracticaVincula = @"practica_vincula";
public static string ObjPrestacionVincula = @"obj_prestacion_vincula";
public static string Diagnostico = @"diagnostico";
public static string GrupoEtareo = @"grupo_etareo";
public static string Sexo = @"sexo";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Win32;
using System.IO;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.InteropServices;
namespace EPocalipse.IFilter
{
/// <summary>
/// FilterLoader finds the dll and ClassID of the COM object responsible
/// for filtering a specific file extension.
/// It then loads that dll, creates the appropriate COM object and returns
/// a pointer to an IFilter instance
/// </summary>
static class FilterLoader
{
#region CacheEntry
private class CacheEntry
{
public string DllName;
public string ClassName;
public CacheEntry(string dllName, string className)
{
DllName = dllName;
ClassName = className;
}
}
#endregion
static Dictionary<string, CacheEntry> _cache = new Dictionary<string, CacheEntry>();
#region Registry Read String helper
static string ReadStrFromHKLM(string key)
{
return ReadStrFromHKLM(key, null);
}
static string ReadStrFromHKLM(string key, string value)
{
RegistryKey rk = Registry.LocalMachine.OpenSubKey(key);
if (rk == null)
{
var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
rk = hklm.OpenSubKey(key);
if (rk == null)
{
return null;
}
}
using (rk)
{
return (string)rk.GetValue(value);
}
}
#endregion
/// <summary>
/// finds an IFilter implementation for a file type
/// </summary>
/// <param name="ext">The extension of the file</param>
/// <returns>an IFilter instance used to retreive text from that file type</returns>
private static IFilter LoadIFilter(string ext)
{
string dllName, filterPersistClass;
//Find the dll and ClassID
if (GetFilterDllAndClass(ext, out dllName, out filterPersistClass))
{
//load the dll and return an IFilter instance.
return LoadFilterFromDll(dllName, filterPersistClass);
}
return null;
}
internal static IFilter LoadAndInitIFilter(string fileName)
{
return LoadAndInitIFilter(fileName, Path.GetExtension(fileName));
}
internal static IFilter LoadAndInitIFilter(string fileName, string extension)
{
IFilter filter = LoadIFilter(extension);
if (filter == null)
return null;
IPersistFile persistFile = (filter as IPersistFile);
if (persistFile != null)
{
persistFile.Load(fileName, 0);
IFILTER_FLAGS flags;
IFILTER_INIT iflags =
IFILTER_INIT.CANON_HYPHENS |
IFILTER_INIT.CANON_PARAGRAPHS |
IFILTER_INIT.CANON_SPACES |
IFILTER_INIT.APPLY_INDEX_ATTRIBUTES |
IFILTER_INIT.HARD_LINE_BREAKS |
IFILTER_INIT.FILTER_OWNED_VALUE_OK;
if (filter.Init(iflags, 0, IntPtr.Zero, out flags) == IFilterReturnCode.S_OK)
return filter;
}
//If we failed to retreive an IPersistFile interface or to initialize
//the filter, we release it and return null.
Marshal.ReleaseComObject(filter);
return null;
}
private static IFilter LoadFilterFromDll(string dllName, string filterPersistClass)
{
//Get a classFactory for our classID
IClassFactory classFactory = ComHelper.GetClassFactory(dllName, filterPersistClass);
if (classFactory == null)
return null;
//And create an IFilter instance using that class factory
Guid IFilterGUID = new Guid("89BCB740-6119-101A-BCB7-00DD010655AF");
Object obj;
classFactory.CreateInstance(null, ref IFilterGUID, out obj);
return (obj as IFilter);
}
private static bool GetFilterDllAndClass(string ext, out string dllName, out string filterPersistClass)
{
if (!GetFilterDllAndClassFromCache(ext, out dllName, out filterPersistClass))
{
string persistentHandlerClass;
persistentHandlerClass = GetPersistentHandlerClass(ext, true);
if (persistentHandlerClass != null)
{
GetFilterDllAndClassFromPersistentHandler(persistentHandlerClass,
out dllName, out filterPersistClass);
}
AddExtensionToCache(ext, dllName, filterPersistClass);
}
return (dllName != null && filterPersistClass != null);
}
private static void AddExtensionToCache(string ext, string dllName, string filterPersistClass)
{
lock (_cache)
{
_cache.Add(ext.ToLower(), new CacheEntry(dllName, filterPersistClass));
}
}
private static bool GetFilterDllAndClassFromPersistentHandler(string persistentHandlerClass, out string dllName, out string filterPersistClass)
{
dllName = null;
filterPersistClass = null;
//Read the CLASS ID of the IFilter persistent handler
filterPersistClass = ReadStrFromHKLM(@"Software\Classes\CLSID\" + persistentHandlerClass +
@"\PersistentAddinsRegistered\{89BCB740-6119-101A-BCB7-00DD010655AF}");
if (String.IsNullOrEmpty(filterPersistClass))
return false;
//Read the dll name
dllName = ReadStrFromHKLM(@"Software\Classes\CLSID\" + filterPersistClass +
@"\InprocServer32");
return (!String.IsNullOrEmpty(dllName));
}
private static string GetPersistentHandlerClass(string ext, bool searchContentType)
{
//Try getting the info from the file extension
string persistentHandlerClass = GetPersistentHandlerClassFromExtension(ext);
if (String.IsNullOrEmpty(persistentHandlerClass))
//try getting the info from the document type
persistentHandlerClass = GetPersistentHandlerClassFromDocumentType(ext);
if (searchContentType && String.IsNullOrEmpty(persistentHandlerClass))
//Try getting the info from the Content Type
persistentHandlerClass = GetPersistentHandlerClassFromContentType(ext);
return persistentHandlerClass;
}
private static string GetPersistentHandlerClassFromContentType(string ext)
{
string contentType = ReadStrFromHKLM(@"Software\Classes\" + ext, "Content Type");
if (String.IsNullOrEmpty(contentType))
return null;
string contentTypeExtension = ReadStrFromHKLM(@"Software\Classes\MIME\Database\Content Type\" + contentType,
"Extension");
if (ext.Equals(contentTypeExtension, StringComparison.CurrentCultureIgnoreCase))
return null; //No need to look further. This extension does not have any persistent handler
//We know the extension that is assciated with that content type. Simply try again with the new extension
return GetPersistentHandlerClass(contentTypeExtension, false); //Don't search content type this time.
}
private static string GetPersistentHandlerClassFromDocumentType(string ext)
{
//Get the DocumentType of this file extension
string docType = ReadStrFromHKLM(@"Software\Classes\" + ext);
if (String.IsNullOrEmpty(docType))
return null;
//Get the Class ID for this document type
string docClass = ReadStrFromHKLM(@"Software\Classes\" + docType + @"\CLSID");
if (String.IsNullOrEmpty(docType))
return null;
//Now get the PersistentHandler for that Class ID
return ReadStrFromHKLM(@"Software\Classes\CLSID\" + docClass + @"\PersistentHandler");
}
private static string GetPersistentHandlerClassFromExtension(string ext)
{
return ReadStrFromHKLM(@"Software\Classes\" + ext + @"\PersistentHandler");
}
private static bool GetFilterDllAndClassFromCache(string ext, out string dllName, out string filterPersistClass)
{
string lowerExt = ext.ToLower();
lock (_cache)
{
CacheEntry cacheEntry;
if (_cache.TryGetValue(lowerExt, out cacheEntry))
{
dllName = cacheEntry.DllName;
filterPersistClass = cacheEntry.ClassName;
return true;
}
}
dllName = null;
filterPersistClass = null;
return false;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SortedList
**
** <OWNER>[....]</OWNER>
**
** Purpose: A sorted dictionary.
**
**
===========================================================*/
namespace System.Collections {
using System;
using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
// The SortedList class implements a sorted list of keys and values. Entries in
// a sorted list are sorted by their keys and are accessible both by key and by
// index. The keys of a sorted list can be ordered either according to a
// specific IComparer implementation given when the sorted list is
// instantiated, or according to the IComparable implementation provided
// by the keys themselves. In either case, a sorted list does not allow entries
// with duplicate keys.
//
// A sorted list internally maintains two arrays that store the keys and
// values of the entries. The capacity of a sorted list is the allocated
// length of these internal arrays. As elements are added to a sorted list, the
// capacity of the sorted list is automatically increased as required by
// reallocating the internal arrays. The capacity is never automatically
// decreased, but users can call either TrimToSize or
// Capacity explicitly.
//
// The GetKeyList and GetValueList methods of a sorted list
// provides access to the keys and values of the sorted list in the form of
// List implementations. The List objects returned by these
// methods are aliases for the underlying sorted list, so modifications
// made to those lists are directly reflected in the sorted list, and vice
// versa.
//
// The SortedList class provides a convenient way to create a sorted
// copy of another dictionary, such as a Hashtable. For example:
//
// Hashtable h = new Hashtable();
// h.Add(...);
// h.Add(...);
// ...
// SortedList s = new SortedList(h);
//
// The last line above creates a sorted list that contains a copy of the keys
// and values stored in the hashtable. In this particular example, the keys
// will be ordered according to the IComparable interface, which they
// all must implement. To impose a different ordering, SortedList also
// has a constructor that allows a specific IComparer implementation to
// be specified.
//
[DebuggerTypeProxy(typeof(System.Collections.SortedList.SortedListDebugView))]
[DebuggerDisplay("Count = {Count}")]
[System.Runtime.InteropServices.ComVisible(true)]
#if FEATURE_CORECLR
[Obsolete("Non-generic collections have been deprecated. Please use collections in System.Collections.Generic.")]
#endif
[Serializable]
public class SortedList : IDictionary, ICloneable
{
private Object[] keys;
private Object[] values;
private int _size;
private int version;
private IComparer comparer;
private KeyList keyList;
private ValueList valueList;
[NonSerialized]
private Object _syncRoot;
private const int _defaultCapacity = 16;
private static Object[] emptyArray = EmptyArray<Object>.Value;
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
public SortedList() {
Init();
}
private void Init()
{
keys = emptyArray;
values = emptyArray;
_size = 0;
comparer = new Comparer(CultureInfo.CurrentCulture);
}
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
//
public SortedList(int initialCapacity) {
if (initialCapacity < 0)
throw new ArgumentOutOfRangeException("initialCapacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
keys = new Object[initialCapacity];
values = new Object[initialCapacity];
comparer = new Comparer(CultureInfo.CurrentCulture);
}
// Constructs a new sorted list with a given IComparer
// implementation. The sorted list is initially empty and has a capacity of
// zero. Upon adding the first element to the sorted list the capacity is
// increased to 16, and then increased in multiples of two as required. The
// elements of the sorted list are ordered according to the given
// IComparer implementation. If comparer is null, the
// elements are compared to each other using the IComparable
// interface, which in that case must be implemented by the keys of all
// entries added to the sorted list.
//
public SortedList(IComparer comparer)
: this() {
if (comparer != null) this.comparer = comparer;
}
// Constructs a new sorted list with a given IComparer
// implementation and a given initial capacity. The sorted list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required. The elements of the sorted list
// are ordered according to the given IComparer implementation. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by the keys of all entries added to the sorted list.
//
public SortedList(IComparer comparer, int capacity)
: this(comparer) {
Capacity = capacity;
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the IComparable interface, which must be implemented by the
// keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary d)
: this(d, null) {
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the given IComparer implementation. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented
// by the keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary d, IComparer comparer)
: this(comparer, (d != null ? d.Count : 0)) {
if (d==null)
throw new ArgumentNullException("d", Environment.GetResourceString("ArgumentNull_Dictionary"));
Contract.EndContractBlock();
d.Keys.CopyTo(keys, 0);
d.Values.CopyTo(values, 0);
Array.Sort(keys, values, comparer);
_size = d.Count;
}
// Adds an entry with the given key and value to this sorted list. An
// ArgumentException is thrown if the key is already present in the sorted list.
//
public virtual void Add(Object key, Object value) {
if (key == null) throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
Contract.EndContractBlock();
int i = Array.BinarySearch(keys, 0, _size, key, comparer);
if (i >= 0)
throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", GetKey(i), key));
Insert(~i, key, value);
}
// Returns the capacity of this sorted list. The capacity of a sorted list
// represents the allocated length of the internal arrays used to store the
// keys and values of the list, and thus also indicates the maximum number
// of entries the list can contain before a reallocation of the internal
// arrays is required.
//
public virtual int Capacity {
get {
return keys.Length;
}
set {
if (value < Count) {
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
Contract.EndContractBlock();
if (value != keys.Length) {
if (value > 0) {
Object[] newKeys = new Object[value];
Object[] newValues = new Object[value];
if (_size > 0) {
Array.Copy(keys, 0, newKeys, 0, _size);
Array.Copy(values, 0, newValues, 0, _size);
}
keys = newKeys;
values = newValues;
}
else {
// size can only be zero here.
Contract.Assert( _size == 0, "Size is not zero");
keys = emptyArray;
values = emptyArray;
}
}
}
}
// Returns the number of entries in this sorted list.
//
public virtual int Count {
get {
return _size;
}
}
// Returns a collection representing the keys of this sorted list. This
// method returns the same object as GetKeyList, but typed as an
// ICollection instead of an IList.
//
public virtual ICollection Keys {
get {
return GetKeyList();
}
}
// Returns a collection representing the values of this sorted list. This
// method returns the same object as GetValueList, but typed as an
// ICollection instead of an IList.
//
public virtual ICollection Values {
get {
return GetValueList();
}
}
// Is this SortedList read-only?
public virtual bool IsReadOnly {
get { return false; }
}
public virtual bool IsFixedSize {
get { return false; }
}
// Is this SortedList synchronized (thread-safe)?
public virtual bool IsSynchronized {
get { return false; }
}
// Synchronization root for this object.
public virtual Object SyncRoot {
get {
if( _syncRoot == null) {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all entries from this sorted list.
public virtual void Clear() {
// clear does not change the capacity
version++;
Array.Clear(keys, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
Array.Clear(values, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
}
// Makes a virtually identical copy of this SortedList. This is a shallow
// copy. IE, the Objects in the SortedList are not cloned - we copy the
// references to those objects.
public virtual Object Clone()
{
SortedList sl = new SortedList(_size);
Array.Copy(keys, 0, sl.keys, 0, _size);
Array.Copy(values, 0, sl.values, 0, _size);
sl._size = _size;
sl.version = version;
sl.comparer = comparer;
// Don't copy keyList nor valueList.
return sl;
}
// Checks if this sorted list contains an entry with the given key.
//
public virtual bool Contains(Object key) {
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given key.
//
public virtual bool ContainsKey(Object key) {
// Yes, this is a SPEC'ed duplicate of Contains().
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given value. The
// values of the entries of the sorted list are compared to the given value
// using the Object.Equals method. This method performs a linear
// search and is substantially slower than the Contains
// method.
//
public virtual bool ContainsValue(Object value) {
return IndexOfValue(value) >= 0;
}
// Copies the values in this SortedList to an array.
public virtual void CopyTo(Array array, int arrayIndex) {
if (array == null)
throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Array"));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - arrayIndex < Count)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
Contract.EndContractBlock();
for (int i = 0; i<Count; i++) {
DictionaryEntry entry = new DictionaryEntry(keys[i],values[i]);
array.SetValue(entry, i + arrayIndex);
}
}
// Copies the values in this SortedList to an KeyValuePairs array.
// KeyValuePairs is different from Dictionary Entry in that it has special
// debugger attributes on its fields.
internal virtual KeyValuePairs[] ToKeyValuePairsArray() {
KeyValuePairs[] array = new KeyValuePairs[Count];
for (int i = 0; i < Count; i++) {
array[i] = new KeyValuePairs(keys[i],values[i]);
}
return array;
}
// Ensures that the capacity of this sorted list is at least the given
// minimum value. If the currect capacity of the list is less than
// min, the capacity is increased to twice the current capacity or
// to min, whichever is larger.
private void EnsureCapacity(int min) {
int newCapacity = keys.Length == 0? 16: keys.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
// Returns the value of the entry at the given index.
//
public virtual Object GetByIndex(int index) {
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return values[index];
}
// Returns an IEnumerator for this sorted list. If modifications
// made to the sorted list while an enumeration is in progress,
// the MoveNext and Remove methods
// of the enumerator will throw an exception.
//
IEnumerator IEnumerable.GetEnumerator() {
return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry);
}
// Returns an IDictionaryEnumerator for this sorted list. If modifications
// made to the sorted list while an enumeration is in progress,
// the MoveNext and Remove methods
// of the enumerator will throw an exception.
//
public virtual IDictionaryEnumerator GetEnumerator() {
return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry);
}
// Returns the key of the entry at the given index.
//
public virtual Object GetKey(int index) {
if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return keys[index];
}
// Returns an IList representing the keys of this sorted list. The
// returned list is an alias for the keys of this sorted list, so
// modifications made to the returned list are directly reflected in the
// underlying sorted list, and vice versa. The elements of the returned
// list are ordered in the same way as the elements of the sorted list. The
// returned list does not support adding, inserting, or modifying elements
// (the Add, AddRange, Insert, InsertRange,
// Reverse, Set, SetRange, and Sort methods
// throw exceptions), but it does allow removal of elements (through the
// Remove and RemoveRange methods or through an enumerator).
// Null is an invalid key value.
//
public virtual IList GetKeyList() {
if (keyList == null) keyList = new KeyList(this);
return keyList;
}
// Returns an IList representing the values of this sorted list. The
// returned list is an alias for the values of this sorted list, so
// modifications made to the returned list are directly reflected in the
// underlying sorted list, and vice versa. The elements of the returned
// list are ordered in the same way as the elements of the sorted list. The
// returned list does not support adding or inserting elements (the
// Add, AddRange, Insert and InsertRange
// methods throw exceptions), but it does allow modification and removal of
// elements (through the Remove, RemoveRange, Set and
// SetRange methods or through an enumerator).
//
public virtual IList GetValueList() {
if (valueList == null) valueList = new ValueList(this);
return valueList;
}
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
//
public virtual Object this[Object key] {
get {
int i = IndexOfKey(key);
if (i >= 0) return values[i];
return null;
}
set {
if (key == null) throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
Contract.EndContractBlock();
int i = Array.BinarySearch(keys, 0, _size, key, comparer);
if (i >= 0) {
values[i] = value;
version++;
return;
}
Insert(~i, key, value);
}
}
// Returns the index of the entry with a given key in this sorted list. The
// key is located through a binary search, and thus the average execution
// time of this method is proportional to Log2(size), where
// size is the size of this sorted list. The returned value is -1 if
// the given key does not occur in this sorted list. Null is an invalid
// key value.
//
public virtual int IndexOfKey(Object key) {
if (key == null)
throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
Contract.EndContractBlock();
int ret = Array.BinarySearch(keys, 0, _size, key, comparer);
return ret >=0 ? ret : -1;
}
// Returns the index of the first occurrence of an entry with a given value
// in this sorted list. The entry is located through a linear search, and
// thus the average execution time of this method is proportional to the
// size of this sorted list. The elements of the list are compared to the
// given value using the Object.Equals method.
//
public virtual int IndexOfValue(Object value) {
return Array.IndexOf(values, value, 0, _size);
}
// Inserts an entry with a given key and value at a given index.
private void Insert(int index, Object key, Object value) {
if (_size == keys.Length) EnsureCapacity(_size + 1);
if (index < _size) {
Array.Copy(keys, index, keys, index + 1, _size - index);
Array.Copy(values, index, values, index + 1, _size - index);
}
keys[index] = key;
values[index] = value;
_size++;
version++;
}
// Removes the entry at the given index. The size of the sorted list is
// decreased by one.
//
public virtual void RemoveAt(int index) {
if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
_size--;
if (index < _size) {
Array.Copy(keys, index + 1, keys, index, _size - index);
Array.Copy(values, index + 1, values, index, _size - index);
}
keys[_size] = null;
values[_size] = null;
version++;
}
// Removes an entry from this sorted list. If an entry with the specified
// key exists in the sorted list, it is removed. An ArgumentException is
// thrown if the key is null.
//
public virtual void Remove(Object key) {
int i = IndexOfKey(key);
if (i >= 0)
RemoveAt(i);
}
// Sets the value at an index to a given value. The previous value of
// the given entry is overwritten.
//
public virtual void SetByIndex(int index, Object value) {
if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
values[index] = value;
version++;
}
// Returns a thread-safe SortedList.
//
[HostProtection(Synchronization=true)]
public static SortedList Synchronized(SortedList list) {
if (list==null)
throw new ArgumentNullException("list");
Contract.EndContractBlock();
return new SyncSortedList(list);
}
// Sets the capacity of this sorted list to the size of the sorted list.
// This method can be used to minimize a sorted list's memory overhead once
// it is known that no new elements will be added to the sorted list. To
// completely clear a sorted list and release all memory referenced by the
// sorted list, execute the following statements:
//
// sortedList.Clear();
// sortedList.TrimToSize();
//
public virtual void TrimToSize() {
Capacity = _size;
}
[Serializable]
private class SyncSortedList : SortedList
{
private SortedList _list;
private Object _root;
internal SyncSortedList(SortedList list) {
_list = list;
_root = list.SyncRoot;
}
public override int Count {
get { lock(_root) { return _list.Count; } }
}
public override Object SyncRoot {
get { return _root; }
}
public override bool IsReadOnly {
get { return _list.IsReadOnly; }
}
public override bool IsFixedSize {
get { return _list.IsFixedSize; }
}
public override bool IsSynchronized {
get { return true; }
}
public override Object this[Object key] {
get {
lock(_root) {
return _list[key];
}
}
set {
lock(_root) {
_list[key] = value;
}
}
}
public override void Add(Object key, Object value) {
lock(_root) {
_list.Add(key, value);
}
}
public override int Capacity {
get{ lock(_root) { return _list.Capacity; } }
}
public override void Clear() {
lock(_root) {
_list.Clear();
}
}
public override Object Clone() {
lock(_root) {
return _list.Clone();
}
}
public override bool Contains(Object key) {
lock(_root) {
return _list.Contains(key);
}
}
public override bool ContainsKey(Object key) {
lock(_root) {
return _list.ContainsKey(key);
}
}
public override bool ContainsValue(Object key) {
lock(_root) {
return _list.ContainsValue(key);
}
}
public override void CopyTo(Array array, int index) {
lock(_root) {
_list.CopyTo(array, index);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override Object GetByIndex(int index) {
lock(_root) {
return _list.GetByIndex(index);
}
}
public override IDictionaryEnumerator GetEnumerator() {
lock(_root) {
return _list.GetEnumerator();
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override Object GetKey(int index) {
lock(_root) {
return _list.GetKey(index);
}
}
public override IList GetKeyList() {
lock(_root) {
return _list.GetKeyList();
}
}
public override IList GetValueList() {
lock(_root) {
return _list.GetValueList();
}
}
public override int IndexOfKey(Object key) {
if (key == null)
throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
Contract.EndContractBlock();
lock(_root) {
return _list.IndexOfKey(key);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int IndexOfValue(Object value) {
lock(_root) {
return _list.IndexOfValue(value);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void RemoveAt(int index) {
lock(_root) {
_list.RemoveAt(index);
}
}
public override void Remove(Object key) {
lock(_root) {
_list.Remove(key);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void SetByIndex(int index, Object value) {
lock(_root) {
_list.SetByIndex(index, value);
}
}
internal override KeyValuePairs[] ToKeyValuePairsArray() {
return _list.ToKeyValuePairsArray();
}
public override void TrimToSize() {
lock(_root) {
_list.TrimToSize();
}
}
}
[Serializable]
private class SortedListEnumerator : IDictionaryEnumerator, ICloneable
{
private SortedList sortedList;
private Object key;
private Object value;
private int index;
private int startIndex; // Store for Reset.
private int endIndex;
private int version;
private bool current; // Is the current element valid?
private int getObjectRetType; // What should GetObject return?
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictEntry = 3;
internal SortedListEnumerator(SortedList sortedList, int index, int count,
int getObjRetType) {
this.sortedList = sortedList;
this.index = index;
startIndex = index;
endIndex = index + count;
version = sortedList.version;
getObjectRetType = getObjRetType;
current = false;
}
public Object Clone()
{
return MemberwiseClone();
}
public virtual Object Key {
get {
if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
return key;
}
}
public virtual bool MoveNext() {
if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
if (index < endIndex) {
key = sortedList.keys[index];
value = sortedList.values[index];
index++;
current = true;
return true;
}
key = null;
value = null;
current = false;
return false;
}
public virtual DictionaryEntry Entry {
get {
if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
return new DictionaryEntry(key, value);
}
}
public virtual Object Current {
get {
if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
if (getObjectRetType==Keys)
return key;
else if (getObjectRetType==Values)
return value;
else
return new DictionaryEntry(key, value);
}
}
public virtual Object Value {
get {
if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
return value;
}
}
public virtual void Reset() {
if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
index = startIndex;
current = false;
key = null;
value = null;
}
}
[Serializable]
private class KeyList : IList
{
private SortedList sortedList;
internal KeyList(SortedList sortedList) {
this.sortedList = sortedList;
}
public virtual int Count {
get { return sortedList._size; }
}
public virtual bool IsReadOnly {
get { return true; }
}
public virtual bool IsFixedSize {
get { return true; }
}
public virtual bool IsSynchronized {
get { return sortedList.IsSynchronized; }
}
public virtual Object SyncRoot {
get { return sortedList.SyncRoot; }
}
public virtual int Add(Object key) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
// return 0; // suppress compiler warning
}
public virtual void Clear() {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual bool Contains(Object key) {
return sortedList.Contains(key);
}
public virtual void CopyTo(Array array, int arrayIndex) {
if (array != null && array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
Contract.EndContractBlock();
// defer error checking to Array.Copy
Array.Copy(sortedList.keys, 0, array, arrayIndex, sortedList.Count);
}
public virtual void Insert(int index, Object value) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual Object this[int index] {
get {
return sortedList.GetKey(index);
}
set {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_KeyCollectionSet"));
}
}
public virtual IEnumerator GetEnumerator() {
return new SortedListEnumerator(sortedList, 0, sortedList.Count, SortedListEnumerator.Keys);
}
public virtual int IndexOf(Object key) {
if (key==null)
throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
Contract.EndContractBlock();
int i = Array.BinarySearch(sortedList.keys, 0,
sortedList.Count, key, sortedList.comparer);
if (i >= 0) return i;
return -1;
}
public virtual void Remove(Object key) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual void RemoveAt(int index) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
}
[Serializable]
private class ValueList : IList
{
private SortedList sortedList;
internal ValueList(SortedList sortedList) {
this.sortedList = sortedList;
}
public virtual int Count {
get { return sortedList._size; }
}
public virtual bool IsReadOnly {
get { return true; }
}
public virtual bool IsFixedSize {
get { return true; }
}
public virtual bool IsSynchronized {
get { return sortedList.IsSynchronized; }
}
public virtual Object SyncRoot {
get { return sortedList.SyncRoot; }
}
public virtual int Add(Object key) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual void Clear() {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual bool Contains(Object value) {
return sortedList.ContainsValue(value);
}
public virtual void CopyTo(Array array, int arrayIndex) {
if (array != null && array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
Contract.EndContractBlock();
// defer error checking to Array.Copy
Array.Copy(sortedList.values, 0, array, arrayIndex, sortedList.Count);
}
public virtual void Insert(int index, Object value) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual Object this[int index] {
get {
return sortedList.GetByIndex(index);
}
set {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
}
public virtual IEnumerator GetEnumerator() {
return new SortedListEnumerator(sortedList, 0, sortedList.Count, SortedListEnumerator.Values);
}
public virtual int IndexOf(Object value) {
return Array.IndexOf(sortedList.values, value, 0, sortedList.Count);
}
public virtual void Remove(Object value) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual void RemoveAt(int index) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
}
// internal debug view class for sorted list
internal class SortedListDebugView {
private SortedList sortedList;
public SortedListDebugView( SortedList sortedList) {
if( sortedList == null) {
throw new ArgumentNullException("sortedList");
}
Contract.EndContractBlock();
this.sortedList = sortedList;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePairs[] Items {
get {
return sortedList.ToKeyValuePairsArray();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform;
namespace Xamarin.Forms
{
[RenderWith(typeof(_PageRenderer))]
public class Page : VisualElement, ILayout, IPageController, IElementConfiguration<Page>
{
public const string BusySetSignalName = "Xamarin.BusySet";
public const string AlertSignalName = "Xamarin.SendAlert";
public const string ActionSheetSignalName = "Xamarin.ShowActionSheet";
internal static readonly BindableProperty IgnoresContainerAreaProperty = BindableProperty.Create("IgnoresContainerArea", typeof(bool), typeof(Page), false);
public static readonly BindableProperty BackgroundImageProperty = BindableProperty.Create("BackgroundImage", typeof(string), typeof(Page), default(string));
public static readonly BindableProperty IsBusyProperty = BindableProperty.Create("IsBusy", typeof(bool), typeof(Page), false, propertyChanged: (bo, o, n) => ((Page)bo).OnPageBusyChanged());
public static readonly BindableProperty PaddingProperty = BindableProperty.Create("Padding", typeof(Thickness), typeof(Page), default(Thickness), propertyChanged: (bindable, old, newValue) =>
{
var layout = (Page)bindable;
layout.UpdateChildrenLayout();
});
public static readonly BindableProperty TitleProperty = BindableProperty.Create("Title", typeof(string), typeof(Page), null);
public static readonly BindableProperty IconProperty = BindableProperty.Create("Icon", typeof(FileImageSource), typeof(Page), default(FileImageSource));
readonly Lazy<PlatformConfigurationRegistry<Page>> _platformConfigurationRegistry;
bool _allocatedFlag;
Rectangle _containerArea;
bool _containerAreaSet;
bool _hasAppeared;
ReadOnlyCollection<Element> _logicalChildren;
IPageController PageController => this as IPageController;
IElementController ElementController => this as IElementController;
public Page()
{
var toolbarItems = new ObservableCollection<ToolbarItem>();
toolbarItems.CollectionChanged += OnToolbarItemsCollectionChanged;
ToolbarItems = toolbarItems;
PageController.InternalChildren.CollectionChanged += InternalChildrenOnCollectionChanged;
_platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<Page>>(() => new PlatformConfigurationRegistry<Page>(this));
}
public string BackgroundImage
{
get { return (string)GetValue(BackgroundImageProperty); }
set { SetValue(BackgroundImageProperty, value); }
}
public FileImageSource Icon
{
get { return (FileImageSource)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public bool IsBusy
{
get { return (bool)GetValue(IsBusyProperty); }
set { SetValue(IsBusyProperty, value); }
}
public Thickness Padding
{
get { return (Thickness)GetValue(PaddingProperty); }
set { SetValue(PaddingProperty, value); }
}
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public IList<ToolbarItem> ToolbarItems { get; internal set; }
Rectangle IPageController.ContainerArea
{
get { return _containerArea; }
set
{
if (_containerArea == value)
return;
_containerAreaSet = true;
_containerArea = value;
ForceLayout();
}
}
bool IPageController.IgnoresContainerArea
{
get { return (bool)GetValue(IgnoresContainerAreaProperty); }
set { SetValue(IgnoresContainerAreaProperty, value); }
}
ObservableCollection<Element> IPageController.InternalChildren { get; } = new ObservableCollection<Element>();
internal override ReadOnlyCollection<Element> LogicalChildrenInternal =>
_logicalChildren ?? (_logicalChildren = new ReadOnlyCollection<Element>(PageController.InternalChildren));
public event EventHandler LayoutChanged;
public event EventHandler Appearing;
public event EventHandler Disappearing;
public Task<string> DisplayActionSheet(string title, string cancel, string destruction, params string[] buttons)
{
var args = new ActionSheetArguments(title, cancel, destruction, buttons);
MessagingCenter.Send(this, ActionSheetSignalName, args);
return args.Result.Task;
}
public Task DisplayAlert(string title, string message, string cancel)
{
return DisplayAlert(title, message, null, cancel);
}
public Task<bool> DisplayAlert(string title, string message, string accept, string cancel)
{
if (string.IsNullOrEmpty(cancel))
throw new ArgumentNullException("cancel");
var args = new AlertArguments(title, message, accept, cancel);
MessagingCenter.Send(this, AlertSignalName, args);
return args.Result.Task;
}
public void ForceLayout()
{
SizeAllocated(Width, Height);
}
public bool SendBackButtonPressed()
{
return OnBackButtonPressed();
}
protected virtual void LayoutChildren(double x, double y, double width, double height)
{
var area = new Rectangle(x, y, width, height);
Rectangle originalArea = area;
if (_containerAreaSet)
{
area = PageController.ContainerArea;
area.X += Padding.Left;
area.Y += Padding.Right;
area.Width -= Padding.HorizontalThickness;
area.Height -= Padding.VerticalThickness;
area.Width = Math.Max(0, area.Width);
area.Height = Math.Max(0, area.Height);
}
List<Element> elements = ElementController.LogicalChildren.ToList();
foreach (Element element in elements)
{
var child = element as VisualElement;
if (child == null)
continue;
var page = child as Page;
if (page != null && ((IPageController)page).IgnoresContainerArea)
Forms.Layout.LayoutChildIntoBoundingRegion(child, originalArea);
else
Forms.Layout.LayoutChildIntoBoundingRegion(child, area);
}
}
protected virtual void OnAppearing()
{
}
protected virtual bool OnBackButtonPressed()
{
var application = RealParent as Application;
if (application == null || this == application.MainPage)
return false;
var canceled = false;
EventHandler handler = (sender, args) => { canceled = true; };
application.PopCanceled += handler;
Navigation.PopModalAsync().ContinueWith(t => { throw t.Exception; }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
application.PopCanceled -= handler;
return !canceled;
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
foreach (ToolbarItem toolbarItem in ToolbarItems)
{
SetInheritedBindingContext(toolbarItem, BindingContext);
}
}
protected virtual void OnChildMeasureInvalidated(object sender, EventArgs e)
{
InvalidationTrigger trigger = (e as InvalidationEventArgs)?.Trigger ?? InvalidationTrigger.Undefined;
OnChildMeasureInvalidated((VisualElement)sender, trigger);
}
protected virtual void OnDisappearing()
{
}
protected override void OnParentSet()
{
if (!Application.IsApplicationOrNull(RealParent) && !(RealParent is Page))
throw new InvalidOperationException("Parent of a Page must also be a Page");
base.OnParentSet();
}
protected override void OnSizeAllocated(double width, double height)
{
_allocatedFlag = true;
base.OnSizeAllocated(width, height);
UpdateChildrenLayout();
}
protected void UpdateChildrenLayout()
{
if (!ShouldLayoutChildren())
return;
var startingLayout = new List<Rectangle>(ElementController.LogicalChildren.Count);
foreach (VisualElement c in ElementController.LogicalChildren)
{
startingLayout.Add(c.Bounds);
}
double x = Padding.Left;
double y = Padding.Top;
double w = Math.Max(0, Width - Padding.HorizontalThickness);
double h = Math.Max(0, Height - Padding.VerticalThickness);
LayoutChildren(x, y, w, h);
for (var i = 0; i < ElementController.LogicalChildren.Count; i++)
{
var c = (VisualElement)ElementController.LogicalChildren[i];
if (c.Bounds != startingLayout[i])
{
EventHandler handler = LayoutChanged;
if (handler != null)
handler(this, EventArgs.Empty);
return;
}
}
}
internal virtual void OnChildMeasureInvalidated(VisualElement child, InvalidationTrigger trigger)
{
var container = this as IPageContainer<Page>;
if (container != null)
{
Page page = container.CurrentPage;
if (page != null && page.IsVisible && (!page.IsPlatformEnabled || !page.IsNativeStateConsistent))
return;
}
else
{
for (var i = 0; i < ElementController.LogicalChildren.Count; i++)
{
var v = ElementController.LogicalChildren[i] as VisualElement;
if (v != null && v.IsVisible && (!v.IsPlatformEnabled || !v.IsNativeStateConsistent))
return;
}
}
_allocatedFlag = false;
InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
if (!_allocatedFlag && Width >= 0 && Height >= 0)
{
SizeAllocated(Width, Height);
}
}
void IPageController.SendAppearing()
{
if (_hasAppeared)
return;
_hasAppeared = true;
if (IsBusy)
MessagingCenter.Send(this, BusySetSignalName, true);
OnAppearing();
EventHandler handler = Appearing;
if (handler != null)
handler(this, EventArgs.Empty);
var pageContainer = this as IPageContainer<Page>;
((IPageController)pageContainer?.CurrentPage)?.SendAppearing();
}
void IPageController.SendDisappearing()
{
if (!_hasAppeared)
return;
_hasAppeared = false;
if (IsBusy)
MessagingCenter.Send(this, BusySetSignalName, false);
var pageContainer = this as IPageContainer<Page>;
((IPageController)pageContainer?.CurrentPage)?.SendDisappearing();
OnDisappearing();
EventHandler handler = Disappearing;
if (handler != null)
handler(this, EventArgs.Empty);
}
void InternalChildrenOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (VisualElement item in e.OldItems.OfType<VisualElement>())
OnInternalRemoved(item);
}
if (e.NewItems != null)
{
foreach (VisualElement item in e.NewItems.OfType<VisualElement>())
OnInternalAdded(item);
}
}
void OnInternalAdded(VisualElement view)
{
view.MeasureInvalidated += OnChildMeasureInvalidated;
OnChildAdded(view);
InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
}
void OnInternalRemoved(VisualElement view)
{
view.MeasureInvalidated -= OnChildMeasureInvalidated;
OnChildRemoved(view);
}
void OnPageBusyChanged()
{
if (!_hasAppeared)
return;
MessagingCenter.Send(this, BusySetSignalName, IsBusy);
}
void OnToolbarItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
if (args.Action != NotifyCollectionChangedAction.Add)
return;
foreach (IElement item in args.NewItems)
item.Parent = this;
}
bool ShouldLayoutChildren()
{
if (!ElementController.LogicalChildren.Any() || Width <= 0 || Height <= 0 || !IsNativeStateConsistent)
return false;
var container = this as IPageContainer<Page>;
if (container?.CurrentPage != null)
{
if (PageController.InternalChildren.Contains(container.CurrentPage))
return container.CurrentPage.IsPlatformEnabled && container.CurrentPage.IsNativeStateConsistent;
return true;
}
var any = false;
for (var i = 0; i < ElementController.LogicalChildren.Count; i++)
{
var v = ElementController.LogicalChildren[i] as VisualElement;
if (v != null && (!v.IsPlatformEnabled || !v.IsNativeStateConsistent))
{
any = true;
break;
}
}
return !any;
}
public IPlatformElementConfiguration<T, Page> On<T>() where T : IConfigPlatform
{
return _platformConfigurationRegistry.Value.On<T>();
}
}
}
| |
// 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.Automation
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ScheduleOperations.
/// </summary>
public static partial class ScheduleOperationsExtensions
{
/// <summary>
/// Create a schedule.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='scheduleName'>
/// The schedule name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the create or update schedule operation.
/// </param>
public static Schedule CreateOrUpdate(this IScheduleOperations operations, string resourceGroupName, string automationAccountName, string scheduleName, ScheduleCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, automationAccountName, scheduleName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Create a schedule.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='scheduleName'>
/// The schedule name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the create or update schedule operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Schedule> CreateOrUpdateAsync(this IScheduleOperations operations, string resourceGroupName, string automationAccountName, string scheduleName, ScheduleCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, automationAccountName, scheduleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update the schedule identified by schedule name.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='scheduleName'>
/// The schedule name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the update schedule operation.
/// </param>
public static Schedule Update(this IScheduleOperations operations, string resourceGroupName, string automationAccountName, string scheduleName, ScheduleUpdateParameters parameters)
{
return operations.UpdateAsync(resourceGroupName, automationAccountName, scheduleName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Update the schedule identified by schedule name.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='scheduleName'>
/// The schedule name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the update schedule operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Schedule> UpdateAsync(this IScheduleOperations operations, string resourceGroupName, string automationAccountName, string scheduleName, ScheduleUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, automationAccountName, scheduleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve the schedule identified by schedule name.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='scheduleName'>
/// The schedule name.
/// </param>
public static Schedule Get(this IScheduleOperations operations, string resourceGroupName, string automationAccountName, string scheduleName)
{
return operations.GetAsync(resourceGroupName, automationAccountName, scheduleName).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the schedule identified by schedule name.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='scheduleName'>
/// The schedule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Schedule> GetAsync(this IScheduleOperations operations, string resourceGroupName, string automationAccountName, string scheduleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, automationAccountName, scheduleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete the schedule identified by schedule name.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='scheduleName'>
/// The schedule name.
/// </param>
public static void Delete(this IScheduleOperations operations, string resourceGroupName, string automationAccountName, string scheduleName)
{
operations.DeleteAsync(resourceGroupName, automationAccountName, scheduleName).GetAwaiter().GetResult();
}
/// <summary>
/// Delete the schedule identified by schedule name.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='scheduleName'>
/// The schedule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IScheduleOperations operations, string resourceGroupName, string automationAccountName, string scheduleName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, automationAccountName, scheduleName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieve a list of schedules.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
public static IPage<Schedule> ListByAutomationAccount(this IScheduleOperations operations, string resourceGroupName, string automationAccountName)
{
return operations.ListByAutomationAccountAsync(resourceGroupName, automationAccountName).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of schedules.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Schedule>> ListByAutomationAccountAsync(this IScheduleOperations operations, string resourceGroupName, string automationAccountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByAutomationAccountWithHttpMessagesAsync(resourceGroupName, automationAccountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve a list of schedules.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Schedule> ListByAutomationAccountNext(this IScheduleOperations operations, string nextPageLink)
{
return operations.ListByAutomationAccountNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of schedules.
/// <see href="http://aka.ms/azureautomationsdk/scheduleoperations" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Schedule>> ListByAutomationAccountNextAsync(this IScheduleOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByAutomationAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Text;
using Thrift.Transport;
namespace Thrift.Protocol
{
public class TBinaryProtocol : TProtocol
{
protected const uint VERSION_MASK = 0xffff0000;
protected const uint VERSION_1 = 0x80010000;
protected bool strictRead_ = false;
protected bool strictWrite_ = true;
#region BinaryProtocol Factory
/**
* Factory
*/
public class Factory : TProtocolFactory {
protected bool strictRead_ = false;
protected bool strictWrite_ = true;
public Factory()
:this(false, true)
{
}
public Factory(bool strictRead, bool strictWrite)
{
strictRead_ = strictRead;
strictWrite_ = strictWrite;
}
public TProtocol GetProtocol(TTransport trans) {
return new TBinaryProtocol(trans, strictRead_, strictWrite_);
}
}
#endregion
public TBinaryProtocol(TTransport trans)
: this(trans, false, true)
{
}
public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite)
:base(trans)
{
strictRead_ = strictRead;
strictWrite_ = strictWrite;
}
#region Write Methods
public override void WriteMessageBegin(TMessage message)
{
if (strictWrite_)
{
uint version = VERSION_1 | (uint)(message.Type);
WriteI32((int)version);
WriteString(message.Name);
WriteI32(message.SeqID);
}
else
{
WriteString(message.Name);
WriteByte((sbyte)message.Type);
WriteI32(message.SeqID);
}
}
public override void WriteMessageEnd()
{
}
public override void WriteStructBegin(TStruct struc)
{
}
public override void WriteStructEnd()
{
}
public override void WriteFieldBegin(TField field)
{
WriteByte((sbyte)field.Type);
WriteI16(field.ID);
}
public override void WriteFieldEnd()
{
}
public override void WriteFieldStop()
{
WriteByte((sbyte)TType.Stop);
}
public override void WriteMapBegin(TMap map)
{
WriteByte((sbyte)map.KeyType);
WriteByte((sbyte)map.ValueType);
WriteI32(map.Count);
}
public override void WriteMapEnd()
{
}
public override void WriteListBegin(TList list)
{
WriteByte((sbyte)list.ElementType);
WriteI32(list.Count);
}
public override void WriteListEnd()
{
}
public override void WriteSetBegin(TSet set)
{
WriteByte((sbyte)set.ElementType);
WriteI32(set.Count);
}
public override void WriteSetEnd()
{
}
public override void WriteBool(bool b)
{
WriteByte(b ? (sbyte)1 : (sbyte)0);
}
private byte[] bout = new byte[1];
public override void WriteByte(sbyte b)
{
bout[0] = (byte)b;
trans.Write(bout, 0, 1);
}
private byte[] i16out = new byte[2];
public override void WriteI16(short s)
{
i16out[0] = (byte)(0xff & (s >> 8));
i16out[1] = (byte)(0xff & s);
trans.Write(i16out, 0, 2);
}
private byte[] i32out = new byte[4];
public override void WriteI32(int i32)
{
i32out[0] = (byte)(0xff & (i32 >> 24));
i32out[1] = (byte)(0xff & (i32 >> 16));
i32out[2] = (byte)(0xff & (i32 >> 8));
i32out[3] = (byte)(0xff & i32);
trans.Write(i32out, 0, 4);
}
private byte[] i64out = new byte[8];
public override void WriteI64(long i64)
{
i64out[0] = (byte)(0xff & (i64 >> 56));
i64out[1] = (byte)(0xff & (i64 >> 48));
i64out[2] = (byte)(0xff & (i64 >> 40));
i64out[3] = (byte)(0xff & (i64 >> 32));
i64out[4] = (byte)(0xff & (i64 >> 24));
i64out[5] = (byte)(0xff & (i64 >> 16));
i64out[6] = (byte)(0xff & (i64 >> 8));
i64out[7] = (byte)(0xff & i64);
trans.Write(i64out, 0, 8);
}
public override void WriteFloat(float d)
{
#if !SILVERLIGHT
WriteI32((int)BitConverter.DoubleToInt64Bits(d));
#else
var bytes = BitConverter.GetBytes(d);
WriteI32(BitConverter.ToInt32(bytes, 0));
#endif
}
public override void WriteDouble(double d)
{
#if !SILVERLIGHT
WriteI64(BitConverter.DoubleToInt64Bits(d));
#else
var bytes = BitConverter.GetBytes(d);
WriteI64(BitConverter.ToInt64(bytes, 0));
#endif
}
public override void WriteBinary(byte[] b)
{
WriteI32(b.Length);
trans.Write(b, 0, b.Length);
}
#endregion
#region ReadMethods
public override TMessage ReadMessageBegin()
{
TMessage message = new TMessage();
int size = ReadI32();
if (size < 0)
{
uint version = (uint)size & VERSION_MASK;
if (version != VERSION_1)
{
throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in ReadMessageBegin: " + version);
}
message.Type = (TMessageType)(size & 0x000000ff);
message.Name = ReadString();
message.SeqID = ReadI32();
}
else
{
if (strictRead_)
{
throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?");
}
message.Name = ReadStringBody(size);
message.Type = (TMessageType)ReadByte();
message.SeqID = ReadI32();
}
return message;
}
public override void ReadMessageEnd()
{
}
public override TStruct ReadStructBegin()
{
return new TStruct();
}
public override void ReadStructEnd()
{
}
public override TField ReadFieldBegin()
{
TField field = new TField();
field.Type = (TType)ReadByte();
if (field.Type != TType.Stop)
{
field.ID = ReadI16();
}
return field;
}
public override void ReadFieldEnd()
{
}
public override TMap ReadMapBegin()
{
TMap map = new TMap();
map.KeyType = (TType)ReadByte();
map.ValueType = (TType)ReadByte();
map.Count = ReadI32();
return map;
}
public override void ReadMapEnd()
{
}
public override TList ReadListBegin()
{
TList list = new TList();
list.ElementType = (TType)ReadByte();
list.Count = ReadI32();
return list;
}
public override void ReadListEnd()
{
}
public override TSet ReadSetBegin()
{
TSet set = new TSet();
set.ElementType = (TType)ReadByte();
set.Count = ReadI32();
return set;
}
public override void ReadSetEnd()
{
}
public override bool ReadBool()
{
return ReadByte() == 1;
}
private byte[] bin = new byte[1];
public override sbyte ReadByte()
{
ReadAll(bin, 0, 1);
return (sbyte)bin[0];
}
private byte[] i16in = new byte[2];
public override short ReadI16()
{
ReadAll(i16in, 0, 2);
return (short)(((i16in[0] & 0xff) << 8) | ((i16in[1] & 0xff)));
}
private byte[] i32in = new byte[4];
public override int ReadI32()
{
ReadAll(i32in, 0, 4);
return (int)(((i32in[0] & 0xff) << 24) | ((i32in[1] & 0xff) << 16) | ((i32in[2] & 0xff) << 8) | ((i32in[3] & 0xff)));
}
#pragma warning disable 675
private byte[] i64in = new byte[8];
public override long ReadI64()
{
ReadAll(i64in, 0, 8);
unchecked {
return (long)(
((long)(i64in[0] & 0xff) << 56) |
((long)(i64in[1] & 0xff) << 48) |
((long)(i64in[2] & 0xff) << 40) |
((long)(i64in[3] & 0xff) << 32) |
((long)(i64in[4] & 0xff) << 24) |
((long)(i64in[5] & 0xff) << 16) |
((long)(i64in[6] & 0xff) << 8) |
((long)(i64in[7] & 0xff)));
}
}
#pragma warning restore 675
public override float ReadFloat()
{
#if !SILVERLIGHT
return (float)BitConverter.Int64BitsToDouble(ReadI32());
#else
var value = ReadI32();
var bytes = BitConverter.GetBytes(value);
return BitConverter.ToFloat(bytes, 0);
#endif
}
public override double ReadDouble()
{
#if !SILVERLIGHT
return BitConverter.Int64BitsToDouble(ReadI64());
#else
var value = ReadI64();
var bytes = BitConverter.GetBytes(value);
return BitConverter.ToDouble(bytes, 0);
#endif
}
public override byte[] ReadBinary()
{
int size = ReadI32();
byte[] buf = new byte[size];
trans.ReadAll(buf, 0, size);
return buf;
}
private string ReadStringBody(int size)
{
byte[] buf = new byte[size];
trans.ReadAll(buf, 0, size);
return Encoding.UTF8.GetString(buf, 0, buf.Length);
}
private int ReadAll(byte[] buf, int off, int len)
{
return trans.ReadAll(buf, off, len);
}
#endregion
}
}
| |
/*
* 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:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// Describes the storage that is available to a PVS site for caching purposes
/// First published in XenServer 7.1.
/// </summary>
public partial class PVS_cache_storage : XenObject<PVS_cache_storage>
{
public PVS_cache_storage()
{
}
public PVS_cache_storage(string uuid,
XenRef<Host> host,
XenRef<SR> SR,
XenRef<PVS_site> site,
long size,
XenRef<VDI> VDI)
{
this.uuid = uuid;
this.host = host;
this.SR = SR;
this.site = site;
this.size = size;
this.VDI = VDI;
}
/// <summary>
/// Creates a new PVS_cache_storage from a Proxy_PVS_cache_storage.
/// </summary>
/// <param name="proxy"></param>
public PVS_cache_storage(Proxy_PVS_cache_storage proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given PVS_cache_storage.
/// </summary>
public override void UpdateFrom(PVS_cache_storage update)
{
uuid = update.uuid;
host = update.host;
SR = update.SR;
site = update.site;
size = update.size;
VDI = update.VDI;
}
internal void UpdateFromProxy(Proxy_PVS_cache_storage proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
SR = proxy.SR == null ? null : XenRef<SR>.Create(proxy.SR);
site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site);
size = proxy.size == null ? 0 : long.Parse((string)proxy.size);
VDI = proxy.VDI == null ? null : XenRef<VDI>.Create(proxy.VDI);
}
public Proxy_PVS_cache_storage ToProxy()
{
Proxy_PVS_cache_storage result_ = new Proxy_PVS_cache_storage();
result_.uuid = uuid ?? "";
result_.host = host ?? "";
result_.SR = SR ?? "";
result_.site = site ?? "";
result_.size = size.ToString();
result_.VDI = VDI ?? "";
return result_;
}
/// <summary>
/// Creates a new PVS_cache_storage from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public PVS_cache_storage(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this PVS_cache_storage
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("host"))
host = Marshalling.ParseRef<Host>(table, "host");
if (table.ContainsKey("SR"))
SR = Marshalling.ParseRef<SR>(table, "SR");
if (table.ContainsKey("site"))
site = Marshalling.ParseRef<PVS_site>(table, "site");
if (table.ContainsKey("size"))
size = Marshalling.ParseLong(table, "size");
if (table.ContainsKey("VDI"))
VDI = Marshalling.ParseRef<VDI>(table, "VDI");
}
public bool DeepEquals(PVS_cache_storage other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._SR, other._SR) &&
Helper.AreEqual2(this._site, other._site) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._VDI, other._VDI);
}
internal static List<PVS_cache_storage> ProxyArrayToObjectList(Proxy_PVS_cache_storage[] input)
{
var result = new List<PVS_cache_storage>();
foreach (var item in input)
result.Add(new PVS_cache_storage(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, PVS_cache_storage server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static PVS_cache_storage get_record(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_record(session.opaque_ref, _pvs_cache_storage);
else
return new PVS_cache_storage((Proxy_PVS_cache_storage)session.proxy.pvs_cache_storage_get_record(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get a reference to the PVS_cache_storage instance with the specified UUID.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PVS_cache_storage> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<PVS_cache_storage>.Create(session.proxy.pvs_cache_storage_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new PVS_cache_storage instance, and return its handle.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<PVS_cache_storage> create(Session session, PVS_cache_storage _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_create(session.opaque_ref, _record);
else
return XenRef<PVS_cache_storage>.Create(session.proxy.pvs_cache_storage_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new PVS_cache_storage instance, and return its handle.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, PVS_cache_storage _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pvs_cache_storage_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.proxy.async_pvs_cache_storage_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified PVS_cache_storage instance.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static void destroy(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage);
else
session.proxy.pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage ?? "").parse();
}
/// <summary>
/// Destroy the specified PVS_cache_storage instance.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<Task> async_destroy(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<Task>.Create(session.proxy.async_pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static string get_uuid(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_uuid(session.opaque_ref, _pvs_cache_storage);
else
return (string)session.proxy.pvs_cache_storage_get_uuid(session.opaque_ref, _pvs_cache_storage ?? "").parse();
}
/// <summary>
/// Get the host field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<Host> get_host(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_host(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<Host>.Create(session.proxy.pvs_cache_storage_get_host(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the SR field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<SR> get_SR(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_sr(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<SR>.Create(session.proxy.pvs_cache_storage_get_sr(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the site field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<PVS_site> get_site(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_site(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<PVS_site>.Create(session.proxy.pvs_cache_storage_get_site(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the size field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static long get_size(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_size(session.opaque_ref, _pvs_cache_storage);
else
return long.Parse((string)session.proxy.pvs_cache_storage_get_size(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the VDI field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<VDI> get_VDI(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_vdi(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<VDI>.Create(session.proxy.pvs_cache_storage_get_vdi(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Return a list of all the PVS_cache_storages known to the system.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PVS_cache_storage>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_all(session.opaque_ref);
else
return XenRef<PVS_cache_storage>.Create(session.proxy.pvs_cache_storage_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the PVS_cache_storage Records at once, in a single XML RPC call
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PVS_cache_storage>, PVS_cache_storage> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_all_records(session.opaque_ref);
else
return XenRef<PVS_cache_storage>.Create<Proxy_PVS_cache_storage>(session.proxy.pvs_cache_storage_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// The host on which this object defines PVS cache storage
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host = new XenRef<Host>("OpaqueRef:NULL");
/// <summary>
/// SR providing storage for the PVS cache
/// </summary>
[JsonConverter(typeof(XenRefConverter<SR>))]
public virtual XenRef<SR> SR
{
get { return _SR; }
set
{
if (!Helper.AreEqual(value, _SR))
{
_SR = value;
Changed = true;
NotifyPropertyChanged("SR");
}
}
}
private XenRef<SR> _SR = new XenRef<SR>("OpaqueRef:NULL");
/// <summary>
/// The PVS_site for which this object defines the storage
/// </summary>
[JsonConverter(typeof(XenRefConverter<PVS_site>))]
public virtual XenRef<PVS_site> site
{
get { return _site; }
set
{
if (!Helper.AreEqual(value, _site))
{
_site = value;
Changed = true;
NotifyPropertyChanged("site");
}
}
}
private XenRef<PVS_site> _site = new XenRef<PVS_site>("OpaqueRef:NULL");
/// <summary>
/// The size of the cache VDI (in bytes)
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
Changed = true;
NotifyPropertyChanged("size");
}
}
}
private long _size = 21474836480;
/// <summary>
/// The VDI used for caching
/// </summary>
[JsonConverter(typeof(XenRefConverter<VDI>))]
public virtual XenRef<VDI> VDI
{
get { return _VDI; }
set
{
if (!Helper.AreEqual(value, _VDI))
{
_VDI = value;
Changed = true;
NotifyPropertyChanged("VDI");
}
}
}
private XenRef<VDI> _VDI = new XenRef<VDI>("OpaqueRef:NULL");
}
}
| |
using System;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Text;
using System.Web;
//http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs
namespace Geocoding.Yahoo {
public class OAuthBase {
/// <summary>
/// Provides a predefined set of algorithms that are supported officially by the protocol
/// </summary>
public enum SignatureTypes {
HMACSHA1,
PLAINTEXT,
RSASHA1
}
/// <summary>
/// Provides an internal structure to sort the query parameter
/// </summary>
protected class QueryParameter {
private string name = null;
private string value = null;
public QueryParameter(string name, string value) {
this.name = name;
this.value = value;
}
public string Name {
get { return name; }
}
public string Value {
get { return value; }
}
}
/// <summary>
/// Comparer class used to perform the sorting of the query parameters
/// </summary>
protected class QueryParameterComparer : IComparer<QueryParameter> {
#region IComparer<QueryParameter> Members
public int Compare(QueryParameter x, QueryParameter y) {
if (x.Name == y.Name) {
return string.Compare(x.Value, y.Value);
} else {
return string.Compare(x.Name, y.Name);
}
}
#endregion
}
protected const string OAuthVersion = "1.0";
protected const string OAuthParameterPrefix = "oauth_";
//
// List of know and used oauth parameters' names
//
protected const string OAuthConsumerKeyKey = "oauth_consumer_key";
protected const string OAuthCallbackKey = "oauth_callback";
protected const string OAuthVersionKey = "oauth_version";
protected const string OAuthSignatureMethodKey = "oauth_signature_method";
protected const string OAuthSignatureKey = "oauth_signature";
protected const string OAuthTimestampKey = "oauth_timestamp";
protected const string OAuthNonceKey = "oauth_nonce";
protected const string OAuthTokenKey = "oauth_token";
protected const string OAuthTokenSecretKey = "oauth_token_secret";
protected const string HMACSHA1SignatureType = "HMAC-SHA1";
protected const string PlainTextSignatureType = "PLAINTEXT";
protected const string RSASHA1SignatureType = "RSA-SHA1";
protected Random random = new Random();
protected string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
/// <summary>
/// Helper function to compute a hash value
/// </summary>
/// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param>
/// <param name="data">The data to hash</param>
/// <returns>a Base64 string of the hash value</returns>
private string ComputeHash(HashAlgorithm hashAlgorithm, string data) {
if (hashAlgorithm == null) {
throw new ArgumentNullException("hashAlgorithm");
}
if (string.IsNullOrEmpty(data)) {
throw new ArgumentNullException("data");
}
byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data);
byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
/// <summary>
/// Internal function to cut out all non oauth query string parameters (all parameters not begining with "oauth_")
/// </summary>
/// <param name="parameters">The query string part of the Url</param>
/// <returns>A list of QueryParameter each containing the parameter name and value</returns>
private List<QueryParameter> GetQueryParameters(string parameters) {
if (parameters.StartsWith("?")) {
parameters = parameters.Remove(0, 1);
}
List<QueryParameter> result = new List<QueryParameter>();
if (!string.IsNullOrEmpty(parameters)) {
string[] p = parameters.Split('&');
foreach (string s in p) {
if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix)) {
if (s.IndexOf('=') > -1) {
string[] temp = s.Split('=');
result.Add(new QueryParameter(temp[0], temp[1]));
} else {
result.Add(new QueryParameter(s, string.Empty));
}
}
}
}
return result;
}
/// <summary>
/// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
/// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
/// </summary>
/// <param name="value">The value to Url encode</param>
/// <returns>Returns a Url encoded string</returns>
protected string UrlEncode(string value) {
StringBuilder result = new StringBuilder();
foreach (char symbol in value) {
if (unreservedChars.IndexOf(symbol) != -1) {
result.Append(symbol);
} else {
result.Append('%' + string.Format("{0:X2}", (int)symbol));
}
}
return result.ToString();
}
/// <summary>
/// Normalizes the request parameters according to the spec
/// </summary>
/// <param name="parameters">The list of parameters already sorted</param>
/// <returns>a string representing the normalized parameters</returns>
protected string NormalizeRequestParameters(IList<QueryParameter> parameters) {
StringBuilder sb = new StringBuilder();
QueryParameter p = null;
for (int i = 0; i < parameters.Count; i++) {
p = parameters[i];
sb.AppendFormat("{0}={1}", p.Name, p.Value);
if (i < parameters.Count - 1) {
sb.Append("&");
}
}
return sb.ToString();
}
/// <summary>
/// Generate the signature base that is used to produce the signature
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>.</param>
/// <returns>The signature base</returns>
public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string signatureType, out string normalizedUrl, out string normalizedRequestParameters) {
if (token == null) {
token = string.Empty;
}
if (tokenSecret == null) {
tokenSecret = string.Empty;
}
if (string.IsNullOrEmpty(consumerKey)) {
throw new ArgumentNullException("consumerKey");
}
if (string.IsNullOrEmpty(httpMethod)) {
throw new ArgumentNullException("httpMethod");
}
if (string.IsNullOrEmpty(signatureType)) {
throw new ArgumentNullException("signatureType");
}
normalizedUrl = null;
normalizedRequestParameters = null;
List<QueryParameter> parameters = GetQueryParameters(url.Query);
parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion));
parameters.Add(new QueryParameter(OAuthNonceKey, nonce));
parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));
parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType));
parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey));
if (!string.IsNullOrEmpty(token)) {
parameters.Add(new QueryParameter(OAuthTokenKey, token));
}
parameters.Sort(new QueryParameterComparer());
normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
{
normalizedUrl += ":" + url.Port;
}
normalizedUrl += url.AbsolutePath;
normalizedRequestParameters = NormalizeRequestParameters(parameters);
StringBuilder signatureBase = new StringBuilder();
signatureBase.AppendFormat("{0}&", httpMethod.ToUpper());
signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));
return signatureBase.ToString();
}
/// <summary>
/// Generate the signature value based on the given signature base and hash algorithm
/// </summary>
/// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
/// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash) {
return ComputeHash(hash, signatureBase);
}
/// <summary>
/// Generates a signature using the HMAC-SHA1 algorithm
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="consumerSecret">The consumer seceret</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out string normalizedRequestParameters) {
return GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, httpMethod, timeStamp, nonce, SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
}
/// <summary>
/// Generates a signature using the specified signatureType
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="consumerSecret">The consumer seceret</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The type of signature to use</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters) {
normalizedUrl = null;
normalizedRequestParameters = null;
switch (signatureType) {
case SignatureTypes.PLAINTEXT:
return HttpUtility.UrlEncode(string.Format("{0}&{1}", consumerSecret, tokenSecret));
case SignatureTypes.HMACSHA1:
string signatureBase = GenerateSignatureBase(url, consumerKey, token, tokenSecret, httpMethod, timeStamp, nonce, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters);
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)));
return GenerateSignatureUsingHash(signatureBase, hmacsha1);
case SignatureTypes.RSASHA1:
throw new NotImplementedException();
default:
throw new ArgumentException("Unknown signature type", "signatureType");
}
}
/// <summary>
/// Generate the timestamp for the signature
/// </summary>
/// <returns></returns>
public virtual string GenerateTimeStamp() {
// Default implementation of UNIX time of the current UTC time
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/// <summary>
/// Generate a nonce
/// </summary>
/// <returns></returns>
public virtual string GenerateNonce() {
// Just a simple implementation of a random number between 123400 and 9999999
return random.Next(123400, 9999999).ToString();
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Security;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Security
{
/// <summary>
/// A base membership provider class offering much of the underlying functionality for initializing and password encryption/hashing.
/// </summary>
public abstract class MembershipProviderBase : MembershipProvider
{
/// <summary>
/// Providers can override this setting, default is 7
/// </summary>
public virtual int DefaultMinPasswordLength
{
get { return 7; }
}
/// <summary>
/// Providers can override this setting, default is 1
/// </summary>
public virtual int DefaultMinNonAlphanumericChars
{
get { return 1; }
}
/// <summary>
/// Providers can override this setting, default is false to use better security
/// </summary>
public virtual bool DefaultUseLegacyEncoding
{
get { return false; }
}
/// <summary>
/// Providers can override this setting, by default this is false which means that the provider will
/// authenticate the username + password when ChangePassword is called. This property exists purely for
/// backwards compatibility.
/// </summary>
public virtual bool AllowManuallyChangingPassword
{
get { return false; }
}
private string _applicationName;
private bool _enablePasswordReset;
private bool _enablePasswordRetrieval;
private int _maxInvalidPasswordAttempts;
private int _minRequiredNonAlphanumericCharacters;
private int _minRequiredPasswordLength;
private int _passwordAttemptWindow;
private MembershipPasswordFormat _passwordFormat;
private string _passwordStrengthRegularExpression;
private bool _requiresQuestionAndAnswer;
private bool _requiresUniqueEmail;
private string _customHashAlgorithmType ;
internal bool UseLegacyEncoding;
#region Properties
/// <summary>
/// Indicates whether the membership provider is configured to allow users to reset their passwords.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider supports password reset; otherwise, false. The default is true.</returns>
public override bool EnablePasswordReset
{
get { return _enablePasswordReset; }
}
/// <summary>
/// Indicates whether the membership provider is configured to allow users to retrieve their passwords.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.</returns>
public override bool EnablePasswordRetrieval
{
get { return _enablePasswordRetrieval; }
}
/// <summary>
/// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out.
/// </summary>
/// <value></value>
/// <returns>The number of invalid password or password-answer attempts allowed before the membership user is locked out.</returns>
public override int MaxInvalidPasswordAttempts
{
get { return _maxInvalidPasswordAttempts; }
}
/// <summary>
/// Gets the minimum number of special characters that must be present in a valid password.
/// </summary>
/// <value></value>
/// <returns>The minimum number of special characters that must be present in a valid password.</returns>
public override int MinRequiredNonAlphanumericCharacters
{
get { return _minRequiredNonAlphanumericCharacters; }
}
/// <summary>
/// Gets the minimum length required for a password.
/// </summary>
/// <value></value>
/// <returns>The minimum length required for a password. </returns>
public override int MinRequiredPasswordLength
{
get { return _minRequiredPasswordLength; }
}
/// <summary>
/// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.
/// </summary>
/// <value></value>
/// <returns>The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.</returns>
public override int PasswordAttemptWindow
{
get { return _passwordAttemptWindow; }
}
/// <summary>
/// Gets a value indicating the format for storing passwords in the membership data store.
/// </summary>
/// <value></value>
/// <returns>One of the <see cref="T:System.Web.Security.MembershipPasswordFormat"></see> values indicating the format for storing passwords in the data store.</returns>
public override MembershipPasswordFormat PasswordFormat
{
get { return _passwordFormat; }
}
/// <summary>
/// Gets the regular expression used to evaluate a password.
/// </summary>
/// <value></value>
/// <returns>A regular expression used to evaluate a password.</returns>
public override string PasswordStrengthRegularExpression
{
get { return _passwordStrengthRegularExpression; }
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval.
/// </summary>
/// <value></value>
/// <returns>true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.</returns>
public override bool RequiresQuestionAndAnswer
{
get { return _requiresQuestionAndAnswer; }
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.</returns>
public override bool RequiresUniqueEmail
{
get { return _requiresUniqueEmail; }
}
/// <summary>
/// The name of the application using the custom membership provider.
/// </summary>
/// <value></value>
/// <returns>The name of the application using the custom membership provider.</returns>
public override string ApplicationName
{
get
{
return _applicationName;
}
set
{
if (string.IsNullOrEmpty(value))
throw new ProviderException("ApplicationName cannot be empty.");
if (value.Length > 0x100)
throw new ProviderException("Provider application name too long.");
_applicationName = value;
}
}
#endregion
/// <summary>
/// Initializes the provider.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
/// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
/// <exception cref="T:System.InvalidOperationException">An attempt is made to call
/// <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider
/// has already been initialized.</exception>
/// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
public override void Initialize(string name, NameValueCollection config)
{
// Initialize base provider class
base.Initialize(name, config);
_enablePasswordRetrieval = config.GetValue("enablePasswordRetrieval", false);
_enablePasswordReset = config.GetValue("enablePasswordReset", false);
_requiresQuestionAndAnswer = config.GetValue("requiresQuestionAndAnswer", false);
_requiresUniqueEmail = config.GetValue("requiresUniqueEmail", true);
_maxInvalidPasswordAttempts = GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0);
_passwordAttemptWindow = GetIntValue(config, "passwordAttemptWindow", 10, false, 0);
_minRequiredPasswordLength = GetIntValue(config, "minRequiredPasswordLength", DefaultMinPasswordLength, true, 0x80);
_minRequiredNonAlphanumericCharacters = GetIntValue(config, "minRequiredNonalphanumericCharacters", DefaultMinNonAlphanumericChars, true, 0x80);
_passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"];
_applicationName = config["applicationName"];
if (string.IsNullOrEmpty(_applicationName))
_applicationName = GetDefaultAppName();
//by default we will continue using the legacy encoding.
UseLegacyEncoding = config.GetValue("useLegacyEncoding", DefaultUseLegacyEncoding);
// make sure password format is Hashed by default.
string str = config["passwordFormat"] ?? "Hashed";
switch (str.ToLower())
{
case "clear":
_passwordFormat = MembershipPasswordFormat.Clear;
break;
case "encrypted":
_passwordFormat = MembershipPasswordFormat.Encrypted;
break;
case "hashed":
_passwordFormat = MembershipPasswordFormat.Hashed;
break;
default:
throw new ProviderException("Provider bad password format");
}
if ((PasswordFormat == MembershipPasswordFormat.Hashed) && EnablePasswordRetrieval)
{
var ex = new ProviderException("Provider can not retrieve a hashed password");
LogHelper.Error<MembershipProviderBase>("Cannot specify a Hashed password format with the enabledPasswordRetrieval option set to true", ex);
throw ex;
}
_customHashAlgorithmType = config.GetValue("hashAlgorithmType", string.Empty);
}
/// <summary>
/// Override this method to ensure the password is valid before raising the event
/// </summary>
/// <param name="e"></param>
protected override void OnValidatingPassword(ValidatePasswordEventArgs e)
{
var attempt = IsPasswordValid(e.Password, MinRequiredNonAlphanumericCharacters, PasswordStrengthRegularExpression, MinRequiredPasswordLength);
if (attempt.Success == false)
{
e.Cancel = true;
return;
}
base.OnValidatingPassword(e);
}
protected internal enum PasswordValidityError
{
Ok,
Length,
AlphanumericChars,
Strength
}
/// <summary>
/// Processes a request to update the password for a membership user.
/// </summary>
/// <param name="username">The user to update the password for.</param>
/// <param name="oldPassword">This property is ignore for this provider</param>
/// <param name="newPassword">The new password for the specified user.</param>
/// <returns>
/// true if the password was updated successfully; otherwise, false.
/// </returns>
/// <remarks>
/// Checks to ensure the AllowManuallyChangingPassword rule is adhered to
/// </remarks>
public sealed override bool ChangePassword(string username, string oldPassword, string newPassword)
{
if (oldPassword.IsNullOrWhiteSpace() && AllowManuallyChangingPassword == false)
{
//If the old password is empty and AllowManuallyChangingPassword is false, than this provider cannot just arbitrarily change the password
throw new NotSupportedException("This provider does not support manually changing the password");
}
var args = new ValidatePasswordEventArgs(username, newPassword, false);
OnValidatingPassword(args);
if (args.Cancel)
{
if (args.FailureInformation != null)
throw args.FailureInformation;
throw new MembershipPasswordException("Change password canceled due to password validation failure.");
}
if (AllowManuallyChangingPassword == false)
{
if (ValidateUser(username, oldPassword) == false) return false;
}
return PerformChangePassword(username, oldPassword, newPassword);
}
/// <summary>
/// Processes a request to update the password for a membership user.
/// </summary>
/// <param name="username">The user to update the password for.</param>
/// <param name="oldPassword">This property is ignore for this provider</param>
/// <param name="newPassword">The new password for the specified user.</param>
/// <returns>
/// true if the password was updated successfully; otherwise, false.
/// </returns>
protected abstract bool PerformChangePassword(string username, string oldPassword, string newPassword);
/// <summary>
/// Processes a request to update the password question and answer for a membership user.
/// </summary>
/// <param name="username">The user to change the password question and answer for.</param>
/// <param name="password">The password for the specified user.</param>
/// <param name="newPasswordQuestion">The new password question for the specified user.</param>
/// <param name="newPasswordAnswer">The new password answer for the specified user.</param>
/// <returns>
/// true if the password question and answer are updated successfully; otherwise, false.
/// </returns>
/// <remarks>
/// Performs the basic validation before passing off to PerformChangePasswordQuestionAndAnswer
/// </remarks>
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
if (RequiresQuestionAndAnswer == false)
{
throw new NotSupportedException("Updating the password Question and Answer is not available if requiresQuestionAndAnswer is not set in web.config");
}
if (AllowManuallyChangingPassword == false)
{
if (ValidateUser(username, password) == false)
{
return false;
}
}
return PerformChangePasswordQuestionAndAnswer(username, password, newPasswordQuestion, newPasswordAnswer);
}
/// <summary>
/// Processes a request to update the password question and answer for a membership user.
/// </summary>
/// <param name="username">The user to change the password question and answer for.</param>
/// <param name="password">The password for the specified user.</param>
/// <param name="newPasswordQuestion">The new password question for the specified user.</param>
/// <param name="newPasswordAnswer">The new password answer for the specified user.</param>
/// <returns>
/// true if the password question and answer are updated successfully; otherwise, false.
/// </returns>
protected abstract bool PerformChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer);
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">The password for the new user.</param>
/// <param name="email">The e-mail address for the new user.</param>
/// <param name="passwordQuestion">The password question for the new user.</param>
/// <param name="passwordAnswer">The password answer for the new user</param>
/// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
/// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
/// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user.
/// </returns>
/// <remarks>
/// Ensures the ValidatingPassword event is executed before executing PerformCreateUser and performs basic membership provider validation of values.
/// </remarks>
public sealed override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
var valStatus = ValidateNewUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey);
if (valStatus != MembershipCreateStatus.Success)
{
status = valStatus;
return null;
}
return PerformCreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status);
}
/// <summary>
/// Performs the validation of the information for creating a new user
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="email"></param>
/// <param name="passwordQuestion"></param>
/// <param name="passwordAnswer"></param>
/// <param name="isApproved"></param>
/// <param name="providerUserKey"></param>
/// <returns></returns>
protected MembershipCreateStatus ValidateNewUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey)
{
var args = new ValidatePasswordEventArgs(username, password, true);
OnValidatingPassword(args);
if (args.Cancel)
{
return MembershipCreateStatus.InvalidPassword;
}
// Validate password
var passwordValidAttempt = IsPasswordValid(password, MinRequiredNonAlphanumericCharacters, PasswordStrengthRegularExpression, MinRequiredPasswordLength);
if (passwordValidAttempt.Success == false)
{
return MembershipCreateStatus.InvalidPassword;
}
// Validate email
if (IsEmailValid(email) == false)
{
return MembershipCreateStatus.InvalidEmail;
}
// Make sure username isn't all whitespace
if (string.IsNullOrWhiteSpace(username.Trim()))
{
return MembershipCreateStatus.InvalidUserName;
}
// Check password question
if (string.IsNullOrWhiteSpace(passwordQuestion) && RequiresQuestionAndAnswer)
{
return MembershipCreateStatus.InvalidQuestion;
}
// Check password answer
if (string.IsNullOrWhiteSpace(passwordAnswer) && RequiresQuestionAndAnswer)
{
return MembershipCreateStatus.InvalidAnswer;
}
return MembershipCreateStatus.Success;
}
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">The password for the new user.</param>
/// <param name="email">The e-mail address for the new user.</param>
/// <param name="passwordQuestion">The password question for the new user.</param>
/// <param name="passwordAnswer">The password answer for the new user</param>
/// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
/// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
/// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user.
/// </returns>
protected abstract MembershipUser PerformCreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status);
/// <summary>
/// Gets the members password if password retreival is enabled
/// </summary>
/// <param name="username"></param>
/// <param name="answer"></param>
/// <returns></returns>
public sealed override string GetPassword(string username, string answer)
{
if (EnablePasswordRetrieval == false)
throw new ProviderException("Password Retrieval Not Enabled.");
if (PasswordFormat == MembershipPasswordFormat.Hashed)
throw new ProviderException("Cannot retrieve Hashed passwords.");
return PerformGetPassword(username, answer);
}
/// <summary>
/// Gets the members password if password retreival is enabled
/// </summary>
/// <param name="username"></param>
/// <param name="answer"></param>
/// <returns></returns>
protected abstract string PerformGetPassword(string username, string answer);
public sealed override string ResetPassword(string username, string answer)
{
if (EnablePasswordReset == false)
{
throw new NotSupportedException("Password reset is not supported");
}
var newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters);
var args = new ValidatePasswordEventArgs(username, newPassword, true);
OnValidatingPassword(args);
if (args.Cancel)
{
if (args.FailureInformation != null)
{
throw args.FailureInformation;
}
throw new MembershipPasswordException("Reset password canceled due to password validation failure.");
}
return PerformResetPassword(username, answer, newPassword);
}
protected abstract string PerformResetPassword(string username, string answer, string generatedPassword);
protected internal static Attempt<PasswordValidityError> IsPasswordValid(string password, int minRequiredNonAlphanumericChars, string strengthRegex, int minLength)
{
if (minRequiredNonAlphanumericChars > 0)
{
var nonAlphaNumeric = Regex.Replace(password, "[a-zA-Z0-9]", "", RegexOptions.Multiline | RegexOptions.IgnoreCase);
if (nonAlphaNumeric.Length < minRequiredNonAlphanumericChars)
{
return Attempt.Fail(PasswordValidityError.AlphanumericChars);
}
}
if (string.IsNullOrEmpty(strengthRegex) == false)
{
if (Regex.IsMatch(password, strengthRegex, RegexOptions.Compiled) == false)
{
return Attempt.Fail(PasswordValidityError.Strength);
}
}
if (password.Length < minLength)
{
return Attempt.Fail(PasswordValidityError.Length);
}
return Attempt.Succeed(PasswordValidityError.Ok);
}
/// <summary>
/// Gets the name of the default app.
/// </summary>
/// <returns></returns>
internal static string GetDefaultAppName()
{
try
{
string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath;
if (string.IsNullOrEmpty(applicationVirtualPath))
{
return "/";
}
return applicationVirtualPath;
}
catch
{
return "/";
}
}
internal static int GetIntValue(NameValueCollection config, string valueName, int defaultValue, bool zeroAllowed, int maxValueAllowed)
{
int num;
string s = config[valueName];
if (s == null)
{
return defaultValue;
}
if (!int.TryParse(s, out num))
{
if (zeroAllowed)
{
throw new ProviderException("Value must be non negative integer");
}
throw new ProviderException("Value must be positive integer");
}
if (zeroAllowed && (num < 0))
{
throw new ProviderException("Value must be non negativeinteger");
}
if (!zeroAllowed && (num <= 0))
{
throw new ProviderException("Value must be positive integer");
}
if ((maxValueAllowed > 0) && (num > maxValueAllowed))
{
throw new ProviderException("Value too big");
}
return num;
}
/// <summary>
/// If the password format is a hashed keyed algorithm then we will pre-pend the salt used to hash the password
/// to the hashed password itself.
/// </summary>
/// <param name="pass"></param>
/// <param name="salt"></param>
/// <returns></returns>
protected internal string FormatPasswordForStorage(string pass, string salt)
{
if (UseLegacyEncoding)
{
return pass;
}
if (PasswordFormat == MembershipPasswordFormat.Hashed)
{
//the better way, we use salt per member
return salt + pass;
}
return pass;
}
internal static bool IsEmailValid(string email)
{
const string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
+ @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
+ @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
return Regex.IsMatch(email, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
protected internal string EncryptOrHashPassword(string pass, string salt)
{
//if we are doing it the old way
if (UseLegacyEncoding)
{
return LegacyEncodePassword(pass);
}
//This is the correct way to implement this (as per the sql membership provider)
if (PasswordFormat == MembershipPasswordFormat.Clear)
return pass;
var bytes = Encoding.Unicode.GetBytes(pass);
var numArray1 = Convert.FromBase64String(salt);
byte[] inArray;
if (PasswordFormat == MembershipPasswordFormat.Hashed)
{
var hashAlgorithm = GetHashAlgorithm(pass);
var algorithm = hashAlgorithm as KeyedHashAlgorithm;
if (algorithm != null)
{
var keyedHashAlgorithm = algorithm;
if (keyedHashAlgorithm.Key.Length == numArray1.Length)
keyedHashAlgorithm.Key = numArray1;
else if (keyedHashAlgorithm.Key.Length < numArray1.Length)
{
var numArray2 = new byte[keyedHashAlgorithm.Key.Length];
Buffer.BlockCopy(numArray1, 0, numArray2, 0, numArray2.Length);
keyedHashAlgorithm.Key = numArray2;
}
else
{
var numArray2 = new byte[keyedHashAlgorithm.Key.Length];
var dstOffset = 0;
while (dstOffset < numArray2.Length)
{
var count = Math.Min(numArray1.Length, numArray2.Length - dstOffset);
Buffer.BlockCopy(numArray1, 0, numArray2, dstOffset, count);
dstOffset += count;
}
keyedHashAlgorithm.Key = numArray2;
}
inArray = keyedHashAlgorithm.ComputeHash(bytes);
}
else
{
var buffer = new byte[numArray1.Length + bytes.Length];
Buffer.BlockCopy(numArray1, 0, buffer, 0, numArray1.Length);
Buffer.BlockCopy(bytes, 0, buffer, numArray1.Length, bytes.Length);
inArray = hashAlgorithm.ComputeHash(buffer);
}
}
else
{
//this code is copied from the sql membership provider - pretty sure this could be nicely re-written to completely
// ignore the salt stuff since we are not salting the password when encrypting.
var password = new byte[numArray1.Length + bytes.Length];
Buffer.BlockCopy(numArray1, 0, password, 0, numArray1.Length);
Buffer.BlockCopy(bytes, 0, password, numArray1.Length, bytes.Length);
inArray = EncryptPassword(password, MembershipPasswordCompatibilityMode.Framework40);
}
return Convert.ToBase64String(inArray);
}
/// <summary>
/// Checks the password.
/// </summary>
/// <param name="password">The password.</param>
/// <param name="dbPassword">The dbPassword.</param>
/// <returns></returns>
protected internal bool CheckPassword(string password, string dbPassword)
{
switch (PasswordFormat)
{
case MembershipPasswordFormat.Encrypted:
var decrypted = DecryptPassword(dbPassword);
return decrypted == password;
case MembershipPasswordFormat.Hashed:
string salt;
var storedHashedPass = StoredPassword(dbPassword, out salt);
var hashed = EncryptOrHashPassword(password, salt);
return storedHashedPass == hashed;
case MembershipPasswordFormat.Clear:
return password == dbPassword;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Encrypt/hash a new password with a new salt
/// </summary>
/// <param name="newPassword"></param>
/// <param name="salt"></param>
/// <returns></returns>
protected internal string EncryptOrHashNewPassword(string newPassword, out string salt)
{
salt = GenerateSalt();
return EncryptOrHashPassword(newPassword, salt);
}
protected internal string DecryptPassword(string pass)
{
//if we are doing it the old way
if (UseLegacyEncoding)
{
return LegacyUnEncodePassword(pass);
}
//This is the correct way to implement this (as per the sql membership provider)
switch ((int)PasswordFormat)
{
case 0:
return pass;
case 1:
throw new ProviderException("Provider can not decrypt hashed password");
default:
var bytes = DecryptPassword(Convert.FromBase64String(pass));
return bytes == null ? null : Encoding.Unicode.GetString(bytes, 16, bytes.Length - 16);
}
}
/// <summary>
/// Returns the hashed password without the salt if it is hashed
/// </summary>
/// <param name="storedString"></param>
/// <param name="salt">returns the salt</param>
/// <returns></returns>
internal string StoredPassword(string storedString, out string salt)
{
if (UseLegacyEncoding)
{
salt = string.Empty;
return storedString;
}
switch (PasswordFormat)
{
case MembershipPasswordFormat.Hashed:
var saltLen = GenerateSalt();
salt = storedString.Substring(0, saltLen.Length);
return storedString.Substring(saltLen.Length);
case MembershipPasswordFormat.Clear:
case MembershipPasswordFormat.Encrypted:
default:
salt = string.Empty;
return storedString;
}
}
protected internal static string GenerateSalt()
{
var numArray = new byte[16];
new RNGCryptoServiceProvider().GetBytes(numArray);
return Convert.ToBase64String(numArray);
}
protected internal HashAlgorithm GetHashAlgorithm(string password)
{
if (UseLegacyEncoding)
{
//before we were never checking for an algorithm type so we were always using HMACSHA1
// for any SHA specified algorithm :( so we'll need to keep doing that for backwards compat support.
if (Membership.HashAlgorithmType.InvariantContains("SHA"))
{
return new HMACSHA1
{
//the legacy salt was actually the password :(
Key = Encoding.Unicode.GetBytes(password)
};
}
}
//get the algorithm by name
if (_customHashAlgorithmType.IsNullOrWhiteSpace())
{
_customHashAlgorithmType = Membership.HashAlgorithmType;
}
var alg = HashAlgorithm.Create(_customHashAlgorithmType);
if (alg == null)
{
throw new InvalidOperationException("The hash algorithm specified " + Membership.HashAlgorithmType + " cannot be resolved");
}
return alg;
}
/// <summary>
/// Encodes the password.
/// </summary>
/// <param name="password">The password.</param>
/// <returns>The encoded password.</returns>
protected string LegacyEncodePassword(string password)
{
string encodedPassword = password;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
encodedPassword =
Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
break;
case MembershipPasswordFormat.Hashed:
var hashAlgorith = GetHashAlgorithm(password);
encodedPassword = Convert.ToBase64String(hashAlgorith.ComputeHash(Encoding.Unicode.GetBytes(password)));
break;
default:
throw new ProviderException("Unsupported password format.");
}
return encodedPassword;
}
/// <summary>
/// Unencode password.
/// </summary>
/// <param name="encodedPassword">The encoded password.</param>
/// <returns>The unencoded password.</returns>
protected string LegacyUnEncodePassword(string encodedPassword)
{
string password = encodedPassword;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
break;
case MembershipPasswordFormat.Hashed:
throw new ProviderException("Cannot unencode a hashed password.");
default:
throw new ProviderException("Unsupported password format.");
}
return password;
}
public override string ToString()
{
var result = base.ToString();
var sb = new StringBuilder(result);
sb.AppendLine("Name =" + Name);
sb.AppendLine("_applicationName =" + _applicationName);
sb.AppendLine("_enablePasswordReset=" + _enablePasswordReset);
sb.AppendLine("_enablePasswordRetrieval=" + _enablePasswordRetrieval);
sb.AppendLine("_maxInvalidPasswordAttempts=" + _maxInvalidPasswordAttempts);
sb.AppendLine("_minRequiredNonAlphanumericCharacters=" + _minRequiredNonAlphanumericCharacters);
sb.AppendLine("_minRequiredPasswordLength=" + _minRequiredPasswordLength);
sb.AppendLine("_passwordAttemptWindow=" + _passwordAttemptWindow);
sb.AppendLine("_passwordFormat=" + _passwordFormat);
sb.AppendLine("_passwordStrengthRegularExpression=" + _passwordStrengthRegularExpression);
sb.AppendLine("_requiresQuestionAndAnswer=" + _requiresQuestionAndAnswer);
sb.AppendLine("_requiresUniqueEmail=" + _requiresUniqueEmail);
return sb.ToString();
}
}
}
| |
using System;
using ArrayList = System.Collections.ArrayList;
//using CharFormatter = antlr.CharFormatter;
namespace Spring.Expressions.Parser.antlr.collections.impl
{
/*ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/license.html
*
* $Id:$
*/
//
// ANTLR C# Code Generator by Micheal Jordan
// Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com
// Anthony Oguntimehin
//
// With many thanks to Eric V. Smith from the ANTLR list.
//
/*A BitSet to replace java.util.BitSet.
* Primary differences are that most set operators return new sets
* as opposed to oring and anding "in place". Further, a number of
* operations were added. I cannot contain a BitSet because there
* is no way to access the internal bits (which I need for speed)
* and, because it is final, I cannot subclass to add functionality.
* Consider defining set degree. Without access to the bits, I must
* call a method n times to test the ith bit...ack!
*
* Also seems like or() from util is wrong when size of incoming set is bigger
* than this.bits.length.
*
* @author Terence Parr
* @author <br><a href="mailto:pete@yamuna.demon.co.uk">Pete Wells</a>
*/
public class BitSet : ICloneable
{
protected internal const int BITS = 64; // number of bits / long
protected internal const int NIBBLE = 4;
protected internal const int LOG_BITS = 6; // 2^6 == 64
/*We will often need to do a mod operator (i mod nbits). Its
* turns out that, for powers of two, this mod operation is
* same as (i & (nbits-1)). Since mod is slow, we use a
* precomputed mod mask to do the mod instead.
*/
protected internal static readonly int MOD_MASK = BITS - 1;
/*The actual data bits */
protected internal long[] dataBits;
/*Construct a bitset of size one word (64 bits) */
public BitSet() : this(BITS)
{
}
/*Construction from a static array of longs */
public BitSet(long[] bits_)
{
dataBits = bits_;
}
/*Construct a bitset given the size
* @param nbits The size of the bitset in bits
*/
public BitSet(int nbits)
{
dataBits = new long[((nbits - 1) >> LOG_BITS) + 1];
}
/*or this element into this set (grow as necessary to accommodate) */
public virtual void add(int el)
{
int n = wordNumber(el);
if (n >= dataBits.Length)
{
growToInclude(el);
}
dataBits[n] |= bitMask(el);
}
public virtual BitSet and(BitSet a)
{
BitSet s = (BitSet) this.Clone();
s.andInPlace(a);
return s;
}
public virtual void andInPlace(BitSet a)
{
int min = (int) (Math.Min(dataBits.Length, a.dataBits.Length));
for (int i = min - 1; i >= 0; i--)
{
dataBits[i] &= a.dataBits[i];
}
// clear all bits in this not present in a (if this bigger than a).
for (int i = min; i < dataBits.Length; i++)
{
dataBits[i] = 0;
}
}
private static long bitMask(int bitNumber)
{
int bitPosition = bitNumber & MOD_MASK; // bitNumber mod BITS
return 1L << bitPosition;
}
public virtual void clear()
{
for (int i = dataBits.Length - 1; i >= 0; i--)
{
dataBits[i] = 0;
}
}
public virtual void clear(int el)
{
int n = wordNumber(el);
if (n >= dataBits.Length)
{
// grow as necessary to accommodate
growToInclude(el);
}
dataBits[n] &= ~ bitMask(el);
}
public virtual object Clone()
{
BitSet s;
try
{
s = new BitSet();
s.dataBits = new long[dataBits.Length];
Array.Copy(dataBits, 0, s.dataBits, 0, dataBits.Length);
}
catch //(System.Exception e)
{
throw new System.ApplicationException();
}
return s;
}
public virtual int degree()
{
int deg = 0;
for (int i = dataBits.Length - 1; i >= 0; i--)
{
long word = dataBits[i];
if (word != 0L)
{
for (int bit = BITS - 1; bit >= 0; bit--)
{
if ((word & (1L << bit)) != 0)
{
deg++;
}
}
}
}
return deg;
}
override public int GetHashCode()
{
return dataBits.GetHashCode();
}
/*code "inherited" from java.util.BitSet */
override public bool Equals(object obj)
{
if ((obj != null) && (obj is BitSet))
{
BitSet bset = (BitSet) obj;
int n = (int) (System.Math.Min(dataBits.Length, bset.dataBits.Length));
for (int i = n; i-- > 0; )
{
if (dataBits[i] != bset.dataBits[i])
{
return false;
}
}
if (dataBits.Length > n)
{
for (int i = (int) (dataBits.Length); i-- > n; )
{
if (dataBits[i] != 0)
{
return false;
}
}
}
else if (bset.dataBits.Length > n)
{
for (int i = (int) (bset.dataBits.Length); i-- > n; )
{
if (bset.dataBits[i] != 0)
{
return false;
}
}
}
return true;
}
return false;
}
/*
* Grows the set to a larger number of bits.
* @param bit element that must fit in set
*/
public virtual void growToInclude(int bit)
{
int newSize = (int) (System.Math.Max(dataBits.Length << 1, numWordsToHold(bit)));
long[] newbits = new long[newSize];
Array.Copy(dataBits, 0, newbits, 0, dataBits.Length);
dataBits = newbits;
}
public virtual bool member(int el)
{
int n = wordNumber(el);
if (n >= dataBits.Length)
return false;
return (dataBits[n] & bitMask(el)) != 0;
}
public virtual bool nil()
{
for (int i = dataBits.Length - 1; i >= 0; i--)
{
if (dataBits[i] != 0)
return false;
}
return true;
}
public virtual BitSet not()
{
BitSet s = (BitSet) this.Clone();
s.notInPlace();
return s;
}
public virtual void notInPlace()
{
for (int i = dataBits.Length - 1; i >= 0; i--)
{
dataBits[i] = ~ dataBits[i];
}
}
/*complement bits in the range 0..maxBit. */
public virtual void notInPlace(int maxBit)
{
notInPlace(0, maxBit);
}
/*complement bits in the range minBit..maxBit.*/
public virtual void notInPlace(int minBit, int maxBit)
{
// make sure that we have room for maxBit
growToInclude(maxBit);
for (int i = minBit; i <= maxBit; i++)
{
int n = wordNumber(i);
dataBits[n] ^= bitMask(i);
}
}
private int numWordsToHold(int el)
{
return (el >> LOG_BITS) + 1;
}
public static BitSet of(int el)
{
BitSet s = new BitSet(el + 1);
s.add(el);
return s;
}
/*return this | a in a new set */
public virtual BitSet or(BitSet a)
{
BitSet s = (BitSet) this.Clone();
s.orInPlace(a);
return s;
}
public virtual void orInPlace(BitSet a)
{
// If this is smaller than a, grow this first
if (a.dataBits.Length > dataBits.Length)
{
setSize((int) (a.dataBits.Length));
}
int min = (int) (System.Math.Min(dataBits.Length, a.dataBits.Length));
for (int i = min - 1; i >= 0; i--)
{
dataBits[i] |= a.dataBits[i];
}
}
// remove this element from this set
public virtual void remove(int el)
{
int n = wordNumber(el);
if (n >= dataBits.Length)
{
growToInclude(el);
}
dataBits[n] &= ~ bitMask(el);
}
/*
* Sets the size of a set.
* @param nwords how many words the new set should be
*/
private void setSize(int nwords)
{
long[] newbits = new long[nwords];
int n = (int) (System.Math.Min(nwords, dataBits.Length));
Array.Copy(dataBits, 0, newbits, 0, n);
dataBits = newbits;
}
public virtual int size()
{
return dataBits.Length << LOG_BITS; // num words * bits per word
}
/*return how much space is being used by the dataBits array not
* how many actually have member bits on.
*/
public virtual int lengthInLongWords()
{
return dataBits.Length;
}
/*Is this contained within a? */
public virtual bool subset(BitSet a)
{
if (a == null) //(a == null || !(a is BitSet))
return false;
return this.and(a).Equals(this);
}
/*Subtract the elements of 'a' from 'this' in-place.
* Basically, just turn off all bits of 'this' that are in 'a'.
*/
public virtual void subtractInPlace(BitSet a)
{
if (a == null)
return ;
// for all words of 'a', turn off corresponding bits of 'this'
for (int i = 0; i < dataBits.Length && i < a.dataBits.Length; i++)
{
dataBits[i] &= ~ a.dataBits[i];
}
}
public virtual int[] toArray()
{
int[] elems = new int[degree()];
int en = 0;
for (int i = 0; i < (dataBits.Length << LOG_BITS); i++)
{
if (member(i))
{
elems[en++] = i;
}
}
return elems;
}
public virtual long[] toPackedArray()
{
return dataBits;
}
override public string ToString()
{
return ToString(",");
}
/*Transform a bit set into a string by formatting each element as an integer
* @separator The string to put in between elements
* @return A commma-separated list of values
*/
public virtual string ToString(string separator)
{
string str = "";
for (int i = 0; i < (dataBits.Length << LOG_BITS); i++)
{
if (member(i))
{
if (str.Length > 0)
{
str += separator;
}
str = str + i;
}
}
return str;
}
/*Create a string representation where instead of integer elements, the
* ith element of vocabulary is displayed instead. Vocabulary is a Vector
* of Strings.
* @separator The string to put in between elements
* @return A commma-separated list of character constants.
*/
public virtual string ToString(string separator, ArrayList vocabulary)
{
if (vocabulary == null)
{
return ToString(separator);
}
string str = "";
for (int i = 0; i < (dataBits.Length << LOG_BITS); i++)
{
if (member(i))
{
if (str.Length > 0)
{
str += separator;
}
if (i >= vocabulary.Count)
{
str += "<bad element " + i + ">";
}
else if (vocabulary[i] == null)
{
str += "<" + i + ">";
}
else
{
str += (string) vocabulary[i];
}
}
}
return str;
}
/*
* Dump a comma-separated list of the words making up the bit set.
* Split each 64 bit number into two more manageable 32 bit numbers.
* This generates a comma-separated list of C++-like unsigned long constants.
*/
public virtual string toStringOfHalfWords()
{
string s = new string("".ToCharArray());
for (int i = 0; i < dataBits.Length; i++)
{
if (i != 0)
s += ", ";
long tmp = dataBits[i];
tmp &= 0xFFFFFFFFL;
s += (tmp + "UL");
s += ", ";
tmp = SupportClass.URShift(dataBits[i], 32);
tmp &= 0xFFFFFFFFL;
s += (tmp + "UL");
}
return s;
}
/*
* Dump a comma-separated list of the words making up the bit set.
* This generates a comma-separated list of Java-like long int constants.
*/
public virtual string toStringOfWords()
{
string s = new string("".ToCharArray());
for (int i = 0; i < dataBits.Length; i++)
{
if (i != 0)
s += ", ";
s += (dataBits[i] + "L");
}
return s;
}
/*Print out the bit set but collapse char ranges. */
/* public virtual string toStringWithRanges(string separator, CharFormatter formatter)
{
string str = "";
int[] elems = this.toArray();
if (elems.Length == 0)
{
return "";
}
// look for ranges
int i = 0;
while (i < elems.Length)
{
int lastInRange;
lastInRange = 0;
for (int j = i + 1; j < elems.Length; j++)
{
if (elems[j] != elems[j - 1] + 1)
{
break;
}
lastInRange = j;
}
// found a range
if (str.Length > 0)
{
str += separator;
}
if (lastInRange - i >= 2)
{
str += formatter.literalChar(elems[i]);
str += "..";
str += formatter.literalChar(elems[lastInRange]);
i = lastInRange; // skip past end of range for next range
}
else
{
// no range, just print current char and move on
str += formatter.literalChar(elems[i]);
}
i++;
}
return str;
}
*/
private static int wordNumber(int bit)
{
return bit >> LOG_BITS; // bit / BITS
}
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
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.Runtime.InteropServices;
using System.ComponentModel;
using System.Xml.Serialization;
namespace OpenTK
{
/// <summary>
/// Represents a Quaternion.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Quaternion : IEquatable<Quaternion>
{
#region Fields
Vector3 xyz;
float w;
#endregion
#region Constructors
/// <summary>
/// Construct a new Quaternion from vector and w components
/// </summary>
/// <param name="v">The vector part</param>
/// <param name="w">The w part</param>
public Quaternion(Vector3 v, float w)
{
this.xyz = v;
this.w = w;
}
/// <summary>
/// Construct a new Quaternion
/// </summary>
/// <param name="x">The x component</param>
/// <param name="y">The y component</param>
/// <param name="z">The z component</param>
/// <param name="w">The w component</param>
public Quaternion(float x, float y, float z, float w)
: this(new Vector3(x, y, z), w)
{ }
#endregion
#region Public Members
#region Properties
#pragma warning disable 3005 // Identifier differing only in case is not CLS-compliant, compiler bug in Mono 3.4.0
/// <summary>
/// Gets or sets an OpenTK.Vector3 with the X, Y and Z components of this instance.
/// </summary>
[Obsolete("Use Xyz property instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
[XmlIgnore]
[CLSCompliant(false)]
public Vector3 XYZ { get { return Xyz; } set { Xyz = value; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3 with the X, Y and Z components of this instance.
/// </summary>
[CLSCompliant(false)]
public Vector3 Xyz { get { return xyz; } set { xyz = value; } }
#pragma warning restore 3005
/// <summary>
/// Gets or sets the X component of this instance.
/// </summary>
[XmlIgnore]
public float X { get { return xyz.X; } set { xyz.X = value; } }
/// <summary>
/// Gets or sets the Y component of this instance.
/// </summary>
[XmlIgnore]
public float Y { get { return xyz.Y; } set { xyz.Y = value; } }
/// <summary>
/// Gets or sets the Z component of this instance.
/// </summary>
[XmlIgnore]
public float Z { get { return xyz.Z; } set { xyz.Z = value; } }
/// <summary>
/// Gets or sets the W component of this instance.
/// </summary>
public float W { get { return w; } set { w = value; } }
#endregion
#region Instance
#region ToAxisAngle
/// <summary>
/// Convert the current quaternion to axis angle representation
/// </summary>
/// <param name="axis">The resultant axis</param>
/// <param name="angle">The resultant angle</param>
public void ToAxisAngle(out Vector3 axis, out float angle)
{
Vector4 result = ToAxisAngle();
axis = result.Xyz;
angle = result.W;
}
/// <summary>
/// Convert this instance to an axis-angle representation.
/// </summary>
/// <returns>A Vector4 that is the axis-angle representation of this quaternion.</returns>
public Vector4 ToAxisAngle()
{
Quaternion q = this;
if (Math.Abs(q.W) > 1.0f)
q.Normalize();
Vector4 result = new Vector4();
result.W = 2.0f * (float)System.Math.Acos(q.W); // angle
float den = (float)System.Math.Sqrt(1.0 - q.W * q.W);
if (den > 0.0001f)
{
result.Xyz = q.Xyz / den;
}
else
{
// This occurs when the angle is zero.
// Not a problem: just set an arbitrary normalized axis.
result.Xyz = Vector3.UnitX;
}
return result;
}
#endregion
#region public float Length
/// <summary>
/// Gets the length (magnitude) of the quaternion.
/// </summary>
/// <seealso cref="LengthSquared"/>
public float Length
{
get
{
return (float)System.Math.Sqrt(W * W + Xyz.LengthSquared);
}
}
#endregion
#region public float LengthSquared
/// <summary>
/// Gets the square of the quaternion length (magnitude).
/// </summary>
public float LengthSquared
{
get
{
return W * W + Xyz.LengthSquared;
}
}
#endregion
/// <summary>
/// Returns a copy of the Quaternion scaled to unit length.
/// </summary>
public Quaternion Normalized()
{
Quaternion q = this;
q.Normalize();
return q;
}
/// <summary>
/// Reverses the rotation angle of this Quaterniond.
/// </summary>
public void Invert()
{
W = -W;
}
/// <summary>
/// Returns a copy of this Quaterniond with its rotation angle reversed.
/// </summary>
public Quaternion Inverted()
{
var q = this;
q.Invert();
return q;
}
#region public void Normalize()
/// <summary>
/// Scales the Quaternion to unit length.
/// </summary>
public void Normalize()
{
float scale = 1.0f / this.Length;
Xyz *= scale;
W *= scale;
}
#endregion
#region public void Conjugate()
/// <summary>
/// Inverts the Vector3 component of this Quaternion.
/// </summary>
public void Conjugate()
{
Xyz = -Xyz;
}
#endregion
#endregion
#region Static
#region Fields
/// <summary>
/// Defines the identity quaternion.
/// </summary>
public static readonly Quaternion Identity = new Quaternion(0, 0, 0, 1);
#endregion
#region Add
/// <summary>
/// Add two quaternions
/// </summary>
/// <param name="left">The first operand</param>
/// <param name="right">The second operand</param>
/// <returns>The result of the addition</returns>
public static Quaternion Add(Quaternion left, Quaternion right)
{
return new Quaternion(
left.Xyz + right.Xyz,
left.W + right.W);
}
/// <summary>
/// Add two quaternions
/// </summary>
/// <param name="left">The first operand</param>
/// <param name="right">The second operand</param>
/// <param name="result">The result of the addition</param>
public static void Add(ref Quaternion left, ref Quaternion right, out Quaternion result)
{
result = new Quaternion(
left.Xyz + right.Xyz,
left.W + right.W);
}
#endregion
#region Sub
/// <summary>
/// Subtracts two instances.
/// </summary>
/// <param name="left">The left instance.</param>
/// <param name="right">The right instance.</param>
/// <returns>The result of the operation.</returns>
public static Quaternion Sub(Quaternion left, Quaternion right)
{
return new Quaternion(
left.Xyz - right.Xyz,
left.W - right.W);
}
/// <summary>
/// Subtracts two instances.
/// </summary>
/// <param name="left">The left instance.</param>
/// <param name="right">The right instance.</param>
/// <param name="result">The result of the operation.</param>
public static void Sub(ref Quaternion left, ref Quaternion right, out Quaternion result)
{
result = new Quaternion(
left.Xyz - right.Xyz,
left.W - right.W);
}
#endregion
#region Mult
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
[Obsolete("Use Multiply instead.")]
public static Quaternion Mult(Quaternion left, Quaternion right)
{
return new Quaternion(
right.W * left.Xyz + left.W * right.Xyz + Vector3.Cross(left.Xyz, right.Xyz),
left.W * right.W - Vector3.Dot(left.Xyz, right.Xyz));
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <param name="result">A new instance containing the result of the calculation.</param>
[Obsolete("Use Multiply instead.")]
public static void Mult(ref Quaternion left, ref Quaternion right, out Quaternion result)
{
result = new Quaternion(
right.W * left.Xyz + left.W * right.Xyz + Vector3.Cross(left.Xyz, right.Xyz),
left.W * right.W - Vector3.Dot(left.Xyz, right.Xyz));
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
public static Quaternion Multiply(Quaternion left, Quaternion right)
{
Quaternion result;
Multiply(ref left, ref right, out result);
return result;
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <param name="result">A new instance containing the result of the calculation.</param>
public static void Multiply(ref Quaternion left, ref Quaternion right, out Quaternion result)
{
result = new Quaternion(
right.W * left.Xyz + left.W * right.Xyz + Vector3.Cross(left.Xyz, right.Xyz),
left.W * right.W - Vector3.Dot(left.Xyz, right.Xyz));
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="quaternion">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <param name="result">A new instance containing the result of the calculation.</param>
public static void Multiply(ref Quaternion quaternion, float scale, out Quaternion result)
{
result = new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale);
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="quaternion">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
public static Quaternion Multiply(Quaternion quaternion, float scale)
{
return new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale);
}
#endregion
#region Conjugate
/// <summary>
/// Get the conjugate of the given quaternion
/// </summary>
/// <param name="q">The quaternion</param>
/// <returns>The conjugate of the given quaternion</returns>
public static Quaternion Conjugate(Quaternion q)
{
return new Quaternion(-q.Xyz, q.W);
}
/// <summary>
/// Get the conjugate of the given quaternion
/// </summary>
/// <param name="q">The quaternion</param>
/// <param name="result">The conjugate of the given quaternion</param>
public static void Conjugate(ref Quaternion q, out Quaternion result)
{
result = new Quaternion(-q.Xyz, q.W);
}
#endregion
#region Invert
/// <summary>
/// Get the inverse of the given quaternion
/// </summary>
/// <param name="q">The quaternion to invert</param>
/// <returns>The inverse of the given quaternion</returns>
public static Quaternion Invert(Quaternion q)
{
Quaternion result;
Invert(ref q, out result);
return result;
}
/// <summary>
/// Get the inverse of the given quaternion
/// </summary>
/// <param name="q">The quaternion to invert</param>
/// <param name="result">The inverse of the given quaternion</param>
public static void Invert(ref Quaternion q, out Quaternion result)
{
float lengthSq = q.LengthSquared;
if (lengthSq != 0.0)
{
float i = 1.0f / lengthSq;
result = new Quaternion(q.Xyz * -i, q.W * i);
}
else
{
result = q;
}
}
#endregion
#region Normalize
/// <summary>
/// Scale the given quaternion to unit length
/// </summary>
/// <param name="q">The quaternion to normalize</param>
/// <returns>The normalized quaternion</returns>
public static Quaternion Normalize(Quaternion q)
{
Quaternion result;
Normalize(ref q, out result);
return result;
}
/// <summary>
/// Scale the given quaternion to unit length
/// </summary>
/// <param name="q">The quaternion to normalize</param>
/// <param name="result">The normalized quaternion</param>
public static void Normalize(ref Quaternion q, out Quaternion result)
{
float scale = 1.0f / q.Length;
result = new Quaternion(q.Xyz * scale, q.W * scale);
}
#endregion
#region FromAxisAngle
/// <summary>
/// Build a quaternion from the given axis and angle
/// </summary>
/// <param name="axis">The axis to rotate about</param>
/// <param name="angle">The rotation angle in radians</param>
/// <returns>The equivalent quaternion</returns>
public static Quaternion FromAxisAngle(Vector3 axis, float angle)
{
if (axis.LengthSquared == 0.0f)
return Identity;
Quaternion result = Identity;
angle *= 0.5f;
axis.Normalize();
result.Xyz = axis * (float)System.Math.Sin(angle);
result.W = (float)System.Math.Cos(angle);
return Normalize(result);
}
#endregion
#region FromMatrix
/// <summary>
/// Builds a quaternion from the given rotation matrix
/// </summary>
/// <param name="matrix">A rotation matrix</param>
/// <returns>The equivalent quaternion</returns>
public static Quaternion FromMatrix(Matrix3 matrix)
{
Quaternion result;
FromMatrix(ref matrix, out result);
return result;
}
/// <summary>
/// Builds a quaternion from the given rotation matrix
/// </summary>
/// <param name="matrix">A rotation matrix</param>
/// <param name="result">The equivalent quaternion</param>
public static void FromMatrix(ref Matrix3 matrix, out Quaternion result)
{
float trace = matrix.Trace;
if (trace > 0)
{
float s = (float)Math.Sqrt(trace + 1) * 2;
float invS = 1f / s;
result.w = s * 0.25f;
result.xyz.X = (matrix.Row2.Y - matrix.Row1.Z) * invS;
result.xyz.Y = (matrix.Row0.Z - matrix.Row2.X) * invS;
result.xyz.Z = (matrix.Row1.X - matrix.Row0.Y) * invS;
}
else
{
float m00 = matrix.Row0.X, m11 = matrix.Row1.Y, m22 = matrix.Row2.Z;
if (m00 > m11 && m00 > m22)
{
float s = (float)Math.Sqrt(1 + m00 - m11 - m22) * 2;
float invS = 1f / s;
result.w = (matrix.Row2.Y - matrix.Row1.Z) * invS;
result.xyz.X = s * 0.25f;
result.xyz.Y = (matrix.Row0.Y + matrix.Row1.X) * invS;
result.xyz.Z = (matrix.Row0.Z + matrix.Row2.X) * invS;
}
else if (m11 > m22)
{
float s = (float)Math.Sqrt(1 + m11 - m00 - m22) * 2;
float invS = 1f / s;
result.w = (matrix.Row0.Z - matrix.Row2.X) * invS;
result.xyz.X = (matrix.Row0.Y + matrix.Row1.X) * invS;
result.xyz.Y = s * 0.25f;
result.xyz.Z = (matrix.Row1.Z + matrix.Row2.Y) * invS;
}
else
{
float s = (float)Math.Sqrt(1 + m22 - m00 - m11) * 2;
float invS = 1f / s;
result.w = (matrix.Row1.X - matrix.Row0.Y) * invS;
result.xyz.X = (matrix.Row0.Z + matrix.Row2.X) * invS;
result.xyz.Y = (matrix.Row1.Z + matrix.Row2.Y) * invS;
result.xyz.Z = s * 0.25f;
}
}
}
#endregion
#region Slerp
/// <summary>
/// Do Spherical linear interpolation between two quaternions
/// </summary>
/// <param name="q1">The first quaternion</param>
/// <param name="q2">The second quaternion</param>
/// <param name="blend">The blend factor</param>
/// <returns>A smooth blend between the given quaternions</returns>
public static Quaternion Slerp(Quaternion q1, Quaternion q2, float blend)
{
// if either input is zero, return the other.
if (q1.LengthSquared == 0.0f)
{
if (q2.LengthSquared == 0.0f)
{
return Identity;
}
return q2;
}
else if (q2.LengthSquared == 0.0f)
{
return q1;
}
float cosHalfAngle = q1.W * q2.W + Vector3.Dot(q1.Xyz, q2.Xyz);
if (cosHalfAngle >= 1.0f || cosHalfAngle <= -1.0f)
{
// angle = 0.0f, so just return one input.
return q1;
}
else if (cosHalfAngle < 0.0f)
{
q2.Xyz = -q2.Xyz;
q2.W = -q2.W;
cosHalfAngle = -cosHalfAngle;
}
float blendA;
float blendB;
if (cosHalfAngle < 0.99f)
{
// do proper slerp for big angles
float halfAngle = (float)System.Math.Acos(cosHalfAngle);
float sinHalfAngle = (float)System.Math.Sin(halfAngle);
float oneOverSinHalfAngle = 1.0f / sinHalfAngle;
blendA = (float)System.Math.Sin(halfAngle * (1.0f - blend)) * oneOverSinHalfAngle;
blendB = (float)System.Math.Sin(halfAngle * blend) * oneOverSinHalfAngle;
}
else
{
// do lerp if angle is really small.
blendA = 1.0f - blend;
blendB = blend;
}
Quaternion result = new Quaternion(blendA * q1.Xyz + blendB * q2.Xyz, blendA * q1.W + blendB * q2.W);
if (result.LengthSquared > 0.0f)
return Normalize(result);
else
return Identity;
}
#endregion
#endregion
#region Operators
/// <summary>
/// Adds two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Quaternion operator +(Quaternion left, Quaternion right)
{
left.Xyz += right.Xyz;
left.W += right.W;
return left;
}
/// <summary>
/// Subtracts two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Quaternion operator -(Quaternion left, Quaternion right)
{
left.Xyz -= right.Xyz;
left.W -= right.W;
return left;
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Quaternion operator *(Quaternion left, Quaternion right)
{
Multiply(ref left, ref right, out left);
return left;
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="quaternion">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
public static Quaternion operator *(Quaternion quaternion, float scale)
{
Multiply(ref quaternion, scale, out quaternion);
return quaternion;
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="quaternion">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
public static Quaternion operator *(float scale, Quaternion quaternion)
{
return new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale);
}
/// <summary>
/// Compares two instances for equality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left equals right; false otherwise.</returns>
public static bool operator ==(Quaternion left, Quaternion right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances for inequality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left does not equal right; false otherwise.</returns>
public static bool operator !=(Quaternion left, Quaternion right)
{
return !left.Equals(right);
}
#endregion
#region Overrides
#region public override string ToString()
/// <summary>
/// Returns a System.String that represents the current Quaternion.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("V: {0}, W: {1}", Xyz, W);
}
#endregion
#region public override bool Equals (object o)
/// <summary>
/// Compares this object instance to another object for equality.
/// </summary>
/// <param name="other">The other object to be used in the comparison.</param>
/// <returns>True if both objects are Quaternions of equal value. Otherwise it returns false.</returns>
public override bool Equals(object other)
{
if (other is Quaternion == false) return false;
return this == (Quaternion)other;
}
#endregion
#region public override int GetHashCode ()
/// <summary>
/// Provides the hash code for this object.
/// </summary>
/// <returns>A hash code formed from the bitwise XOR of this objects members.</returns>
public override int GetHashCode()
{
return Xyz.GetHashCode() ^ W.GetHashCode();
}
#endregion
#endregion
#endregion
#region IEquatable<Quaternion> Members
/// <summary>
/// Compares this Quaternion instance to another Quaternion for equality.
/// </summary>
/// <param name="other">The other Quaternion to be used in the comparison.</param>
/// <returns>True if both instances are equal; false otherwise.</returns>
public bool Equals(Quaternion other)
{
return Xyz == other.Xyz && W == other.W;
}
#endregion
}
}
| |
// 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 Sensus.UI.UiProperties;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Sensus.Probes
{
/// <summary>
/// Listening Probes are triggered by a change in state within the underlying device. For example, when an accelerometer reading is emitted, the
/// <see cref="Movement.AccelerometerProbe"/> is provided with information about device movement in each direction. Listening Probes do not generate
/// data unless such state changes occur.
/// </summary>
public abstract class ListeningProbe : Probe
{
private enum SamplingModulusMatchAction
{
Store,
Drop
}
private const float DATA_RATE_EPSILON = 0.00000000001f;
private float? _maxDataStoresPerSecond;
private bool _keepDeviceAwake;
private bool _deviceAwake;
private DataRateCalculator _incomingDataRateCalculator;
private int _samplingModulus;
private SamplingModulusMatchAction _samplingModulusMatchAction;
private readonly object _locker = new object();
/// <summary>
/// The maximum number of readings that may be stored in one second.
/// </summary>
/// <value>Maximum data stores per second.</value>
[EntryFloatUiProperty("Max Data / Second:", true, int.MaxValue)]
public float? MaxDataStoresPerSecond
{
get { return _maxDataStoresPerSecond; }
set
{
if (value < 0)
{
value = 0;
}
_maxDataStoresPerSecond = value;
}
}
[JsonIgnore]
public TimeSpan? MinDataStoreDelay
{
get
{
float maxDataStoresPerSecond = _maxDataStoresPerSecond.GetValueOrDefault(-1);
// 0 (or negligible) data per second: maximum delay
if (Math.Abs(maxDataStoresPerSecond) < DATA_RATE_EPSILON)
{
return TimeSpan.MaxValue;
}
// non-negligible data per second: usual calculation
else if (maxDataStoresPerSecond > 0)
{
return TimeSpan.FromSeconds(1 / maxDataStoresPerSecond);
}
// unrestricted data per second: no delay specified
else
{
return default(TimeSpan?);
}
}
}
/// <summary>
/// This parameter only affects Android, and it determines whether or not to keep the device awake while listening for readings while Sensus is
/// backgrounded. If turned on, readings will be delivered to Sensus in the backgrounded; however, more power will be consumed because the processor
/// will not be allowed to sleep. If turned off, readings will be paused when Sensus is backgrounded. This will conserve power because the processor
/// will be allowed to sleep, but readings will be delayed and possibly dropped entirely. When the device wakes up, some readings that were cached
/// while asleep may be delivered in bulk to Sensus. This bulk delivery may not include all readings, and the readings delivered in bulk will have
/// their <see cref="Datum.Timestamp"/> fields set to the time of bulk delivery rather than the time the reading originated. Even a single listening
/// probe with this setting turned on will be sufficient to keep the processor awake and delivering readings to all listening probes in all protocols
/// within Sensus.
/// </summary>
/// <value><c>true</c> to keep device awake; otherwise, <c>false</c>.</value>
[OnOffUiProperty("Keep Device Awake:", true, int.MaxValue - 1)]
public bool KeepDeviceAwake
{
get
{
return _keepDeviceAwake;
}
set
{
// warn the user about this setting if it's being changed
if (value != _keepDeviceAwake && SensusServiceHelper.Get() != null)
{
TimeSpan duration = TimeSpan.FromSeconds(6);
if (value && !string.IsNullOrWhiteSpace(DeviceAwakeWarning))
{
SensusServiceHelper.Get().FlashNotificationAsync(DeviceAwakeWarning);
}
else if (!value && !string.IsNullOrWhiteSpace(DeviceAsleepWarning))
{
SensusServiceHelper.Get().FlashNotificationAsync(DeviceAsleepWarning);
}
}
_keepDeviceAwake = value;
}
}
[JsonIgnore]
protected abstract bool DefaultKeepDeviceAwake { get; }
[JsonIgnore]
protected abstract string DeviceAwakeWarning { get; }
[JsonIgnore]
protected abstract string DeviceAsleepWarning { get; }
protected override double RawParticipation
{
get
{
#if __ANDROID__
// compute participation using successful health test times of the probe
long daySeconds = 60 * 60 * 24;
long participationHorizonSeconds = Protocol.ParticipationHorizonDays * daySeconds;
double fullParticipationHealthTests = participationHorizonSeconds / SensusServiceHelper.HEALTH_TEST_DELAY.TotalSeconds;
// lock collection because it might be concurrently modified by the test health method running in another thread.
lock (SuccessfulHealthTestTimes)
{
return SuccessfulHealthTestTimes.Count(healthTestTime => healthTestTime >= Protocol.ParticipationHorizon) / fullParticipationHealthTests;
}
#elif __IOS__
// on ios, we cannot rely on the health test times to tell us how long the probe has been running. this is
// because, unlike in android, ios does not let local notifications return to the app when the app is in the
// background. instead, the ios user must open a notification or directly open the app in order for the health
// test to run. so the best we can do is keep track of when the probe was started and stopped and compute participation
// based on how much of the participation horizon has been covered by the probe. it is possible that the probe
// is in this running state but is somehow faulty and failing the health tests. thus, the approach is not
// perfect, but it's the best we can do on ios.
double runningSeconds;
lock (StartStopTimes)
{
if (StartStopTimes.Count == 0)
return 0;
runningSeconds = StartStopTimes.Select((startStopTime, index) =>
{
DateTime? startTime = null;
DateTime? stopTime = null;
// if this is the final element and it's a start time, then the probe is currently running and we should calculate
// how much time has elapsed since the probe was started.
if (index == StartStopTimes.Count - 1 && startStopTime.Item1)
{
// if the current start time came before the participation horizon, use the horizon as the start time.
if (startStopTime.Item2 < Protocol.ParticipationHorizon)
{
startTime = Protocol.ParticipationHorizon;
}
else
{
startTime = startStopTime.Item2;
}
// the probe is currently running, so use the current time as the stop time.
stopTime = DateTime.Now;
}
// otherwise, we only need to consider stop times after the participation horizon.
else if (!startStopTime.Item1 && startStopTime.Item2 > Protocol.ParticipationHorizon)
{
stopTime = startStopTime.Item2;
// if the previous element is a start time, use it.
if (index > 0 && StartStopTimes[index - 1].Item1)
{
startTime = StartStopTimes[index - 1].Item2;
}
// if we don't have a previous element that's a start time, or we do but the start time was before the participation horizon, then
// use the participation horizon as the start time.
if (startTime == null || startTime.Value < Protocol.ParticipationHorizon)
{
startTime = Protocol.ParticipationHorizon;
}
}
// if we've got a start and stop time, return the total number of seconds covered.
if (startTime != null && stopTime != null)
{
return (stopTime.Value - startTime.Value).TotalSeconds;
}
else
{
return 0;
}
}).Sum();
}
double participationHorizonSeconds = TimeSpan.FromDays(Protocol.ParticipationHorizonDays).TotalSeconds;
return (float)(runningSeconds / participationHorizonSeconds);
#elif LOCAL_TESTS
return 0;
#else
#warning "Unrecognized platform"
return 0;
#endif
}
}
public override string CollectionDescription
{
get
{
return DisplayName + ": When it changes.";
}
}
protected ListeningProbe()
{
_maxDataStoresPerSecond = null; // no data rate limit by default
_keepDeviceAwake = DefaultKeepDeviceAwake;
_deviceAwake = false;
_incomingDataRateCalculator = new DataRateCalculator(100);
// store all data to start with. we'll compute a store/drop rate after data have arrived.
_samplingModulus = 1;
_samplingModulusMatchAction = SamplingModulusMatchAction.Store;
}
protected sealed override void InternalStart()
{
lock (_locker)
{
_incomingDataRateCalculator.Clear();
// only keep device awake if we're not already running. calls to LetDeviceSleep must match these exactly.
if (!Running && _keepDeviceAwake)
{
SensusServiceHelper.Get().KeepDeviceAwake();
_deviceAwake = true;
}
base.InternalStart();
StartListening();
}
}
protected abstract void StartListening();
public sealed override void Stop()
{
lock (_locker)
{
base.Stop();
StopListening();
if (_deviceAwake)
{
SensusServiceHelper.Get().LetDeviceSleep();
_deviceAwake = false;
}
_incomingDataRateCalculator.Clear();
}
}
protected abstract void StopListening();
public sealed override Task<bool> StoreDatumAsync(Datum datum, CancellationToken? cancellationToken = default(CancellationToken?))
{
bool store = true;
float maxDataStoresPerSecond = _maxDataStoresPerSecond.GetValueOrDefault(-1);
// 0 (or negligible) data per second: don't store. if max data per second is not set, the following inequality will be false.
if (Math.Abs(maxDataStoresPerSecond) < DATA_RATE_EPSILON)
{
store = false;
}
// non-negligible (or default -1) data per second: check data rate
else if (maxDataStoresPerSecond > 0)
{
_incomingDataRateCalculator.Add(datum);
// recalculate the sampling modulus after accumulating a full sample size in the data rate calculator
if ((_incomingDataRateCalculator.TotalAdded % _incomingDataRateCalculator.SampleSize) == 0)
{
double incomingDataPerSecond = _incomingDataRateCalculator.DataPerSecond;
double extraDataPerSecond = incomingDataPerSecond - maxDataStoresPerSecond;
// if we're not over the limit then store all samples
if (extraDataPerSecond <= 0)
{
_samplingModulus = 1;
_samplingModulusMatchAction = SamplingModulusMatchAction.Store;
}
// otherwise calculate a modulus that will get as close as possible to the desired rate given the empirical rate
else
{
double samplingModulusMatchRate = extraDataPerSecond / incomingDataPerSecond;
_samplingModulusMatchAction = SamplingModulusMatchAction.Drop;
if (samplingModulusMatchRate > 0.5)
{
samplingModulusMatchRate = 1 - samplingModulusMatchRate;
_samplingModulusMatchAction = SamplingModulusMatchAction.Store;
}
if (_samplingModulusMatchAction == SamplingModulusMatchAction.Store)
{
// round the (store) modulus down to oversample -- more is better, right?
_samplingModulus = (int)Math.Floor(1 / samplingModulusMatchRate);
}
else
{
// round the (drop) modulus up to oversample -- more is better, right?
_samplingModulus = (int)Math.Ceiling(1 / samplingModulusMatchRate);
}
}
}
bool isModulusMatch = (_incomingDataRateCalculator.TotalAdded % _samplingModulus) == 0;
if ((_samplingModulusMatchAction == SamplingModulusMatchAction.Store && !isModulusMatch) || (_samplingModulusMatchAction == SamplingModulusMatchAction.Drop && isModulusMatch))
{
store = false;
}
}
if (store)
{
return base.StoreDatumAsync(datum, cancellationToken.GetValueOrDefault());
}
else
{
return Task.FromResult(false);
}
}
public override void Reset()
{
base.Reset();
_deviceAwake = false;
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace SpiffLib {
class TBitmap {
enum Align { None, Even, Odd, Both };
enum ColorType { Unknown, Shadow, Side, Transparent, Data };
enum Op {
EvenData1, EvenData2, EvenData3, EvenData4, EvenData5, EvenData6, EvenData7, EvenData8, EvenData9,
EvenData10, EvenData11, EvenData12, EvenData13, EvenData14, EvenData15, EvenData16, EvenData17,
EvenData18, EvenData19, EvenData20, EvenData21, EvenData22, EvenData23, EvenData24, EvenData25,
EvenData26, EvenData27, EvenData28, EvenData29, EvenData30, EvenData31, EvenData32, EvenData33,
EvenData34, EvenData35, EvenData36, EvenData37, EvenData38, EvenData39, EvenData40, EvenData41,
EvenData42, EvenData43, EvenData44, EvenData45, EvenData46, EvenData47, EvenData48,
OddData1, OddData2, OddData3, OddData4, OddData5, OddData6, OddData7, OddData8, OddData9,
OddData10, OddData11, OddData12, OddData13, OddData14, OddData15, OddData16, OddData17,
OddData18, OddData19, OddData20, OddData21, OddData22, OddData23, OddData24, OddData25,
OddData26, OddData27, OddData28, OddData29, OddData30, OddData31, OddData32, OddData33,
OddData34, OddData35, OddData36, OddData37, OddData38, OddData39, OddData40, OddData41,
OddData42, OddData43, OddData44, OddData45, OddData46, OddData47, OddData48,
EvenSide1, EvenSide2, EvenSide3, EvenSide4, EvenSide5, EvenSide6, EvenSide7, EvenSide8, EvenSide9,
EvenSide10, EvenSide11, EvenSide12, EvenSide13, EvenSide14, EvenSide15, EvenSide16,
OddSide1, OddSide2, OddSide3, OddSide4, OddSide5, OddSide6, OddSide7, OddSide8, OddSide9,
OddSide10, OddSide11, OddSide12, OddSide13, OddSide14, OddSide15, OddSide16,
Shadow1, Shadow2, Shadow3, Shadow4, Shadow5, Shadow6, Shadow7, Shadow8, Shadow9,
Shadow10, Shadow11, Shadow12, Shadow13, Shadow14, Shadow15, Shadow16, Shadow17,
Shadow18, Shadow19, Shadow20, Shadow21, Shadow22, Shadow23, Shadow24,
Transparent1, Transparent2, Transparent3, Transparent4, Transparent5, Transparent6, Transparent7, Transparent8, Transparent9,
Transparent10, Transparent11, Transparent12, Transparent13, Transparent14, Transparent15, Transparent16, Transparent17,
Transparent18, Transparent19, Transparent20, Transparent21, Transparent22, Transparent23, Transparent24, Transparent25,
Transparent26, Transparent27, Transparent28, Transparent29, Transparent30, Transparent31, Transparent32,
NextScan0, NextScan1, NextScan2, NextScan3, NextScan4, NextScan5, NextScan6, NextScan7, NextScan8, NextScan9,
NextScan10, NextScan11, NextScan12, NextScan13, NextScan14, NextScan15, NextScan16, NextScan17, NextScan18,
NextScan19, NextScan20, NextScan21, NextScan22, NextScan23, NextScan24, NextScan25, NextScan26, NextScan27,
NextScan28, NextScan29, NextScan30, NextScan31, NextScan32, NextScan33, NextScan34, NextScan35, NextScan36,
NextScan37, NextScan38, NextScan39, NextScan40, NextScan41, NextScan42, NextScan43, NextScan44, NextScan45,
NextScan46, NextScan47, NextScan48,
Align,
End
};
int m_cx;
int m_cy;
int m_yBaseline;
ScanData[] m_asdEven;
Palette m_pal;
ArrayList m_alsFrames = new ArrayList();
static Color s_clrShadow = Color.FromArgb(156, 212, 248);
static Color s_clrTransparent = Color.FromArgb(255, 0, 255);
static Color s_clrSideIndex0 = Color.FromArgb(0, 116, 232);
static Color s_clrSideIndex1 = Color.FromArgb(0, 96, 196);
static Color s_clrSideIndex2 = Color.FromArgb(0, 64, 120);
static Color s_clrSideIndex3 = Color.FromArgb(0, 48, 92);
static Color s_clrSideIndex4 = Color.FromArgb(0, 32, 64);
static int s_iclrShadow = -1;
static int s_iclrTransparent = -2;
static int s_iclrNotAssigned = -3;
static int s_iclrSideFirst = -8;
static int s_iclrSideLast = -4;
static int s_cpDataMax = 48;
static int s_cpSideMax = 16;
static int s_cpShadowMax = 24;
static int s_cpTransparentMax = 32;
static int s_cpNextScanMax = 48;
public TBitmap(string strFile, Palette pal) {
m_pal = pal;
Init(new Bitmap(strFile));
}
public TBitmap(Bitmap bm, Palette pal) {
m_pal = pal;
Init(bm);
}
public TBitmap(Palette pal) {
m_pal = pal;
}
void Init(Bitmap bm) {
m_cx = bm.Width;
m_cy = bm.Height;
m_yBaseline = Misc.FindBaseline(bm);
int[][] aaiclrScans = GetScans(bm);
m_asdEven = CompileScanData(Align.Even, aaiclrScans);
}
ScanData[] CompileScanData(Align alignMaster, int[][] aaiclrScans) {
ArrayList alsSd = new ArrayList();
Align alignStart = Align.Even;
for (int y = 0; y < aaiclrScans.GetLength(0); y++) {
if (alsSd.Count != 0)
alignStart = ((ScanData)alsSd[alsSd.Count - 1]).GetNextDataAlignment(alignStart);
alsSd.Add(new ScanData(alignMaster, alignStart, aaiclrScans[y]));
}
return (ScanData[])alsSd.ToArray(typeof(ScanData));
}
unsafe int[][] GetScans(Bitmap bm) {
// Special colors
int[][] aaiclrScans = new int[m_cy][];
// Lock down bits for speed
Rectangle rc = new Rectangle(0, 0, m_cx, m_cy);
BitmapData bmd = bm.LockBits(rc, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
byte *pbBase = (byte *)bmd.Scan0.ToPointer();
for (int y = 0; y < m_cy; y++) {
int[] aiclrScan = new int[m_cx];
for (int x = 0; x < m_cx; x++) {
// Get color
byte *pb = pbBase + y * bmd.Stride + x * 3;
Color clr = Color.FromArgb(pb[2], pb[1], pb[0]);
if (clr == s_clrTransparent) {
aiclrScan[x] = s_iclrTransparent;
continue;
}
if (clr == s_clrShadow) {
aiclrScan[x] = s_iclrShadow;
continue;
}
if (clr == s_clrSideIndex0) {
aiclrScan[x] = s_iclrSideFirst + 0;
continue;
}
if (clr == s_clrSideIndex1) {
aiclrScan[x] = s_iclrSideFirst + 1;
continue;
}
if (clr == s_clrSideIndex2) {
aiclrScan[x] = s_iclrSideFirst + 2;
continue;
}
if (clr == s_clrSideIndex3) {
aiclrScan[x] = s_iclrSideFirst + 3;
continue;
}
if (clr == s_clrSideIndex4) {
aiclrScan[x] = s_iclrSideFirst + 4;
continue;
}
aiclrScan[x] = m_pal.FindClosestEntry(clr);
}
aaiclrScans[y] = aiclrScan;
}
bm.UnlockBits(bmd);
return aaiclrScans;
}
class ScanData {
ArrayList m_alsIclr = new ArrayList();
ArrayList m_alsSideCodes = new ArrayList();
ArrayList m_alsOps = new ArrayList();
struct Run {
public int cp;
public ColorType ct;
public Align align;
public int[] aiclr;
}
public ScanData(Align alignMaster, Align alignData, int[] aiclrScan) {
CompileRuns(alignData, GetRuns(alignMaster, aiclrScan));
}
public Align GetNextDataAlignment(Align alignStart) {
if (alignStart == Align.Even) {
return (m_alsIclr.Count & 1) != 0 ? Align.Odd : Align.Even;
} else {
return (m_alsIclr.Count & 1) == 0 ? Align.Odd : Align.Even;
}
}
public int[] GetColorData() {
return (int[])m_alsIclr.ToArray(typeof(int));
}
public int[] GetSideCodes() {
return (int[])m_alsSideCodes.ToArray(typeof(int));
}
public Op[] GetOps() {
return (Op[])m_alsOps.ToArray(typeof(Op));
}
void AddSideCodes(Align align, int[] aiclr) {
m_alsSideCodes.AddRange(EncodeSideColors(align, aiclr));
}
ColorType GetColorType(int iclr) {
if (iclr == s_iclrTransparent)
return ColorType.Transparent;
if (iclr == s_iclrShadow)
return ColorType.Shadow;
if (iclr >= s_iclrSideFirst && iclr <= s_iclrSideLast)
return ColorType.Side;
return ColorType.Data;
}
Run[] GetRuns(Align alignScan, int[] aiclrScan) {
// First calc and remember the runs
ArrayList alsCtRuns = new ArrayList();
ArrayList alsCounts = new ArrayList();
ColorType ctRun = ColorType.Unknown;
int iiclrFirst = 0;
for (int iiclr = 0; iiclr < aiclrScan.Length; iiclr++) {
// Classify color
ColorType ctCurrent = GetColorType(aiclrScan[iiclr]);
// Continue if we're in a run
if (ctRun == ctCurrent)
continue;
// Add the run type and the count of pixels this is
if (ctRun != ColorType.Unknown) {
alsCtRuns.Add(ctRun);
alsCounts.Add(iiclr - iiclrFirst);
}
// Start a run with this color type
iiclrFirst = iiclr;
ctRun = ctCurrent;
}
// Add the last run
alsCtRuns.Add(ctRun);
alsCounts.Add(aiclrScan.Length - iiclrFirst);
// Now all the scan is classified in terms of runs of color types. Now create runs.
ArrayList alsRun = new ArrayList();
int iiclrRun = 0;
for (int i = 0; i < alsCtRuns.Count; i++) {
AddRun(alsRun, alignScan, iiclrRun, aiclrScan, (int)alsCounts[i], (ColorType)alsCtRuns[i]);
iiclrRun += (int)alsCounts[i];
}
// All done
return (Run[])alsRun.ToArray(typeof(Run));
}
void AddRun(ArrayList alsRun, Align alignScan, int iiclrRun, int[] aiclrScan, int cpRun, ColorType ctRun) {
// Figure out the alignment of this run at the dst if drawn
Align alignDst;
if (alignScan == Align.Even) {
alignDst = (iiclrRun & 1) != 0 ? Align.Odd : Align.Even;
} else {
alignDst = (iiclrRun & 1) == 0 ? Align.Odd : Align.Even;
}
// Copy run data, figure required alignment
int[] aiclrRun = null;
Align alignRun = Align.None;
switch (ctRun) {
case ColorType.Data:
case ColorType.Side:
alignRun = alignDst;
aiclrRun = new int[cpRun];
for (int iiclr = iiclrRun; iiclr < iiclrRun + cpRun; iiclr++)
aiclrRun[iiclr - iiclrRun] = aiclrScan[iiclr];
break;
case ColorType.Shadow:
break;
case ColorType.Transparent:
break;
default:
Debug.Assert(false);
break;
}
// Add this run
Run run;
run.ct = ctRun;
run.cp = cpRun;
run.align = alignRun;
run.aiclr = aiclrRun;
alsRun.Add(run);
}
int[] EncodeSideColors(Align align, int[] aiclr) {
int[] asc = new int[(aiclr.Length + 1) / 2];
for (int isc = 0; isc < asc.Length; isc++) {
int iclr1 = aiclr[isc * 2];
int iclr2 = s_iclrSideFirst;
if (isc * 2 + 1 < aiclr.Length)
iclr2 = aiclr[isc * 2 + 1];
asc[isc] = (iclr1 - s_iclrSideFirst) * 2 * 16 + (iclr2 - s_iclrSideFirst) * 2;
}
return asc;
}
Run[] ChopRuns(Run[] arun) {
// Chop the runs into compatible pieces. Most runs won't get chopped, only runs whose
// length exceeds the op handlers' abilities. Chop wisely, especially runs with
// alignment and / or optimal size issues.
ArrayList alsRuns = new ArrayList();
foreach (Run run in arun) {
int cp = run.cp;
Align align = run.align;
Align alignNext = align;
int[] aiclr;
switch (run.ct) {
case ColorType.Data:
aiclr = (int[])run.aiclr.Clone();
while (aiclr.Length != 0) {
// Figure out the run length to use if this run is being chopped.
// Best bet is to ensure dword moves across the chop
int cpT = aiclr.Length;
if (cpT > s_cpDataMax) {
if (align == Align.Even) {
cpT = s_cpDataMax;
} else {
cpT = ((s_cpDataMax - 1) & ~3) + 1;
alignNext = Align.Even;
}
}
// Add the run
Run runT = run;
runT.cp = cpT;
runT.align = align;
runT.aiclr = new int[cpT];
for (int iiclr = 0; iiclr < cpT; iiclr++)
runT.aiclr[iiclr] = aiclr[iiclr];
alsRuns.Add(runT);
// Adjust the colors left
int ciclrLeft = aiclr.Length - cpT;
int[] aiclrT = new int[ciclrLeft];
for (int iiclr = 0; iiclr < ciclrLeft; iiclr++)
aiclrT[iiclr] = aiclr[iiclr + cpT];
aiclr = aiclrT;
align = alignNext;
}
break;
case ColorType.Side:
aiclr = (int[])run.aiclr.Clone();
while (aiclr.Length != 0) {
// Figure out the run length to use if this run is being chopped.
// Best bet is to ensure dword moves across the chop
int cpT = aiclr.Length;
if (cpT > s_cpSideMax) {
if (align == Align.Even) {
cpT = s_cpSideMax;
} else {
cpT = ((s_cpSideMax - 1) & ~3) + 1;
alignNext = Align.Even;
}
}
// Add the run
Run runT = run;
runT.cp = cpT;
runT.align = align;
runT.aiclr = new int[cpT];
for (int iiclr = 0; iiclr < cpT; iiclr++)
runT.aiclr[iiclr] = aiclr[iiclr];
alsRuns.Add(runT);
// Adjust the colors left
int ciclrLeft = aiclr.Length - cpT;
int[] aiclrT = new int[ciclrLeft];
for (int iiclr = 0; iiclr < ciclrLeft; iiclr++)
aiclrT[iiclr] = aiclr[iiclr + cpT];
aiclr = aiclrT;
align = alignNext;
}
break;
case ColorType.Shadow:
while (cp != 0) {
int cpT = cp > s_cpShadowMax ? s_cpShadowMax : cp;
Run runT = run;
runT.cp = cpT;
alsRuns.Add(runT);
cp -= cpT;
}
break;
case ColorType.Transparent:
while (cp != 0) {
int cpT = cp > s_cpTransparentMax ? s_cpTransparentMax : cp;
Run runT = run;
runT.cp = cpT;
alsRuns.Add(runT);
cp -= cpT;
}
break;
}
}
return (Run[])alsRuns.ToArray(typeof(Run));
}
void CompileRuns(Align alignStart, Run[] arun) {
// First chop the run into compatible pieces.
arun = ChopRuns(arun);
// Now go through all runs in the scan and encode into ops and data
foreach (Run run in arun) {
switch (run.ct) {
case ColorType.Data:
Align align = GetNextDataAlignment(alignStart);
if (run.align != align && run.cp != 1) {
m_alsOps.Add(Op.Align);
m_alsIclr.Add(s_iclrNotAssigned);
}
if (run.align == Align.Even) {
m_alsOps.Add((Op)(run.cp + (int)Op.EvenData1 - 1));
} else {
m_alsOps.Add((Op)(run.cp + (int)Op.OddData1 - 1));
}
m_alsIclr.AddRange(run.aiclr);
break;
case ColorType.Side:
if (run.align == Align.Even) {
m_alsOps.Add((Op)(run.cp + (int)Op.EvenSide1 - 1));
} else {
m_alsOps.Add((Op)(run.cp + (int)Op.OddSide1 - 1));
}
AddSideCodes(run.align, run.aiclr);
break;
case ColorType.Shadow:
m_alsOps.Add((Op)(run.cp + (int)Op.Shadow1 - 1));
break;
case ColorType.Transparent:
m_alsOps.Add((Op)(run.cp + (int)Op.Transparent1 - 1));
break;
default:
Debug.Assert(false);
break;
}
}
}
}
ArrayList SerializeOps(ScanData[] asd) {
// Serialize ops. Remove trailing and beginning transparency between scans
// and replace with NextScan ops.
ArrayList alsOps = new ArrayList();
ArrayList alsT = new ArrayList();
int cpSkip = -1;
foreach (ScanData sd in asd) {
alsT.Clear();
alsT.AddRange(sd.GetOps());
// If cpSkip != -1 then we've removed some trailing transparency
// from the last scan. Search the start of this new scan.
if (cpSkip != -1) {
int iop = 0;
for (; iop < alsT.Count; iop++) {
// Add up the transparency
Op op = (Op)alsT[iop];
if (op >= Op.Transparent1 && op <= Op.Transparent32) {
cpSkip += op - Op.Transparent1 + 1;
continue;
}
break;
}
// Hit a non-transparent op or end of list. Remove found transparent ops
alsT.RemoveRange(0, iop);
// Max is...
int cpMax = m_cx > s_cpNextScanMax ? s_cpNextScanMax : m_cx;
// If there is too much transparency to endcode in one
// NextScan op, cut into pieces.
int cpExtra = cpSkip - cpMax;
if (cpExtra > 0) {
cpSkip -= cpExtra;
while (cpExtra != 0) {
int cpT = cpExtra <= s_cpTransparentMax ? cpExtra : s_cpTransparentMax;
alsT.Insert(0, Op.Transparent1 + cpT - 1);
cpExtra -= cpT;
}
}
// Insert NextScan op
alsT.Insert(0, Op.NextScan0 + cpSkip);
}
// Now remove trailing transparency if there is any.
cpSkip = 0;
int iopTrailing = -1;
for (int iop = 0; iop < alsT.Count; iop++) {
Op op = (Op)alsT[iop];
if (op >= Op.Transparent1 && op <= Op.Transparent32) {
if (iopTrailing == -1)
iopTrailing = iop;
cpSkip += op - Op.Transparent1 + 1;
continue;
} else {
iopTrailing = -1;
cpSkip = 0;
}
}
// Remove the trailing transparency
if (iopTrailing != -1) {
// Remove this transparency
alsT.RemoveRange(iopTrailing, alsT.Count - iopTrailing);
// If we've skipped more than the largest EndScan, insert some
// transparency.
int cpExtra = cpSkip - s_cpNextScanMax;
if (cpExtra > 0) {
cpSkip -= cpExtra;
while (cpExtra != 0) {
int cpT = cpExtra <= s_cpTransparentMax ? cpExtra : s_cpTransparentMax;
alsT.Add(Op.Transparent1 + cpT - 1);
cpExtra -= cpT;
}
}
}
// alsT is ready to add to the ops list
alsOps.AddRange(alsT);
}
// Add End op
alsOps.Add(Op.End);
return alsOps;
}
byte[] SerializeScanData()
{
// Combine all ScanData data
ScanData[] asd = m_asdEven;
ArrayList alsSideCodes = new ArrayList();
ArrayList alsIclr = new ArrayList();
foreach (ScanData sd in asd) {
alsSideCodes.AddRange(sd.GetSideCodes());
alsIclr.AddRange(sd.GetColorData());
}
// Make ops. Add side codes to op stream to unify stream.
ArrayList alsOpsT = SerializeOps(asd);
ArrayList alsOps = new ArrayList();
foreach (Op op in alsOpsT) {
alsOps.Add(op);
if (op >= Op.EvenSide1 && op <= Op.EvenSide16) {
int csc = (((op - Op.EvenSide1) + 1) + 1) / 2;
for (int isc = 0; isc < csc; isc++)
alsOps.Add(alsSideCodes[isc]);
alsSideCodes.RemoveRange(0, csc);
}
if (op >= Op.OddSide1 && op <= Op.OddSide16) {
int csc = (((op - Op.OddSide1) + 1) + 1) / 2;
for (int isc = 0; isc < csc; isc++)
alsOps.Add(alsSideCodes[isc]);
alsSideCodes.RemoveRange(0, csc);
}
}
// Remember count of bytes needed for aligned data. Add one for both alignements.
// This is needed during compiling. Make it an even count.
int cbaiclrUnpacked = ((alsIclr.Count + 1) + 1) & ~1;
// Create the packed, unaligned color data
ArrayList alsIclrPacked = new ArrayList();
foreach (int iclr in alsIclr) {
if (iclr != s_iclrNotAssigned)
alsIclrPacked.Add(iclr);
}
// Serialize:
// public ushort ibaiclr;
// public ushort cbaiclrUnpacked;
// public byte[] aop;
// public byte[] aiclr;
// Write placeholders
BinaryWriter bwtr = new BinaryWriter(new MemoryStream());
bwtr.Write((ushort)0);
bwtr.Write((ushort)0);
// Data
foreach (Op op in alsOps)
bwtr.Write((byte)op);
int ibaiclr = (ushort)bwtr.BaseStream.Position;
foreach (int iclr in alsIclrPacked)
bwtr.Write((byte)iclr);
// Fix up pointers
int cb = (int)bwtr.BaseStream.Length;
bwtr.BaseStream.Seek(0, SeekOrigin.Begin);
bwtr.Write((ushort)Misc.SwapUShort((ushort)ibaiclr));
bwtr.Write((ushort)Misc.SwapUShort((ushort)cbaiclrUnpacked));
// Return buffer
byte[] ab = new byte[cb];
bwtr.BaseStream.Seek(0, SeekOrigin.Begin);
bwtr.BaseStream.Read(ab, 0, cb);
bwtr.Close();
return ab;
}
static byte[] Serialize(TBitmap[] atbm) {
//struct TBitmapHeader:
// ctbm
// TBitmapEntry[] atbme;
// word cx;
// word cy;
// word yBaseline;
// word ibsd;
// word cbsd;
// ScanData[] asd;
// Write header info
BinaryWriter bwtr = new BinaryWriter(new MemoryStream());
bwtr.Write(Misc.SwapUShort((ushort)atbm.Length));
// Serialize TBitmapEntry's
ArrayList alsSdBytes = new ArrayList();
int ibCurrent = 2 + 10 * atbm.Length;
for (int itbm = 0; itbm < atbm.Length; itbm++) {
bwtr.Write(Misc.SwapUShort((ushort)atbm[itbm].m_cx));
bwtr.Write(Misc.SwapUShort((ushort)atbm[itbm].m_cy));
bwtr.Write(Misc.SwapUShort((ushort)atbm[itbm].m_yBaseline));
bwtr.Write(Misc.SwapUShort((ushort)ibCurrent));
byte[] ab = atbm[itbm].SerializeScanData();
alsSdBytes.AddRange(ab);
bwtr.Write(Misc.SwapUShort((ushort)ab.Length));
ibCurrent += ab.Length;
Debug.Assert(ibCurrent < ushort.MaxValue);
}
// Write sd bytes
bwtr.Write((byte[])alsSdBytes.ToArray(typeof(byte)));
// Done
byte[] abT = new Byte[bwtr.BaseStream.Length];
bwtr.BaseStream.Seek(0, SeekOrigin.Begin);
bwtr.BaseStream.Read(abT, 0, abT.Length);
bwtr.Close();
return abT;
}
static public void Save(Bitmap[] abm, Palette pal, string strFile) {
// Open file for writing
BinaryWriter bwtr = new BinaryWriter(new FileStream(strFile, FileMode.Create, FileAccess.Write));
// Convert into tbm's
TBitmap[] atbm = new TBitmap[abm.Length];
for (int ibm = 0; ibm < abm.Length; ibm++)
atbm[ibm] = new TBitmap(abm[ibm], pal);
// Serialize the whole thing
bwtr.Write(Serialize(atbm));
// All done
bwtr.Close();
}
static public void SaveFont(string strFileBitmap, Palette pal, string strFileAscii, string strFileSave) {
// Get the character order
TextReader tr = new StreamReader(strFileAscii);
string strAscii = tr.ReadLine();
tr.Close();
// Get the character count
int cch = strAscii.Length;
// Load the image, lose scaling factor
Bitmap bmFile = new Bitmap(strFileBitmap);
Bitmap bm = Misc.NormalizeBitmap(bmFile);
bmFile.Dispose();
// Turn this on to see the character -> glyph mapping as it happens (help for
// finding 'font bugs'). Set a breakpoint below on frm.Dispose().
#if SHOWFONT
Form frm = new Form();
frm.Height = 1000;
frm.Show();
Graphics gT = frm.CreateGraphics();
gT.InterpolationMode = InterpolationMode.NearestNeighbor;
int yDst = 0;
int xDst = 0;
#endif
// Scan the bitmap for widths
int xLast = 0;
int ich = 0;
byte[] acxChar = new byte[256];
for (int x = 0; x < bm.Width; x++) {
if (bm.GetPixel(x, 0) != Color.FromArgb(255, 0, 255)) {
Debug.Assert(ich < cch);
acxChar[strAscii[ich]] = (byte)(x - xLast);
#if SHOWFONT
gT.DrawString(strAscii[ich].ToString(), frm.Font, new SolidBrush(frm.ForeColor), new PointF(xDst, yDst));
Rectangle rcDst = new Rectangle(xDst + 20, yDst + 2, (x - xLast), bm.Height);
Rectangle rcSrc = new Rectangle(xLast, 1, x - xLast, bm.Height);
gT.DrawImage(bm, rcDst, rcSrc, GraphicsUnit.Pixel);
yDst += Math.Max(bm.Height, frm.Font.Height);
if (yDst > frm.ClientRectangle.Height) {
xDst += 50;
yDst = 0;
}
gT.Flush();
Application.DoEvents();
#endif
ich++;
xLast = x;
}
}
#if SHOWFONT
gT.Dispose();
frm.Dispose();
#endif
if (ich != cch) {
MessageBox.Show(String.Format("Expecting {0} characters but found {2}{1}.",
cch, ich, ich < cch ? "only " : ""), "bcr2 - Font Compilation Error");
Debug.Assert(ich == cch - 1);
}
int cy = bm.Height - 1;
// Save serialization
ArrayList alsSdEven = new ArrayList();
int xT = 0;
int ichDefault = -1;
for (ich = 0; ich < cch; ich++) {
// ? is the default "no glyph" character
if (strAscii[ich] == '?')
ichDefault = ich;
// Get subimage
int cx = acxChar[strAscii[ich]];
Rectangle rcT = new Rectangle(xT, 1, cx, cy);
xT += cx;
Bitmap bmT = new Bitmap(cx, cy, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bmT);
g.DrawImage(bm, 0, 0, rcT, GraphicsUnit.Pixel);
g.Dispose();
// Compile scan data
TBitmap tbm = new TBitmap(bmT, pal);
bmT.Dispose();
// Save scan data serialization
alsSdEven.Add(tbm.SerializeScanData());
}
//FontHeader {
// word cy;
// byte acxChar[256];
// word mpchibsdEven[256];
// ScanData asd[1];
//};
// First serialize scan data
ArrayList alsIbsdEven = new ArrayList();
ArrayList alsSd = new ArrayList();
foreach (byte[] absd in alsSdEven) {
if ((alsSd.Count & 1) != 0)
alsSd.Add((byte)0);
alsIbsdEven.Add(alsSd.Count);
alsSd.AddRange(absd);
}
// Write out to file
BinaryWriter bwtr = new BinaryWriter(new FileStream(strFileSave, FileMode.Create, FileAccess.Write));
// Height
bwtr.Write(Misc.SwapUShort((ushort)cy));
// Ascii ordered char widths in bytes. First init 0's to width of '?'
if (ichDefault != -1) {
for (ich = 0; ich < acxChar.Length; ich++) {
if (acxChar[ich] == 0) {
acxChar[ich] = acxChar[strAscii[ichDefault]];
}
}
}
bwtr.Write(acxChar);
// Ascii ordered offsets to even scan data (even)
// Fill unused entries to entry for '?'
int[] aibsdEven = new int[256];
for (int ibsd = 0; ibsd < aibsdEven.Length; ibsd++)
aibsdEven[ibsd] = -1;
for (int i = 0; i < cch; i++)
aibsdEven[strAscii[i]] = (int)alsIbsdEven[i];
if (ichDefault != -1) {
for (int ibsd = 0; ibsd < aibsdEven.Length; ibsd++) {
if (aibsdEven[ibsd] == -1) {
aibsdEven[ibsd] = (int)alsIbsdEven[ichDefault];
}
}
}
// Write it out
int cbHeader = 2 + 256 + 512;
for (int i = 0; i < 256; i++)
bwtr.Write(Misc.SwapUShort((ushort)(cbHeader + aibsdEven[i])));
// Now save scan data
bwtr.Write((byte[])alsSd.ToArray(typeof(byte)));
// Done
bwtr.Close();
}
}
}
| |
using System;
using System.IO;
using System.Windows.Forms;
using Aspose.Words;
using Aspose.Words.Saving;
using DocsExamples;
namespace DocumentExplorer
{
/// <summary>
/// The main form of the DocumentExplorer demo.
///
/// DocumentExplorer allows to open documents using Aspose.Words.
/// Once a document is opened, you can explore its object model in the tree.
/// You can also save the document into DOC, DOCX, ODF, EPUB, PDF, RTF, WordML,
/// HTML, MHTML and plain text formats.
/// </summary>
public class MainForm : Form
{
#region Windows Form Designer generated code
private System.Windows.Forms.ToolBar toolBar1;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.Panel panel2;
public System.Windows.Forms.StatusBar StatusBar;
public System.Windows.Forms.TreeView Tree;
private System.Windows.Forms.ToolBarButton toolOpenDocument;
private System.Windows.Forms.ToolBarButton toolSaveDocument;
private System.Windows.Forms.ToolBarButton toolExpandAll;
private System.Windows.Forms.ToolBarButton toolCollapseAll;
private System.Windows.Forms.ToolBarButton toolSeparator1;
public System.Windows.Forms.TextBox Text1;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuFile;
private System.Windows.Forms.MenuItem menuOpen;
private System.Windows.Forms.MenuItem menuSaveAs;
private System.Windows.Forms.MenuItem menuBar1;
private System.Windows.Forms.MenuItem menuExit;
private System.Windows.Forms.MenuItem menuView;
private System.Windows.Forms.MenuItem menuExpandAll;
private System.Windows.Forms.MenuItem menuCollapseAll;
private System.Windows.Forms.MenuItem menuHelp;
private System.Windows.Forms.MenuItem menuAbout;
private System.Windows.Forms.ToolBarButton toolSeparator2;
private System.Windows.Forms.ToolBarButton toolViewInWord;
private System.Windows.Forms.ToolBarButton toolViewInPdf;
private System.Windows.Forms.ToolBarButton toolRemove;
private System.Windows.Forms.MenuItem menuRemoveNode;
private System.Windows.Forms.MenuItem menuEdit;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuRender;
private System.Windows.Forms.ToolBarButton toolRenderDocument;
private System.Windows.Forms.ToolBarButton toolBarButton1;
private System.Windows.Forms.ToolBarButton toolPreviewButton;
private System.Windows.Forms.MenuItem menuPreview;
private System.ComponentModel.IContainer components;
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
this.StatusBar = new System.Windows.Forms.StatusBar();
this.toolBar1 = new System.Windows.Forms.ToolBar();
this.toolOpenDocument = new System.Windows.Forms.ToolBarButton();
this.toolSaveDocument = new System.Windows.Forms.ToolBarButton();
this.toolSeparator1 = new System.Windows.Forms.ToolBarButton();
this.toolRenderDocument = new System.Windows.Forms.ToolBarButton();
this.toolPreviewButton = new System.Windows.Forms.ToolBarButton();
this.toolBarButton1 = new System.Windows.Forms.ToolBarButton();
this.toolExpandAll = new System.Windows.Forms.ToolBarButton();
this.toolCollapseAll = new System.Windows.Forms.ToolBarButton();
this.toolSeparator2 = new System.Windows.Forms.ToolBarButton();
this.toolRemove = new System.Windows.Forms.ToolBarButton();
this.toolViewInWord = new System.Windows.Forms.ToolBarButton();
this.toolViewInPdf = new System.Windows.Forms.ToolBarButton();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.panel1 = new System.Windows.Forms.Panel();
this.Tree = new System.Windows.Forms.TreeView();
this.splitter1 = new System.Windows.Forms.Splitter();
this.panel2 = new System.Windows.Forms.Panel();
this.Text1 = new System.Windows.Forms.TextBox();
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuFile = new System.Windows.Forms.MenuItem();
this.menuOpen = new System.Windows.Forms.MenuItem();
this.menuSaveAs = new System.Windows.Forms.MenuItem();
this.menuBar1 = new System.Windows.Forms.MenuItem();
this.menuRender = new System.Windows.Forms.MenuItem();
this.menuPreview = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuExit = new System.Windows.Forms.MenuItem();
this.menuEdit = new System.Windows.Forms.MenuItem();
this.menuRemoveNode = new System.Windows.Forms.MenuItem();
this.menuView = new System.Windows.Forms.MenuItem();
this.menuExpandAll = new System.Windows.Forms.MenuItem();
this.menuCollapseAll = new System.Windows.Forms.MenuItem();
this.menuHelp = new System.Windows.Forms.MenuItem();
this.menuAbout = new System.Windows.Forms.MenuItem();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// StatusBar
//
this.StatusBar.Location = new System.Drawing.Point(0, 665);
this.StatusBar.Name = "StatusBar";
this.StatusBar.ShowPanels = true;
this.StatusBar.Size = new System.Drawing.Size(884, 24);
this.StatusBar.TabIndex = 0;
this.StatusBar.Text = "statusBar1";
//
// ToolBar1
//
this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.toolOpenDocument,
this.toolSaveDocument,
this.toolSeparator1,
this.toolRenderDocument,
this.toolPreviewButton,
this.toolBarButton1,
this.toolExpandAll,
this.toolCollapseAll,
this.toolSeparator2,
this.toolRemove,
this.toolViewInWord,
this.toolViewInPdf});
this.toolBar1.DropDownArrows = true;
this.toolBar1.ImageList = this.imageList1;
this.toolBar1.Location = new System.Drawing.Point(0, 0);
this.toolBar1.Name = "toolBar1";
this.toolBar1.ShowToolTips = true;
this.toolBar1.Size = new System.Drawing.Size(884, 28);
this.toolBar1.TabIndex = 1;
this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
//
// ToolOpenDocument
//
this.toolOpenDocument.ImageIndex = 0;
this.toolOpenDocument.ToolTipText = "Open Document";
//
// ToolSaveDocument
//
this.toolSaveDocument.Enabled = false;
this.toolSaveDocument.ImageIndex = 1;
this.toolSaveDocument.ToolTipText = "Save Document As...";
//
// ToolSeparator1
//
this.toolSeparator1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// ToolRenderDocument
//
this.toolRenderDocument.Enabled = false;
this.toolRenderDocument.ImageIndex = 7;
this.toolRenderDocument.ToolTipText = "Render Document";
//
// ToolPreviewButton
//
this.toolPreviewButton.Enabled = false;
this.toolPreviewButton.ImageIndex = 8;
this.toolPreviewButton.ToolTipText = "Print Preview";
//
// ToolBarButton1
//
this.toolBarButton1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// ToolExpandAll
//
this.toolExpandAll.Enabled = false;
this.toolExpandAll.ImageIndex = 2;
this.toolExpandAll.ToolTipText = "Expand All";
//
// ToolCollapseAll
//
this.toolCollapseAll.Enabled = false;
this.toolCollapseAll.ImageIndex = 3;
this.toolCollapseAll.ToolTipText = "Collapse All";
//
// ToolSeparator2
//
this.toolSeparator2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// ToolRemove
//
this.toolRemove.Enabled = false;
this.toolRemove.ImageIndex = 4;
this.toolRemove.ToolTipText = "Remove Node";
//
// ToolViewInWord
//
this.toolViewInWord.ImageIndex = 4;
this.toolViewInWord.ToolTipText = "View in MS Word";
this.toolViewInWord.Visible = false;
//
// ToolViewInPdf
//
this.toolViewInPdf.ImageIndex = 5;
this.toolViewInPdf.ToolTipText = "View in Acrobat";
this.toolViewInPdf.Visible = false;
//
// ImageList1
//
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// Panel1
//
this.panel1.Controls.Add(this.Tree);
this.panel1.Dock = System.Windows.Forms.DockStyle.Left;
this.panel1.Location = new System.Drawing.Point(0, 28);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(324, 637);
this.panel1.TabIndex = 2;
//
// Tree
//
this.Tree.Dock = System.Windows.Forms.DockStyle.Fill;
this.Tree.HideSelection = false;
this.Tree.ImageIndex = -1;
this.Tree.Location = new System.Drawing.Point(0, 0);
this.Tree.Name = "Tree";
this.Tree.SelectedImageIndex = -1;
this.Tree.Size = new System.Drawing.Size(324, 637);
this.Tree.TabIndex = 0;
this.Tree.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Tree_KeyDown);
this.Tree.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Tree_MouseDown);
this.Tree.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.Tree_AfterSelect);
this.Tree.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.Tree_BeforeExpand);
//
// Splitter1
//
this.splitter1.Location = new System.Drawing.Point(324, 28);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(4, 637);
this.splitter1.TabIndex = 3;
this.splitter1.TabStop = false;
//
// Panel2
//
this.panel2.Controls.Add(this.Text1);
this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel2.Location = new System.Drawing.Point(328, 28);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(556, 637);
this.panel2.TabIndex = 4;
//
// Text1
//
this.Text1.BackColor = System.Drawing.SystemColors.Window;
this.Text1.Dock = System.Windows.Forms.DockStyle.Fill;
this.Text1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.Text1.HideSelection = false;
this.Text1.Location = new System.Drawing.Point(0, 0);
this.Text1.Multiline = true;
this.Text1.Name = "Text1";
this.Text1.ReadOnly = true;
this.Text1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.Text1.Size = new System.Drawing.Size(556, 637);
this.Text1.TabIndex = 1;
this.Text1.Text = "";
//
// MainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuFile,
this.menuEdit,
this.menuView,
this.menuHelp});
//
// MenuFile
//
this.menuFile.Index = 0;
this.menuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuOpen,
this.menuSaveAs,
this.menuBar1,
this.menuRender,
this.menuPreview,
this.menuItem1,
this.menuExit});
this.menuFile.Text = "&File";
//
// MenuOpen
//
this.menuOpen.Index = 0;
this.menuOpen.Text = "&Open";
this.menuOpen.Click += new System.EventHandler(this.menuOpen_Click);
//
// MenuSaveAs
//
this.menuSaveAs.Enabled = false;
this.menuSaveAs.Index = 1;
this.menuSaveAs.Text = "Save &As...";
this.menuSaveAs.Click += new System.EventHandler(this.menuSaveAs_Click);
//
// MenuBar1
//
this.menuBar1.Index = 2;
this.menuBar1.Text = "-";
//
// MenuRender
//
this.menuRender.Enabled = false;
this.menuRender.Index = 3;
this.menuRender.Text = "&Render...";
this.menuRender.Click += new System.EventHandler(this.menuRender_Click);
//
// MenuPreview
//
this.menuPreview.Enabled = false;
this.menuPreview.Index = 4;
this.menuPreview.Text = "&Print Preview...";
this.menuPreview.Click += new System.EventHandler(this.menuPreview_Click);
//
// MenuItem1
//
this.menuItem1.Index = 5;
this.menuItem1.Text = "-";
//
// MenuExit
//
this.menuExit.Index = 6;
this.menuExit.Text = "E&xit";
this.menuExit.Click += new System.EventHandler(this.menuExit_Click);
//
// MenuEdit
//
this.menuEdit.Index = 1;
this.menuEdit.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuRemoveNode});
this.menuEdit.Text = "Edit";
//
// MenuRemoveNode
//
this.menuRemoveNode.Enabled = false;
this.menuRemoveNode.Index = 0;
this.menuRemoveNode.Text = "Remove Node";
this.menuRemoveNode.Click += new System.EventHandler(this.menuRemoveNode_Click);
//
// MenuView
//
this.menuView.Index = 2;
this.menuView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuExpandAll,
this.menuCollapseAll});
this.menuView.Text = "&View";
//
// MenuExpandAll
//
this.menuExpandAll.Enabled = false;
this.menuExpandAll.Index = 0;
this.menuExpandAll.Text = "&Expand All";
this.menuExpandAll.Click += new System.EventHandler(this.menuExpandAll_Click);
//
// MenuCollapseAll
//
this.menuCollapseAll.Enabled = false;
this.menuCollapseAll.Index = 1;
this.menuCollapseAll.Text = "&Collapse All";
this.menuCollapseAll.Click += new System.EventHandler(this.menuCollapseAll_Click);
//
// MenuHelp
//
this.menuHelp.Index = 3;
this.menuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuAbout});
this.menuHelp.Text = "&Help";
//
// MenuAbout
//
this.menuAbout.Index = 0;
this.menuAbout.Text = "&About";
this.menuAbout.Click += new System.EventHandler(this.menuAbout_Click);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(884, 689);
this.Controls.Add(this.panel2);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel1);
this.Controls.Add(this.toolBar1);
this.Controls.Add(this.StatusBar);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu1;
this.Name = "MainForm";
this.Text = "Document Explorer";
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.ResumeLayout(false);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#endregion
/// <summary>
/// Ctor.
/// </summary>
public MainForm()
{
InitializeComponent();
FindAndApplyLicense();
Tree.ImageList = Item.ImageList;
}
/// <summary>
/// Search for Aspose.Words license in the application directory.
/// The File.Exists check is only needed in this demo so it will work
/// Both when the license file is missing and when it is present.
/// In your real application you just need to call SetLicense.
/// </summary>
private static void FindAndApplyLicense()
{
// Try to find Aspose.Total license.
string licenseFile = Path.Combine(Application.StartupPath, "Aspose.Total.NET.lic");
if (File.Exists(licenseFile))
{
LicenseAsposeWords(licenseFile);
return;
}
// Try to find Aspose.Custom license.
licenseFile = Path.Combine(Application.StartupPath, "Aspose.Custom.lic");
if (File.Exists(licenseFile))
{
LicenseAsposeWords(licenseFile);
return;
}
licenseFile = Path.Combine(Application.StartupPath, "Aspose.Words.lic");
if (File.Exists(licenseFile))
LicenseAsposeWords(licenseFile);
}
/// <summary>
/// This code activates Aspose.Words license.
/// If you don't specify a license, Aspose.Words will work in evaluation mode.
/// </summary>
private static void LicenseAsposeWords(string licenseFile)
{
Aspose.Words.License licenseWords = new Aspose.Words.License();
licenseWords.SetLicense(licenseFile);
}
private void menuOpen_Click(object sender, EventArgs e)
{
OpenDocument();
}
private void menuSaveAs_Click(object sender, EventArgs e)
{
SaveDocument();
}
private void menuRender_Click(object sender, System.EventArgs e)
{
RenderDocument();
}
private void menuPreview_Click(object sender, System.EventArgs e)
{
PrintPreview();
}
private void menuExpandAll_Click(object sender, EventArgs e)
{
ExpandAll();
}
private void menuCollapseAll_Click(object sender, EventArgs e)
{
CollapseAll();
}
private void menuRemoveNode_Click(object sender, EventArgs e)
{
Remove();
}
private void menuAbout_Click(object sender, EventArgs e)
{
Form aboutForm = new AboutForm();
try
{
aboutForm.ShowDialog();
}
finally
{
aboutForm.Dispose();
}
}
private void menuExit_Click(object sender, EventArgs e)
{
Close();
}
private void toolBar1_ButtonClick(object sender, ToolBarButtonClickEventArgs e)
{
switch (e.Button.ToolTipText)
{
case "Open Document":
OpenDocument();
break;
case "Save Document As...":
SaveDocument();
break;
case "Render Document":
RenderDocument();
break;
case "Print Preview":
PrintPreview();
break;
case "Expand All":
ExpandAll();
break;
case "Collapse All":
CollapseAll();
break;
case "Remove Node":
Remove();
break;
}
}
/// <summary>
/// Shows the open file dialog box and opens a document.
/// </summary>
private void OpenDocument()
{
string fileName = SelectOpenFileName();
if (fileName == null)
return;
// This operation can take some time so we set the Cursor to WaitCursor.
Application.DoEvents();
Cursor cursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
// Load document is put in a try-catch block to handle situations when it fails for some reason.
try
{
// Loads the document into Aspose.Words object model.
mDocument = new Document(fileName);
Tree.BeginUpdate();
// Clears the tree from the previously loaded documents.
Tree.Nodes.Clear();
// Creates instance of an Item class which will control the GUI representation of the document root node.
Tree.Nodes.Add(Item.CreateItem(mDocument).TreeNode);
// Shows the immediate children of the document node.
Tree.Nodes[0].Expand();
// Selects root node of the tree.
Tree.SelectedNode = Tree.Nodes[0];
Tree.EndUpdate();
Text = "Document Explorer - " + fileName;
menuSaveAs.Enabled = true;
toolBar1.Buttons[1].Enabled = true;
menuRender.Enabled = true;
toolBar1.Buttons[3].Enabled = true;
menuPreview.Enabled = true;
toolBar1.Buttons[4].Enabled = true;
menuExpandAll.Enabled = true;
toolBar1.Buttons[6].Enabled = true;
menuCollapseAll.Enabled = true;
toolBar1.Buttons[7].Enabled = true;
}
catch (Exception ex)
{
new ExceptionDialog(ex).ShowDialog();
}
// Restore cursor.
Cursor.Current = cursor;
}
/// <summary>
/// Saves the document with the name and format provided in standard Save As dialog.
/// </summary>
private void SaveDocument()
{
if (mDocument == null)
return;
string fileName = SelectSaveFileName();
if (fileName == null)
return;
// This operation can take some time so we set the Cursor to WaitCursor.
Application.DoEvents();
Cursor cursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
// This operation is put in try-catch block to handle situations when operation fails for some reason.
try
{
SaveOptions saveOptions = SaveOptions.CreateSaveOptions(fileName);
saveOptions.PrettyFormat = true;
// For most of the save formats it is enough to just invoke Aspose.Words save.
mDocument.Save(fileName, saveOptions);
}
catch (Exception ex)
{
new ExceptionDialog(ex).ShowDialog();
}
// Restore cursor.
Cursor.Current = cursor;
}
private void RenderDocument()
{
if (mDocument == null)
return;
ViewerForm form = new ViewerForm();
form.Document = mDocument;
form.ShowDialog();
}
private void PrintPreview()
{
if (mDocument == null)
return;
Preview.Execute(mDocument);
}
/// <summary>
/// Selects file name for a document to open or null.
/// </summary>
private string SelectOpenFileName()
{
OpenFileDialog dlg = new OpenFileDialog();
try
{
dlg.CheckFileExists = true;
dlg.CheckPathExists = true;
dlg.Title = "Open Document";
dlg.InitialDirectory = mInitialDirectory;
dlg.Filter =
"All Supported Formats (*.doc;*.dot;*.docx;*.dotx;*.docm;*.dotm;*.xml;*.wml;*.rtf;*.odt;*.ott;*.htm;*.html;*.xhtml;*.mht;*.mhtm;*.mhtml)|*.doc;*.dot;*.docx;*.dotx;*.docm;*.dotm;*.xml;*.wml;*.rtf;*.odt;*.ott;*.htm;*.html;*.xhtml;*.mht;*.mhtm;*.mhtml|" +
"Word 97-2003 Documents (*.doc;*.dot)|*.doc;*.dot|" +
"Word 2007 OOXML Documents (*.docx;*.dotx;*.docm;*.dotm)|*.docx;*.dotx;*.docm;*.dotm|" +
"XML Documents (*.xml;*.wml)|*.xml;*.wml|" +
"Rich Text Format (*.rtf)|*.rtf|" +
"OpenDocument Text (*.odt;*.ott)|*.odt;*.ott|" +
"Web Pages (" +
"*.htm;*.html;*.xhtml;*.mht;*.mhtm;*.mhtml)|" +
"*.htm;*.html;*.xhtml;*.mht;*.mhtm;*.mhtml|" +
"All Files (*.*)|*.*";
DialogResult dlgResult = dlg.ShowDialog();
// Optimized to allow automatic conversion to VB.NET
if (dlgResult.Equals(DialogResult.OK))
{
mInitialDirectory = Path.GetDirectoryName(dlg.FileName);
return dlg.FileName;
}
else
{
return null;
}
}
finally
{
dlg.Dispose();
}
}
/// <summary>
/// Selects file name for saving currently opened document or null.
/// </summary>
private string SelectSaveFileName()
{
SaveFileDialog dlg = new SaveFileDialog();
try
{
dlg.CheckFileExists = false;
dlg.CheckPathExists = true;
dlg.Title = "Save Document As";
dlg.InitialDirectory = mInitialDirectory;
dlg.Filter =
"Word 97-2003 Document (*.doc)|*.doc|" +
"Word 2007 OOXML Document (*.docx)|*.docx|" +
"Word 2007 OOXML Macro-Enabled Document (*.docm)|*.docm|" +
"PDF (*.pdf)|*.pdf|" +
"XPS Document (*.xps)|*.xps|" +
"OpenDocument Text (*.odt)|*.odt|" +
"Web Page (*.html)|*.html|" +
"Single File Web Page (*.mht)|*.mht|" +
"Rich Text Format (*.rtf)|*.rtf|" +
"Word 2003 WordprocessingML (*.xml)|*.xml|" +
"FlatOPC XML Document (*.fopc)|*.fopc|" +
"Plain Text (*.txt)|*.txt|" +
"IDPF EPUB Document (*.epub)|*.epub|" +
"XAML Fixed Document (*.xaml)|*.xaml";
dlg.FileName = Path.GetFileNameWithoutExtension(mDocument.OriginalFileName);
DialogResult dlgResult = dlg.ShowDialog();
// Optimized to allow automatic conversion to VB.NET
if (dlgResult.Equals(DialogResult.OK))
{
mInitialDirectory = Path.GetDirectoryName(dlg.FileName);
return dlg.FileName;
}
else
{
return null;
}
}
finally
{
dlg.Dispose();
}
}
/// <summary>
/// Expands all nodes under currently selected node.
/// </summary>
private void ExpandAll()
{
// This operation can take some time so we set the Cursor to WaitCursor.
Application.DoEvents();
Cursor cursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
if (Tree.SelectedNode != null)
{
Tree.BeginUpdate();
Tree.SelectedNode.ExpandAll();
Tree.SelectedNode.EnsureVisible();
Tree.EndUpdate();
}
// Restore cursor.
Cursor.Current = cursor;
}
/// <summary>
/// Collapses all nodes under currently selected node.
/// </summary>
private void CollapseAll()
{
// This operation can take some time so we set the Cursor to WaitCursor.
Application.DoEvents();
Cursor cursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
if (Tree.SelectedNode != null)
{
Tree.BeginUpdate();
Tree.SelectedNode.Collapse();
Tree.SelectedNode.EnsureVisible();
Tree.EndUpdate();
}
// Restore cursor.
Cursor.Current = cursor;
}
/// <summary>
/// Removes currently selected node.
/// </summary>
private void Remove()
{
if (Tree.SelectedNode != null)
((Item)Tree.SelectedNode.Tag).Remove();
}
/// <summary>
/// Informs Item class, which provides GUI representation of a document node,
/// That the corresponding TreeNode was selected.
/// </summary>
private void Tree_AfterSelect(object sender, TreeViewEventArgs e)
{
// This operation can take some time so we set the Cursor to WaitCursor.
Application.DoEvents();
Cursor cursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
Item selectedItem = (Item)e.Node.Tag;
// Set 'Remove Node' menu and tool button visibility.
menuRemoveNode.Enabled = selectedItem.IsRemovable;
toolBar1.Buttons[9].Enabled = selectedItem.IsRemovable;
// Show the text contained by selected document node.
Text1.Text = selectedItem.Text;
// Restore cursor.
Cursor.Current = cursor;
}
/// <summary>
/// Informs Item class, which provides GUI representation of a document node,
/// That the corresponding TreeNode is about being expanded.
/// </summary>
private void Tree_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
((Item)e.Node.Tag).OnExpand();
}
/// <summary>
/// Ensures that tree nodes are selected by right-click also.
/// </summary>
private void Tree_MouseDown(object sender, MouseEventArgs e)
{
TreeNode treeNode = Tree.GetNodeAt(e.X, e.Y);
// Optimized to allow automatic conversion to VB.NET
if (e.Button.Equals(MouseButtons.Right) && treeNode != null)
Tree.SelectedNode = treeNode;
}
private void Tree_KeyDown(object sender, KeyEventArgs e)
{
// Optimized to allow automatic conversion to VB.NET
if (e.KeyCode.Equals(Keys.Delete))
Remove();
}
/// <summary>
/// The currently opened document.
/// </summary>
private Document mDocument;
/// <summary>
/// Last selected directory in the open and save dialogs.
/// </summary>
private string mInitialDirectory = DocsExamplesBase.MyDir;
}
}
| |
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 MyWebapi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Notes about TaiwanLunisolarCalendar
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1912/02/18 2051/02/10
** TaiwanLunisolar 1912/01/01 2050/13/29
*/
[Serializable]
public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar
{
// Since
// Gregorian Year = Era Year + yearOffset
// When Gregorian Year 1912 is year 1, so that
// 1912 = 1 + yearOffset
// So yearOffset = 1911
//m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911);
// Initialize our era info.
static internal EraInfo[] taiwanLunisolarEraInfo = new EraInfo[] {
new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear
};
internal GregorianCalendarHelper helper;
internal const int MIN_LUNISOLAR_YEAR = 1912;
internal const int MAX_LUNISOLAR_YEAR = 2050;
internal const int MIN_GREGORIAN_YEAR = 1912;
internal const int MIN_GREGORIAN_MONTH = 2;
internal const int MIN_GREGORIAN_DAY = 18;
internal const int MAX_GREGORIAN_YEAR = 2051;
internal const int MAX_GREGORIAN_MONTH = 2;
internal const int MAX_GREGORIAN_DAY = 10;
internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY);
internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999);
public override DateTime MinSupportedDateTime
{
get
{
return (minDate);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (maxDate);
}
}
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// 1911 from ChineseLunisolarCalendar
return 384;
}
}
static readonly int[,] yinfo =
{
/*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days
1912 */
{ 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355
1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385
1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384
1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354
1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354
1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383
1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355
1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353
1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355
1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384
1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384
1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354
1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384
1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354
2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354
2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384
2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384
2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355
2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384
2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384
2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384
2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355
2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354
2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
*/};
internal override int MinCalendarYear
{
get
{
return (MIN_LUNISOLAR_YEAR);
}
}
internal override int MaxCalendarYear
{
get
{
return (MAX_LUNISOLAR_YEAR);
}
}
internal override DateTime MinDate
{
get
{
return (minDate);
}
}
internal override DateTime MaxDate
{
get
{
return (maxDate);
}
}
internal override EraInfo[] CalEraInfo
{
get
{
return (taiwanLunisolarEraInfo);
}
}
internal override int GetYearInfo(int LunarYear, int Index)
{
if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR))
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
MIN_LUNISOLAR_YEAR,
MAX_LUNISOLAR_YEAR));
}
Contract.EndContractBlock();
return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
}
internal override int GetYear(int year, DateTime time)
{
return helper.GetYear(year, time);
}
internal override int GetGregorianYear(int year, int era)
{
return helper.GetGregorianYear(year, era);
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of TaiwanLunisolarCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance()
{
if (m_defaultInstance == null) {
m_defaultInstance = new TaiwanLunisolarCalendar();
}
return (m_defaultInstance);
}
*/
// Construct an instance of TaiwanLunisolar calendar.
public TaiwanLunisolarCalendar()
{
helper = new GregorianCalendarHelper(this, taiwanLunisolarEraInfo);
}
public override int GetEra(DateTime time)
{
return (helper.GetEra(time));
}
internal override CalendarId BaseCalendarID
{
get
{
return (CalendarId.TAIWAN);
}
}
internal override CalendarId ID
{
get
{
return (CalendarId.TAIWANLUNISOLAR);
}
}
public override int[] Eras
{
get
{
return (helper.Eras);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium
{
[TestFixture]
public class AlertsTest : DriverTestFixture
{
[Test]
public void ShouldBeAbleToOverrideTheWindowAlertMethod()
{
driver.Url = CreateAlertPage("cheese");
((IJavaScriptExecutor)driver).ExecuteScript(
"window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }");
driver.FindElement(By.Id("alert")).Click();
}
[Test]
public void ShouldAllowUsersToAcceptAnAlertManually()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void ShouldThrowArgumentNullExceptionWhenKeysNull()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
Assert.That(() => alert.SendKeys(null), Throws.ArgumentNullException);
}
finally
{
alert.Accept();
}
}
[Test]
public void ShouldAllowUsersToAcceptAnAlertWithNoTextManually()
{
driver.Url = CreateAlertPage("");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
[IgnoreBrowser(Browser.Edge, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
[IgnoreBrowser(Browser.IE, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
[IgnoreBrowser(Browser.Firefox, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
[IgnoreBrowser(Browser.Safari, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
public void ShouldGetTextOfAlertOpenedInSetTimeout()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithScripts(
"function slowAlert() { window.setTimeout(function(){ alert('Slow'); }, 200); }")
.WithBody(
"<a href='#' id='slow-alert' onclick='slowAlert();'>click me</a>"));
driver.FindElement(By.Id("slow-alert")).Click();
// DO NOT WAIT OR SLEEP HERE.
// This is a regression test for a bug where only the first switchTo call would throw,
// and only if it happens before the alert actually loads.
IAlert alert = driver.SwitchTo().Alert();
try
{
Assert.AreEqual("Slow", alert.Text);
}
finally
{
alert.Accept();
}
}
[Test]
public void ShouldAllowUsersToDismissAnAlertManually()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void ShouldAllowAUserToAcceptAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Prompt", driver.Title);
}
[Test]
public void ShouldAllowAUserToDismissAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Prompt", driver.Title);
}
[Test]
public void ShouldAllowAUserToSetTheValueOfAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.SendKeys("cheese");
alert.Accept();
string result = driver.FindElement(By.Id("text")).Text;
Assert.AreEqual("cheese", result);
}
[Test]
public void SettingTheValueOfAnAlertThrows()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
alert.SendKeys("cheese");
Assert.Fail("Expected exception");
}
catch (ElementNotInteractableException)
{
}
finally
{
alert.Accept();
}
}
[Test]
public void ShouldAllowTheUserToGetTheTextOfAnAlert()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("cheese", value);
}
[Test]
public void ShouldAllowTheUserToGetTheTextOfAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("Enter something", value);
}
[Test]
public void AlertShouldNotAllowAdditionalCommandsIfDimissed()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
string text;
Assert.That(() => text = alert.Text, Throws.InstanceOf<NoAlertPresentException>());
}
[Test]
public void ShouldAllowUsersToAcceptAnAlertInAFrame()
{
string iframe = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody("<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click me</a>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithBody(String.Format("<iframe src='{0}' name='iframeWithAlert'></iframe>", iframe)));
driver.SwitchTo().Frame("iframeWithAlert");
driver.FindElement(By.Id("alertInFrame")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void ShouldAllowUsersToAcceptAnAlertInANestedFrame()
{
string iframe = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody("<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click me</a>"));
string iframe2 = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format("<iframe src='{0}' name='iframeWithAlert'></iframe>", iframe)));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithBody(string.Format("<iframe src='{0}' name='iframeWithIframe'></iframe>", iframe2)));
driver.SwitchTo().Frame("iframeWithIframe").SwitchTo().Frame("iframeWithAlert");
driver.FindElement(By.Id("alertInFrame")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void SwitchingToMissingAlertThrows()
{
driver.Url = CreateAlertPage("cheese");
Assert.That(() => AlertToBePresent(), Throws.InstanceOf<NoAlertPresentException>());
}
[Test]
public void SwitchingToMissingAlertInAClosedWindowThrows()
{
string blank = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage());
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(String.Format(
"<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", blank)));
string mainWindow = driver.CurrentWindowHandle;
try
{
driver.FindElement(By.Id("open-new-window")).Click();
WaitFor(WindowHandleCountToBe(2), "Window count was not 2");
WaitFor(WindowWithName("newwindow"), "Could not find window with name 'newwindow'");
driver.Close();
WaitFor(WindowHandleCountToBe(1), "Window count was not 1");
try
{
AlertToBePresent().Accept();
Assert.Fail("Expected exception");
}
catch (NoSuchWindowException)
{
// Expected
}
}
finally
{
driver.SwitchTo().Window(mainWindow);
WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text 'open new window'");
}
}
[Test]
public void PromptShouldUseDefaultValueIfNoKeysSent()
{
driver.Url = CreatePromptPage("This is a default value");
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
IWebElement element = driver.FindElement(By.Id("text"));
WaitFor(ElementTextToEqual(element, "This is a default value"), "Element text was not 'This is a default value'");
Assert.AreEqual("This is a default value", element.Text);
}
[Test]
public void PromptShouldHaveNullValueIfDismissed()
{
driver.Url = CreatePromptPage("This is a default value");
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
IWebElement element = driver.FindElement(By.Id("text"));
WaitFor(ElementTextToEqual(element, "null"), "Element text was not 'null'");
Assert.AreEqual("null", element.Text);
}
[Test]
[IgnoreBrowser(Browser.Remote)]
public void HandlesTwoAlertsFromOneInteraction()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithScripts(
"function setInnerText(id, value) {",
" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",
"}",
"function displayTwoPrompts() {",
" setInnerText('text1', prompt('First'));",
" setInnerText('text2', prompt('Second'));",
"}")
.WithBody(
"<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>",
"<div id='text1'></div>",
"<div id='text2'></div>"));
driver.FindElement(By.Id("double-prompt")).Click();
IAlert alert1 = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert1.SendKeys("brie");
alert1.Accept();
IAlert alert2 = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert2.SendKeys("cheddar");
alert2.Accept();
IWebElement element1 = driver.FindElement(By.Id("text1"));
WaitFor(ElementTextToEqual(element1, "brie"), "Element text was not 'brie'");
Assert.AreEqual("brie", element1.Text);
IWebElement element2 = driver.FindElement(By.Id("text2"));
WaitFor(ElementTextToEqual(element2, "cheddar"), "Element text was not 'cheddar'");
Assert.AreEqual("cheddar", element2.Text);
}
[Test]
public void ShouldHandleAlertOnPageLoad()
{
string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnLoad("javascript:alert(\"onload\")")
.WithBody("<p>Page with onload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format("<a id='open-page-with-onload-alert' href='{0}'>open new page</a>", pageWithOnLoad)));
driver.FindElement(By.Id("open-page-with-onload-alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onload", value);
IWebElement element = driver.FindElement(By.TagName("p"));
WaitFor(ElementTextToEqual(element, "Page with onload event handler"), "Element text was not 'Page with onload event handler'");
}
[Test]
public void ShouldHandleAlertOnPageLoadUsingGet()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnLoad("javascript:alert(\"onload\")")
.WithBody("<p>Page with onload event handler</p>"));
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onload", value);
WaitFor(ElementTextToEqual(driver.FindElement(By.TagName("p")), "Page with onload event handler"), "Could not find element with text 'Page with onload event handler'");
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Test with onLoad alert hangs Chrome.")]
[IgnoreBrowser(Browser.Safari, "Safari driver does not allow commands in any window when an alert is active")]
public void ShouldNotHandleAlertInAnotherWindow()
{
string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnLoad("javascript:alert(\"onload\")")
.WithBody("<p>Page with onload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format(
"<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", pageWithOnLoad)));
string mainWindow = driver.CurrentWindowHandle;
string onloadWindow = null;
try
{
driver.FindElement(By.Id("open-new-window")).Click();
List<String> allWindows = new List<string>(driver.WindowHandles);
allWindows.Remove(mainWindow);
Assert.AreEqual(1, allWindows.Count);
onloadWindow = allWindows[0];
try
{
IWebElement el = driver.FindElement(By.Id("open-new-window"));
WaitFor<IAlert>(AlertToBePresent, TimeSpan.FromSeconds(5), "No alert found");
Assert.Fail("Expected exception");
}
catch (WebDriverException)
{
// An operation timed out exception is expected,
// since we're using WaitFor<T>.
}
}
finally
{
driver.SwitchTo().Window(onloadWindow);
WaitFor<IAlert>(AlertToBePresent, "No alert found").Dismiss();
driver.Close();
driver.SwitchTo().Window(mainWindow);
WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text 'open new window'");
}
}
[Test]
[IgnoreBrowser(Browser.Firefox, "After version 27, Firefox does not trigger alerts on unload.")]
[IgnoreBrowser(Browser.Chrome, "Chrome does not trigger alerts on unload.")]
[IgnoreBrowser(Browser.Edge, "Edge does not trigger alerts on unload.")]
public void ShouldHandleAlertOnPageUnload()
{
string pageWithOnBeforeUnload = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnBeforeUnload("return \"onunload\";")
.WithBody("<p>Page with onbeforeunload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format("<a id='open-page-with-onunload-alert' href='{0}'>open new page</a>", pageWithOnBeforeUnload)));
IWebElement element = WaitFor<IWebElement>(ElementToBePresent(By.Id("open-page-with-onunload-alert")), "Could not find element with id 'open-page-with-onunload-alert'");
element.Click();
driver.Navigate().Back();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onunload", value);
element = WaitFor<IWebElement>(ElementToBePresent(By.Id("open-page-with-onunload-alert")), "Could not find element with id 'open-page-with-onunload-alert'");
WaitFor(ElementTextToEqual(element, "open new page"), "Element text was not 'open new page'");
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome does not implicitly handle onBeforeUnload alert")]
[IgnoreBrowser(Browser.Safari, "Safari driver does not implicitly (or otherwise) handle onBeforeUnload alerts")]
[IgnoreBrowser(Browser.Edge, "Edge driver does not implicitly (or otherwise) handle onBeforeUnload alerts")]
public void ShouldImplicitlyHandleAlertOnPageBeforeUnload()
{
string blank = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage().WithTitle("Success"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Page with onbeforeunload handler")
.WithBody(String.Format(
"<a id='link' href='{0}'>Click here to navigate to another page.</a>", blank)));
SetSimpleOnBeforeUnload("onbeforeunload message");
driver.FindElement(By.Id("link")).Click();
WaitFor(() => driver.Title == "Success", "Title was not 'Success'");
}
[Test]
[IgnoreBrowser(Browser.IE, "Test as written does not trigger alert; also onbeforeunload alert on close will hang browser")]
[IgnoreBrowser(Browser.Chrome, "Test as written does not trigger alert")]
[IgnoreBrowser(Browser.Firefox, "After version 27, Firefox does not trigger alerts on unload.")]
[IgnoreBrowser(Browser.Edge, "Edge does not trigger alerts on unload.")]
public void ShouldHandleAlertOnWindowClose()
{
string pageWithOnBeforeUnload = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnBeforeUnload("javascript:alert(\"onbeforeunload\")")
.WithBody("<p>Page with onbeforeunload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format(
"<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", pageWithOnBeforeUnload)));
string mainWindow = driver.CurrentWindowHandle;
try
{
driver.FindElement(By.Id("open-new-window")).Click();
WaitFor(WindowHandleCountToBe(2), "Window count was not 2");
WaitFor(WindowWithName("newwindow"), "Could not find window with name 'newwindow'");
driver.Close();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onbeforeunload", value);
}
finally
{
driver.SwitchTo().Window(mainWindow);
WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text equal to 'open new window'");
}
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Driver chooses not to return text from unhandled alert")]
[IgnoreBrowser(Browser.Edge, "Driver chooses not to return text from unhandled alert")]
[IgnoreBrowser(Browser.Firefox, "Driver chooses not to return text from unhandled alert")]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Safari, "Safari driver does not do unhandled alerts")]
public void IncludesAlertTextInUnhandledAlertException()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
string title = driver.Title;
Assert.Fail("Expected UnhandledAlertException");
}
catch (UnhandledAlertException e)
{
Assert.AreEqual("cheese", e.AlertText);
}
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
[IgnoreBrowser(Browser.Opera)]
public void CanQuitWhenAnAlertIsPresent()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
EnvironmentManager.Instance.CloseCurrentDriver();
}
[Test]
[IgnoreBrowser(Browser.Safari, "Safari driver cannot handle alert thrown via JavaScript")]
public void ShouldHandleAlertOnFormSubmit()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts").
WithBody("<form id='theForm' action='javascript:alert(\"Tasty cheese\");'>",
"<input id='unused' type='submit' value='Submit'>",
"</form>"));
IWebElement element = driver.FindElement(By.Id("theForm"));
element.Submit();
IAlert alert = driver.SwitchTo().Alert();
string text = alert.Text;
alert.Accept();
Assert.AreEqual("Tasty cheese", text);
Assert.AreEqual("Testing Alerts", driver.Title);
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
[IgnoreBrowser(Browser.Safari, "onBeforeUnload dialogs hang Safari")]
public void ShouldHandleAlertOnPageBeforeUnload()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("pageWithOnBeforeUnloadMessage.html");
IWebElement element = driver.FindElement(By.Id("navigate"));
element.Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
Assert.That(driver.Url, Does.Contain("pageWithOnBeforeUnloadMessage.html"));
// Can't move forward or even quit the driver
// until the alert is accepted.
element.Click();
alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
WaitFor(() => { return driver.Url.Contains(alertsPage); }, "Browser URL does not contain " + alertsPage);
Assert.That(driver.Url, Does.Contain(alertsPage));
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
[IgnoreBrowser(Browser.Safari, "onBeforeUnload dialogs hang Safari")]
public void ShouldHandleAlertOnPageBeforeUnloadAlertAtQuit()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("pageWithOnBeforeUnloadMessage.html");
IWebElement element = driver.FindElement(By.Id("navigate"));
element.Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
driver.Quit();
driver = null;
}
// Disabling test for all browsers. Authentication API is not supported by any driver yet.
// [Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.Edge)]
[IgnoreBrowser(Browser.Firefox)]
[IgnoreBrowser(Browser.IE)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Remote)]
[IgnoreBrowser(Browser.Safari)]
public void ShouldBeAbleToHandleAuthenticationDialog()
{
driver.Url = authenticationPage;
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.SetAuthenticationCredentials("test", "test");
alert.Accept();
Assert.That(driver.FindElement(By.TagName("h1")).Text, Does.Contain("authorized"));
}
// Disabling test for all browsers. Authentication API is not supported by any driver yet.
// [Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.Edge)]
[IgnoreBrowser(Browser.Firefox)]
[IgnoreBrowser(Browser.IE)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Remote)]
[IgnoreBrowser(Browser.Safari)]
public void ShouldBeAbleToDismissAuthenticationDialog()
{
driver.Url = authenticationPage;
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
}
// Disabling test for all browsers. Authentication API is not supported by any driver yet.
// [Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.Edge)]
[IgnoreBrowser(Browser.Firefox)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Remote)]
[IgnoreBrowser(Browser.Safari)]
public void ShouldThrowAuthenticatingOnStandardAlert()
{
driver.Url = alertsPage;
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
alert.SetAuthenticationCredentials("test", "test");
Assert.Fail("Should not be able to Authenticate");
}
catch (UnhandledAlertException)
{
// this is an expected exception
}
// but the next call should be good.
alert.Dismiss();
}
private IAlert AlertToBePresent()
{
return driver.SwitchTo().Alert();
}
private string CreateAlertPage(string alertText)
{
return EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithBody("<a href='#' id='alert' onclick='alert(\"" + alertText + "\");'>click me</a>"));
}
private string CreatePromptPage(string defaultText)
{
return EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Prompt")
.WithScripts(
"function setInnerText(id, value) {",
" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",
"}",
defaultText == null
? "function displayPrompt() { setInnerText('text', prompt('Enter something')); }"
: "function displayPrompt() { setInnerText('text', prompt('Enter something', '" + defaultText + "')); }")
.WithBody(
"<a href='#' id='prompt' onclick='displayPrompt();'>click me</a>",
"<div id='text'>acceptor</div>"));
}
private void SetSimpleOnBeforeUnload(string returnText)
{
((IJavaScriptExecutor)driver).ExecuteScript(
"var returnText = arguments[0]; window.onbeforeunload = function() { return returnText; }",
returnText);
}
private Func<IWebElement> ElementToBePresent(By locator)
{
return () =>
{
IWebElement foundElement = null;
try
{
foundElement = driver.FindElement(By.Id("open-page-with-onunload-alert"));
}
catch (NoSuchElementException)
{
}
return foundElement;
};
}
private Func<bool> ElementTextToEqual(IWebElement element, string text)
{
return () =>
{
return element.Text == text;
};
}
private Func<bool> WindowWithName(string name)
{
return () =>
{
try
{
driver.SwitchTo().Window(name);
return true;
}
catch (NoSuchWindowException)
{
}
return false;
};
}
private Func<bool> WindowHandleCountToBe(int count)
{
return () =>
{
return driver.WindowHandles.Count == count;
};
}
}
}
| |
// 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.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using System.Transactions;
using Microsoft.SqlServer.Server;
using System.Reflection;
using System.IO;
using System.Globalization;
using System.Security;
namespace System.Data.SqlClient
{
public sealed partial class SqlConnection : DbConnection, ICloneable
{
private bool _AsyncCommandInProgress;
// SQLStatistics support
internal SqlStatistics _statistics;
private bool _collectstats;
private bool _fireInfoMessageEventOnUserErrors; // False by default
// root task associated with current async invocation
private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion;
private SqlCredential _credential;
private string _connectionString;
private int _connectRetryCount;
private string _accessToken; // Access Token to be used for token based authententication
// connection resiliency
private object _reconnectLock = new object();
internal Task _currentReconnectionTask;
private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections
private Guid _originalConnectionId = Guid.Empty;
private CancellationTokenSource _reconnectionCancellationSource;
internal SessionData _recoverySessionData;
internal bool _suppressStateChangeForReconnection;
private int _reconnectCount;
// diagnostics listener
private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName);
// Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not
// The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened
// using SqlConnection.Open() method.
internal bool _applyTransientFaultHandling = false;
public SqlConnection(string connectionString) : this()
{
ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available
CacheConnectionStringProperties();
}
public SqlConnection(string connectionString, SqlCredential credential) : this()
{
ConnectionString = connectionString;
if (credential != null)
{
// The following checks are necessary as setting Credential property will call CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential
// CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential it will throw InvalidOperationException rather than Arguemtn exception
// Need to call setter on Credential property rather than setting _credential directly as pool groups need to be checked
SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
if (UsesClearUserIdOrPassword(connectionOptions))
{
throw ADP.InvalidMixedArgumentOfSecureAndClearCredential();
}
if (UsesIntegratedSecurity(connectionOptions))
{
throw ADP.InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity();
}
Credential = credential;
}
// else
// credential == null: we should not set "Credential" as this will do additional validation check and
// checking pool groups which is not necessary. All necessary operation is already done by calling "ConnectionString = connectionString"
CacheConnectionStringProperties();
}
private SqlConnection(SqlConnection connection)
{
GC.SuppressFinalize(this);
CopyFrom(connection);
_connectionString = connection._connectionString;
if (connection._credential != null)
{
SecureString password = connection._credential.Password.Copy();
password.MakeReadOnly();
_credential = new SqlCredential(connection._credential.UserId, password);
}
_accessToken = connection._accessToken;
CacheConnectionStringProperties();
}
// This method will be called once connection string is set or changed.
private void CacheConnectionStringProperties()
{
SqlConnectionString connString = ConnectionOptions as SqlConnectionString;
if (connString != null)
{
_connectRetryCount = connString.ConnectRetryCount;
}
}
//
// PUBLIC PROPERTIES
//
// used to start/stop collection of statistics data and do verify the current state
//
// devnote: start/stop should not performed using a property since it requires execution of code
//
// start statistics
// set the internal flag (_statisticsEnabled) to true.
// Create a new SqlStatistics object if not already there.
// connect the parser to the object.
// if there is no parser at this time we need to connect it after creation.
//
public bool StatisticsEnabled
{
get
{
return (_collectstats);
}
set
{
{
if (value)
{
// start
if (ConnectionState.Open == State)
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
ADP.TimerCurrent(out _statistics._openTimestamp);
}
// set statistics on the parser
// update timestamp;
Debug.Assert(Parser != null, "Where's the parser?");
Parser.Statistics = _statistics;
}
}
else
{
// stop
if (null != _statistics)
{
if (ConnectionState.Open == State)
{
// remove statistics from parser
// update timestamp;
TdsParser parser = Parser;
Debug.Assert(parser != null, "Where's the parser?");
parser.Statistics = null;
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
}
}
_collectstats = value;
}
}
}
internal bool AsyncCommandInProgress
{
get => _AsyncCommandInProgress;
set => _AsyncCommandInProgress = value;
}
// Does this connection use Integrated Security?
private bool UsesIntegratedSecurity(SqlConnectionString opt)
{
return opt != null ? opt.IntegratedSecurity : false;
}
// Does this connection use old style of clear userID or Password in connection string?
private bool UsesClearUserIdOrPassword(SqlConnectionString opt)
{
bool result = false;
if (null != opt)
{
result = (!string.IsNullOrEmpty(opt.UserID) || !string.IsNullOrEmpty(opt.Password));
}
return result;
}
internal SqlConnectionString.TransactionBindingEnum TransactionBinding
{
get => ((SqlConnectionString)ConnectionOptions).TransactionBinding;
}
internal SqlConnectionString.TypeSystem TypeSystem
{
get => ((SqlConnectionString)ConnectionOptions).TypeSystemVersion;
}
internal Version TypeSystemAssemblyVersion
{
get => ((SqlConnectionString)ConnectionOptions).TypeSystemAssemblyVersion;
}
internal int ConnectRetryInterval
{
get => ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval;
}
public override string ConnectionString
{
get
{
return ConnectionString_Get();
}
set
{
if (_credential != null || _accessToken != null)
{
SqlConnectionString connectionOptions = new SqlConnectionString(value);
if (_credential != null)
{
CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(connectionOptions);
}
else
{
CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken(connectionOptions);
}
}
ConnectionString_Set(new SqlConnectionPoolKey(value, _credential, _accessToken));
_connectionString = value; // Change _connectionString value only after value is validated
CacheConnectionStringProperties();
}
}
public override int ConnectionTimeout
{
get
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout);
}
}
// AccessToken: To be used for token based authentication
public string AccessToken
{
get
{
string result = _accessToken;
// When a connection is connecting or is ever opened, make AccessToken available only if "Persist Security Info" is set to true
// otherwise, return null
SqlConnectionString connectionOptions = (SqlConnectionString)UserConnectionOptions;
return InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo ? null : _accessToken;
}
set
{
// If a connection is connecting or is ever opened, AccessToken cannot be set
if (!InnerConnection.AllowSetConnectionString)
{
throw ADP.OpenConnectionPropertySet("AccessToken", InnerConnection.State);
}
if (value != null)
{
// Check if the usage of AccessToken has any conflict with the keys used in connection string and credential
CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken((SqlConnectionString)ConnectionOptions);
}
// Need to call ConnectionString_Set to do proper pool group check
ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, credential: _credential, accessToken: value));
_accessToken = value;
}
}
public override string Database
{
// if the connection is open, we need to ask the inner connection what it's
// current catalog is because it may have gotten changed, otherwise we can
// just return what the connection string had.
get
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
string result;
if (null != innerConnection)
{
result = innerConnection.CurrentDatabase;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog);
}
return result;
}
}
public override string DataSource
{
get
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
string result;
if (null != innerConnection)
{
result = innerConnection.CurrentDataSource;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source);
}
return result;
}
}
public int PacketSize
{
// if the connection is open, we need to ask the inner connection what it's
// current packet size is because it may have gotten changed, otherwise we
// can just return what the connection string had.
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
int result;
if (null != innerConnection)
{
result = innerConnection.PacketSize;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size);
}
return result;
}
}
public Guid ClientConnectionId
{
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null != innerConnection)
{
return innerConnection.ClientConnectionId;
}
else
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return _originalConnectionId;
}
return Guid.Empty;
}
}
}
public override string ServerVersion
{
get => GetOpenTdsConnection().ServerVersion;
}
public override ConnectionState State
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return ConnectionState.Open;
}
return InnerConnection.State;
}
}
internal SqlStatistics Statistics
{
get => _statistics;
}
public string WorkstationId
{
get
{
// If not supplied by the user, the default value is the MachineName
// Note: In Longhorn you'll be able to rename a machine without
// rebooting. Therefore, don't cache this machine name.
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
string result = constr?.WorkstationId ?? Environment.MachineName;
return result;
}
}
public SqlCredential Credential
{
get
{
SqlCredential result = _credential;
// When a connection is connecting or is ever opened, make credential available only if "Persist Security Info" is set to true
// otherwise, return null
SqlConnectionString connectionOptions = (SqlConnectionString)UserConnectionOptions;
if (InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo)
{
result = null;
}
return result;
}
set
{
// If a connection is connecting or is ever opened, user id/password cannot be set
if (!InnerConnection.AllowSetConnectionString)
{
throw ADP.OpenConnectionPropertySet(nameof(Credential), InnerConnection.State);
}
// check if the usage of credential has any conflict with the keys used in connection string
if (value != null)
{
CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential((SqlConnectionString)ConnectionOptions);
if (_accessToken != null)
{
throw ADP.InvalidMixedUsageOfCredentialAndAccessToken();
}
}
_credential = value;
// Need to call ConnectionString_Set to do proper pool group check
ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, _credential, accessToken: _accessToken));
}
}
// CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential: check if the usage of credential has any conflict
// with the keys used in connection string
// If there is any conflict, it throws InvalidOperationException
// This is used in the setter of ConnectionString and Credential properties.
private void CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(SqlConnectionString connectionOptions)
{
if (UsesClearUserIdOrPassword(connectionOptions))
{
throw ADP.InvalidMixedUsageOfSecureAndClearCredential();
}
if (UsesIntegratedSecurity(connectionOptions))
{
throw ADP.InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity();
}
}
// CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken: check if the usage of AccessToken has any conflict
// with the keys used in connection string and credential
// If there is any conflict, it throws InvalidOperationException
// This is to be used setter of ConnectionString and AccessToken properties
private void CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken(SqlConnectionString connectionOptions)
{
if (UsesClearUserIdOrPassword(connectionOptions))
{
throw ADP.InvalidMixedUsageOfAccessTokenAndUserIDPassword();
}
if (UsesIntegratedSecurity(connectionOptions))
{
throw ADP.InvalidMixedUsageOfAccessTokenAndIntegratedSecurity();
}
// Check if the usage of AccessToken has the conflict with credential
if (_credential != null)
{
throw ADP.InvalidMixedUsageOfCredentialAndAccessToken();
}
}
protected override DbProviderFactory DbProviderFactory
{
get => SqlClientFactory.Instance;
}
// SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication
//
// PUBLIC EVENTS
//
public event SqlInfoMessageEventHandler InfoMessage;
public bool FireInfoMessageEventOnUserErrors
{
get => _fireInfoMessageEventOnUserErrors;
set => _fireInfoMessageEventOnUserErrors = value;
}
// Approx. number of times that the internal connection has been reconnected
internal int ReconnectCount
{
get => _reconnectCount;
}
internal bool ForceNewConnection { get; set; }
protected override void OnStateChange(StateChangeEventArgs stateChange)
{
if (!_suppressStateChangeForReconnection)
{
base.OnStateChange(stateChange);
}
}
//
// PUBLIC METHODS
//
new public SqlTransaction BeginTransaction()
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(IsolationLevel.Unspecified, null);
}
new public SqlTransaction BeginTransaction(IsolationLevel iso)
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(iso, null);
}
public SqlTransaction BeginTransaction(string transactionName)
{
// Use transaction names only on the outermost pair of nested
// BEGIN...COMMIT or BEGIN...ROLLBACK statements. Transaction names
// are ignored for nested BEGIN's. The only way to rollback a nested
// transaction is to have a save point from a SAVE TRANSACTION call.
return BeginTransaction(IsolationLevel.Unspecified, transactionName);
}
[SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
DbTransaction transaction = BeginTransaction(isolationLevel);
// InnerConnection doesn't maintain a ref on the outer connection (this) and
// subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction
// is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable
// until the completion of BeginTransaction with KeepAlive
GC.KeepAlive(this);
return transaction;
}
public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName)
{
WaitForPendingReconnection();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
SqlTransaction transaction;
bool isFirstAttempt = true;
do
{
transaction = GetOpenTdsConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice
Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt");
isFirstAttempt = false;
} while (transaction.InternalTransaction.ConnectionHasBeenRestored);
// The GetOpenConnection line above doesn't keep a ref on the outer connection (this),
// and it could be collected before the inner connection can hook it to the transaction, resulting in
// a transaction with a null connection property. Use GC.KeepAlive to ensure this doesn't happen.
GC.KeepAlive(this);
return transaction;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
public override void ChangeDatabase(string database)
{
SqlStatistics statistics = null;
RepairInnerConnection();
try
{
statistics = SqlStatistics.StartTimer(Statistics);
InnerConnection.ChangeDatabase(database);
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
public static void ClearAllPools()
{
SqlConnectionFactory.SingletonInstance.ClearAllPools();
}
public static void ClearPool(SqlConnection connection)
{
ADP.CheckArgumentNull(connection, nameof(connection));
DbConnectionOptions connectionOptions = connection.UserConnectionOptions;
if (null != connectionOptions)
{
SqlConnectionFactory.SingletonInstance.ClearPool(connection);
}
}
private void CloseInnerConnection()
{
// CloseConnection() now handles the lock
// The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and
// the command will no longer be cancelable. It might be desirable to be able to cancel the close operation, but this is
// outside of the scope of Whidbey RTM. See (SqlCommand::Cancel) for other lock.
InnerConnection.CloseConnection(this, ConnectionFactory);
}
public override void Close()
{
ConnectionState previousState = State;
Guid operationId = default(Guid);
Guid clientConnectionId = default(Guid);
// during the call to Dispose() there is a redundant call to
// Close(). because of this, the second time Close() is invoked the
// connection is already in a closed state. this doesn't seem to be a
// problem except for logging, as we'll get duplicate Before/After/Error
// log entries
if (previousState != ConnectionState.Closed)
{
operationId = s_diagnosticListener.WriteConnectionCloseBefore(this);
// we want to cache the ClientConnectionId for After/Error logging, as when the connection
// is closed then we will lose this identifier
//
// note: caching this is only for diagnostics logging purposes
clientConnectionId = ClientConnectionId;
}
SqlStatistics statistics = null;
Exception e = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
CancellationTokenSource cts = _reconnectionCancellationSource;
if (cts != null)
{
cts.Cancel();
}
AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection
if (State != ConnectionState.Open)
{// if we cancelled before the connection was opened
OnStateChange(DbConnectionInternal.StateChangeClosed);
}
}
CancelOpenAndWait();
CloseInnerConnection();
GC.SuppressFinalize(this);
if (null != Statistics)
{
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
}
catch (Exception ex)
{
e = ex;
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
// we only want to log this if the previous state of the
// connection is open, as that's the valid use-case
if (previousState != ConnectionState.Closed)
{
if (e != null)
{
s_diagnosticListener.WriteConnectionCloseError(operationId, clientConnectionId, this, e);
}
else
{
s_diagnosticListener.WriteConnectionCloseAfter(operationId, clientConnectionId, this);
}
}
}
}
new public SqlCommand CreateCommand()
{
return new SqlCommand(null, this);
}
private void DisposeMe(bool disposing)
{
_credential = null;
_accessToken = null;
if (!disposing)
{
// For non-pooled connections we need to make sure that if the SqlConnection was not closed,
// then we release the GCHandle on the stateObject to allow it to be GCed
// For pooled connections, we will rely on the pool reclaiming the connection
var innerConnection = (InnerConnection as SqlInternalConnectionTds);
if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling))
{
var parser = innerConnection.Parser;
if ((parser != null) && (parser._physicalStateObj != null))
{
parser._physicalStateObj.DecrementPendingCallbacks(release: false);
}
}
}
}
public override void Open()
{
Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this);
PrepareStatisticsForNewConnection();
SqlStatistics statistics = null;
Exception e = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
if (!TryOpen(null))
{
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
catch (Exception ex)
{
e = ex;
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
if (e != null)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, e);
}
else
{
s_diagnosticListener.WriteConnectionOpenAfter(operationId, this);
}
}
}
internal void RegisterWaitingForReconnect(Task waitingTask)
{
if (((SqlConnectionString)ConnectionOptions).MARS)
{
return;
}
Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null);
if (_asyncWaitingForReconnection != waitingTask)
{ // somebody else managed to register
throw SQL.MARSUnspportedOnConnection();
}
}
private async Task ReconnectAsync(int timeout)
{
try
{
long commandTimeoutExpiration = 0;
if (timeout > 0)
{
commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout);
}
CancellationTokenSource cts = new CancellationTokenSource();
_reconnectionCancellationSource = cts;
CancellationToken ctoken = cts.Token;
int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string
for (int attempt = 0; attempt < retryCount; attempt++)
{
if (ctoken.IsCancellationRequested)
{
return;
}
try
{
try
{
ForceNewConnection = true;
await OpenAsync(ctoken).ConfigureAwait(false);
// On success, increment the reconnect count - we don't really care if it rolls over since it is approx.
_reconnectCount = unchecked(_reconnectCount + 1);
#if DEBUG
Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !");
#endif
}
finally
{
ForceNewConnection = false;
}
return;
}
catch (SqlException e)
{
if (attempt == retryCount - 1)
{
throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId);
}
if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval))
{
throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId);
}
}
await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false);
}
}
finally
{
_recoverySessionData = null;
_suppressStateChangeForReconnection = false;
}
Debug.Fail("Should not reach this point");
}
internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout)
{
Task runningReconnect = _currentReconnectionTask;
// This loop in the end will return not completed reconnect task or null
while (runningReconnect != null && runningReconnect.IsCompleted)
{
// clean current reconnect task (if it is the same one we checked
Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect);
// make sure nobody started new task (if which case we did not clean it)
runningReconnect = _currentReconnectionTask;
}
if (runningReconnect == null)
{
if (_connectRetryCount > 0)
{
SqlInternalConnectionTds tdsConn = GetOpenTdsConnection();
if (tdsConn._sessionRecoveryAcknowledged)
{
TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj;
if (!stateObj.ValidateSNIConnection())
{
if (tdsConn.Parser._sessionPool != null)
{
if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0)
{
// >1 MARS session
if (beforeDisconnect != null)
{
beforeDisconnect();
}
OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null);
}
}
SessionData cData = tdsConn.CurrentSessionData;
cData.AssertUnrecoverableStateCountIsCorrect();
if (cData._unrecoverableStatesCount == 0)
{
bool callDisconnect = false;
lock (_reconnectLock)
{
tdsConn.CheckEnlistedTransactionBinding();
runningReconnect = _currentReconnectionTask; // double check after obtaining the lock
if (runningReconnect == null)
{
if (cData._unrecoverableStatesCount == 0)
{ // could change since the first check, but now is stable since connection is know to be broken
_originalConnectionId = ClientConnectionId;
_recoverySessionData = cData;
if (beforeDisconnect != null)
{
beforeDisconnect();
}
try
{
_suppressStateChangeForReconnection = true;
tdsConn.DoomThisConnection();
}
catch (SqlException)
{
}
// use Task.Factory.StartNew with state overload instead of Task.Run to avoid anonymous closure context capture in method scope and avoid the unneeded allocation
runningReconnect = Task.Factory.StartNew(state => ReconnectAsync((int)state), timeout, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
// if current reconnect is not null, somebody already started reconnection task - some kind of race condition
Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected");
_currentReconnectionTask = runningReconnect;
}
}
else
{
callDisconnect = true;
}
}
if (callDisconnect && beforeDisconnect != null)
{
beforeDisconnect();
}
}
else
{
if (beforeDisconnect != null)
{
beforeDisconnect();
}
OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null);
}
} // ValidateSNIConnection
} // sessionRecoverySupported
} // connectRetryCount>0
}
else
{ // runningReconnect = null
if (beforeDisconnect != null)
{
beforeDisconnect();
}
}
return runningReconnect;
}
// this is straightforward, but expensive method to do connection resiliency - it take locks and all preparations as for TDS request
partial void RepairInnerConnection()
{
WaitForPendingReconnection();
if (_connectRetryCount == 0)
{
return;
}
SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds;
if (tdsConn != null)
{
tdsConn.ValidateConnectionForExecute(null);
tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this);
}
}
private void WaitForPendingReconnection()
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false);
}
}
private void CancelOpenAndWait()
{
// copy from member to avoid changes by background thread
var completion = _currentCompletion;
if (completion != null)
{
completion.Item1.TrySetCanceled();
((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne();
}
Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source");
}
public override Task OpenAsync(CancellationToken cancellationToken)
{
Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this);
PrepareStatisticsForNewConnection();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
System.Transactions.Transaction transaction = ADP.GetCurrentTransaction();
TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>(transaction);
TaskCompletionSource<object> result = new TaskCompletionSource<object>();
if (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection) ||
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlErrorOpenConnection))
{
result.Task.ContinueWith((t) =>
{
if (t.Exception != null)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, t.Exception);
}
else
{
s_diagnosticListener.WriteConnectionOpenAfter(operationId, this);
}
}, TaskScheduler.Default);
}
if (cancellationToken.IsCancellationRequested)
{
result.SetCanceled();
return result.Task;
}
bool completed;
try
{
completed = TryOpen(completion);
}
catch (Exception e)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, e);
result.SetException(e);
return result.Task;
}
if (completed)
{
result.SetResult(null);
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(s => ((TaskCompletionSource<DbConnectionInternal>)s).TrySetCanceled(), completion);
}
OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration);
_currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task);
completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default);
return result.Task;
}
return result.Task;
}
catch (Exception ex)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, ex);
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
public override DataTable GetSchema()
{
return GetSchema(DbMetaDataCollectionNames.MetaDataCollections, null);
}
public override DataTable GetSchema(string collectionName)
{
return GetSchema(collectionName, null);
}
public override DataTable GetSchema(string collectionName, string[] restrictionValues)
{
return InnerConnection.GetSchema(ConnectionFactory, PoolGroup, this, collectionName, restrictionValues);
}
private class OpenAsyncRetry
{
private SqlConnection _parent;
private TaskCompletionSource<DbConnectionInternal> _retry;
private TaskCompletionSource<object> _result;
private CancellationTokenRegistration _registration;
public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result, CancellationTokenRegistration registration)
{
_parent = parent;
_retry = retry;
_result = result;
_registration = registration;
}
internal void Retry(Task<DbConnectionInternal> retryTask)
{
_registration.Dispose();
try
{
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(_parent.Statistics);
if (retryTask.IsFaulted)
{
Exception e = retryTask.Exception.InnerException;
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(retryTask.Exception.InnerException);
}
else if (retryTask.IsCanceled)
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetCanceled();
}
else
{
bool result;
// protect continuation from races with close and cancel
lock (_parent.InnerConnection)
{
result = _parent.TryOpen(_retry);
}
if (result)
{
_parent._currentCompletion = null;
_result.SetResult(null);
}
else
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending)));
}
}
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
catch (Exception e)
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(e);
}
}
}
private void PrepareStatisticsForNewConnection()
{
if (StatisticsEnabled ||
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) ||
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection))
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
}
else
{
_statistics.ContinueOnNewConnection();
}
}
}
private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry)
{
SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
_applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0);
if (ForceNewConnection)
{
if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions))
{
return false;
}
}
else
{
if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions))
{
return false;
}
}
// does not require GC.KeepAlive(this) because of ReRegisterForFinalize below.
var tdsInnerConnection = (SqlInternalConnectionTds)InnerConnection;
Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?");
if (!tdsInnerConnection.ConnectionOptions.Pooling)
{
// For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles
GC.ReRegisterForFinalize(this);
}
// The _statistics can change with StatisticsEnabled. Copying to a local variable before checking for a null value.
SqlStatistics statistics = _statistics;
if (StatisticsEnabled ||
(s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) && statistics != null))
{
ADP.TimerCurrent(out _statistics._openTimestamp);
tdsInnerConnection.Parser.Statistics = _statistics;
}
else
{
tdsInnerConnection.Parser.Statistics = null;
_statistics = null; // in case of previous Open/Close/reset_CollectStats sequence
}
return true;
}
//
// INTERNAL PROPERTIES
//
internal bool HasLocalTransaction
{
get
{
return GetOpenTdsConnection().HasLocalTransaction;
}
}
internal bool HasLocalTransactionFromAPI
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return false; //we will not go into reconnection if we are inside the transaction
}
return GetOpenTdsConnection().HasLocalTransactionFromAPI;
}
}
internal bool IsKatmaiOrNewer
{
get
{
if (_currentReconnectionTask != null)
{ // holds true even if task is completed
return true; // if CR is enabled, connection, if established, will be Katmai+
}
return GetOpenTdsConnection().IsKatmaiOrNewer;
}
}
internal TdsParser Parser
{
get
{
SqlInternalConnectionTds tdsConnection = GetOpenTdsConnection();
return tdsConnection.Parser;
}
}
//
// INTERNAL METHODS
//
internal void ValidateConnectionForExecute(string method, SqlCommand command)
{
Task asyncWaitingForReconnection = _asyncWaitingForReconnection;
if (asyncWaitingForReconnection != null)
{
if (!asyncWaitingForReconnection.IsCompleted)
{
throw SQL.MARSUnspportedOnConnection();
}
else
{
Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection);
}
}
if (_currentReconnectionTask != null)
{
Task currentReconnectionTask = _currentReconnectionTask;
if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted)
{
return; // execution will wait for this task later
}
}
SqlInternalConnectionTds innerConnection = GetOpenTdsConnection(method);
innerConnection.ValidateConnectionForExecute(command);
}
// Surround name in brackets and then escape any end bracket to protect against SQL Injection.
// NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well
// as native OleDb and Odbc.
internal static string FixupDatabaseTransactionName(string name)
{
if (!string.IsNullOrEmpty(name))
{
return SqlServerEscapeHelper.EscapeIdentifier(name);
}
else
{
return name;
}
}
// If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter
// The close action also supports being run asynchronously
internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
{
Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!");
if (breakConnection && (ConnectionState.Open == State))
{
if (wrapCloseInAction != null)
{
int capturedCloseCount = _closeCount;
Action closeAction = () =>
{
if (capturedCloseCount == _closeCount)
{
Close();
}
};
wrapCloseInAction(closeAction);
}
else
{
Close();
}
}
if (exception.Class >= TdsEnums.MIN_ERROR_CLASS)
{
// It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS or above is an error,
// below TdsEnums.MIN_ERROR_CLASS denotes an info message.
throw exception;
}
else
{
// If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler
this.OnInfoMessage(new SqlInfoMessageEventArgs(exception));
}
}
//
// PRIVATE METHODS
//
internal SqlInternalConnectionTds GetOpenTdsConnection()
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null == innerConnection)
{
throw ADP.ClosedConnectionError();
}
return innerConnection;
}
internal SqlInternalConnectionTds GetOpenTdsConnection(string method)
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null == innerConnection)
{
throw ADP.OpenConnectionRequired(method, InnerConnection.State);
}
return innerConnection;
}
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent)
{
bool notified;
OnInfoMessage(imevent, out notified);
}
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified)
{
SqlInfoMessageEventHandler handler = InfoMessage;
if (null != handler)
{
notified = true;
try
{
handler(this, imevent);
}
catch (Exception e)
{
if (!ADP.IsCatchableOrSecurityExceptionType(e))
{
throw;
}
}
}
else
{
notified = false;
}
}
public static void ChangePassword(string connectionString, string newPassword)
{
if (string.IsNullOrEmpty(connectionString))
{
throw SQL.ChangePasswordArgumentMissing(nameof(newPassword));
}
if (string.IsNullOrEmpty(newPassword))
{
throw SQL.ChangePasswordArgumentMissing(nameof(newPassword));
}
if (TdsEnums.MAXLEN_NEWPASSWORD < newPassword.Length)
{
throw ADP.InvalidArgumentLength(nameof(newPassword), TdsEnums.MAXLEN_NEWPASSWORD);
}
SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential: null, accessToken: null);
SqlConnectionString connectionOptions = SqlConnectionFactory.FindSqlConnectionOptions(key);
if (connectionOptions.IntegratedSecurity)
{
throw SQL.ChangePasswordConflictsWithSSPI();
}
if (!string.IsNullOrEmpty(connectionOptions.AttachDBFilename))
{
throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.AttachDBFilename);
}
ChangePassword(connectionString, connectionOptions, null, newPassword, null);
}
public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword)
{
if (string.IsNullOrEmpty(connectionString))
{
throw SQL.ChangePasswordArgumentMissing(nameof(connectionString));
}
// check credential; not necessary to check the length of password in credential as the check is done by SqlCredential class
if (credential == null)
{
throw SQL.ChangePasswordArgumentMissing(nameof(credential));
}
if (newSecurePassword == null || newSecurePassword.Length == 0)
{
throw SQL.ChangePasswordArgumentMissing(nameof(newSecurePassword));
}
if (!newSecurePassword.IsReadOnly())
{
throw ADP.MustBeReadOnly(nameof(newSecurePassword));
}
if (TdsEnums.MAXLEN_NEWPASSWORD < newSecurePassword.Length)
{
throw ADP.InvalidArgumentLength(nameof(newSecurePassword), TdsEnums.MAXLEN_NEWPASSWORD);
}
SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential, accessToken: null);
SqlConnectionString connectionOptions = SqlConnectionFactory.FindSqlConnectionOptions(key);
// Check for connection string values incompatible with SqlCredential
if (!string.IsNullOrEmpty(connectionOptions.UserID) || !string.IsNullOrEmpty(connectionOptions.Password))
{
throw ADP.InvalidMixedArgumentOfSecureAndClearCredential();
}
if (connectionOptions.IntegratedSecurity)
{
throw SQL.ChangePasswordConflictsWithSSPI();
}
if (!string.IsNullOrEmpty(connectionOptions.AttachDBFilename))
{
throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.AttachDBFilename);
}
ChangePassword(connectionString, connectionOptions, credential, null, newSecurePassword);
}
private static void ChangePassword(string connectionString, SqlConnectionString connectionOptions, SqlCredential credential, string newPassword, SecureString newSecurePassword)
{
// note: This is the only case where we directly construct the internal connection, passing in the new password.
// Normally we would simply create a regular connection and open it, but there is no other way to pass the
// new password down to the constructor. This would have an unwanted impact on the connection pool.
SqlInternalConnectionTds con = null;
try
{
con = new SqlInternalConnectionTds(null, connectionOptions, credential, null, newPassword, newSecurePassword, false);
}
finally
{
if (con != null)
con.Dispose();
}
SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential, accessToken: null);
SqlConnectionFactory.SingletonInstance.ClearPool(key);
}
//
// SQL DEBUGGING SUPPORT
//
// this only happens once per connection
// SxS: using named file mapping APIs
internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask, object value, int tag)
{
// Connection exists, schedule removal, will be added to ref collection after calling ValidateAndReconnect
outerTask = outerTask.ContinueWith(task =>
{
RemoveWeakReference(value);
return task;
}, TaskScheduler.Default).Unwrap();
}
public void ResetStatistics()
{
if (null != Statistics)
{
Statistics.Reset();
if (ConnectionState.Open == State)
{
// update timestamp;
ADP.TimerCurrent(out _statistics._openTimestamp);
}
}
}
public IDictionary RetrieveStatistics()
{
if (null != Statistics)
{
UpdateStatistics();
return Statistics.GetDictionary();
}
else
{
return new SqlStatistics().GetDictionary();
}
}
private void UpdateStatistics()
{
if (ConnectionState.Open == State)
{
// update timestamp
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
// delegate the rest of the work to the SqlStatistics class
Statistics.UpdateStatistics();
}
object ICloneable.Clone() => new SqlConnection(this);
private void CopyFrom(SqlConnection connection)
{
ADP.CheckArgumentNull(connection, nameof(connection));
_userConnectionOptions = connection.UserConnectionOptions;
_poolGroup = connection.PoolGroup;
if (DbConnectionClosedNeverOpened.SingletonInstance == connection._innerConnection)
{
_innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}
else
{
_innerConnection = DbConnectionClosedPreviouslyOpened.SingletonInstance;
}
}
// UDT SUPPORT
private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError)
{
Debug.Assert(TypeSystemAssemblyVersion != null, "TypeSystemAssembly should be set !");
if (string.Equals(asmRef.Name, "Microsoft.SqlServer.Types", StringComparison.OrdinalIgnoreCase))
{
asmRef.Version = TypeSystemAssemblyVersion;
}
try
{
return Assembly.Load(asmRef);
}
catch (Exception e)
{
if (throwOnError || !ADP.IsCatchableExceptionType(e))
{
throw;
}
else
{
return null;
};
}
}
internal void CheckGetExtendedUDTInfo(SqlMetaDataPriv metaData, bool fThrow)
{
if (metaData.udt?.Type == null)
{ // If null, we have not obtained extended info.
Debug.Assert(!string.IsNullOrEmpty(metaData.udt?.AssemblyQualifiedName), "Unexpected state on GetUDTInfo");
// Parameter throwOnError determines whether exception from Assembly.Load is thrown.
metaData.udt.Type =
Type.GetType(typeName: metaData.udt.AssemblyQualifiedName, assemblyResolver: asmRef => ResolveTypeAssembly(asmRef, fThrow), typeResolver: null, throwOnError: fThrow);
if (fThrow && metaData.udt.Type == null)
{
throw SQL.UDTUnexpectedResult(metaData.udt.AssemblyQualifiedName);
}
}
}
internal object GetUdtValue(object value, SqlMetaDataPriv metaData, bool returnDBNull)
{
if (returnDBNull && ADP.IsNull(value))
{
return DBNull.Value;
}
object o = null;
// Since the serializer doesn't handle nulls...
if (ADP.IsNull(value))
{
Type t = metaData.udt?.Type;
Debug.Assert(t != null, "Unexpected null of udtType on GetUdtValue!");
o = t.InvokeMember("Null", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static, null, null, Array.Empty<object>(), CultureInfo.InvariantCulture);
Debug.Assert(o != null);
return o;
}
else
{
MemoryStream stm = new MemoryStream((byte[])value);
o = SerializationHelperSql9.Deserialize(stm, metaData.udt?.Type);
Debug.Assert(o != null, "object could NOT be created");
return o;
}
}
internal byte[] GetBytes(object o)
{
Format format = Format.Native;
return GetBytes(o, out format, out int maxSize);
}
internal byte[] GetBytes(object o, out Format format, out int maxSize)
{
SqlUdtInfo attr = GetInfoFromType(o.GetType());
maxSize = attr.MaxByteSize;
format = attr.SerializationFormat;
if (maxSize < -1 || maxSize >= ushort.MaxValue)
{
throw new InvalidOperationException(o.GetType() + ": invalid Size");
}
byte[] retval;
using (MemoryStream stm = new MemoryStream(maxSize < 0 ? 0 : maxSize))
{
SerializationHelperSql9.Serialize(stm, o);
retval = stm.ToArray();
}
return retval;
}
private SqlUdtInfo GetInfoFromType(Type t)
{
Debug.Assert(t != null, "Type object cant be NULL");
Type orig = t;
do
{
SqlUdtInfo attr = SqlUdtInfo.TryGetFromType(t);
if (attr != null)
{
return attr;
}
else
{
t = t.BaseType;
}
}
while (t != null);
throw SQL.UDTInvalidSqlType(orig.AssemblyQualifiedName);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Streams.Core;
namespace Orleans.Streams
{
[Serializable]
[GenerateSerializer]
internal class PubSubGrainState
{
[Id(1)]
public HashSet<PubSubPublisherState> Producers { get; set; } = new HashSet<PubSubPublisherState>();
[Id(2)]
public HashSet<PubSubSubscriptionState> Consumers { get; set; } = new HashSet<PubSubSubscriptionState>();
}
[GrainType("pubsubrendezvous")]
[StorageProvider(ProviderName = "PubSubStore")]
internal class PubSubRendezvousGrain : Grain<PubSubGrainState>, IPubSubRendezvousGrain
{
private readonly ILogger logger;
private const bool DEBUG_PUB_SUB = false;
private static readonly CounterStatistic counterProducersAdded;
private static readonly CounterStatistic counterProducersRemoved;
private static readonly CounterStatistic counterProducersTotal;
private static readonly CounterStatistic counterConsumersAdded;
private static readonly CounterStatistic counterConsumersRemoved;
private static readonly CounterStatistic counterConsumersTotal;
static PubSubRendezvousGrain()
{
counterProducersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_ADDED);
counterProducersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_REMOVED);
counterProducersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_TOTAL);
counterConsumersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_ADDED);
counterConsumersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_REMOVED);
counterConsumersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_TOTAL);
}
public PubSubRendezvousGrain(ILogger<PubSubRendezvousGrain> logger)
{
this.logger = logger;
}
public override Task OnActivateAsync()
{
LogPubSubCounts("OnActivateAsync");
return Task.CompletedTask;
}
public override Task OnDeactivateAsync()
{
LogPubSubCounts("OnDeactivateAsync");
return Task.CompletedTask;
}
public async Task<ISet<PubSubSubscriptionState>> RegisterProducer(InternalStreamId streamId, IStreamProducerExtension streamProducer)
{
counterProducersAdded.Increment();
try
{
var publisherState = new PubSubPublisherState(streamId, streamProducer);
State.Producers.Add(publisherState);
LogPubSubCounts("RegisterProducer {0}", streamProducer);
await WriteStateAsync();
counterProducersTotal.Increment();
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_RegisterProducerFailed, $"Failed to register a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
return State.Consumers.Where(c => !c.IsFaulted).ToSet();
}
public async Task UnregisterProducer(InternalStreamId streamId, IStreamProducerExtension streamProducer)
{
counterProducersRemoved.Increment();
try
{
int numRemoved = State.Producers.RemoveWhere(s => s.Equals(streamId, streamProducer));
LogPubSubCounts("UnregisterProducer {0} NumRemoved={1}", streamProducer, numRemoved);
if (numRemoved > 0)
{
Task updateStorageTask = State.Producers.Count == 0 && State.Consumers.Count == 0
? ClearStateAsync() //State contains no producers or consumers, remove it from storage
: WriteStateAsync();
await updateStorageTask;
}
counterProducersTotal.DecrementBy(numRemoved);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_UnegisterProducerFailed,
$"Failed to unregister a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
if (State.Producers.Count == 0 && State.Consumers.Count == 0)
{
DeactivateOnIdle(); // No producers or consumers left now, so flag ourselves to expedite Deactivation
}
}
public async Task RegisterConsumer(
GuidId subscriptionId,
InternalStreamId streamId,
IStreamConsumerExtension streamConsumer,
string filterData)
{
counterConsumersAdded.Increment();
PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId));
if (pubSubState != null && pubSubState.IsFaulted)
throw new FaultedSubscriptionException(subscriptionId, streamId);
try
{
if (pubSubState == null)
{
pubSubState = new PubSubSubscriptionState(subscriptionId, streamId, streamConsumer);
State.Consumers.Add(pubSubState);
}
if (!string.IsNullOrWhiteSpace(filterData))
pubSubState.AddFilter(filterData);
LogPubSubCounts("RegisterConsumer {0}", streamConsumer);
await WriteStateAsync();
counterConsumersTotal.Increment();
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_RegisterConsumerFailed,
$"Failed to register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
int numProducers = State.Producers.Count;
if (numProducers <= 0)
return;
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug("Notifying {0} existing producer(s) about new consumer {1}. Producers={2}",
numProducers, streamConsumer, Utils.EnumerableToString(State.Producers));
// Notify producers about a new streamConsumer.
var tasks = new List<Task>();
var producers = State.Producers.ToList();
int initialProducerCount = producers.Count;
try
{
foreach (PubSubPublisherState producerState in producers)
{
tasks.Add(ExecuteProducerTask(producerState, producerState.Producer.AddSubscriber(subscriptionId, streamId, streamConsumer, filterData)));
}
Exception exception = null;
try
{
await Task.WhenAll(tasks);
}
catch (Exception exc)
{
exception = exc;
}
// if the number of producers has been changed, resave state.
if (State.Producers.Count != initialProducerCount)
{
await WriteStateAsync();
counterConsumersTotal.DecrementBy(initialProducerCount - State.Producers.Count);
}
if (exception != null)
{
throw exception;
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_RegisterConsumerFailed,
$"Failed to update producers while register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
}
private void RemoveProducer(PubSubPublisherState producer)
{
logger.Warn(ErrorCode.Stream_ProducerIsDead,
"Producer {0} on stream {1} is no longer active - permanently removing producer.",
producer, producer.Stream);
State.Producers.Remove(producer);
}
public async Task UnregisterConsumer(GuidId subscriptionId, InternalStreamId streamId)
{
counterConsumersRemoved.Increment();
try
{
int numRemoved = State.Consumers.RemoveWhere(c => c.Equals(subscriptionId));
LogPubSubCounts("UnregisterSubscription {0} NumRemoved={1}", subscriptionId, numRemoved);
if (await TryClearState())
{
// If state was cleared expedite Deactivation
DeactivateOnIdle();
}
else
{
if (numRemoved != 0)
{
await WriteStateAsync();
}
await NotifyProducersOfRemovedSubscription(subscriptionId, streamId);
}
counterConsumersTotal.DecrementBy(numRemoved);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_UnregisterConsumerFailed,
$"Failed to unregister a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
}
public Task<int> ProducerCount(InternalStreamId streamId)
{
return Task.FromResult(State.Producers.Count);
}
public Task<int> ConsumerCount(InternalStreamId streamId)
{
return Task.FromResult(GetConsumersForStream(streamId).Length);
}
public Task<PubSubSubscriptionState[]> DiagGetConsumers(InternalStreamId streamId)
{
return Task.FromResult(GetConsumersForStream(streamId));
}
private PubSubSubscriptionState[] GetConsumersForStream(InternalStreamId streamId)
{
return State.Consumers.Where(c => !c.IsFaulted && c.Stream.Equals(streamId)).ToArray();
}
private void LogPubSubCounts(string fmt, params object[] args)
{
if (logger.IsEnabled(LogLevel.Debug) || DEBUG_PUB_SUB)
{
int numProducers = 0;
int numConsumers = 0;
if (State?.Producers != null)
numProducers = State.Producers.Count;
if (State?.Consumers != null)
numConsumers = State.Consumers.Count;
string when = args != null && args.Length != 0 ? string.Format(fmt, args) : fmt;
logger.Info("{0}. Now have total of {1} producers and {2} consumers. All Consumers = {3}, All Producers = {4}",
when, numProducers, numConsumers, Utils.EnumerableToString(State?.Consumers), Utils.EnumerableToString(State?.Producers));
}
}
// Check that what we have cached locally matches what is in the persistent table.
public async Task Validate()
{
var captureProducers = State.Producers;
var captureConsumers = State.Consumers;
await ReadStateAsync();
if (captureProducers.Count != State.Producers.Count)
{
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers.Count={captureProducers.Count}, State.Producers.Count={State.Producers.Count}");
}
if (captureProducers.Any(producer => !State.Producers.Contains(producer)))
{
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers={Utils.EnumerableToString(captureProducers)}, State.Producers={Utils.EnumerableToString(State.Producers)}");
}
if (captureConsumers.Count != State.Consumers.Count)
{
LogPubSubCounts("Validate: Consumer count mismatch");
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers.Count={captureConsumers.Count}, State.Consumers.Count={State.Consumers.Count}");
}
if (captureConsumers.Any(consumer => !State.Consumers.Contains(consumer)))
{
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers={Utils.EnumerableToString(captureConsumers)}, State.Consumers={Utils.EnumerableToString(State.Consumers)}");
}
}
public Task<List<StreamSubscription>> GetAllSubscriptions(InternalStreamId streamId, IStreamConsumerExtension streamConsumer)
{
var grainRef = streamConsumer as GrainReference;
if (grainRef != null)
{
List<StreamSubscription> subscriptions =
State.Consumers.Where(c => !c.IsFaulted && c.Consumer.Equals(streamConsumer))
.Select(
c =>
new StreamSubscription(c.SubscriptionId.Guid, streamId.ProviderName, streamId,
grainRef.GrainId)).ToList();
return Task.FromResult(subscriptions);
}
else
{
List<StreamSubscription> subscriptions =
State.Consumers.Where(c => !c.IsFaulted)
.Select(
c =>
new StreamSubscription(c.SubscriptionId.Guid, streamId.ProviderName, streamId,
c.consumerReference.GrainId)).ToList();
return Task.FromResult(subscriptions);
}
}
public async Task FaultSubscription(GuidId subscriptionId)
{
PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId));
if (pubSubState == null)
{
return;
}
try
{
pubSubState.Fault();
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Setting subscription {0} to a faulted state.", subscriptionId.Guid);
await WriteStateAsync();
await NotifyProducersOfRemovedSubscription(pubSubState.SubscriptionId, pubSubState.Stream);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_SetSubscriptionToFaultedFailed,
$"Failed to set subscription state to faulted. SubscriptionId {subscriptionId}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
}
private async Task NotifyProducersOfRemovedSubscription(GuidId subscriptionId, InternalStreamId streamId)
{
int numProducersBeforeNotify = State.Producers.Count;
if (numProducersBeforeNotify > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Notifying {0} existing producers about unregistered consumer.", numProducersBeforeNotify);
// Notify producers about unregistered consumer.
List<Task> tasks = State.Producers
.Select(producerState => ExecuteProducerTask(producerState, producerState.Producer.RemoveSubscriber(subscriptionId, streamId)))
.ToList();
await Task.WhenAll(tasks);
//if producers got removed
if (State.Producers.Count < numProducersBeforeNotify)
await this.WriteStateAsync();
}
}
/// <summary>
/// Try clear state will only clear the state if there are no producers or consumers.
/// </summary>
/// <returns></returns>
private async Task<bool> TryClearState()
{
if (State.Producers.Count == 0 && State.Consumers.Count == 0) // + we already know that numProducers == 0 from previous if-clause
{
await ClearStateAsync(); //State contains no producers or consumers, remove it from storage
return true;
}
return false;
}
private async Task ExecuteProducerTask(PubSubPublisherState producer, Task producerTask)
{
try
{
await producerTask;
}
catch (GrainExtensionNotInstalledException)
{
RemoveProducer(producer);
}
catch (ClientNotAvailableException)
{
RemoveProducer(producer);
}
catch (OrleansMessageRejectionException)
{
var grainRef = producer.Producer as GrainReference;
// if producer is a system target on and unavailable silo, remove it.
if (grainRef == null || grainRef.GrainId.IsSystemTarget())
{
RemoveProducer(producer);
}
else // otherwise, throw
{
throw;
}
}
}
}
}
| |
/*
* Copyright 1999-2012 Alibaba Group.
*
* 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;
namespace Tup.Cobar4Net.Parser.Recognizer.Mysql
{
/// <author>
/// <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a>
/// </author>
[Serializable]
public enum MySqlToken
{
None = 0,
Eof,
PlaceHolder,
Identifier,
SysVar,
UsrVar,
LiteralNumPureDigit,
LiteralNumMixDigit,
LiteralHex,
LiteralBit,
LiteralChars,
LiteralNchars,
LiteralNull,
LiteralBoolTrue,
LiteralBoolFalse,
QuestionMark,
PuncLeftParen,
PuncRightParen,
PuncLeftBrace,
PuncRightBrace,
PuncLeftBracket,
PuncRightBracket,
PuncSemicolon,
PuncComma,
PuncDot,
PuncColon,
PuncCStyleCommentEnd,
OpEquals,
OpGreaterThan,
OpLessThan,
OpExclamation,
OpTilde,
OpPlus,
OpMinus,
OpAsterisk,
OpSlash,
OpAmpersand,
OpVerticalBar,
OpCaret,
OpPercent,
OpAssign,
OpLessOrEquals,
OpLessOrGreater,
OpGreaterOrEquals,
OpNotEquals,
OpLogicalAnd,
OpLogicalOr,
OpLeftShift,
OpRightShift,
OpNullSafeEquals,
KwAccessible,
KwAdd,
KwAll,
KwAlter,
KwAnalyze,
KwAnd,
KwAs,
KwAsc,
KwAsensitive,
KwBefore,
KwBetween,
KwBigint,
KwBinary,
KwBlob,
KwBoth,
KwBy,
KwCall,
KwCascade,
KwCase,
KwChange,
KwChar,
KwCharacter,
KwCheck,
KwCollate,
KwColumn,
KwCondition,
KwConstraint,
KwContinue,
KwConvert,
KwCreate,
KwCross,
KwCurrentDate,
KwCurrentTime,
KwCurrentTimestamp,
KwCurrentUser,
KwCursor,
KwDatabase,
KwDatabases,
KwDayHour,
KwDayMicrosecond,
KwDayMinute,
KwDaySecond,
KwDec,
KwDecimal,
KwDeclare,
KwDefault,
KwDelayed,
KwDelete,
KwDesc,
KwDescribe,
KwDeterministic,
KwDistinct,
KwDistinctrow,
KwDiv,
KwDouble,
KwDrop,
KwDual,
KwEach,
KwElse,
KwElseif,
KwEnclosed,
KwEscaped,
KwExists,
KwExit,
KwExplain,
KwFetch,
KwFloat,
KwFloat4,
KwFloat8,
KwFor,
KwForce,
KwForeign,
KwFrom,
KwFulltext,
KwGeneral,
KwGrant,
KwGroup,
KwHaving,
KwHighPriority,
KwHourMicrosecond,
KwHourMinute,
KwHourSecond,
KwIf,
KwIgnore,
KwIgnoreServerIds,
KwIn,
KwIndex,
KwInfile,
KwInner,
KwInout,
KwInsensitive,
KwInsert,
KwInt,
KwInt1,
KwInt2,
KwInt3,
KwInt4,
KwInt8,
KwInteger,
KwInterval,
KwInto,
KwIs,
KwIterate,
KwJoin,
KwKey,
KwKeys,
KwKill,
KwLeading,
KwLeave,
KwLeft,
KwLike,
KwLimit,
KwLinear,
KwLines,
KwLoad,
KwLocaltime,
KwLocaltimestamp,
KwLock,
KwLong,
KwLongblob,
KwLongtext,
KwLoop,
KwLowPriority,
KwMasterHeartbeatPeriod,
KwMasterSslVerifyServerCert,
KwMatch,
KwMaxvalue,
KwMediumblob,
KwMediumint,
KwMediumtext,
KwMiddleint,
KwMinuteMicrosecond,
KwMinuteSecond,
KwMod,
KwModifies,
KwNatural,
KwNot,
KwNoWriteToBinlog,
KwNumeric,
KwOn,
KwOptimize,
KwOption,
KwOptionally,
KwOr,
KwOrder,
KwOut,
KwOuter,
KwOutfile,
KwPrecision,
KwPrimary,
KwProcedure,
KwPurge,
KwRange,
KwRead,
KwReads,
KwReadWrite,
KwReal,
KwReferences,
KwRegexp,
KwRelease,
KwRename,
KwRepeat,
KwReplace,
KwRequire,
KwResignal,
KwRestrict,
KwReturn,
KwRevoke,
KwRight,
KwRlike,
KwSchema,
KwSchemas,
KwSecondMicrosecond,
KwSelect,
KwSensitive,
KwSeparator,
KwSet,
KwShow,
KwSignal,
KwSlow,
KwSmallint,
KwSpatial,
KwSpecific,
KwSql,
KwSqlexception,
KwSqlstate,
KwSqlwarning,
KwSqlBigResult,
KwSqlCalcFoundRows,
KwSqlSmallResult,
KwSsl,
KwStarting,
KwStraightJoin,
KwTable,
KwTerminated,
KwThen,
KwTinyblob,
KwTinyint,
KwTinytext,
KwTo,
KwTrailing,
KwTrigger,
KwUndo,
KwUnion,
KwUnique,
KwUnlock,
KwUnsigned,
KwUpdate,
KwUsage,
KwUse,
KwUsing,
KwUtcDate,
KwUtcTime,
KwUtcTimestamp,
KwValues,
KwVarbinary,
KwVarchar,
KwVarcharacter,
KwVarying,
KwWhen,
KwWhere,
KwWhile,
KwWith,
KwWrite,
KwXor,
KwYearMonth,
KwZerofill
}
internal static class MySqlTokenUtils
{
// /** @ */
// OP_AT,
public static string KeyWordToString(this MySqlToken token)
{
switch (token)
{
case MySqlToken.KwAccessible:
{
return "ACCESSIBLE";
}
case MySqlToken.KwAdd:
{
return "ADD";
}
case MySqlToken.KwAll:
{
return "ALL";
}
case MySqlToken.KwAlter:
{
return "ALTER";
}
case MySqlToken.KwAnalyze:
{
return "ANALYZE";
}
case MySqlToken.KwAnd:
{
return "AND";
}
case MySqlToken.KwAs:
{
return "AS";
}
case MySqlToken.KwAsc:
{
return "ASC";
}
case MySqlToken.KwAsensitive:
{
return "ASENSITIVE";
}
case MySqlToken.KwBefore:
{
return "BEFORE";
}
case MySqlToken.KwBetween:
{
return "BETWEEN";
}
case MySqlToken.KwBigint:
{
return "BIGINT";
}
case MySqlToken.KwBinary:
{
return "BINARY";
}
case MySqlToken.KwBlob:
{
return "BLOB";
}
case MySqlToken.KwBoth:
{
return "BOTH";
}
case MySqlToken.KwBy:
{
return "BY";
}
case MySqlToken.KwCall:
{
return "CALL";
}
case MySqlToken.KwCascade:
{
return "CASCADE";
}
case MySqlToken.KwCase:
{
return "CASE";
}
case MySqlToken.KwChange:
{
return "CHANGE";
}
case MySqlToken.KwChar:
{
return "CHAR";
}
case MySqlToken.KwCharacter:
{
return "CHARACTER";
}
case MySqlToken.KwCheck:
{
return "CHECK";
}
case MySqlToken.KwCollate:
{
return "COLLATE";
}
case MySqlToken.KwColumn:
{
return "COLUMN";
}
case MySqlToken.KwCondition:
{
return "CONDITION";
}
case MySqlToken.KwConstraint:
{
return "CONSTRAINT";
}
case MySqlToken.KwContinue:
{
return "CONTINUE";
}
case MySqlToken.KwConvert:
{
return "CONVERT";
}
case MySqlToken.KwCreate:
{
return "CREATE";
}
case MySqlToken.KwCross:
{
return "CROSS";
}
case MySqlToken.KwCurrentDate:
{
return "CURRENT_DATE";
}
case MySqlToken.KwCurrentTime:
{
return "CURRENT_TIME";
}
case MySqlToken.KwCurrentTimestamp:
{
return "CURRENT_TIMESTAMP";
}
case MySqlToken.KwCurrentUser:
{
return "CURRENT_USER";
}
case MySqlToken.KwCursor:
{
return "CURSOR";
}
case MySqlToken.KwDatabase:
{
return "DATABASE";
}
case MySqlToken.KwDatabases:
{
return "DATABASES";
}
case MySqlToken.KwDayHour:
{
return "DAY_HOUR";
}
case MySqlToken.KwDayMicrosecond:
{
return "DAY_MICROSECOND";
}
case MySqlToken.KwDayMinute:
{
return "DAY_MINUTE";
}
case MySqlToken.KwDaySecond:
{
return "DAY_SECOND";
}
case MySqlToken.KwDec:
{
return "DEC";
}
case MySqlToken.KwDecimal:
{
return "DECIMAL";
}
case MySqlToken.KwDeclare:
{
return "DECLARE";
}
case MySqlToken.KwDefault:
{
return "DEFAULT";
}
case MySqlToken.KwDelayed:
{
return "DELAYED";
}
case MySqlToken.KwDelete:
{
return "DELETE";
}
case MySqlToken.KwDesc:
{
return "DESC";
}
case MySqlToken.KwDescribe:
{
return "DESCRIBE";
}
case MySqlToken.KwDeterministic:
{
return "DETERMINISTIC";
}
case MySqlToken.KwDistinct:
{
return "DISTINCT";
}
case MySqlToken.KwDistinctrow:
{
return "DISTINCTROW";
}
case MySqlToken.KwDiv:
{
return "DIV";
}
case MySqlToken.KwDouble:
{
return "DOUBLE";
}
case MySqlToken.KwDrop:
{
return "DROP";
}
case MySqlToken.KwDual:
{
return "DUAL";
}
case MySqlToken.KwEach:
{
return "EACH";
}
case MySqlToken.KwElse:
{
return "ELSE";
}
case MySqlToken.KwElseif:
{
return "ELSEIF";
}
case MySqlToken.KwEnclosed:
{
return "ENCLOSED";
}
case MySqlToken.KwEscaped:
{
return "ESCAPED";
}
case MySqlToken.KwExists:
{
return "EXISTS";
}
case MySqlToken.KwExit:
{
return "EXIT";
}
case MySqlToken.KwExplain:
{
return "EXPLAIN";
}
case MySqlToken.KwFetch:
{
return "FETCH";
}
case MySqlToken.KwFloat:
{
return "FLOAT";
}
case MySqlToken.KwFloat4:
{
return "FLOAT4";
}
case MySqlToken.KwFloat8:
{
return "FLOAT8";
}
case MySqlToken.KwFor:
{
return "FOR";
}
case MySqlToken.KwForce:
{
return "FORCE";
}
case MySqlToken.KwForeign:
{
return "FOREIGN";
}
case MySqlToken.KwFrom:
{
return "FROM";
}
case MySqlToken.KwFulltext:
{
return "FULLTEXT";
}
case MySqlToken.KwGeneral:
{
return "GENERAL";
}
case MySqlToken.KwGrant:
{
return "GRANT";
}
case MySqlToken.KwGroup:
{
return "GROUP";
}
case MySqlToken.KwHaving:
{
return "HAVING";
}
case MySqlToken.KwHighPriority:
{
return "HIGH_PRIORITY";
}
case MySqlToken.KwHourMicrosecond:
{
return "HOUR_MICROSECOND";
}
case MySqlToken.KwHourMinute:
{
return "HOUR_MINUTE";
}
case MySqlToken.KwHourSecond:
{
return "HOUR_SECOND";
}
case MySqlToken.KwIf:
{
return "IF";
}
case MySqlToken.KwIgnore:
{
return "IGNORE";
}
case MySqlToken.KwIgnoreServerIds:
{
return "IGNORE_SERVER_IDS";
}
case MySqlToken.KwIn:
{
return "IN";
}
case MySqlToken.KwIndex:
{
return "INDEX";
}
case MySqlToken.KwInfile:
{
return "INFILE";
}
case MySqlToken.KwInner:
{
return "INNER";
}
case MySqlToken.KwInout:
{
return "INOUT";
}
case MySqlToken.KwInsensitive:
{
return "INSENSITIVE";
}
case MySqlToken.KwInsert:
{
return "INSERT";
}
case MySqlToken.KwInt:
{
return "INT";
}
case MySqlToken.KwInt1:
{
return "INT1";
}
case MySqlToken.KwInt2:
{
return "INT2";
}
case MySqlToken.KwInt3:
{
return "INT3";
}
case MySqlToken.KwInt4:
{
return "INT4";
}
case MySqlToken.KwInt8:
{
return "INT8";
}
case MySqlToken.KwInteger:
{
return "INTEGER";
}
case MySqlToken.KwInterval:
{
return "INTERVAL";
}
case MySqlToken.KwInto:
{
return "INTO";
}
case MySqlToken.KwIs:
{
return "IS";
}
case MySqlToken.KwIterate:
{
return "ITERATE";
}
case MySqlToken.KwJoin:
{
return "JOIN";
}
case MySqlToken.KwKey:
{
return "KEY";
}
case MySqlToken.KwKeys:
{
return "KEYS";
}
case MySqlToken.KwKill:
{
return "KILL";
}
case MySqlToken.KwLeading:
{
return "LEADING";
}
case MySqlToken.KwLeave:
{
return "LEAVE";
}
case MySqlToken.KwLeft:
{
return "LEFT";
}
case MySqlToken.KwLike:
{
return "LIKE";
}
case MySqlToken.KwLimit:
{
return "LIMIT";
}
case MySqlToken.KwLinear:
{
return "LINEAR";
}
case MySqlToken.KwLines:
{
return "LINES";
}
case MySqlToken.KwLoad:
{
return "LOAD";
}
case MySqlToken.KwLocaltime:
{
return "LOCALTIME";
}
case MySqlToken.KwLocaltimestamp:
{
return "LOCALTIMESTAMP";
}
case MySqlToken.KwLock:
{
return "LOCK";
}
case MySqlToken.KwLong:
{
return "LONG";
}
case MySqlToken.KwLongblob:
{
return "LONGBLOB";
}
case MySqlToken.KwLongtext:
{
return "LONGTEXT";
}
case MySqlToken.KwLoop:
{
return "LOOP";
}
case MySqlToken.KwLowPriority:
{
return "LOW_PRIORITY";
}
case MySqlToken.KwMasterHeartbeatPeriod:
{
return "MASTER_HEARTBEAT_PERIOD";
}
case MySqlToken.KwMasterSslVerifyServerCert:
{
return "MASTER_SSL_VERIFY_SERVER_CERT";
}
case MySqlToken.KwMatch:
{
return "MATCH";
}
case MySqlToken.KwMaxvalue:
{
return "MAXVALUE";
}
case MySqlToken.KwMediumblob:
{
return "MEDIUMBLOB";
}
case MySqlToken.KwMediumint:
{
return "MEDIUMINT";
}
case MySqlToken.KwMediumtext:
{
return "MEDIUMTEXT";
}
case MySqlToken.KwMiddleint:
{
return "MIDdlEINT";
}
case MySqlToken.KwMinuteMicrosecond:
{
return "MINUTE_MICROSECOND";
}
case MySqlToken.KwMinuteSecond:
{
return "MINUTE_SECOND";
}
case MySqlToken.KwMod:
{
return "MOD";
}
case MySqlToken.KwModifies:
{
return "MODIFIES";
}
case MySqlToken.KwNatural:
{
return "NATURAL";
}
case MySqlToken.KwNot:
{
return "NOT";
}
case MySqlToken.KwNoWriteToBinlog:
{
return "NO_WRITE_TO_BINLOG";
}
case MySqlToken.KwNumeric:
{
return "NUMERIC";
}
case MySqlToken.KwOn:
{
return "ON";
}
case MySqlToken.KwOptimize:
{
return "OPTIMIZE";
}
case MySqlToken.KwOption:
{
return "OPTION";
}
case MySqlToken.KwOptionally:
{
return "OPTIONALLY";
}
case MySqlToken.KwOr:
{
return "OR";
}
case MySqlToken.KwOrder:
{
return "ORDER";
}
case MySqlToken.KwOut:
{
return "OUT";
}
case MySqlToken.KwOuter:
{
return "OUTER";
}
case MySqlToken.KwOutfile:
{
return "OUTFILE";
}
case MySqlToken.KwPrecision:
{
return "PRECISION";
}
case MySqlToken.KwPrimary:
{
return "PRIMARY";
}
case MySqlToken.KwProcedure:
{
return "PROCEDURE";
}
case MySqlToken.KwPurge:
{
return "PURGE";
}
case MySqlToken.KwRange:
{
return "RANGE";
}
case MySqlToken.KwRead:
{
return "READ";
}
case MySqlToken.KwReads:
{
return "READS";
}
case MySqlToken.KwReadWrite:
{
return "READ_WRITE";
}
case MySqlToken.KwReal:
{
return "REAL";
}
case MySqlToken.KwReferences:
{
return "REFERENCES";
}
case MySqlToken.KwRegexp:
{
return "REGEXP";
}
case MySqlToken.KwRelease:
{
return "RELEASE";
}
case MySqlToken.KwRename:
{
return "RENAME";
}
case MySqlToken.KwRepeat:
{
return "REPEAT";
}
case MySqlToken.KwReplace:
{
return "REPLACE";
}
case MySqlToken.KwRequire:
{
return "REQUIRE";
}
case MySqlToken.KwResignal:
{
return "RESIGNAL";
}
case MySqlToken.KwRestrict:
{
return "RESTRICT";
}
case MySqlToken.KwReturn:
{
return "RETURN";
}
case MySqlToken.KwRevoke:
{
return "REVOKE";
}
case MySqlToken.KwRight:
{
return "RIGHT";
}
case MySqlToken.KwRlike:
{
return "RLIKE";
}
case MySqlToken.KwSchema:
{
return "SCHEMA";
}
case MySqlToken.KwSchemas:
{
return "SCHEMAS";
}
case MySqlToken.KwSecondMicrosecond:
{
return "SECOND_MICROSECOND";
}
case MySqlToken.KwSelect:
{
return "SELECT";
}
case MySqlToken.KwSensitive:
{
return "SENSITIVE";
}
case MySqlToken.KwSeparator:
{
return "SEPARATOR";
}
case MySqlToken.KwSet:
{
return "SET";
}
case MySqlToken.KwShow:
{
return "SHOW";
}
case MySqlToken.KwSignal:
{
return "SIGNAL";
}
case MySqlToken.KwSlow:
{
return "SLOW";
}
case MySqlToken.KwSmallint:
{
return "SMALLINT";
}
case MySqlToken.KwSpatial:
{
return "SPATIAL";
}
case MySqlToken.KwSpecific:
{
return "SPECIFIC";
}
case MySqlToken.KwSql:
{
return "Sql";
}
case MySqlToken.KwSqlexception:
{
return "SQLEXCEPTION";
}
case MySqlToken.KwSqlstate:
{
return "SQLSTATE";
}
case MySqlToken.KwSqlwarning:
{
return "SQLWARNING";
}
case MySqlToken.KwSqlBigResult:
{
return "SQL_BIG_RESULT";
}
case MySqlToken.KwSqlCalcFoundRows:
{
return "SQL_CALC_FOUND_ROWS";
}
case MySqlToken.KwSqlSmallResult:
{
return "SQL_SMALL_RESULT";
}
case MySqlToken.KwSsl:
{
return "SSL";
}
case MySqlToken.KwStarting:
{
return "STARTING";
}
case MySqlToken.KwStraightJoin:
{
return "STRAIGHT_JOIN";
}
case MySqlToken.KwTable:
{
return "TABLE";
}
case MySqlToken.KwTerminated:
{
return "TERMINATED";
}
case MySqlToken.KwThen:
{
return "THEN";
}
case MySqlToken.KwTinyblob:
{
return "TINYBLOB";
}
case MySqlToken.KwTinyint:
{
return "TINYINT";
}
case MySqlToken.KwTinytext:
{
return "TINYTEXT";
}
case MySqlToken.KwTo:
{
return "TO";
}
case MySqlToken.KwTrailing:
{
return "TRAILING";
}
case MySqlToken.KwTrigger:
{
return "TRIGGER";
}
case MySqlToken.KwUndo:
{
return "UNDO";
}
case MySqlToken.KwUnion:
{
return "UNION";
}
case MySqlToken.KwUnique:
{
return "UNIQUE";
}
case MySqlToken.KwUnlock:
{
return "UNLOCK";
}
case MySqlToken.KwUnsigned:
{
return "UNSIGNED";
}
case MySqlToken.KwUpdate:
{
return "UPDATE";
}
case MySqlToken.KwUsage:
{
return "USAGE";
}
case MySqlToken.KwUse:
{
return "USE";
}
case MySqlToken.KwUsing:
{
return "USING";
}
case MySqlToken.KwUtcDate:
{
return "UTC_DATE";
}
case MySqlToken.KwUtcTime:
{
return "UTC_TIME";
}
case MySqlToken.KwUtcTimestamp:
{
return "UTC_TIMESTAMP";
}
case MySqlToken.KwValues:
{
return "VALUES";
}
case MySqlToken.KwVarbinary:
{
return "VARBINARY";
}
case MySqlToken.KwVarchar:
{
return "VARCHAR";
}
case MySqlToken.KwVarcharacter:
{
return "VARCHARACTER";
}
case MySqlToken.KwVarying:
{
return "VARYING";
}
case MySqlToken.KwWhen:
{
return "WHEN";
}
case MySqlToken.KwWhere:
{
return "WHERE";
}
case MySqlToken.KwWhile:
{
return "WHILE";
}
case MySqlToken.KwWith:
{
return "WITH";
}
case MySqlToken.KwWrite:
{
return "WRITE";
}
case MySqlToken.KwXor:
{
return "XOR";
}
case MySqlToken.KwYearMonth:
{
return "YEAR_MONTH";
}
case MySqlToken.KwZerofill:
{
return "ZEROFILL";
}
default:
{
throw new ArgumentException("token is not keyword: " + token);
}
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.ServiceModel;
using System.Security.Cryptography.X509Certificates;
public class IssuedTokenServiceCredential
{
internal const bool DefaultAllowUntrustedRsaIssuers = false;
internal const AudienceUriMode DefaultAudienceUriMode = AudienceUriMode.Always;
internal const X509CertificateValidationMode DefaultCertificateValidationMode = X509CertificateValidationMode.ChainTrust;
internal const X509RevocationMode DefaultRevocationMode = X509RevocationMode.Online;
internal const StoreLocation DefaultTrustedStoreLocation = StoreLocation.LocalMachine;
List<string> allowedAudienceUris;
AudienceUriMode audienceUriMode = DefaultAudienceUriMode;
List<X509Certificate2> knownCertificates;
SamlSerializer samlSerializer;
X509CertificateValidationMode certificateValidationMode = DefaultCertificateValidationMode;
X509RevocationMode revocationMode = DefaultRevocationMode;
StoreLocation trustedStoreLocation = DefaultTrustedStoreLocation;
X509CertificateValidator customCertificateValidator = null;
bool allowUntrustedRsaIssuers = DefaultAllowUntrustedRsaIssuers;
bool isReadOnly;
internal IssuedTokenServiceCredential()
{
this.allowedAudienceUris = new List<string>();
this.knownCertificates = new List<X509Certificate2>();
}
internal IssuedTokenServiceCredential(IssuedTokenServiceCredential other)
{
this.audienceUriMode = other.audienceUriMode;
this.allowedAudienceUris = new List<string>(other.allowedAudienceUris);
this.samlSerializer = other.samlSerializer;
this.knownCertificates = new List<X509Certificate2>(other.knownCertificates);
this.certificateValidationMode = other.certificateValidationMode;
this.customCertificateValidator = other.customCertificateValidator;
this.trustedStoreLocation = other.trustedStoreLocation;
this.revocationMode = other.revocationMode;
this.allowUntrustedRsaIssuers = other.allowUntrustedRsaIssuers;
this.isReadOnly = other.isReadOnly;
}
public IList<string> AllowedAudienceUris
{
get
{
if (this.isReadOnly)
return this.allowedAudienceUris.AsReadOnly();
else
return this.allowedAudienceUris;
}
}
public AudienceUriMode AudienceUriMode
{
get
{
return this.audienceUriMode;
}
set
{
ThrowIfImmutable();
AudienceUriModeValidationHelper.Validate(audienceUriMode);
this.audienceUriMode = value;
}
}
public IList<X509Certificate2> KnownCertificates
{
get
{
if (this.isReadOnly)
return this.knownCertificates.AsReadOnly();
else
return this.knownCertificates;
}
}
public SamlSerializer SamlSerializer
{
get
{
return this.samlSerializer;
}
set
{
ThrowIfImmutable();
this.samlSerializer = value;
}
}
public X509CertificateValidationMode CertificateValidationMode
{
get
{
return this.certificateValidationMode;
}
set
{
X509CertificateValidationModeHelper.Validate(value);
ThrowIfImmutable();
this.certificateValidationMode = value;
}
}
public X509RevocationMode RevocationMode
{
get
{
return this.revocationMode;
}
set
{
ThrowIfImmutable();
this.revocationMode = value;
}
}
public StoreLocation TrustedStoreLocation
{
get
{
return this.trustedStoreLocation;
}
set
{
ThrowIfImmutable();
this.trustedStoreLocation = value;
}
}
public X509CertificateValidator CustomCertificateValidator
{
get
{
return this.customCertificateValidator;
}
set
{
ThrowIfImmutable();
this.customCertificateValidator = value;
}
}
public bool AllowUntrustedRsaIssuers
{
get
{
return this.allowUntrustedRsaIssuers;
}
set
{
ThrowIfImmutable();
this.allowUntrustedRsaIssuers = value;
}
}
internal X509CertificateValidator GetCertificateValidator()
{
if (this.certificateValidationMode == X509CertificateValidationMode.None)
{
return X509CertificateValidator.None;
}
else if (this.certificateValidationMode == X509CertificateValidationMode.PeerTrust)
{
return X509CertificateValidator.PeerTrust;
}
else if (this.certificateValidationMode == X509CertificateValidationMode.Custom)
{
if (this.customCertificateValidator == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MissingCustomCertificateValidator)));
}
return this.customCertificateValidator;
}
else
{
bool useMachineContext = this.trustedStoreLocation == StoreLocation.LocalMachine;
X509ChainPolicy chainPolicy = new X509ChainPolicy();
chainPolicy.RevocationMode = this.revocationMode;
if (this.certificateValidationMode == X509CertificateValidationMode.ChainTrust)
{
return X509CertificateValidator.CreateChainTrustValidator(useMachineContext, chainPolicy);
}
else
{
return X509CertificateValidator.CreatePeerOrChainTrustValidator(useMachineContext, chainPolicy);
}
}
}
internal void MakeReadOnly()
{
this.isReadOnly = true;
}
void ThrowIfImmutable()
{
if (this.isReadOnly)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly)));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
namespace AllReady.Migrations
{
public partial class UpdatingModelForUserEmailChange : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.CreateTable(
name: "ClosestLocation",
columns: table => new
{
PostalCode = table.Column<string>(nullable: false),
City = table.Column<string>(nullable: true),
Distance = table.Column<double>(nullable: false),
State = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ClosestLocation", x => x.PostalCode);
});
migrationBuilder.CreateTable(
name: "PostalCodeGeoCoordinate",
columns: table => new
{
Latitude = table.Column<double>(nullable: false),
Longitude = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PostalCodeGeoCoordinate", x => new { x.Latitude, x.Longitude });
});
migrationBuilder.AddColumn<string>(
name: "PendingNewEmail",
table: "AspNetUsers",
nullable: true);
migrationBuilder.AddForeignKey(
name: "FK_Activity_Campaign_CampaignId",
table: "Activity",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Activity_ActivityId",
table: "ActivitySkill",
column: "ActivityId",
principalTable: "Activity",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Skill_SkillId",
table: "ActivitySkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Campaign_Organization_ManagingOrganizationId",
table: "Campaign",
column: "ManagingOrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Campaign_CampaignId",
table: "CampaignContact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Contact_ContactId",
table: "CampaignContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Contact_ContactId",
table: "OrganizationContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Organization_OrganizationId",
table: "OrganizationContact",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_Skill_SkillId",
table: "TaskSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_AllReadyTask_TaskId",
table: "TaskSkill",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_Skill_SkillId",
table: "UserSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_ApplicationUser_UserId",
table: "UserSkill",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropColumn(name: "PendingNewEmail", table: "AspNetUsers");
migrationBuilder.DropTable("ClosestLocation");
migrationBuilder.DropTable("PostalCodeGeoCoordinate");
migrationBuilder.AddForeignKey(
name: "FK_Activity_Campaign_CampaignId",
table: "Activity",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Activity_ActivityId",
table: "ActivitySkill",
column: "ActivityId",
principalTable: "Activity",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Skill_SkillId",
table: "ActivitySkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Campaign_Organization_ManagingOrganizationId",
table: "Campaign",
column: "ManagingOrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Campaign_CampaignId",
table: "CampaignContact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Contact_ContactId",
table: "CampaignContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Contact_ContactId",
table: "OrganizationContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Organization_OrganizationId",
table: "OrganizationContact",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_Skill_SkillId",
table: "TaskSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_AllReadyTask_TaskId",
table: "TaskSkill",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_Skill_SkillId",
table: "UserSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_ApplicationUser_UserId",
table: "UserSkill",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Data.Converters;
using Avalonia.Data.Core;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.Threading;
using Avalonia.UnitTests;
using Avalonia.VisualTree;
using JetBrains.Annotations;
using Xunit;
namespace Avalonia.Markup.Xaml.UnitTests
{
public class XamlIlTests : XamlTestBase
{
[Fact]
public void Binding_Button_IsPressed_ShouldWork()
{
var parsed = (Button)AvaloniaRuntimeXamlLoader.Parse(@"
<Button xmlns='https://github.com/avaloniaui' IsPressed='{Binding IsPressed, Mode=TwoWay}' />");
var ctx = new XamlIlBugTestsDataContext();
parsed.DataContext = ctx;
parsed.SetValue(Button.IsPressedProperty, true);
Assert.True(ctx.IsPressed);
}
[Fact]
public void Transitions_Should_Be_Properly_Parsed()
{
var parsed = (Grid)AvaloniaRuntimeXamlLoader.Parse(@"
<Grid xmlns='https://github.com/avaloniaui' >
<Grid.Transitions>
<Transitions>
<DoubleTransition Property='Opacity'
Easing='CircularEaseIn'
Duration='0:0:0.5' />
</Transitions>
</Grid.Transitions>
</Grid>");
Assert.Equal(1, parsed.Transitions.Count);
Assert.Equal(Visual.OpacityProperty, parsed.Transitions[0].Property);
}
[Fact]
public void Parser_Should_Override_Precompiled_Xaml()
{
var precompiled = new XamlIlClassWithPrecompiledXaml();
Assert.Equal(Brushes.Red, precompiled.Background);
Assert.Equal(1, precompiled.Opacity);
var loaded = (XamlIlClassWithPrecompiledXaml)AvaloniaRuntimeXamlLoader.Parse(@"
<UserControl xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
x:Class='Avalonia.Markup.Xaml.UnitTests.XamlIlClassWithPrecompiledXaml'
Opacity='0'>
</UserControl>");
Assert.Equal(loaded.Opacity, 0);
Assert.Null(loaded.Background);
}
[Fact]
public void RelativeSource_TemplatedParent_Works()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
AvaloniaRuntimeXamlLoader.Load(@"
<Application
xmlns='https://github.com/avaloniaui'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests;assembly=Avalonia.Markup.Xaml.UnitTests'
>
<Application.Styles>
<Style Selector='Button'>
<Setter Property='Template'>
<ControlTemplate>
<Grid><Grid><Grid>
<Canvas>
<Canvas.Background>
<SolidColorBrush>
<SolidColorBrush.Color>
<MultiBinding>
<MultiBinding.Converter>
<local:XamlIlBugTestsBrushToColorConverter/>
</MultiBinding.Converter>
<Binding Path='Background' RelativeSource='{RelativeSource TemplatedParent}'/>
<Binding Path='Background' RelativeSource='{RelativeSource TemplatedParent}'/>
<Binding Path='Background' RelativeSource='{RelativeSource TemplatedParent}'/>
</MultiBinding>
</SolidColorBrush.Color>
</SolidColorBrush>
</Canvas.Background>
</Canvas>
</Grid></Grid></Grid>
</ControlTemplate>
</Setter>
</Style>
</Application.Styles>
</Application>",
null, Application.Current);
var parsed = (Window)AvaloniaRuntimeXamlLoader.Parse(@"
<Window
xmlns='https://github.com/avaloniaui'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests;assembly=Avalonia.Markup.Xaml.UnitTests'
>
<Button Background='Red' />
</Window>
");
var btn = ((Button)parsed.Content);
btn.ApplyTemplate();
var canvas = (Canvas)btn.GetVisualChildren().First()
.VisualChildren.First()
.VisualChildren.First()
.VisualChildren.First();
Assert.Equal(Brushes.Red.Color, ((ISolidColorBrush)canvas.Background).Color);
}
}
[Fact]
public void Event_Handlers_Should_Work_For_Templates()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var w =new XamlIlBugTestsEventHandlerCodeBehind();
w.ApplyTemplate();
w.Show();
Dispatcher.UIThread.RunJobs();
var itemsPresenter = ((ItemsControl)w.Content).GetVisualChildren().FirstOrDefault();
var item = itemsPresenter
.GetVisualChildren().First()
.GetVisualChildren().First()
.GetVisualChildren().First();
((Control)item).DataContext = "test";
Assert.Equal("test", w.SavedContext);
}
}
[Fact]
public void Custom_Properties_Should_Work_With_XClass()
{
var precompiled = new XamlIlClassWithCustomProperty();
Assert.Equal("123", precompiled.Test);
var loaded = (XamlIlClassWithCustomProperty)AvaloniaRuntimeXamlLoader.Parse(@"
<UserControl xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
x:Class='Avalonia.Markup.Xaml.UnitTests.XamlIlClassWithCustomProperty'
Test='321'>
</UserControl>");
Assert.Equal("321", loaded.Test);
}
void AssertThrows(Action callback, Func<Exception, bool> check)
{
try
{
callback();
}
catch (Exception e) when (check(e))
{
return;
}
throw new Exception("Expected exception was not thrown");
}
public static object SomeStaticProperty { get; set; }
[Fact]
public void Bug2570()
{
SomeStaticProperty = "123";
AssertThrows(() => AvaloniaRuntimeXamlLoader
.Load(@"
<UserControl
xmlns='https://github.com/avaloniaui'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:tests='clr-namespace:Avalonia.Markup.Xaml.UnitTests'
d:DataContext='{x:Static tests:XamlIlTests.SomeStaticPropery}'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'/>", typeof(XamlIlTests).Assembly,
designMode: true),
e => e.Message.Contains("Unable to resolve ")
&& e.Message.Contains(" as static field, property, constant or enum value"));
}
[Fact]
public void Design_Mode_DataContext_Should_Be_Set()
{
SomeStaticProperty = "123";
var loaded = (UserControl)AvaloniaRuntimeXamlLoader
.Load(@"
<UserControl
xmlns='https://github.com/avaloniaui'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:tests='clr-namespace:Avalonia.Markup.Xaml.UnitTests'
d:DataContext='{x:Static tests:XamlIlTests.SomeStaticProperty}'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'/>", typeof(XamlIlTests).Assembly,
designMode: true);
Assert.Equal(Design.GetDataContext(loaded), SomeStaticProperty);
}
[Fact]
public void Attached_Properties_From_Static_Types_Should_Work_In_Style_Setters_Bug_2561()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var parsed = (Window)AvaloniaRuntimeXamlLoader.Parse(@"
<Window
xmlns='https://github.com/avaloniaui'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests;assembly=Avalonia.Markup.Xaml.UnitTests'
>
<Window.Styles>
<Style Selector='TextBox'>
<Setter Property='local:XamlIlBugTestsStaticClassWithAttachedProperty.TestInt' Value='100'/>
</Style>
</Window.Styles>
<TextBox/>
</Window>
");
var tb = ((TextBox)parsed.Content);
parsed.Show();
tb.ApplyTemplate();
Assert.Equal(100, XamlIlBugTestsStaticClassWithAttachedProperty.GetTestInt(tb));
}
}
[Fact]
public void Provide_Value_Target_Should_Provide_Clr_Property_Info()
{
var parsed = AvaloniaRuntimeXamlLoader.Parse<XamlIlClassWithClrPropertyWithValue>(@"
<XamlIlClassWithClrPropertyWithValue
xmlns='clr-namespace:Avalonia.Markup.Xaml.UnitTests'
Count='{XamlIlCheckClrPropertyInfo ExpectedPropertyName=Count}'
/>", typeof(XamlIlClassWithClrPropertyWithValue).Assembly);
Assert.Equal(6, parsed.Count);
}
[Fact]
public void DataContextType_Resolution()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var parsed = AvaloniaRuntimeXamlLoader.Parse<UserControl>(@"
<UserControl
xmlns='https://github.com/avaloniaui'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests;assembly=Avalonia.Markup.Xaml.UnitTests'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:DataType='local:XamlIlBugTestsDataContext' />");
}
}
[Fact]
public void DataTemplates_Should_Resolve_Named_Controls_From_Parent_Scope()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var parsed = (Window)AvaloniaRuntimeXamlLoader.Parse(@"
<Window
xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
>
<StackPanel>
<StackPanel.DataTemplates>
<DataTemplate DataType='{x:Type x:String}'>
<TextBlock Classes='target' Text='{Binding #txt.Text}'/>
</DataTemplate>
</StackPanel.DataTemplates>
<TextBlock Text='Test' Name='txt'/>
<ContentControl Content='tst'/>
</StackPanel>
</Window>
");
parsed.DataContext = new List<string>() {"Test"};
parsed.Show();
parsed.ApplyTemplate();
var cc = ((ContentControl)((StackPanel)parsed.Content).Children.Last());
cc.ApplyTemplate();
var templated = cc.GetVisualDescendants().OfType<TextBlock>()
.First(x => x.Classes.Contains("target"));
Assert.Equal("Test", templated.Text);
}
}
[Fact]
public void Should_Work_With_Base_Property()
{
var parsed = (ListBox)AvaloniaRuntimeXamlLoader.Load(@"
<ListBox
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns='https://github.com/avaloniaui'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests;assembly=Avalonia.Markup.Xaml.UnitTests'
>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl Content='{Binding}' />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>");
Assert.NotNull(parsed.ItemTemplate);
}
}
public class XamlIlBugTestsEventHandlerCodeBehind : Window
{
public object SavedContext;
public void HandleDataContextChanged(object sender, EventArgs args)
{
SavedContext = ((Control)sender).DataContext;
}
public XamlIlBugTestsEventHandlerCodeBehind()
{
AvaloniaRuntimeXamlLoader.Load(@"
<Window x:Class='Avalonia.Markup.Xaml.UnitTests.XamlIlBugTestsEventHandlerCodeBehind'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns='https://github.com/avaloniaui'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests;assembly=Avalonia.Markup.Xaml.UnitTests'
>
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button DataContextChanged='HandleDataContextChanged' Content='{Binding .}' />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
", typeof(XamlIlBugTestsEventHandlerCodeBehind).Assembly, this);
((ItemsControl)Content).Items = new[] {"123"};
}
}
public class XamlIlClassWithCustomProperty : UserControl
{
public string Test { get; set; }
public XamlIlClassWithCustomProperty()
{
AvaloniaXamlLoader.Load(this);
}
}
public class XamlIlBugTestsBrushToColorConverter : IMultiValueConverter
{
public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture)
{
return (values[0] as ISolidColorBrush)?.Color;
}
}
public class XamlIlBugTestsDataContext : INotifyPropertyChanged
{
public bool IsPressed { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class XamlIlClassWithPrecompiledXaml : UserControl
{
}
public static class XamlIlBugTestsStaticClassWithAttachedProperty
{
public static readonly AvaloniaProperty<int> TestIntProperty = AvaloniaProperty
.RegisterAttached<Control, int>("TestInt", typeof(XamlIlBugTestsStaticClassWithAttachedProperty));
public static void SetTestInt(Control control, int value)
{
control.SetValue(TestIntProperty, value);
}
public static int GetTestInt(Control control)
{
return (int)control.GetValue(TestIntProperty);
}
}
public class XamlIlCheckClrPropertyInfoExtension
{
public string ExpectedPropertyName { get; set; }
public object ProvideValue(IServiceProvider prov)
{
var pvt = prov.GetService<IProvideValueTarget>();
var info = (ClrPropertyInfo)pvt.TargetProperty;
var v = (int)info.Get(pvt.TargetObject);
return v + 1;
}
}
public class XamlIlClassWithClrPropertyWithValue
{
public int Count { get; set; }= 5;
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// CredentialListMappingResource
/// </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;
namespace Twilio.Rest.Api.V2010.Account.Sip.Domain
{
public class CredentialListMappingResource : Resource
{
private static Request BuildCreateRequest(CreateCredentialListMappingOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/SIP/Domains/" + options.PathDomainSid + "/CredentialListMappings.json",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Create a CredentialListMapping resource for an account.
/// </summary>
/// <param name="options"> Create CredentialListMapping parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CredentialListMapping </returns>
public static CredentialListMappingResource Create(CreateCredentialListMappingOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Create a CredentialListMapping resource for an account.
/// </summary>
/// <param name="options"> Create CredentialListMapping parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CredentialListMapping </returns>
public static async System.Threading.Tasks.Task<CredentialListMappingResource> CreateAsync(CreateCredentialListMappingOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Create a CredentialListMapping resource for an account.
/// </summary>
/// <param name="pathDomainSid"> A string that identifies the SIP Domain for which the CredentialList resource will be
/// mapped </param>
/// <param name="credentialListSid"> A string that identifies the CredentialList resource to map to the SIP domain
/// </param>
/// <param name="pathAccountSid"> The unique sid that identifies this account </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CredentialListMapping </returns>
public static CredentialListMappingResource Create(string pathDomainSid,
string credentialListSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new CreateCredentialListMappingOptions(pathDomainSid, credentialListSid){PathAccountSid = pathAccountSid};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Create a CredentialListMapping resource for an account.
/// </summary>
/// <param name="pathDomainSid"> A string that identifies the SIP Domain for which the CredentialList resource will be
/// mapped </param>
/// <param name="credentialListSid"> A string that identifies the CredentialList resource to map to the SIP domain
/// </param>
/// <param name="pathAccountSid"> The unique sid that identifies this account </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CredentialListMapping </returns>
public static async System.Threading.Tasks.Task<CredentialListMappingResource> CreateAsync(string pathDomainSid,
string credentialListSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new CreateCredentialListMappingOptions(pathDomainSid, credentialListSid){PathAccountSid = pathAccountSid};
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadCredentialListMappingOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/SIP/Domains/" + options.PathDomainSid + "/CredentialListMappings.json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Read multiple CredentialListMapping resources from an account.
/// </summary>
/// <param name="options"> Read CredentialListMapping parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CredentialListMapping </returns>
public static ResourceSet<CredentialListMappingResource> Read(ReadCredentialListMappingOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<CredentialListMappingResource>.FromJson("credential_list_mappings", response.Content);
return new ResourceSet<CredentialListMappingResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Read multiple CredentialListMapping resources from an account.
/// </summary>
/// <param name="options"> Read CredentialListMapping parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CredentialListMapping </returns>
public static async System.Threading.Tasks.Task<ResourceSet<CredentialListMappingResource>> ReadAsync(ReadCredentialListMappingOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<CredentialListMappingResource>.FromJson("credential_list_mappings", response.Content);
return new ResourceSet<CredentialListMappingResource>(page, options, client);
}
#endif
/// <summary>
/// Read multiple CredentialListMapping resources from an account.
/// </summary>
/// <param name="pathDomainSid"> A string that identifies the SIP Domain that includes the resource to read </param>
/// <param name="pathAccountSid"> The unique sid that identifies this account </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 CredentialListMapping </returns>
public static ResourceSet<CredentialListMappingResource> Read(string pathDomainSid,
string pathAccountSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadCredentialListMappingOptions(pathDomainSid){PathAccountSid = pathAccountSid, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Read multiple CredentialListMapping resources from an account.
/// </summary>
/// <param name="pathDomainSid"> A string that identifies the SIP Domain that includes the resource to read </param>
/// <param name="pathAccountSid"> The unique sid that identifies this account </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 CredentialListMapping </returns>
public static async System.Threading.Tasks.Task<ResourceSet<CredentialListMappingResource>> ReadAsync(string pathDomainSid,
string pathAccountSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadCredentialListMappingOptions(pathDomainSid){PathAccountSid = pathAccountSid, 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<CredentialListMappingResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<CredentialListMappingResource>.FromJson("credential_list_mappings", 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<CredentialListMappingResource> NextPage(Page<CredentialListMappingResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<CredentialListMappingResource>.FromJson("credential_list_mappings", 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<CredentialListMappingResource> PreviousPage(Page<CredentialListMappingResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<CredentialListMappingResource>.FromJson("credential_list_mappings", response.Content);
}
private static Request BuildFetchRequest(FetchCredentialListMappingOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/SIP/Domains/" + options.PathDomainSid + "/CredentialListMappings/" + options.PathSid + ".json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch a single CredentialListMapping resource from an account.
/// </summary>
/// <param name="options"> Fetch CredentialListMapping parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CredentialListMapping </returns>
public static CredentialListMappingResource Fetch(FetchCredentialListMappingOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch a single CredentialListMapping resource from an account.
/// </summary>
/// <param name="options"> Fetch CredentialListMapping parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CredentialListMapping </returns>
public static async System.Threading.Tasks.Task<CredentialListMappingResource> FetchAsync(FetchCredentialListMappingOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch a single CredentialListMapping resource from an account.
/// </summary>
/// <param name="pathDomainSid"> A string that identifies the SIP Domain that includes the resource to fetch </param>
/// <param name="pathSid"> A string that identifies the resource to fetch </param>
/// <param name="pathAccountSid"> The unique sid that identifies this account </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CredentialListMapping </returns>
public static CredentialListMappingResource Fetch(string pathDomainSid,
string pathSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new FetchCredentialListMappingOptions(pathDomainSid, pathSid){PathAccountSid = pathAccountSid};
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch a single CredentialListMapping resource from an account.
/// </summary>
/// <param name="pathDomainSid"> A string that identifies the SIP Domain that includes the resource to fetch </param>
/// <param name="pathSid"> A string that identifies the resource to fetch </param>
/// <param name="pathAccountSid"> The unique sid that identifies this account </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CredentialListMapping </returns>
public static async System.Threading.Tasks.Task<CredentialListMappingResource> FetchAsync(string pathDomainSid,
string pathSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new FetchCredentialListMappingOptions(pathDomainSid, pathSid){PathAccountSid = pathAccountSid};
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteCredentialListMappingOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/SIP/Domains/" + options.PathDomainSid + "/CredentialListMappings/" + options.PathSid + ".json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Delete a CredentialListMapping resource from an account.
/// </summary>
/// <param name="options"> Delete CredentialListMapping parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CredentialListMapping </returns>
public static bool Delete(DeleteCredentialListMappingOptions 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 a CredentialListMapping resource from an account.
/// </summary>
/// <param name="options"> Delete CredentialListMapping parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CredentialListMapping </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteCredentialListMappingOptions 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 a CredentialListMapping resource from an account.
/// </summary>
/// <param name="pathDomainSid"> A string that identifies the SIP Domain that includes the resource to delete </param>
/// <param name="pathSid"> A string that identifies the resource to delete </param>
/// <param name="pathAccountSid"> The unique sid that identifies this account </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CredentialListMapping </returns>
public static bool Delete(string pathDomainSid,
string pathSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new DeleteCredentialListMappingOptions(pathDomainSid, pathSid){PathAccountSid = pathAccountSid};
return Delete(options, client);
}
#if !NET35
/// <summary>
/// Delete a CredentialListMapping resource from an account.
/// </summary>
/// <param name="pathDomainSid"> A string that identifies the SIP Domain that includes the resource to delete </param>
/// <param name="pathSid"> A string that identifies the resource to delete </param>
/// <param name="pathAccountSid"> The unique sid that identifies this account </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CredentialListMapping </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathDomainSid,
string pathSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new DeleteCredentialListMappingOptions(pathDomainSid, pathSid){PathAccountSid = pathAccountSid};
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a CredentialListMappingResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> CredentialListMappingResource object represented by the provided JSON </returns>
public static CredentialListMappingResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<CredentialListMappingResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique id of the Account that is responsible for this resource.
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The date that this resource was created, given as GMT in RFC 2822 format.
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The date that this resource was last updated, given as GMT in RFC 2822 format.
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The unique string that identifies the SipDomain resource.
/// </summary>
[JsonProperty("domain_sid")]
public string DomainSid { get; private set; }
/// <summary>
/// A human readable descriptive text for this resource, up to 64 characters long.
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The URI for this resource, relative to https://api.twilio.com
/// </summary>
[JsonProperty("uri")]
public string Uri { get; private set; }
private CredentialListMappingResource()
{
}
}
}
| |
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls.Primitives;
using WPFDemo.Common.Extensions;
using WPFDemo.Presentation.EventManagers;
namespace WPFDemo.Presentation.Behaviors
{
public static class Navigation
{
#region Static Properties
public static readonly DependencyProperty ProcessEnterAsTabProperty = DependencyProperty.RegisterAttached(
"ProcessEnterAsTab", typeof(bool), typeof(Navigation),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None, ProcessEnterAsTab_PropertyChanged)
);
private static readonly DependencyProperty ProcessEnterAsTabWeakEventListenerProperty = DependencyProperty.RegisterAttached(
"ProcessEnterAsTabWeakEventListener", typeof(IWeakEventListener), typeof(Navigation),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None)
);
public static readonly DependencyProperty SelectAllOnKeyboardFocusProperty = DependencyProperty.RegisterAttached(
"SelectAllOnKeyboardFocus", typeof(bool), typeof(Navigation),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None, SelectAllOnKeyboardFocus_PropertyChanged)
);
private static readonly DependencyProperty SelectAllOnKeyboardFocusWeakEventListenerProperty = DependencyProperty.RegisterAttached(
"SelectAllOnKeyboardFocusWeakEventListener", typeof(IWeakEventListener), typeof(Navigation),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None)
);
public static readonly DependencyProperty InitialFocusProperty = DependencyProperty.RegisterAttached(
"InitialFocus", typeof(bool), typeof(Navigation),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None, InitialFocus_PropertyChanged)
);
#endregion
#region Static Methods
public static bool GetProcessEnterAsTab(FrameworkElement element)
{
return (bool)element.GetValue(ProcessEnterAsTabProperty);
}
public static void SetProcessEnterAsTab(FrameworkElement element, bool Value)
{
element.SetValue(ProcessEnterAsTabProperty, Value);
}
private static IWeakEventListener GetProcessEnterAsTabWeakEventListener(FrameworkElement element)
{
return (IWeakEventListener)element.GetValue(ProcessEnterAsTabWeakEventListenerProperty);
}
private static void SetProcessEnterAsTabWeakEventListener(FrameworkElement element, IWeakEventListener Value)
{
element.SetValue(ProcessEnterAsTabWeakEventListenerProperty, Value);
}
public static bool GetSelectAllOnKeyboardFocus(TextBoxBase element)
{
return (bool)element.GetValue(SelectAllOnKeyboardFocusProperty);
}
public static void SetSelectAllOnKeyboardFocus(TextBoxBase element, bool Value)
{
element.SetValue(SelectAllOnKeyboardFocusProperty, Value);
}
private static IWeakEventListener GetSelectAllOnKeyboardFocusWeakEventListener(FrameworkElement element)
{
return (IWeakEventListener)element.GetValue(SelectAllOnKeyboardFocusWeakEventListenerProperty);
}
private static void SetSelectAllOnKeyboardFocusWeakEventListener(FrameworkElement element, IWeakEventListener Value)
{
element.SetValue(SelectAllOnKeyboardFocusWeakEventListenerProperty, Value);
}
public static bool GetInitialFocus(FrameworkElement element)
{
return (bool)element.GetValue(InitialFocusProperty);
}
public static void SetInitialFocus(FrameworkElement element, bool Value)
{
element.SetValue(InitialFocusProperty, Value);
}
private static void ProcessEnterAsTab_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var Element = o as FrameworkElement;
if (Element == null)
throw new ArgumentException("Type mismatch", "o");
var Value = (bool)e.NewValue;
var Listener = GetProcessEnterAsTabWeakEventListener(Element);
if (Value)
{
if (Listener == null)
Listener = new ProcessEnterAsTabEventListener();
SetProcessEnterAsTabWeakEventListener(Element, Listener);
PreviewKeyDownEventManager.AddListener(Element, Listener);
}
else if (Listener != null)
{
SetProcessEnterAsTabWeakEventListener(Element, null);
PreviewKeyDownEventManager.RemoveListener(Element, Listener);
}
}
private static void SelectAllOnKeyboardFocus_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var TextBoxBase = o as TextBoxBase;
if (TextBoxBase == null)
throw new ArgumentException("Type mismatch", "o");
var Value = (bool)e.NewValue;
var Listener = GetSelectAllOnKeyboardFocusWeakEventListener(TextBoxBase);
if (Value)
{
if (Listener == null)
Listener = new SelectAllOnKeyboardFocusEventListener();
SetSelectAllOnKeyboardFocusWeakEventListener(TextBoxBase, Listener);
GotKeyboardFocusEventManager.AddListener(TextBoxBase, Listener);
}
else if (Listener != null)
{
SetSelectAllOnKeyboardFocusWeakEventListener(TextBoxBase, null);
GotKeyboardFocusEventManager.RemoveListener(TextBoxBase, Listener);
}
}
private static void InitialFocus_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var Element = o as FrameworkElement;
if (Element == null)
throw new ArgumentException("Type mismatch", "o");
Element.Loaded -= Element_InitialFocus_Loaded;
var Value = (bool)e.NewValue;
if (Value)
Element.Loaded += Element_InitialFocus_Loaded;
}
static void Element_InitialFocus_Loaded(object sender, RoutedEventArgs e)
{
var Element = sender as FrameworkElement;
if (Element == null)
throw new ArgumentException("Type mismatch", "sender");
try
{
Element.Focus();
Keyboard.Focus(Element);
}
finally
{
Element.Loaded -= Element_InitialFocus_Loaded;
}
}
#endregion
}
internal class ProcessEnterAsTabEventListener : IWeakEventListener
{
//Explanation for this type of IWeakEventListener implementation:
//This uses weak events to prevent memory leaks from holding onto the WPF elements' event handlers
//To prevent the weak listener from being destroyed, it is saved as an attached property on
//its owning WPF element.
//This is fine because the only GC reference to the listener is contained on the element itself,
//so when the GC collects after the element is zero-ref'd, the listener will be destroyed as well.
#region IWeakEventListener Members
public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs args)
{
if (managerType != typeof(PreviewKeyDownEventManager))
return false;
var Element = sender as FrameworkElement;
if (Element == null)
return true;
var e = args as System.Windows.Input.KeyEventArgs;
if (e == null)
return true;
if (e.Key == Key.Enter)
{
e.Handled = true;
var OriginalElement = e.OriginalSource as FrameworkElement;
if (OriginalElement != null)
OriginalElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
else
Element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
return true;
}
return true;
}
#endregion
}
internal class SelectAllOnKeyboardFocusEventListener : IWeakEventListener
{
#region IWeakEventListener Members
public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs args)
{
if (managerType != typeof(GotKeyboardFocusEventManager))
return false;
var TextBoxBase = sender as TextBoxBase;
if (TextBoxBase == null)
return true;
TextBoxBase.SelectAll();
return true;
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/1/2010 2:03:50 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using DotSpatial.NTSExtension;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
public class Segment
{
#region Private Variables
/// <summary>
/// The start point of the segment
/// </summary>
public Vertex P1;
/// <summary>
/// the end point of the segment
/// </summary>
public Vertex P2;
/// <summary>
/// Gets or sets the precision for calculating equality, but this is just a re-direction to Vertex.Epsilon
/// </summary>
public static double Epsilon
{
get { return Vertex.Epsilon; }
set { Vertex.Epsilon = value; }
}
#endregion
#region Constructors
/// <summary>
/// Creates a segment from double valued ordinates.
/// </summary>
/// <param name="x1"></param>
/// <param name="y1"></param>
/// <param name="x2"></param>
/// <param name="y2"></param>
public Segment(double x1, double y1, double x2, double y2)
{
P1 = new Vertex(x1, y1);
P2 = new Vertex(x2, y2);
}
/// <summary>
/// Creates a new instance of Segment
/// </summary>
public Segment(Vertex p1, Vertex p2)
{
P1 = p1;
P2 = p2;
}
#endregion
#region Methods
/// <summary>
/// Uses the intersection count to detect if there is an intersection
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Intersects(Segment other)
{
return (IntersectionCount(other) > 0);
}
/// <summary>
/// Calculates the shortest distance to this line segment from the specified MapWinGIS.Point
/// </summary>
/// <param name="point">A MapWinGIS.Point specifing the location to find the distance to the line</param>
/// <returns>A double value that is the shortest distance from the given Point to this line segment</returns>
public double DistanceTo(Coordinate point)
{
Vertex p = new Vertex(point.X, point.Y);
Vertex pt = ClosestPointTo(p);
Vector dist = new Vector(new Coordinate(pt.X, pt.Y), point);
return dist.Length2D;
}
/// <summary>
/// Returns a vertex representing the closest point on this line segment from a given vertex
/// </summary>
/// <param name="point">The point we want to be close to</param>
/// <returns>The point on this segment that is closest to the given point</returns>
public Vertex ClosestPointTo(Vertex point)
{
EndPointInteraction endPointFlag;
return ClosestPointTo(point, false, out endPointFlag);
}
/// <summary>
/// Returns a vertex representing the closest point on this line segment from a given vertex
/// </summary>
/// <param name="point">The point we want to be close to</param>
/// <param name="isInfiniteLine">If true treat the line as infinitly long</param>
/// <param name="endPointFlag">Outputs 0 if the vertex is on the line segment, 1 if beyond P0, 2 if beyong P1 and -1 if P1=P2</param>
/// <returns>The point on this segment or infinite line that is closest to the given point</returns>
public Vertex ClosestPointTo(Vertex point, bool isInfiniteLine, out EndPointInteraction endPointFlag)
{
// If the points defining this segment are the same, we treat the segment as a point
// special handling to avoid 0 in denominator later
if (P2.X == P1.X && P2.Y == P1.Y)
{
endPointFlag = EndPointInteraction.P1equalsP2;
return P1;
}
//http://softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm
Vector v = ToVector(); // vector from p1 to p2 in the segment
v.Z = 0;
Vector w = new Vector(P1.ToCoordinate(), point.ToCoordinate()); // vector from p1 to Point
w.Z = 0;
double c1 = w.Dot(v); // the dot product represents the projection onto the line
if (c1 < 0)
{
endPointFlag = EndPointInteraction.PastP1;
if (!isInfiniteLine) // The closest point on the segment to Point is p1
return P1;
}
double c2 = v.Dot(v);
if (c2 <= c1)
{
endPointFlag = EndPointInteraction.PastP2;
if (!isInfiniteLine) // The closest point on the segment to Point is p2
return P2;
}
// The closest point on the segment is perpendicular to the point,
// but somewhere on the segment between P1 and P2
endPointFlag = EndPointInteraction.OnLine;
double b = c1 / c2;
v = v.Multiply(b);
Vertex pb = new Vertex(P1.X + v.X, P1.Y + v.Y);
return pb;
}
/// <summary>
/// Casts this to a vector
/// </summary>
/// <returns></returns>
public Vector ToVector()
{
double x = P2.X - P1.X;
double y = P2.Y - P1.Y;
return new Vector(x, y, 0);
}
/// <summary>
/// Determines the shortest distance between two segments
/// </summary>
/// <param name="lineSegment">Segment, The line segment to test against this segment</param>
/// <returns>Double, the shortest distance between two segments</returns>
public double DistanceTo(Segment lineSegment)
{
//http://www.geometryalgorithms.com/Archive/algorithm_0106/algorithm_0106.htm
const double smallNum = 0.00000001;
Vector u = ToVector(); // Segment 1
Vector v = lineSegment.ToVector(); // Segment 2
Vector w = ToVector();
double a = u.Dot(u); // length of segment 1
double b = u.Dot(v); // length of segment 2 projected onto line 1
double c = v.Dot(v); // length of segment 2
double d = u.Dot(w); //
double e = v.Dot(w);
double dist = a * c - b * b;
double sc, sN, sD = dist;
double tc, tN, tD = dist;
// compute the line parameters of the two closest points
if (dist < smallNum)
{
// the lines are almost parallel force using point P0 on segment 1
// to prevent possible division by 0 later
sN = 0.0;
sD = 1.0;
tN = e;
tD = c;
}
else
{
// get the closest points on the infinite lines
sN = (b * e - c * d);
tN = (a * e - b * d);
if (sN < 0.0)
{
// sc < 0 => the s=0 edge is visible
sN = 0.0;
tN = e;
tD = c;
}
else if (sN > sD)
{
// sc > 1 => the s=1 edge is visible
sN = sD;
tN = e + b;
tD = c;
}
}
if (tN < 0.0)
{
// tc < 0 => the t=0 edge is visible
tN = 0.0;
// recompute sc for this edge
if (-d < 0.0)
{
sN = 0.0;
}
else if (-d > a)
{
sN = sD;
}
else
{
sN = -d;
sD = a;
}
}
else if (tN > tD)
{
// tc > 1 => the t = 1 edge is visible
// recompute sc for this edge
if ((-d + b) < 0.0)
{
sN = 0;
}
else if ((-d + b) > a)
{
sN = sD;
}
else
{
sN = (-d + b);
sD = a;
}
}
// finally do the division to get sc and tc
if (Math.Abs(sN) < smallNum)
{
sc = 0.0;
}
else
{
sc = sN / sD;
}
if (Math.Abs(tN) < smallNum)
{
tc = 0.0;
}
else
{
tc = tN / tD;
}
// get the difference of the two closest points
Vector dU = u.Multiply(sc);
Vector dV = v.Multiply(tc);
Vector dP = (w.Add(dU)).Subtract(dV);
// S1(sc) - S2(tc)
return dP.Length2D;
}
/// <summary>
/// Returns 0 if no intersections occur, 1 if an intersection point is found,
/// and 2 if the segments are colinear and overlap.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int IntersectionCount(Segment other)
{
double x1 = P1.X;
double y1 = P1.Y;
double x2 = P2.X;
double y2 = P2.Y;
double x3 = other.P1.X;
double y3 = other.P1.Y;
double x4 = other.P2.X;
double y4 = other.P2.Y;
double denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
//The case of two degenerate segements
if ((x1 == x2) && (y1 == y2) && (x3 == x4) && (y3 == y4))
{
if ((x1 != x3) || (y1 != y3))
return 0;
}
// if denom is 0, then the two lines are parallel
double na = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
double nb = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);
// if denom is 0 AND na and nb are 0, then the lines are coincident and DO intersect
if (Math.Abs(denom) < Epsilon && Math.Abs(na) < Epsilon && Math.Abs(nb) < Epsilon) return 2;
// If denom is 0, but na or nb are not 0, then the lines are parallel and not coincident
if (denom == 0) return 0;
double ua = na / denom;
double ub = nb / denom;
if (ua < 0 || ua > 1) return 0; // not intersecting with segment a
if (ub < 0 || ub > 1) return 0; // not intersecting with segment b
// If we get here, then one intersection exists and it is found on both line segments
return 1;
}
/// <summary>
/// Tests to see if the specified segment contains the point within Epsilon tollerance.
/// </summary>
/// <returns></returns>
public bool IntersectsVertex(Vertex point)
{
double x1 = P1.X;
double y1 = P1.Y;
double x2 = P2.X;
double y2 = P2.Y;
double pX = point.X;
double pY = point.Y;
// COllinear
if (Math.Abs((x2 - x1) * (pY - y1) - (pX - x1) * (y2 - y1)) > Epsilon) return false;
// In the x is in bounds and it is colinear, it is on the segment
if (x1 < x2)
{
if (x1 <= pX && pX <= x2) return true;
}
else
{
if (x2 <= pX && pX <= x1) return true;
}
return false;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
namespace System.Diagnostics
{
public sealed partial class FileVersionInfo
{
private FileVersionInfo(string fileName)
{
_fileName = fileName;
// For managed assemblies, read the file version information from the assembly's metadata.
// This isn't quite what's done on Windows, which uses the Win32 GetFileVersionInfo to read
// the Win32 resource information from the file, and the managed compiler uses these attributes
// to fill in that resource information when compiling the assembly. It's possible
// that after compilation, someone could have modified the resource information such that it
// no longer matches what was or wasn't in the assembly. But that's a rare enough case
// that this should match for all intents and purposes. If this ever becomes a problem,
// we can implement a full-fledged Win32 resource parser; that would also enable support
// for native Win32 PE files on Unix, but that should also be an extremely rare case.
if (!TryLoadManagedAssemblyMetadata())
{
// We could try to parse Executable and Linkable Format (ELF) files, but at present
// for executables they don't store version information, which is typically just
// available in the filename itself. For now, we won't do anything special, but
// we can add more cases here as we find need and opportunity.
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Attempt to load our fields from the metadata of the file, if it's a managed assembly.</summary>
/// <returns>true if the file is a managed assembly; otherwise, false.</returns>
private bool TryLoadManagedAssemblyMetadata()
{
try
{
// Try to load the file using the managed metadata reader
using (FileStream assemblyStream = File.OpenRead(_fileName))
using (PEReader peReader = new PEReader(assemblyStream))
{
if (peReader.HasMetadata)
{
MetadataReader metadataReader = peReader.GetMetadataReader();
if (metadataReader.IsAssembly)
{
LoadManagedAssemblyMetadata(metadataReader);
return true;
}
}
}
}
catch (BadImageFormatException) { }
return false;
}
/// <summary>Load our fields from the metadata of the file as represented by the provided metadata reader.</summary>
/// <param name="metadataReader">The metadata reader for the CLI file this represents.</param>
private void LoadManagedAssemblyMetadata(MetadataReader metadataReader)
{
AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition();
// Set the internal and original names based on the file name.
_internalName = _originalFilename = Path.GetFileName(_fileName);
// Set the product version based on the assembly's version (this may be overwritten
// later in the method).
Version productVersion = assemblyDefinition.Version;
_productVersion = productVersion.ToString();
_productMajor = productVersion.Major;
_productMinor = productVersion.Minor;
_productBuild = productVersion.Build != -1 ? productVersion.Build : 0;
_productPrivate = productVersion.Revision != -1 ? productVersion.Revision : 0;
// "Language Neutral" is used on Win32 for unknown language identifiers.
_language = "Language Neutral";
// Set other fields to default values in case they're not overwritten by attributes
_companyName = string.Empty;
_comments = string.Empty;
_fileDescription = " "; // this is what the managed compiler outputs when value isn't set
_fileVersion = string.Empty;
_legalCopyright = " "; // this is what the managed compiler outputs when value isn't set
_legalTrademarks = string.Empty;
_productName = string.Empty;
_privateBuild = string.Empty;
_specialBuild = string.Empty;
// Be explicit about initialization to suppress warning about fields not being set
_isDebug = false;
_isPatched = false;
_isPreRelease = false;
_isPrivateBuild = false;
_isSpecialBuild = false;
// Everything else is parsed from assembly attributes
MetadataStringComparer comparer = metadataReader.StringComparer;
foreach (CustomAttributeHandle attrHandle in assemblyDefinition.GetCustomAttributes())
{
CustomAttribute attr = metadataReader.GetCustomAttribute(attrHandle);
StringHandle typeNamespaceHandle = default(StringHandle), typeNameHandle = default(StringHandle);
if (TryGetAttributeName(metadataReader, attr, out typeNamespaceHandle, out typeNameHandle) &&
comparer.Equals(typeNamespaceHandle, "System.Reflection"))
{
if (comparer.Equals(typeNameHandle, "AssemblyCompanyAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _companyName);
}
else if (comparer.Equals(typeNameHandle, "AssemblyCopyrightAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _legalCopyright);
}
else if (comparer.Equals(typeNameHandle, "AssemblyDescriptionAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _comments);
}
else if (comparer.Equals(typeNameHandle, "AssemblyFileVersionAttribute"))
{
string versionString = string.Empty;
GetStringAttributeArgumentValue(metadataReader, attr, ref versionString);
Version v;
if (Version.TryParse(versionString, out v))
{
_fileVersion = v.ToString();
_fileMajor = v.Major;
_fileMinor = v.Minor;
_fileBuild = v.Build != -1 ? v.Build : 0;
_filePrivate = v.Revision != -1 ? v.Revision : 0;
// When the managed compiler sees an [AssemblyVersion(...)] attribute, it uses that to set
// both the assembly version and the product version in the Win32 resources. If it doesn't
// see an [AssemblyVersion(...)], then it sets the assembly version to 0.0.0.0, however it
// sets the product version in the Win32 resources to whatever was defined in the
// [AssemblyFileVersionAttribute(...)] if there was one. Without parsing the Win32 resources,
// we can't differentiate these two cases, so given the rarity of explicitly setting an
// assembly's version number to 0.0.0.0, we assume that if it is 0.0.0.0 then the attribute
// wasn't specified and we use the file version.
if (_productVersion == "0.0.0.0")
{
_productVersion = _fileVersion;
_productMajor = _fileMajor;
_productMinor = _fileMinor;
_productBuild = _fileBuild;
_productPrivate = _filePrivate;
}
}
}
else if (comparer.Equals(typeNameHandle, "AssemblyProductAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _productName);
}
else if (comparer.Equals(typeNameHandle, "AssemblyTrademarkAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _legalTrademarks);
}
else if (comparer.Equals(typeNameHandle, "AssemblyTitleAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _fileDescription);
}
}
}
}
/// <summary>Gets the name of an attribute.</summary>
/// <param name="reader">The metadata reader.</param>
/// <param name="attr">The attribute.</param>
/// <param name="typeNamespaceHandle">The namespace of the attribute.</param>
/// <param name="typeNameHandle">The name of the attribute.</param>
/// <returns>true if the name could be retrieved; otherwise, false.</returns>
private static bool TryGetAttributeName(MetadataReader reader, CustomAttribute attr, out StringHandle typeNamespaceHandle, out StringHandle typeNameHandle)
{
EntityHandle ctorHandle = attr.Constructor;
switch (ctorHandle.Kind)
{
case HandleKind.MemberReference:
EntityHandle container = reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent;
if (container.Kind == HandleKind.TypeReference)
{
TypeReference tr = reader.GetTypeReference((TypeReferenceHandle)container);
typeNamespaceHandle = tr.Namespace;
typeNameHandle = tr.Name;
return true;
}
break;
case HandleKind.MethodDefinition:
MethodDefinition md = reader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle);
TypeDefinition td = reader.GetTypeDefinition(md.GetDeclaringType());
typeNamespaceHandle = td.Namespace;
typeNameHandle = td.Name;
return true;
}
// Unusual case, potentially invalid IL
typeNamespaceHandle = default(StringHandle);
typeNameHandle = default(StringHandle);
return false;
}
/// <summary>Gets the string argument value of an attribute with a single fixed string argument.</summary>
/// <param name="reader">The metadata reader.</param>
/// <param name="attr">The attribute.</param>
/// <param name="value">The value parsed from the attribute, if it could be retrieved; otherwise, the value is left unmodified.</param>
private static void GetStringAttributeArgumentValue(MetadataReader reader, CustomAttribute attr, ref string value)
{
EntityHandle ctorHandle = attr.Constructor;
BlobHandle signature;
switch (ctorHandle.Kind)
{
case HandleKind.MemberReference:
signature = reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Signature;
break;
case HandleKind.MethodDefinition:
signature = reader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle).Signature;
break;
default:
// Unusual case, potentially invalid IL
return;
}
BlobReader signatureReader = reader.GetBlobReader(signature);
BlobReader valueReader = reader.GetBlobReader(attr.Value);
const ushort Prolog = 1; // two-byte "prolog" defined by Ecma 335 (II.23.3) to be at the beginning of attribute value blobs
if (valueReader.ReadUInt16() == Prolog)
{
SignatureHeader header = signatureReader.ReadSignatureHeader();
int parameterCount;
if (header.Kind == SignatureKind.Method && // attr ctor must be a method
!header.IsGeneric && // attr ctor must be non-generic
signatureReader.TryReadCompressedInteger(out parameterCount) && // read parameter count
parameterCount == 1 && // attr ctor must have 1 parameter
signatureReader.ReadSignatureTypeCode() == SignatureTypeCode.Void && // attr ctor return type must be void
signatureReader.ReadSignatureTypeCode() == SignatureTypeCode.String) // attr ctor first parameter must be string
{
value = valueReader.ReadSerializedString();
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
namespace InstallerLib
{
/// <summary>
/// A pair of source->target file for embedding.
/// </summary>
public class ResourceFilePair
{
private string _path;
private string _id;
public string path
{
get { return _path; }
}
public string id
{
get { return _id; }
}
public ResourceFilePair(string id, string path)
{
_id = id;
_path = path;
}
public override bool Equals(object obj)
{
if (obj is ResourceFilePair)
{
ResourceFilePair pair = obj as ResourceFilePair;
return pair._id == _id;
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
/// <summary>
/// A collection of elements of type ResourceFile.
/// </summary>
public class ResourceFileCollection : IList<ResourceFilePair>, ICollection<ResourceFilePair>, IEnumerable<ResourceFilePair>
{
private List<ResourceFilePair> _files = new List<ResourceFilePair>();
private string _supportdir;
public ResourceFileCollection(string supportdir)
{
_supportdir = supportdir;
}
/// <summary>
/// Add a file with an id and a relative path.
/// </summary>
/// <param name="id">resource id</param>
/// <param name="path">path</param>
public void Add(string id, string path)
{
string fullpath = path
.Replace(@"#APPPATH", _supportdir)
.Replace(@"#TEMPPATH", _supportdir)
.Replace(@"#CABPATH", _supportdir);
Add(new ResourceFilePair(id, fullpath));
}
/// <summary>
/// Check whether all embedded files exist.
/// </summary>
/// <param name="args"></param>
public void CheckFilesExist(InstallerLinkerArguments args)
{
int filesMissing = 0;
foreach (ResourceFilePair file in _files)
{
args.WriteLine(string.Format(" {0} ({1})", file.id, file.path));
if (!File.Exists(file.path))
{
args.WriteError(string.Format("Resource file '{0}' does not exist", file.path));
filesMissing++;
}
}
if (filesMissing > 0)
{
throw new Exception(string.Format("Missing {0} resource file(s)",
filesMissing));
}
}
/// <summary>
/// Add a unique file pair.
/// </summary>
/// <param name="pair">file pair</param>
/// <returns>true if added a unique file pair</returns>
public bool Add(ResourceFilePair pair)
{
foreach (ResourceFilePair existingPair in _files)
{
if (existingPair.Equals(pair))
return false;
}
_files.Add(pair);
return true;
}
/// <summary>
/// Add a range of file pairs.
/// </summary>
/// <param name="range">a range of file pairs</param>
public void AddRange(IEnumerable<ResourceFilePair> range)
{
foreach (ResourceFilePair pair in range)
{
Add(pair);
}
}
/// <summary>
/// Add a range of file pairs.
/// </summary>
/// <param name="range">a range of file pairs</param>
public void AddRange(ResourceFileCollection range)
{
foreach (ResourceFilePair pair in range._files)
{
Add(pair);
}
}
#region IEnumerable<ResourceFilePair> Members
public IEnumerator<ResourceFilePair> GetEnumerator()
{
return _files.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return _files.GetEnumerator();
}
#endregion
#region IList<ResourceFilePair> Members
public int IndexOf(ResourceFilePair item)
{
return _files.IndexOf(item);
}
public void Insert(int index, ResourceFilePair item)
{
_files.Insert(index, item);
}
public void RemoveAt(int index)
{
_files.RemoveAt(index);
}
public ResourceFilePair this[int index]
{
get
{
return _files[index];
}
set
{
_files[index] = value;
}
}
#endregion
#region ICollection<ResourceFilePair> Members
void ICollection<ResourceFilePair>.Add(ResourceFilePair item)
{
throw new Exception("The method or operation is not implemented.");
}
public void Clear()
{
throw new Exception("The method or operation is not implemented.");
}
public bool Contains(ResourceFilePair item)
{
throw new Exception("The method or operation is not implemented.");
}
public void CopyTo(ResourceFilePair[] array, int arrayIndex)
{
throw new Exception("The method or operation is not implemented.");
}
public bool IsReadOnly
{
get { throw new Exception("The method or operation is not implemented."); }
}
public bool Remove(ResourceFilePair item)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region ICollection<ResourceFilePair> Members
void ICollection<ResourceFilePair>.Clear()
{
_files.Clear();
}
bool ICollection<ResourceFilePair>.Contains(ResourceFilePair item)
{
return _files.Contains(item);
}
void ICollection<ResourceFilePair>.CopyTo(ResourceFilePair[] array, int arrayIndex)
{
_files.CopyTo(array, arrayIndex);
}
public int Count
{
get
{
return _files.Count;
}
}
int ICollection<ResourceFilePair>.Count
{
get { return _files.Count; }
}
bool ICollection<ResourceFilePair>.IsReadOnly
{
get { return false; }
}
bool ICollection<ResourceFilePair>.Remove(ResourceFilePair item)
{
return _files.Remove(item);
}
#endregion
#region IEnumerable<ResourceFilePair> Members
IEnumerator<ResourceFilePair> IEnumerable<ResourceFilePair>.GetEnumerator()
{
return _files.GetEnumerator();
}
#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.Threading;
using System.Threading.Tasks;
using System.Reflection;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public static class MARSTest
{
private static readonly string s_yukonConnectionString = (new SqlConnectionStringBuilder(DataTestClass.SQL2005_Northwind) { MultipleActiveResultSets = true }).ConnectionString;
[Fact]
public static void MARSAsyncTimeoutTest()
{
using (SqlConnection connection = new SqlConnection(s_yukonConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
command.CommandTimeout = 1;
Task<object> result = command.ExecuteScalarAsync();
Assert.True(((IAsyncResult)result).AsyncWaitHandle.WaitOne(30 * 1000), "Expected timeout after one second, but no results after 30 seconds");
Assert.True(result.IsFaulted, string.Format("Expected task result to be faulted, but instead it was {0}", result.Status));
Assert.True(connection.State == ConnectionState.Open, string.Format("Expected connection to be open after soft timeout, but it was {0}", connection.State));
Type type = typeof(SqlDataReader).GetTypeInfo().Assembly.GetType("System.Data.SqlClient.TdsParserStateObject");
FieldInfo field = type.GetField("_skipSendAttention", BindingFlags.NonPublic | BindingFlags.Static);
Assert.True(field != null, "Error: This test cannot succeed on retail builds because it uses the _skipSendAttention test hook");
field.SetValue(null, true);
try
{
SqlCommand command2 = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
command2.CommandTimeout = 1;
result = command2.ExecuteScalarAsync();
Assert.True(((IAsyncResult)result).AsyncWaitHandle.WaitOne(30 * 1000), "Expected timeout after six or so seconds, but no results after 30 seconds");
Assert.True(result.IsFaulted, string.Format("Expected task result to be faulted, but instead it was {0}", result.Status));
// Pause here to ensure that the async closing is completed
Thread.Sleep(200);
Assert.True(connection.State == ConnectionState.Closed, string.Format("Expected connection to be closed after hard timeout, but it was {0}", connection.State));
}
finally
{
field.SetValue(null, false);
}
}
}
[Fact]
public static void MARSSyncTimeoutTest()
{
using (SqlConnection connection = new SqlConnection(s_yukonConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
command.CommandTimeout = 1;
bool hitException = false;
try
{
object result = command.ExecuteScalar();
}
catch (Exception e)
{
Assert.True(e is SqlException, "Expected SqlException but found " + e);
hitException = true;
}
Assert.True(hitException, "Expected a timeout exception but ExecutScalar succeeded");
Assert.True(connection.State == ConnectionState.Open, string.Format("Expected connection to be open after soft timeout, but it was {0}", connection.State));
Type type = typeof(SqlDataReader).GetTypeInfo().Assembly.GetType("System.Data.SqlClient.TdsParserStateObject");
FieldInfo field = type.GetField("_skipSendAttention", BindingFlags.NonPublic | BindingFlags.Static);
Assert.True(field != null, "Error: This test cannot succeed on retail builds because it uses the _skipSendAttention test hook");
field.SetValue(null, true);
hitException = false;
try
{
SqlCommand command2 = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
command2.CommandTimeout = 1;
try
{
object result = command2.ExecuteScalar();
}
catch (Exception e)
{
Assert.True(e is SqlException, "Expected SqlException but found " + e);
hitException = true;
}
Assert.True(hitException, "Expected a timeout exception but ExecutScalar succeeded");
Assert.True(connection.State == ConnectionState.Closed, string.Format("Expected connection to be closed after hard timeout, but it was {0}", connection.State));
}
finally
{
field.SetValue(null, false);
}
}
}
[Fact]
public static void MARSSyncBusyReaderTest()
{
using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
{
conn.Open();
using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
{
int rows1 = 0;
while (reader1.Read())
{
rows1++;
if (rows1 == 415)
break;
}
Assert.True(rows1 == 415, "MARSSyncBusyReaderTest Failure, #1");
using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
{
int rows2 = 0;
while (reader2.Read())
{
rows2++;
if (rows2 == 415)
break;
}
Assert.True(rows2 == 415, "MARSSyncBusyReaderTest Failure, #2");
for (int i = 415; i < 830; i++)
{
Assert.True(reader1.Read() && reader2.Read(), "MARSSyncBusyReaderTest Failure #3");
Assert.True(reader1.GetInt32(0) == reader2.GetInt32(0),
"MARSSyncBusyReaderTest, Failure #4" + "\n" +
"reader1.GetInt32(0): " + reader1.GetInt32(0) + "\n" +
"reader2.GetInt32(0): " + reader2.GetInt32(0));
}
Assert.False(reader1.Read() || reader2.Read(), "MARSSyncBusyReaderTest, Failure #5");
}
}
}
}
[Fact]
public static void MARSSyncExecuteNonQueryTest()
{
using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
{
conn.Open();
using (SqlCommand comm1 = new SqlCommand("select * from Orders", conn))
using (SqlCommand comm2 = new SqlCommand("select * from Orders", conn))
using (SqlCommand comm3 = new SqlCommand("select * from Orders", conn))
using (SqlCommand comm4 = new SqlCommand("select * from Orders", conn))
using (SqlCommand comm5 = new SqlCommand("select * from Orders", conn))
{
comm1.ExecuteNonQuery();
comm2.ExecuteNonQuery();
comm3.ExecuteNonQuery();
comm4.ExecuteNonQuery();
comm5.ExecuteNonQuery();
}
}
}
[Fact]
public static void MARSSyncExecuteReaderTest1()
{
using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
{
conn.Open();
using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
{
int rows = 0;
while (reader1.Read())
{
rows++;
}
Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #1");
rows = 0;
while (reader2.Read())
{
rows++;
}
Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #2");
rows = 0;
while (reader3.Read())
{
rows++;
}
Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #3");
rows = 0;
while (reader4.Read())
{
rows++;
}
Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #4");
rows = 0;
while (reader5.Read())
{
rows++;
}
Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #5");
}
}
}
[Fact]
public static void MARSSyncExecuteReaderTest2()
{
using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
{
conn.Open();
using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
{
for (int i = 0; i < 830; i++)
{
Assert.True(reader1.Read() && reader2.Read() && reader3.Read() && reader4.Read() && reader5.Read(), "MARSSyncExecuteReaderTest2 Failure #1");
}
Assert.False(reader1.Read() || reader2.Read() || reader3.Read() || reader4.Read() || reader5.Read(), "MARSSyncExecuteReaderTest2 Failure #2");
}
}
}
[Fact]
public static void MARSSyncExecuteReaderTest3()
{
using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
{
conn.Open();
using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
{
for (int i = 0; i < 830; i++)
{
Assert.True(reader1.Read() && reader2.Read() && reader3.Read() && reader4.Read() && reader5.Read(), "MARSSyncExecuteReaderTest3 Failure #1");
// All reads succeeded - check values.
Assert.True(reader1.GetInt32(0) == reader2.GetInt32(0) &&
reader2.GetInt32(0) == reader3.GetInt32(0) &&
reader3.GetInt32(0) == reader4.GetInt32(0) &&
reader4.GetInt32(0) == reader5.GetInt32(0),
"MARSSyncExecuteReaderTest3, Failure #2" + "\n" +
"reader1.GetInt32(0): " + reader1.GetInt32(0) + "\n" +
"reader2.GetInt32(0): " + reader2.GetInt32(0) + "\n" +
"reader3.GetInt32(0): " + reader3.GetInt32(0) + "\n" +
"reader4.GetInt32(0): " + reader4.GetInt32(0) + "\n" +
"reader5.GetInt32(0): " + reader5.GetInt32(0));
}
Assert.False(reader1.Read() || reader2.Read() || reader3.Read() || reader4.Read() || reader5.Read(), "MARSSyncExecuteReaderTest3 Failure #3");
}
}
}
[Fact]
public static void MARSSyncExecuteReaderTest4()
{
using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
{
conn.Open();
using (SqlDataReader reader1 = (new SqlCommand("select * from Orders where OrderID = 10248", conn)).ExecuteReader())
using (SqlDataReader reader2 = (new SqlCommand("select * from Orders where OrderID = 10249", conn)).ExecuteReader())
using (SqlDataReader reader3 = (new SqlCommand("select * from Orders where OrderID = 10250", conn)).ExecuteReader())
{
Assert.True(reader1.Read() && reader2.Read() && reader3.Read(), "MARSSyncExecuteReaderTest4 failure #1");
Assert.True(reader1.GetInt32(0) == 10248 &&
reader2.GetInt32(0) == 10249 &&
reader3.GetInt32(0) == 10250,
"MARSSyncExecuteReaderTest4 failure #2");
Assert.False(reader1.Read() || reader2.Read() || reader3.Read(), "MARSSyncExecuteReaderTest4 failure #3");
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Test.ModuleCore;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.Threading;
using XmlCoreTest.Common;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeBuilderTests : XLinqTestCase
{
public partial class OmitAnotation : XLinqTestCase
{
private static string s_MyPath = Path.Combine(FilePathUtil.GetTestDataPath(), @"Xlinq\DuplicateNamespaces");
private static XContainer GetContainer(string filename, Type type)
{
switch (type.Name)
{
case "XElement":
return XElement.Load(FilePathUtil.getStream(filename));
case "XDocument":
return XDocument.Load(FilePathUtil.getStream(filename));
default:
throw new TestFailedException("Type not recognized");
}
}
private static XContainer GetContainer(Stream stream, Type type)
{
switch (type.Name)
{
case "XElement":
return XElement.Load(stream);
case "XDocument":
return XDocument.Load(stream);
default:
throw new TestFailedException("Type not recognized");
}
}
//[Variation(Priority = 0, Desc = "No annotation - element", Params = new object[] { typeof(XElement), "Simple.xml" })]
//[Variation(Priority = 0, Desc = "No annotation - document", Params = new object[] { typeof(XDocument), "Simple.xml" })]
public void NoAnnotation()
{
Type t = CurrentChild.Params[0] as Type;
string fileName = Path.Combine(s_MyPath, CurrentChild.Params[1] as string);
// create normal reader for comparison
using (XmlReader r1 = XmlReader.Create(FilePathUtil.getStream(fileName), new XmlReaderSettings() { IgnoreWhitespace = true, DtdProcessing = DtdProcessing.Ignore }))
{
// create reader from Xlinq
XContainer c = GetContainer(fileName, t);
using (XmlReader r2 = c.CreateReader())
{
ReaderDiff.Compare(r1, r2);
}
}
}
//[Variation(Priority = 2, Desc = "Annotation on document without omit - None", Params = new object[] { typeof(XDocument), "Simple.xml", SaveOptions.None })]
//[Variation(Priority = 2, Desc = "Annotation on document without omit - DisableFormating", Params = new object[] { typeof(XDocument), "Simple.xml", SaveOptions.DisableFormatting })]
//[Variation(Priority = 2, Desc = "Annotation on element without omit - None", Params = new object[] { typeof(XElement), "Simple.xml", SaveOptions.None })]
//[Variation(Priority = 2, Desc = "Annotation on element without omit - DisableFormating", Params = new object[] { typeof(XElement), "Simple.xml", SaveOptions.DisableFormatting })]
public void AnnotationWithoutTheOmitDuplicates()
{
Type t = CurrentChild.Params[0] as Type;
string fileName = Path.Combine(s_MyPath, CurrentChild.Params[1] as string);
SaveOptions so = (SaveOptions)CurrentChild.Params[2];
using (XmlReader r1 = XmlReader.Create(FilePathUtil.getStream(fileName), new XmlReaderSettings() { IgnoreWhitespace = true, DtdProcessing = DtdProcessing.Ignore }))
{
XContainer doc = GetContainer(fileName, t);
doc.AddAnnotation(so);
using (XmlReader r2 = doc.CreateReader())
{
ReaderDiff.Compare(r1, r2);
}
}
}
//[Variation(Priority = 0, Desc = "Annotation on document - Omit", Params = new object[] { typeof(XDocument), "Simple.xml", SaveOptions.OmitDuplicateNamespaces })]
//[Variation(Priority = 1, Desc = "Annotation on document - Omit + Disable", Params = new object[] { typeof(XDocument), "Simple.xml", SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting })]
//[Variation(Priority = 0, Desc = "Annotation on element - Omit", Params = new object[] { typeof(XElement), "Simple.xml", SaveOptions.OmitDuplicateNamespaces })]
//[Variation(Priority = 1, Desc = "Annotation on element - Omit + Disable", Params = new object[] { typeof(XElement), "Simple.xml", SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting })]
public void XDocAnnotation()
{
Type t = CurrentChild.Params[0] as Type;
string fileName = Path.Combine(s_MyPath, CurrentChild.Params[1] as string);
SaveOptions so = (SaveOptions)CurrentChild.Params[2];
using (MemoryStream ms = new MemoryStream())
{
XDocument toClean = XDocument.Load(FilePathUtil.getStream(fileName));
using (XmlWriter w = XmlWriter.Create(ms, new XmlWriterSettings() { OmitXmlDeclaration = true, NamespaceHandling = NamespaceHandling.OmitDuplicates }))
{
toClean.Save(w);
}
ms.Position = 0;
using (XmlReader r1 = XmlReader.Create(ms, new XmlReaderSettings() { IgnoreWhitespace = true, DtdProcessing = DtdProcessing.Ignore }))
{
XContainer doc = GetContainer(fileName, t);
doc.AddAnnotation(so);
using (XmlReader r2 = doc.CreateReader())
{
ReaderDiff.Compare(r1, r2);
}
}
}
}
//[Variation(Priority = 0, Desc = "Annotation on the parent nodes, XElement", Params = new object[] { typeof(XElement), "simple.xml" })]
//[Variation(Priority = 0, Desc = "Annotation on the parent nodes, XDocument", Params = new object[] { typeof(XDocument), "simple.xml" })]
public void AnnotationOnParent1()
{
Type t = CurrentChild.Params[0] as Type;
string fileName = Path.Combine(s_MyPath, CurrentChild.Params[1] as string);
var orig = GetContainer(fileName, t).DescendantNodes().ToArray();
var test = GetContainer(fileName, t).DescendantNodes().ToArray();
for (int i = 0; i < test.Count(); i++)
{
XNode n = test[i];
XNode parent = n; // verify parent and self
while (parent != null)
{ // for all parents
// verify original version
TestLog.Compare(n.ToString(), n.ToString(SaveOptions.None), "Initial value");
TestLog.Compare(n.ToString(), orig[i].ToString(), "Initial value, via orig");
ReaderDiff.Compare(orig[i].CreateReader(), n.CreateReader());
// add annotation on parent
parent.AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
// verify with annotation
TestLog.Compare(n.ToString(), n.ToString(SaveOptions.OmitDuplicateNamespaces), "with the annotation, normal");
ReaderDiffNSAware.CompareNamespaceAware(orig[i].CreateReader(), n.CreateReader());
// removeannotation
parent.RemoveAnnotations(typeof(SaveOptions));
// verify after removal
TestLog.Compare(n.ToString(), n.ToString(SaveOptions.None), "after removed annotation value");
TestLog.Compare(n.ToString(), orig[i].ToString(), "after removed annotation, via orig");
ReaderDiff.Compare(orig[i].CreateReader(), n.CreateReader());
// move parent
if (parent is XDocument) break;
parent = parent.Parent ?? parent.Document as XNode;
}
}
}
//[Variation(Priority = 0, Desc = "Multiple annotations in the tree - both up - XElement", Param = typeof(XElement))]
//[Variation(Priority = 0, Desc = "Multiple annotations in the tree - both up - XDocument", Param = typeof(XDocument))]
public void MultipleAnnotationsInTree()
{
Type t = CurrentChild.Param as Type;
string xml = @"<A xmlns:p='a1'><B xmlns:q='a2'><C xmlns:p='a1'><D xmlns:q='a2' ><E xmlns:p='a1' /></D></C></B></A>";
XContainer reF = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer); // I want dynamics!!!
SaveOptions[] options = new SaveOptions[] { SaveOptions.None, SaveOptions.DisableFormatting, SaveOptions.OmitDuplicateNamespaces, SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces };
foreach (SaveOptions[] opts in Tuples2(options))
{
XContainer gp = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer);
gp.AddAnnotation(opts[0]);
gp.FirstNode.AddAnnotation(opts[1]);
TestLog.Compare(reF.Descendants("C").First().ToString(opts[1]), gp.Descendants("C").First().ToString(), "On C - ToString()");
ReaderDiffNSAware.CompareNamespaceAware(opts[1], reF.Descendants("C").First().CreateReader(), gp.Descendants("C").First().CreateReader());
TestLog.Compare(reF.Descendants("B").First().ToString(opts[1]), gp.Descendants("B").First().ToString(), "On C - ToString()");
ReaderDiffNSAware.CompareNamespaceAware(opts[1], reF.Descendants("B").First().CreateReader(), gp.Descendants("B").First().CreateReader());
}
}
//[Variation(Priority = 0, Desc = "Multiple annotations in the tree - up/down - XElement", Param = typeof(XElement))]
//[Variation(Priority = 0, Desc = "Multiple annotations in the tree - up/down - XDocument", Param = typeof(XDocument))]
public void MultipleAnnotationsInTree2()
{
Type t = CurrentChild.Param as Type;
string xml = @"<A xmlns:p='a1'><B xmlns:q='a2'><C xmlns:p='a1'><D xmlns:q='a2' ><E xmlns:p='a1' /></D></C></B></A>";
XContainer reF = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer); // I want dynamics!!!
SaveOptions[] options = new SaveOptions[] { SaveOptions.None, SaveOptions.DisableFormatting, SaveOptions.OmitDuplicateNamespaces, SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces };
foreach (SaveOptions[] opts in Tuples2(options))
{
XContainer gp = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer);
gp.AddAnnotation(opts[0]);
gp.Descendants("C").First().AddAnnotation(opts[1]);
TestLog.Compare(reF.ToString(opts[0]), gp.ToString(), "On root - ToString()");
ReaderDiffNSAware.CompareNamespaceAware(opts[0], reF.CreateReader(), gp.CreateReader());
TestLog.Compare(reF.Descendants("B").First().ToString(opts[0]), gp.Descendants("B").First().ToString(), "On C - ToString()");
ReaderDiffNSAware.CompareNamespaceAware(opts[0], reF.Descendants("B").First().CreateReader(), gp.Descendants("B").First().CreateReader());
}
}
//[Variation(Priority = 0, Desc = "Multiple annotations on node - XDocument", Param = typeof(XDocument))]
//[Variation(Priority = 0, Desc = "Multiple annotations on node - XElement", Param = typeof(XElement))]
public void MultipleAnnotationsOnElement()
{
Type t = CurrentChild.Param as Type;
string xml = @"<A xmlns:p='a1'><B xmlns:q='a2'><C xmlns:p='a1'><D xmlns:q='a2' ><E xmlns:p='a1' /></D></C></B></A>";
XContainer reF = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer); // I want dynamics!!!
SaveOptions[] options = new SaveOptions[] { SaveOptions.None, SaveOptions.DisableFormatting, SaveOptions.OmitDuplicateNamespaces, SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces };
foreach (SaveOptions[] opts in Tuples2(options))
{
XContainer gp = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer);
foreach (SaveOptions o in opts)
{
gp.AddAnnotation(o);
}
TestLog.Compare(reF.ToString(opts[0]), gp.ToString(), "On root - ToString()");
ReaderDiffNSAware.CompareNamespaceAware(opts[0], reF.CreateReader(), gp.CreateReader());
}
}
static IEnumerable<T[]> Tuples2<T>(T[] array)
{
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
if (i != j) yield return new T[] { array[i], array[j] };
}
}
}
//[Variation(Priority = 2, Desc = "On other node types - attributes", Param = typeof(XElement))]
public void OnOtherNodesAttrs()
{
string fileName = Path.Combine(s_MyPath, "attributes.xml");
TestLog.WriteLineIgnore("Loading: .... " + fileName);
XElement reF = XElement.Load(FilePathUtil.getStream(fileName));
XElement e = XElement.Load(FilePathUtil.getStream(fileName));
e.AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
XAttribute[] refAttrs = reF.DescendantsAndSelf().Attributes().ToArray();
XAttribute[] eAttrs = e.DescendantsAndSelf().Attributes().ToArray();
for (int i = 0; i < refAttrs.Length; i++)
{
TestLog.Compare(refAttrs[i].ToString(), eAttrs[i].ToString(), "without annotation on attribute");
eAttrs[i].AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
TestLog.Compare(refAttrs[i].ToString(), eAttrs[i].ToString(), "with annotation on attribute");
}
}
private static XElement CreateVBSample()
{
XElement e1 = new XElement("{ns1}A", new XAttribute("xmlns", "ns1"));
XElement c1 = new XElement("{ns1}B", new XAttribute("xmlns", "ns1"));
XElement c2 = new XElement("{ns1}C", new XAttribute("xmlns", "ns1"));
e1.Add(c1, c2);
e1.AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
return e1;
}
//[Variation(Priority = 0, Desc = "Simulate the VB behavior - Save")]
public void SimulateVb1()
{
string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<A xmlns=\"ns1\">\n <B />\n <C />\n</A>";
XElement e1 = CreateVBSample();
StringBuilder sb = new StringBuilder();
e1.Save(new StringWriter(sb));
ReaderDiff.Compare(sb.ToString(), expected);
}
//[Variation(Priority = 0, Desc = "Simulate the VB behavior - Reader")]
public void SimulateVb2()
{
string expected = "<A xmlns=\"ns1\"><B /><C /></A>";
XElement e1 = CreateVBSample();
using (XmlReader r1 = XmlReader.Create(new StringReader(expected)))
{
using (XmlReader r2 = e1.CreateReader())
{
ReaderDiff.Compare(r1, r2);
}
}
}
//[Variation(Priority = 0, Desc = "Local settings override annotation")]
public void LocalOverride()
{
string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<A xmlns=\"ns1\">\n <B xmlns=\"ns1\"/>\n <C xmlns=\"ns1\"/>\n</A>";
XElement e1 = CreateVBSample();
StringBuilder sb = new StringBuilder();
e1.Save(new StringWriter(sb), SaveOptions.None);
ReaderDiff.Compare(sb.ToString(), expected);
}
//[Variation(Priority = 0, Desc = "XDocument - ReaderOptions.None", Params = new object[] { typeof(XDocument), "simple.xml", ReaderOptions.None })]
//[Variation(Priority = 0, Desc = "XDocument - ReaderOptions.OmitDuplicateNamespaces", Params = new object[] { typeof(XDocument), "simple.xml", ReaderOptions.OmitDuplicateNamespaces })]
//[Variation(Priority = 0, Desc = "XElement - ReaderOptions.None", Params= new object [] {typeof(XElement), "simple.xml", ReaderOptions.None })]
//[Variation(Priority = 0, Desc = "XElement - ReaderOptions.OmitDuplicateNamespaces", Params = new object[] { typeof(XElement), "simple.xml", ReaderOptions.OmitDuplicateNamespaces })]
public void ReaderOptionsSmoke()
{
Type t = CurrentChild.Params[0] as Type;
string fileName = Path.Combine(s_MyPath, CurrentChild.Params[1] as string);
ReaderOptions ro = (ReaderOptions)CurrentChild.Params[2];
var original = GetContainer(fileName, t).DescendantNodes().ToArray();
var clone = GetContainer(fileName, t).DescendantNodes().ToArray();
TestLog.Compare(original.Length, clone.Length, "original.Length != clone.Length"); // assert
Action<XmlReader, XmlReader> compareDelegate = ro == ReaderOptions.None ? (Action<XmlReader, XmlReader>)ReaderDiff.Compare : (Action<XmlReader, XmlReader>)ReaderDiffNSAware.CompareNamespaceAware;
foreach (int i in Enumerable.Range(0, original.Length))
{
// no annotation
compareDelegate(original[i].CreateReader(), clone[i].CreateReader(ro));
// annotation on self
foreach (SaveOptions so in new SaveOptions[] { SaveOptions.None, SaveOptions.OmitDuplicateNamespaces })
{
clone[i].AddAnnotation(so);
compareDelegate(original[i].CreateReader(), clone[i].CreateReader(ro));
clone[i].RemoveAnnotations(typeof(object));
}
// annotation on parents
foreach (SaveOptions so in new SaveOptions[] { SaveOptions.None, SaveOptions.OmitDuplicateNamespaces })
{
foreach (XNode anc in clone[i].Ancestors())
{
anc.AddAnnotation(so);
compareDelegate(original[i].CreateReader(), clone[i].CreateReader(ro));
anc.RemoveAnnotations(typeof(object));
}
}
}
}
}
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Common;
using Mosa.Compiler.Framework;
using System;
using System.Diagnostics;
namespace Mosa.Platform.ARMv6
{
public enum Indexing { Pre, Post };
public enum TransferSize { Byte, Word };
public enum TransferType { Store, Load };
public enum WriteBack { NoWriteBack, Write }
public enum OffsetDirection { Up, Down };
/// <summary>
/// An ARMv6 machine code emitter.
/// </summary>
public sealed class MachineCodeEmitter : BaseCodeEmitter
{
#region Code Generation Members
public override void ResolvePatches()
{
// TODO: Check x86 Implementation
}
/// <summary>
/// Writes the unsigned int.
/// </summary>
/// <param name="data">The data.</param>
public void Write(uint data)
{
codeStream.WriteByte((byte)((data >> 24) & 0xFF));
codeStream.WriteByte((byte)((data >> 16) & 0xFF));
codeStream.WriteByte((byte)((data >> 8) & 0xFF));
codeStream.WriteByte((byte)(data & 0xFF));
}
#endregion Code Generation Members
#region Instruction Format Emitters
public static byte GetConditionCode(ConditionCode condition)
{
switch (condition)
{
case ConditionCode.Always: return Bits.b1110;
case ConditionCode.Never: return Bits.b1111;
case ConditionCode.Equal: return Bits.b0000;
case ConditionCode.GreaterOrEqual: return Bits.b1010;
case ConditionCode.GreaterThan: return Bits.b1100;
case ConditionCode.LessOrEqual: return Bits.b1101;
case ConditionCode.LessThan: return Bits.b1011;
case ConditionCode.NotEqual: return Bits.b0001;
case ConditionCode.UnsignedGreaterOrEqual: return Bits.b0010;
case ConditionCode.UnsignedGreaterThan: return Bits.b1000;
case ConditionCode.UnsignedLessOrEqual: return Bits.b1001;
case ConditionCode.UnsignedLessThan: return Bits.b0011;
case ConditionCode.NotSigned: return Bits.b0000;
case ConditionCode.Signed: return Bits.b0000;
case ConditionCode.Zero: return Bits.b0101;
case ConditionCode.Overflow: return Bits.b0110;
case ConditionCode.NoOverflow: return Bits.b0111;
case ConditionCode.Positive: return Bits.b0101;
default: throw new NotSupportedException();
}
}
public static byte GetShiftTypeCode(ShiftType shiftType)
{
switch (shiftType)
{
case ShiftType.LogicalLeft: return Bits.b00;
case ShiftType.LogicalRight: return Bits.b01;
case ShiftType.ArithmeticRight: return Bits.b10;
case ShiftType.RotateRight: return Bits.b11;
default: throw new NotSupportedException();
}
}
public void EmitBranch(ConditionCode conditionCode, int register)
{
Debug.Assert(register <= 0xF);
uint value = 0;
value |= (uint)(GetConditionCode(conditionCode) << 28);
value |= 0x12FFF10;
value |= (uint)register;
Write(value);
}
public void EmitBranch(ConditionCode conditionCode, int offset, bool link)
{
Debug.Assert(offset <= 0xFFF);
uint value = 0;
value |= (uint)(GetConditionCode(conditionCode) << 28);
value |= Bits.b0101 << 25;
value |= (uint)(link ? 1 : 0 << 24);
value |= (uint)offset;
Write(value);
}
public void EmitInstructionWithRegister(ConditionCode conditionCode, byte opcode, bool setCondition, int firstRegister, int destinationRegister, ShiftType secondShiftType, int secondRegister)
{
Debug.Assert(opcode <= 0xF);
Debug.Assert(destinationRegister <= 0xF);
Debug.Assert(firstRegister <= 0xF);
Debug.Assert(secondRegister <= 0xF);
uint value = 0;
value |= (uint)(GetConditionCode(conditionCode) << 28);
value |= 0x0 << 25;
value |= (uint)(opcode << 21);
value |= (uint)(setCondition ? 1 : 0 << 20);
value |= (uint)(firstRegister << 16);
value |= (uint)(destinationRegister << 12);
value |= (uint)(GetShiftTypeCode(secondShiftType) << 4);
value |= (uint)secondRegister;
Write(value);
}
public void EmitInstructionWithImmediate(ConditionCode conditionCode, byte opcode, bool setCondition, int firstRegister, int destinationRegister, int rotate, int immediate)
{
Debug.Assert(opcode <= 0xF);
Debug.Assert(destinationRegister <= 0xF);
Debug.Assert(firstRegister <= 0xF);
Debug.Assert(rotate <= 0xF);
Debug.Assert(immediate <= 0xFF);
uint value = 0;
value |= (uint)(GetConditionCode(conditionCode) << 28);
value |= 0x1 << 25;
value |= (uint)(opcode << 21);
value |= (uint)(setCondition ? 1 : 0 << 20);
value |= (uint)(firstRegister << 16);
value |= (uint)(destinationRegister << 12);
value |= (uint)(rotate << 8);
value |= (uint)immediate;
Write(value);
}
public void EmitMultiply(ConditionCode conditionCode, bool setCondition, int firstRegister, int destinationRegister, int secondRegister)
{
Debug.Assert(destinationRegister <= 0xF);
Debug.Assert(secondRegister <= 0xF);
Debug.Assert(firstRegister <= 0xF);
uint value = 0;
value |= (uint)(GetConditionCode(conditionCode) << 28);
value |= (uint)(setCondition ? 1 : 0 << 20);
value |= (uint)(destinationRegister << 16);
value |= (uint)(firstRegister << 12);
value |= Bits.b1001 << 4;
value |= (uint)(secondRegister << 8);
Write(value);
}
public void EmitMultiplyWithAccumulate(ConditionCode conditionCode, bool setCondition, int firstRegister, int destinationRegister, int secondRegister, int accumulateRegister)
{
Debug.Assert(destinationRegister <= 0xF);
Debug.Assert(secondRegister <= 0xF);
Debug.Assert(firstRegister <= 0xF);
uint value = 0;
value |= (uint)(GetConditionCode(conditionCode) << 28);
value |= 1 << 21;
value |= (uint)(setCondition ? 1 : 0 << 20);
value |= (uint)(destinationRegister << 16);
value |= (uint)(firstRegister << 12);
value |= (uint)(secondRegister << 8);
value |= Bits.b1001 << 4;
value |= (uint)accumulateRegister;
Write(value);
}
public void EmitSingleDataTransfer(ConditionCode conditionCode, Indexing indexing, OffsetDirection offsetDirection, TransferSize transferSize, WriteBack writeBack, TransferType transferType, int firstRegister, int destinationRegister, uint immediate)
{
Debug.Assert(destinationRegister <= 0xF);
Debug.Assert(firstRegister <= 0xF);
Debug.Assert(immediate <= 0xFFF);
uint value = 0;
value |= (uint)(GetConditionCode(conditionCode) << 28);
value |= 1 << 26;
value |= 1 << 25;
value |= (uint)((indexing == Indexing.Post ? 0 : 1) << 24);
value |= (uint)((transferSize == TransferSize.Word ? 0 : 1) << 23);
value |= (uint)((offsetDirection == OffsetDirection.Down ? 0 : 1) << 22);
value |= (uint)((writeBack == WriteBack.NoWriteBack ? 0 : 1) << 21);
value |= (uint)((transferType == TransferType.Store ? 0 : 1) << 20);
value |= (uint)(destinationRegister << 12);
value |= (uint)(firstRegister << 16);
value |= immediate;
Write(value);
}
public void EmitSingleDataTransfer(ConditionCode conditionCode, Indexing indexing, OffsetDirection offsetDirection, TransferSize transferSize, WriteBack writeBack, TransferType transferType, int firstRegister, int destinationRegister, ShiftType secondShiftType, int secondRegister)
{
Debug.Assert(destinationRegister <= 0xF);
Debug.Assert(firstRegister <= 0xF);
Debug.Assert(secondRegister <= 0xF);
uint value = 0;
value |= (uint)(GetConditionCode(conditionCode) << 28);
value |= 1 << 26;
value |= 1 << 25;
value |= (uint)((indexing == Indexing.Post ? 0 : 1) << 24);
value |= (uint)((transferSize == TransferSize.Word ? 0 : 1) << 23);
value |= (uint)((offsetDirection == OffsetDirection.Down ? 0 : 1) << 22);
value |= (uint)((writeBack == WriteBack.NoWriteBack ? 0 : 1) << 21);
value |= (uint)((transferType == TransferType.Store ? 0 : 1) << 20);
value |= (uint)(destinationRegister << 12);
value |= (uint)(firstRegister << 16);
value |= (uint)(GetShiftTypeCode(secondShiftType) << 4);
value |= (uint)secondRegister;
Write(value);
}
// TODO: Add additional instruction formats
#endregion Instruction Format Emitters
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
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 library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Security;
using System.Security.Permissions;
using log4net;
using FluorineFx.Context;
using FluorineFx.Util;
using FluorineFx.Messaging.Api.Service;
using FluorineFx.Messaging.Api;
using FluorineFx.Messaging.Api.Stream;
using FluorineFx.Messaging.Api.Event;
using FluorineFx.Messaging.Api.SO;
using FluorineFx.Messaging.Api.Messaging;
using FluorineFx.Exceptions;
using FluorineFx.Messaging.Messages;
using FluorineFx.Messaging.Services;
using FluorineFx.Messaging.Endpoints;
using FluorineFx.IO;
using FluorineFx.Messaging.Rtmp.Event;
using FluorineFx.Messaging.Rtmp.SO;
using FluorineFx.Messaging.Rtmp.Stream;
using FluorineFx.Messaging.Rtmp.Service;
using FluorineFx.Scheduling;
using FluorineFx.Threading;
namespace FluorineFx.Messaging.Rtmp
{
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
class RtmpHandler : BaseRtmpHandler
{
private static readonly ILog log = LogManager.GetLogger(typeof(RtmpHandler));
IEndpoint _endpoint;
public RtmpHandler(IEndpoint endpoint)
: base()
{
_endpoint = endpoint;
}
internal IEndpoint Endpoint
{
get { return _endpoint; }
}
public override void ConnectionOpened(RtmpConnection connection)
{
base.ConnectionOpened(connection);
if (connection.Context.Mode == RtmpMode.Server)
{
connection.StartWaitForHandshake();
}
}
public override void MessageSent(RtmpConnection connection, object message)
{
base.MessageSent(connection, message);
RtmpPacket sent = message as RtmpPacket;
int channelId = sent.Header.ChannelId;
IClientStream stream = null;
if( connection is IStreamCapableConnection )
stream = (connection as IStreamCapableConnection).GetStreamByChannelId(channelId);
// XXX we'd better use new event model for notification
if (stream != null && (stream is PlaylistSubscriberStream))
{
(stream as PlaylistSubscriberStream).Written(sent.Message);
}
}
/*
FlexInvoke flexInvoke = new FlexInvoke();
flexInvoke.Cmd = "onstatus";
flexInvoke.DataType = DataType.TypeUnknown;
StatusASO statusASO = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_CLOSED, connection.ObjectEncoding);
flexInvoke.Parameters = new object[]{ statusASO };
RtmpChannel channel = connection.GetChannel(3);
channel.Write(flexInvoke);
*/
protected override void OnChunkSize(RtmpConnection connection, RtmpChannel channel, RtmpHeader source, ChunkSize chunkSize)
{
if (connection is IStreamCapableConnection)
{
IStreamCapableConnection streamCapableConnection = connection as IStreamCapableConnection;
{
foreach (IClientStream stream in streamCapableConnection.GetStreams())
{
if (stream is IClientBroadcastStream)
{
IClientBroadcastStream bs = stream as IClientBroadcastStream;
IBroadcastScope scope = bs.Scope.GetBasicScope(Constants.BroadcastScopeType, bs.PublishedName) as IBroadcastScope;
if (scope == null)
continue;
OOBControlMessage setChunkSize = new OOBControlMessage();
setChunkSize.Target = "ClientBroadcastStream";
setChunkSize.ServiceName = "chunkSize";
setChunkSize.ServiceParameterMap.Add("chunkSize", chunkSize.Size);
scope.SendOOBControlMessage((IConsumer)null, setChunkSize);
if (log.IsDebugEnabled)
{
log.Debug("Sending chunksize " + chunkSize + " to " + bs.Provider);
}
}
}
}
}
}
protected override void OnPing(RtmpConnection connection, RtmpChannel channel, RtmpHeader source, Ping ping)
{
switch (ping.PingType)
{
case Ping.ClientBuffer:
IClientStream stream = null;
// Get the stream id
int streamId = ping.Value2;
// Get requested buffer size in milliseconds
int buffer = ping.Value3;
if (streamId != 0)
{
// The client wants to set the buffer time
stream = connection.GetStreamById(streamId);
if (stream != null)
{
stream.SetClientBufferDuration(buffer);
if (log.IsDebugEnabled)
log.Debug(string.Format("Client sent a buffer size: {0} ms for stream id: {1}", buffer, streamId ));
}
}
// Catch-all to make sure buffer size is set
if (stream == null)
{
// Remember buffer time until stream is created
connection.RememberStreamBufferDuration(streamId, buffer);
if (log.IsDebugEnabled)
log.Debug(string.Format("Remembering client buffer size: {0} on stream id: {1} ", buffer, streamId));
}
break;
case Ping.PongServer:
// This is the response to an IConnection.Ping request
connection.PingReceived(ping);
break;
default:
log.Warn("Unhandled ping: " + ping);
break;
}
}
protected override void OnServerBW(RtmpConnection connection, RtmpChannel channel, RtmpHeader source, ServerBW serverBW)
{
}
protected override void OnClientBW(RtmpConnection connection, RtmpChannel channel, RtmpHeader source, ClientBW clientBW)
{
}
protected override void OnInvoke(RtmpConnection connection, RtmpChannel channel, RtmpHeader header, Notify invoke)
{
IServiceCall serviceCall = invoke.ServiceCall;
// If it's a callback for server remote call then pass it over to callbacks handler
// and return
if(serviceCall.ServiceMethodName.Equals("_result") || serviceCall.ServiceMethodName.Equals("_error"))
{
HandlePendingCallResult(connection, invoke);
return;
}
bool disconnectOnReturn = false;
string action = null;
if (serviceCall.ServiceName == null)
{
action = serviceCall.ServiceMethodName;
switch (action)
{
case ACTION_CONNECT:
{
if (!connection.IsConnected)
{
IDictionary parameters = invoke.ConnectionParameters;
string host = null;
if( parameters.Contains("tcUrl") )
host = GetHostname(parameters["tcUrl"] as string);
if (host != null && host.IndexOf(":") != -1)
{
// Remove default port from connection string
host = host.Substring(0, host.IndexOf(":"));
}
string app = parameters["app"] as string;
string path = parameters["app"] as string;
// App name as path, but without query string if there is one
if (path != null && path.IndexOf("?") != -1)
{
int idx = path.IndexOf("?");
parameters["queryString"] = path.Substring(idx);
path = path.Substring(0, idx);
}
parameters["path"] = path;
connection.Setup(host, path, parameters);
try
{
//IGlobalScope global = this.Endpoint.LookupGlobal(host, path);
IGlobalScope global = this.Endpoint.GetMessageBroker().GlobalScope;
if (global == null)
{
serviceCall.Status = Call.STATUS_SERVICE_NOT_FOUND;
if (serviceCall is IPendingServiceCall)
{
StatusASO status = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_INVALID_APPLICATION, connection.ObjectEncoding);
status.description = "No global scope on this server.";
(serviceCall as IPendingServiceCall).Result = status;
}
log.Info(string.Format("No application scope found for {0} on host {1}. Misspelled or missing application folder?", path, host));
disconnectOnReturn = true;
}
else
{
IScopeContext context = global.Context;
IScope scope = null;
try
{
scope = context.ResolveScope(global, path);
}
catch (ScopeNotFoundException /*exception*/)
{
if (log.IsErrorEnabled)
log.Error(__Res.GetString(__Res.Scope_NotFound, path));
serviceCall.Status = Call.STATUS_SERVICE_NOT_FOUND;
if (serviceCall is IPendingServiceCall)
{
StatusASO status = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_REJECTED, connection.ObjectEncoding);
status.description = "No scope \"" + path + "\" on this server.";
(serviceCall as IPendingServiceCall).Result = status;
}
disconnectOnReturn = true;
}
catch (ScopeShuttingDownException)
{
serviceCall.Status = Call.STATUS_APP_SHUTTING_DOWN;
if (serviceCall is IPendingServiceCall)
{
StatusASO status = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_APPSHUTDOWN, connection.ObjectEncoding);
status.description = "Application at \"" + path + "\" is currently shutting down.";
(serviceCall as IPendingServiceCall).Result = status;
}
log.Info(string.Format("Application at {0} currently shutting down on {1}", path, host));
disconnectOnReturn = true;
}
if (scope != null)
{
if (log.IsInfoEnabled)
log.Info(__Res.GetString(__Res.Scope_Connect, scope.Name));
bool okayToConnect;
try
{
//The only way to differentiate NetConnection.connect() and Consumer.subscribe() seems to be the app name
if (app == string.Empty)
{
connection.SetIsFlexClient(true);
okayToConnect = connection.Connect(scope, serviceCall.Arguments);
if (okayToConnect)
{
if (serviceCall.Arguments != null && serviceCall.Arguments.Length >= 3)
{
string credentials = serviceCall.Arguments[2] as string;
if (credentials != null && credentials != string.Empty)
{
MessageBroker messageBroker = this.Endpoint.GetMessageBroker();
AuthenticationService authenticationService = messageBroker.GetService(AuthenticationService.ServiceId) as AuthenticationService;
authenticationService.Authenticate(credentials);
}
}
//FDS 2.0.1 fds.swc
if (serviceCall.Arguments != null && serviceCall.Arguments.Length == 1)
{
string credentials = serviceCall.Arguments[0] as string;
if (credentials != null && credentials != string.Empty)
{
MessageBroker messageBroker = this.Endpoint.GetMessageBroker();
AuthenticationService authenticationService = messageBroker.GetService(AuthenticationService.ServiceId) as AuthenticationService;
authenticationService.Authenticate(credentials);
}
}
}
}
else
{
connection.SetIsFlexClient(false);
okayToConnect = connection.Connect(scope, serviceCall.Arguments);
}
if (okayToConnect)
{
if (log.IsDebugEnabled)
log.Debug("Connected RtmpClient: " + connection.Client.Id);
serviceCall.Status = Call.STATUS_SUCCESS_RESULT;
if (serviceCall is IPendingServiceCall)
{
StatusASO statusASO = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_SUCCESS, connection.ObjectEncoding);
statusASO.Add("id", connection.Client.Id);
(serviceCall as IPendingServiceCall).Result = statusASO;
}
// Measure initial roundtrip time after connecting
connection.GetChannel((byte)2).Write(new Ping(Ping.StreamBegin, 0, -1));
connection.StartRoundTripMeasurement();
}
else
{
if (log.IsDebugEnabled)
log.Debug("Connect failed");
serviceCall.Status = Call.STATUS_ACCESS_DENIED;
if (serviceCall is IPendingServiceCall)
(serviceCall as IPendingServiceCall).Result = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_REJECTED, connection.ObjectEncoding);
disconnectOnReturn = true;
}
}
catch (ClientRejectedException rejected)
{
if (log.IsDebugEnabled)
log.Debug("Connect rejected");
serviceCall.Status = Call.STATUS_ACCESS_DENIED;
if (serviceCall is IPendingServiceCall)
{
StatusASO statusASO = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_REJECTED, connection.ObjectEncoding);
statusASO.Application = rejected.Reason;
(serviceCall as IPendingServiceCall).Result = statusASO;
}
disconnectOnReturn = true;
}
}
}
}
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("Error connecting", ex);
serviceCall.Status = Call.STATUS_GENERAL_EXCEPTION;
if (serviceCall is IPendingServiceCall)
(serviceCall as IPendingServiceCall).Result = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_FAILED, connection.ObjectEncoding);
disconnectOnReturn = true;
}
}
else
{
// Service calls, must be connected.
InvokeCall(connection, serviceCall);
}
}
break;
case ACTION_DISCONNECT:
connection.Close();
break;
case ACTION_CREATE_STREAM:
case ACTION_DELETE_STREAM:
case ACTION_RELEASE_STREAM:
case ACTION_PUBLISH:
case ACTION_PLAY:
case ACTION_SEEK:
case ACTION_PAUSE:
case ACTION_CLOSE_STREAM:
case ACTION_RECEIVE_VIDEO:
case ACTION_RECEIVE_AUDIO:
{
IStreamService streamService = ScopeUtils.GetScopeService(connection.Scope, typeof(IStreamService)) as IStreamService;
StatusASO status = null;
try
{
if (!InvokeCall(connection, serviceCall, streamService))
{
status = StatusASO.GetStatusObject(StatusASO.NS_INVALID_ARGUMENT, connection.ObjectEncoding);
status.description = "Failed to " + action + " (stream ID: " + header.StreamId + ")";
}
}
catch (Exception ex)
{
log.Error("Error while invoking " + action + " on stream service.", ex);
status = StatusASO.GetStatusObject(StatusASO.NS_FAILED, connection.ObjectEncoding);
status.description = "Error while invoking " + action + " (stream ID: " + header.StreamId + ")";
status.details = ex.Message;
}
if (status != null)
channel.SendStatus(status);
}
break;
default:
if (connection.IsConnected)
InvokeCall(connection, serviceCall);
else
{
// Warn user attemps to call service without being connected
if (log.IsWarnEnabled)
log.Warn("Not connected, closing connection");
connection.Close();
}
break;
}
}
/*
if(invoke is FlexInvoke)
{
FlexInvoke reply = new FlexInvoke();
reply.InvokeId = invoke.InvokeId;
reply.SetResponseSuccess();
//TODO
if( serviceCall is IPendingServiceCall )
{
IPendingServiceCall pendingCall = (IPendingServiceCall)serviceCall;
reply.Response = pendingCall.Result;
}
channel.Write(reply);
}
else if(invoke is Invoke)
*/
if (invoke is Invoke)
{
if((header.StreamId != 0)
&& (serviceCall.Status == Call.STATUS_SUCCESS_VOID || serviceCall.Status == Call.STATUS_SUCCESS_NULL))
{
if (log.IsDebugEnabled)
log.Debug("Method does not have return value, do not reply");
return;
}
// The client expects a result for the method call.
Invoke reply = new Invoke();
reply.ServiceCall = serviceCall;
reply.InvokeId = invoke.InvokeId;
//sending reply
channel.Write(reply);
}
if (disconnectOnReturn)
{
connection.Close();
}
if (action == ACTION_CONNECT)
{
connection.Context.ObjectEncoding = connection.ObjectEncoding;
}
}
protected override void OnSharedObject(RtmpConnection connection, RtmpChannel channel, RtmpHeader header, SharedObjectMessage message)
{
ISharedObject so = null;
string name = message.Name;
IScope scope = connection.Scope;
bool persistent = message.IsPersistent;
if(scope == null)
{
// The scope already has been deleted.
SendSOCreationFailed(connection, name, persistent);
return;
}
ISharedObjectService sharedObjectService = ScopeUtils.GetScopeService(scope, typeof(ISharedObjectService)) as ISharedObjectService;
if (!sharedObjectService.HasSharedObject(scope, name))
{
ISharedObjectSecurityService securityService = ScopeUtils.GetScopeService(scope, typeof(ISharedObjectSecurityService)) as ISharedObjectSecurityService;
if (securityService != null)
{
// Check handlers to see if creation is allowed
IEnumerator enumerator = securityService.GetSharedObjectSecurity();
while(enumerator.MoveNext())
{
ISharedObjectSecurity handler = enumerator.Current as ISharedObjectSecurity;
if (!handler.IsCreationAllowed(scope, name, persistent))
{
SendSOCreationFailed(connection, name, persistent);
return;
}
}
}
if (!sharedObjectService.CreateSharedObject(scope, name, persistent))
{
SendSOCreationFailed(connection, name, persistent);
return;
}
}
so = sharedObjectService.GetSharedObject(scope, name);
if (so.IsPersistentObject != persistent)
{
log.Debug(string.Format("Shared object '{0}' persistence mismatch", name));
SendSOPersistenceMismatch(connection, name, persistent);
return;
}
so.DispatchEvent(message);
}
private static void SendSOCreationFailed(RtmpConnection connection, string name, bool persistent)
{
SharedObjectMessage msg;
if (connection.ObjectEncoding == ObjectEncoding.AMF0)
msg = new SharedObjectMessage(name, 0, persistent);
else
msg = new FlexSharedObjectMessage(name, 0, persistent);
msg.AddEvent(new SharedObjectEvent(SharedObjectEventType.CLIENT_STATUS, StatusASO.SO_CREATION_FAILED, "error"));
connection.GetChannel((byte)3).Write(msg);
}
private static void SendSOPersistenceMismatch(RtmpConnection connection, string name, bool persistent)
{
SharedObjectMessage msg;
if (connection.ObjectEncoding == ObjectEncoding.AMF0)
msg = new SharedObjectMessage(name, 0, persistent);
else
msg = new FlexSharedObjectMessage(name, 0, persistent);
msg.AddEvent(new SharedObjectEvent(SharedObjectEventType.CLIENT_STATUS, StatusASO.SO_PERSISTENCE_MISMATCH, "error"));
connection.GetChannel((byte)3).Write(msg);
}
protected override void OnFlexInvoke(RtmpConnection connection, RtmpChannel channel, RtmpHeader header, FlexInvoke invoke)
{
IMessage message = null;
if (invoke.ServiceCall.Arguments != null && invoke.ServiceCall.Arguments.Length > 0)
message = invoke.ServiceCall.Arguments[0] as IMessage;
if( message != null )
{
MessageBroker messageBroker = this.Endpoint.GetMessageBroker();
if( message.clientId == null )
{
message.clientId = Guid.NewGuid().ToString("D");
/*
if( !(message is CommandMessage) )
{
//producer may send messages without subscribing
CommandMessage commandMessageSubscribe = new CommandMessage(CommandMessage.SubscribeOperation);
commandMessageSubscribe.messageId = Guid.NewGuid().ToString("D");
commandMessageSubscribe.headers = message.headers.Clone() as Hashtable;
commandMessageSubscribe.messageRefType = message.GetType().FullName;//"flex.messaging.messages.AsyncMessage"
commandMessageSubscribe.destination = message.destination;
IMessage subscribeResponse = messageBroker.RouteMessage(commandMessageSubscribe, _endpoint, connection);
message.clientId = subscribeResponse.clientId;
}
}
*/
}
IMessage response = messageBroker.RouteMessage(message, this.Endpoint);
invoke.ServiceCall.Status = response is ErrorMessage ? Call.STATUS_INVOCATION_EXCEPTION : Call.STATUS_SUCCESS_RESULT;
if (invoke.ServiceCall is IPendingServiceCall)
(invoke.ServiceCall as IPendingServiceCall).Result = response;
FlexInvoke reply = new FlexInvoke();
reply.InvokeId = invoke.InvokeId;
reply.ServiceCall = invoke.ServiceCall;
/*
if( response is ErrorMessage )
reply.SetResponseFailure();
else
reply.SetResponseSuccess();
reply.Response = response;
*/
channel.Write(reply);
}
else
{
// If it's a callback for server remote call then pass it over to callbacks handler and return
OnInvoke(connection, channel, header, invoke);
}
}
public static void InvokeCall(RtmpConnection connection, IServiceCall serviceCall)
{
IScope scope = connection.Scope;
if(scope.HasHandler)
{
IScopeHandler handler = scope.Handler;
if(!handler.ServiceCall(connection, serviceCall))
{
// What do do here? Return an error?
return;
}
}
IScopeContext context = scope.Context;
context.ServiceInvoker.Invoke(serviceCall, scope);
}
/// <summary>
/// Remoting call invocation handler.
/// </summary>
/// <param name="connection">RTMP connection.</param>
/// <param name="serviceCall">Service call.</param>
/// <param name="service">Server-side service object.</param>
/// <returns><code>true</code> if the call was performed, otherwise <code>false</code>.</returns>
private static bool InvokeCall(RtmpConnection connection, IServiceCall serviceCall, object service)
{
IScope scope = connection.Scope;
IScopeContext context = scope.Context;
if (log.IsDebugEnabled)
{
log.Debug("Scope: " + scope);
log.Debug("Service: " + service);
log.Debug("Context: " + context);
}
return context.ServiceInvoker.Invoke(serviceCall, service);
}
}
}
| |
using System;
using System.Text;
namespace ReliableUdp.Utility
{
public class UdpDataReader
{
protected byte[] data;
protected int position;
protected int DataSize;
public byte[] Data
{
get { return this.data; }
}
public int Position
{
get { return this.position; }
}
public bool EndOfData
{
get { return this.position == this.DataSize; }
}
public int AvailableBytes
{
get { return this.DataSize - this.position; }
}
public void SetSource(UdpDataWriter dataWriter)
{
this.data = dataWriter.Data;
this.position = 0;
this.DataSize = dataWriter.Length;
}
public void SetSource(byte[] source)
{
this.data = source;
this.position = 0;
this.DataSize = source.Length;
}
public void SetSource(byte[] source, int offset)
{
this.data = source;
this.position = offset;
this.DataSize = source.Length - offset;
}
public void SetSource(byte[] source, int offset, int dataSize)
{
this.data = source;
this.position = offset;
this.DataSize = dataSize;
}
public UdpDataReader()
{
}
public UdpDataReader(byte[] source)
{
this.SetSource(source);
}
public UdpDataReader(byte[] source, int position)
{
this.SetSource(source, position);
}
public UdpDataReader(byte[] source, int position, int datasize)
{
this.SetSource(source, position, datasize);
}
public byte GetByte()
{
byte res = this.data[this.position];
this.position += 1;
return res;
}
public byte PeekByte()
{
byte res = this.data[this.position];
return res;
}
public sbyte GetSByte()
{
var b = (sbyte)this.data[this.position];
this.position++;
return b;
}
public bool[] GetBoolArray()
{
ushort size = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
var arr = new bool[size];
for (int i = 0; i < size; i++)
{
arr[i] = this.GetBool();
}
return arr;
}
public ushort[] GetUShortArray()
{
ushort size = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
var arr = new ushort[size];
for (int i = 0; i < size; i++)
{
arr[i] = this.GetUShort();
}
return arr;
}
public short[] GetShortArray()
{
ushort size = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
var arr = new short[size];
for (int i = 0; i < size; i++)
{
arr[i] = this.GetShort();
}
return arr;
}
public long[] GetLongArray()
{
ushort size = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
var arr = new long[size];
for (int i = 0; i < size; i++)
{
arr[i] = this.GetLong();
}
return arr;
}
public ulong[] GetULongArray()
{
ushort size = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
var arr = new ulong[size];
for (int i = 0; i < size; i++)
{
arr[i] = this.GetULong();
}
return arr;
}
public int[] GetIntArray()
{
ushort size = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
var arr = new int[size];
for (int i = 0; i < size; i++)
{
arr[i] = this.GetInt();
}
return arr;
}
public uint[] GetUIntArray()
{
ushort size = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
var arr = new uint[size];
for (int i = 0; i < size; i++)
{
arr[i] = this.GetUInt();
}
return arr;
}
public float[] GetFloatArray()
{
ushort size = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
var arr = new float[size];
for (int i = 0; i < size; i++)
{
arr[i] = this.GetFloat();
}
return arr;
}
public double[] GetDoubleArray()
{
ushort size = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
var arr = new double[size];
for (int i = 0; i < size; i++)
{
arr[i] = this.GetDouble();
}
return arr;
}
public string[] GetStringArray(int maxLength)
{
ushort size = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
var arr = new string[size];
for (int i = 0; i < size; i++)
{
arr[i] = this.GetString(maxLength);
}
return arr;
}
public bool GetBool()
{
bool res = this.data[this.position] > 0;
this.position += 1;
return res;
}
public ushort GetUShort()
{
ushort result = BitConverter.ToUInt16(this.data, this.position);
this.position += 2;
return result;
}
public short GetShort()
{
short result = BitConverter.ToInt16(this.data, this.position);
this.position += 2;
return result;
}
public long GetLong()
{
long result = BitConverter.ToInt64(this.data, this.position);
this.position += 8;
return result;
}
public ulong GetULong()
{
ulong result = BitConverter.ToUInt64(this.data, this.position);
this.position += 8;
return result;
}
public int GetInt()
{
int result = BitConverter.ToInt32(this.data, this.position);
this.position += 4;
return result;
}
public uint GetUInt()
{
uint result = BitConverter.ToUInt32(this.data, this.position);
this.position += 4;
return result;
}
public float GetFloat()
{
float result = BitConverter.ToSingle(this.data, this.position);
this.position += 4;
return result;
}
public double GetDouble()
{
double result = BitConverter.ToDouble(this.data, this.position);
this.position += 8;
return result;
}
public string GetString(int maxLength)
{
int bytesCount = this.GetInt();
if (bytesCount <= 0 || bytesCount > maxLength * 2)
{
return string.Empty;
}
int charCount = Encoding.UTF8.GetCharCount(this.data, this.position, bytesCount);
if (charCount > maxLength)
{
return string.Empty;
}
string result = Encoding.UTF8.GetString(this.data, this.position, bytesCount);
this.position += bytesCount;
return result;
}
public string GetString()
{
int bytesCount = this.GetInt();
string result = Encoding.UTF8.GetString(this.data, this.position, bytesCount);
this.position += bytesCount;
return result;
}
public byte[] GetBytes()
{
byte[] outgoingData = new byte[this.AvailableBytes];
Buffer.BlockCopy(this.data, this.position, outgoingData, 0, this.AvailableBytes);
this.position = this.data.Length;
return outgoingData;
}
public void GetBytes(byte[] destination)
{
Buffer.BlockCopy(this.data, this.position, destination, 0, this.AvailableBytes);
this.position = this.data.Length;
}
public void GetBytes(byte[] destination, int lenght)
{
Buffer.BlockCopy(this.data, this.position, destination, 0, lenght);
this.position += lenght;
}
public void Clear()
{
this.position = 0;
this.DataSize = 0;
this.data = null;
}
public UdpDataReader CloneWithoutCopy()
{
return new UdpDataReader(data, this.position, this.DataSize);
}
}
}
| |
namespace Cik.PP.Web.Areas.HelpPage
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Cik.PP.Web.Areas.HelpPage.Models;
using Cik.PP.Web.Areas.HelpPage.SampleGeneration;
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// GtkSharp.Generation.InterfaceGen.cs - The Interface Generatable.
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2001-2003 Mike Kestner
// Copyright (c) 2004, 2007 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301
namespace GtkSharp.Generation {
using System;
using System.Collections;
using System.IO;
using System.Xml;
public class InterfaceGen : ObjectBase {
bool consume_only;
ArrayList vms = new ArrayList ();
ArrayList members = new ArrayList ();
public InterfaceGen (XmlElement ns, XmlElement elem) : base (ns, elem)
{
consume_only = elem.HasAttribute ("consume_only");
foreach (XmlNode node in elem.ChildNodes) {
switch (node.Name) {
case "virtual_method":
VirtualMethod vm = new VirtualMethod (node as XmlElement, this);
vms.Add (vm);
members.Add (vm);
break;
case "signal":
object sig = sigs [(node as XmlElement).GetAttribute ("name")];
if (sig == null)
sig = new Signal (node as XmlElement, this);
members.Add (sig);
break;
default:
if (!IsNodeNameHandled (node.Name))
Console.WriteLine ("Unexpected node " + node.Name + " in " + CName);
break;
}
}
}
public bool IsConsumeOnly {
get {
return consume_only;
}
}
public override string FromNative (string var, bool owned)
{
return QualifiedName + "Adapter.GetObject (" + var + ", " + (owned ? "true" : "false") + ")";
}
public override bool ValidateForSubclass ()
{
ArrayList invalids = new ArrayList ();
foreach (Method method in methods.Values) {
if (!method.Validate ()) {
Console.WriteLine ("in type " + QualifiedName);
invalids.Add (method);
}
}
foreach (Method method in invalids)
methods.Remove (method.Name);
invalids.Clear ();
return base.ValidateForSubclass ();
}
string IfaceName {
get {
return Name + "Iface";
}
}
void GenerateIfaceStruct (StreamWriter sw)
{
sw.WriteLine ("\t\tstatic " + IfaceName + " iface;");
sw.WriteLine ();
sw.WriteLine ("\t\tstruct " + IfaceName + " {");
sw.WriteLine ("\t\t\tpublic IntPtr gtype;");
sw.WriteLine ("\t\t\tpublic IntPtr itype;");
sw.WriteLine ();
foreach (object member in members) {
if (member is Signal) {
Signal sig = member as Signal;
sw.WriteLine ("\t\t\tpublic IntPtr {0};", sig.CName.Replace ("\"", "").Replace ("-", "_"));
} else if (member is VirtualMethod) {
VirtualMethod vm = member as VirtualMethod;
bool has_target = methods [vm.Name] != null;
if (!has_target)
Console.WriteLine ("Interface " + QualifiedName + " virtual method " + vm.Name + " has no matching method to invoke.");
string type = has_target && vm.IsValid ? vm.Name + "Delegate" : "IntPtr";
sw.WriteLine ("\t\t\tpublic " + type + " " + vm.CName + ";");
}
}
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
void GenerateStaticCtor (StreamWriter sw)
{
sw.WriteLine ("\t\tstatic " + Name + "Adapter ()");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tGLib.GType.Register (_gtype, typeof({0}Adapter));", Name);
foreach (VirtualMethod vm in vms) {
bool has_target = methods [vm.Name] != null;
if (has_target && vm.IsValid)
sw.WriteLine ("\t\t\tiface.{0} = new {1}Delegate ({1}Callback);", vm.CName, vm.Name);
}
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
void GenerateInitialize (StreamWriter sw)
{
sw.WriteLine ("\t\tstatic void Initialize (IntPtr ifaceptr, IntPtr data)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\t" + IfaceName + " native_iface = (" + IfaceName + ") Marshal.PtrToStructure (ifaceptr, typeof (" + IfaceName + "));");
foreach (VirtualMethod vm in vms)
sw.WriteLine ("\t\t\tnative_iface." + vm.CName + " = iface." + vm.CName + ";");
sw.WriteLine ("\t\t\tMarshal.StructureToPtr (native_iface, ifaceptr, false);");
sw.WriteLine ("\t\t\tGCHandle gch = (GCHandle) data;");
sw.WriteLine ("\t\t\tgch.Free ();");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
void GenerateCallbacks (StreamWriter sw)
{
foreach (VirtualMethod vm in vms) {
if (methods [vm.Name] != null) {
sw.WriteLine ();
vm.GenerateCallback (sw);
}
}
}
void GenerateCtors (StreamWriter sw)
{
if (!IsConsumeOnly) {
sw.WriteLine ("\t\tpublic " + Name + "Adapter ()");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tInitHandler = new GLib.GInterfaceInitHandler (Initialize);");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\t{0}Implementor implementor;", Name);
sw.WriteLine ();
sw.WriteLine ("\t\tpublic {0}Adapter ({0}Implementor implementor)", Name);
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (implementor == null)");
sw.WriteLine ("\t\t\t\tthrow new ArgumentNullException (\"implementor\");");
sw.WriteLine ("\t\t\tthis.implementor = implementor;");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
sw.WriteLine ("\t\tpublic " + Name + "Adapter (IntPtr handle)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tthis.handle = handle;");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
void GenerateGType (StreamWriter sw)
{
Method m = GetMethod ("GetType");
m.GenerateImport (sw);
sw.WriteLine ("\t\tprivate static GLib.GType _gtype = new GLib.GType ({0} ());", m.CName);
sw.WriteLine ();
sw.WriteLine ("\t\tpublic override GLib.GType GType {");
sw.WriteLine ("\t\t\tget {");
sw.WriteLine ("\t\t\t\treturn _gtype;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
void GenerateHandleProp (StreamWriter sw)
{
sw.WriteLine ("\t\tIntPtr handle;");
sw.WriteLine ("\t\tpublic override IntPtr Handle {");
sw.WriteLine ("\t\t\tget {");
if (IsConsumeOnly) {
sw.WriteLine ("\t\t\t\treturn handle;");
} else {
sw.WriteLine ("\t\t\t\tif (handle != IntPtr.Zero)");
sw.WriteLine ("\t\t\t\t\treturn handle;");
sw.WriteLine ("\t\t\t\treturn implementor == null ? IntPtr.Zero : implementor.Handle;");
}
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
void GenerateGetObject (StreamWriter sw)
{
sw.WriteLine ("\t\tpublic static " + Name + " GetObject (IntPtr handle, bool owned)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tGLib.Object obj = GLib.Object.GetObject (handle, owned);");
sw.WriteLine ("\t\t\treturn GetObject (obj);");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\tpublic static " + Name + " GetObject (GLib.Object obj)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (obj == null)");
sw.WriteLine ("\t\t\t\treturn null;");
if (!IsConsumeOnly) {
sw.WriteLine ("\t\t\telse if (obj is " + Name + "Implementor)");
sw.WriteLine ("\t\t\t\treturn new {0}Adapter (obj as {0}Implementor);", Name);
}
sw.WriteLine ("\t\t\telse if (obj as " + Name + " == null)");
sw.WriteLine ("\t\t\t\treturn new {0}Adapter (obj.Handle);", Name);
sw.WriteLine ("\t\t\telse");
sw.WriteLine ("\t\t\t\treturn obj as {0};", Name);
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
void GenerateImplementorProp (StreamWriter sw)
{
sw.WriteLine ("\t\tpublic " + Name + "Implementor Implementor {");
sw.WriteLine ("\t\t\tget {");
sw.WriteLine ("\t\t\t\treturn implementor;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
void GenerateAdapter (GenerationInfo gen_info)
{
StreamWriter sw = gen_info.Writer = gen_info.OpenStream (Name + "Adapter");
sw.WriteLine ("namespace " + NS + " {");
sw.WriteLine ();
sw.WriteLine ("\tusing System;");
sw.WriteLine ("\tusing System.Runtime.InteropServices;");
sw.WriteLine ();
sw.WriteLine ("#region Autogenerated code");
sw.WriteLine ("\tpublic class " + Name + "Adapter : GLib.GInterfaceAdapter, " + QualifiedName + " {");
sw.WriteLine ();
if (!IsConsumeOnly) {
GenerateIfaceStruct (sw);
GenerateStaticCtor (sw);
GenerateCallbacks (sw);
GenerateInitialize (sw);
}
GenerateCtors (sw);
GenerateGType (sw);
GenerateHandleProp (sw);
GenerateGetObject (sw);
if (!IsConsumeOnly)
GenerateImplementorProp (sw);
GenProperties (gen_info, null);
foreach (Signal sig in sigs.Values)
sig.GenEvent (sw, null, "GLib.Object.GetObject (Handle)");
Method temp = methods ["GetType"] as Method;
if (temp != null)
methods.Remove ("GetType");
GenMethods (gen_info, new Hashtable (), this);
if (temp != null)
methods ["GetType"] = temp;
sw.WriteLine ("#endregion");
string custom = Path.Combine (gen_info.CustomDir, Name + "Adapter.custom");
if (File.Exists (custom)) {
sw.WriteLine ("#region Customized extensions");
sw.WriteLine ("#line 1 \"" + Name + "Adapter.custom\"");
using (StreamReader sr = new StreamReader(new FileStream (custom, FileMode.Open, FileAccess.Read)))
sw.WriteLine (sr.ReadToEnd ());
sw.WriteLine ("#endregion");
}
sw.WriteLine ("\t}");
sw.WriteLine ("}");
sw.Close ();
gen_info.Writer = null;
}
void GenerateImplementorIface (StreamWriter sw)
{
if (IsConsumeOnly)
return;
sw.WriteLine ();
sw.WriteLine ("\t[GLib.GInterface (typeof (" + Name + "Adapter))]");
string access = IsInternal ? "internal" : "public";
sw.WriteLine ("\t" + access + " interface " + Name + "Implementor : GLib.IWrapper {");
sw.WriteLine ();
Hashtable vm_table = new Hashtable ();
foreach (VirtualMethod vm in vms)
vm_table [vm.Name] = vm;
foreach (VirtualMethod vm in vms) {
if (vm_table [vm.Name] == null)
continue;
else if (!vm.IsValid) {
vm_table.Remove (vm.Name);
continue;
} else if (vm.IsGetter || vm.IsSetter) {
string cmp_name = (vm.IsGetter ? "Set" : "Get") + vm.Name.Substring (3);
VirtualMethod cmp = vm_table [cmp_name] as VirtualMethod;
if (cmp != null && (cmp.IsGetter || cmp.IsSetter)) {
if (vm.IsSetter)
cmp.GenerateDeclaration (sw, vm);
else
vm.GenerateDeclaration (sw, cmp);
vm_table.Remove (cmp.Name);
} else
vm.GenerateDeclaration (sw, null);
vm_table.Remove (vm.Name);
} else {
vm.GenerateDeclaration (sw, null);
vm_table.Remove (vm.Name);
}
}
sw.WriteLine ("\t}");
}
public override void Generate (GenerationInfo gen_info)
{
GenerateAdapter (gen_info);
StreamWriter sw = gen_info.Writer = gen_info.OpenStream (Name);
sw.WriteLine ("namespace " + NS + " {");
sw.WriteLine ();
sw.WriteLine ("\tusing System;");
sw.WriteLine ();
sw.WriteLine ("#region Autogenerated code");
string access = IsInternal ? "internal" : "public";
sw.WriteLine ("\t" + access + " interface " + Name + " : GLib.IWrapper {");
sw.WriteLine ();
foreach (Signal sig in sigs.Values) {
sig.GenerateDecl (sw);
sig.GenEventHandler (gen_info);
}
foreach (Method method in methods.Values) {
if (IgnoreMethod (method, this))
continue;
method.GenerateDecl (sw);
}
foreach (Property prop in props.Values)
prop.GenerateDecl (sw, "\t\t");
AppendCustom (sw, gen_info.CustomDir);
sw.WriteLine ("\t}");
GenerateImplementorIface (sw);
sw.WriteLine ("#endregion");
sw.WriteLine ("}");
sw.Close ();
gen_info.Writer = null;
Statistics.IFaceCount++;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation;
namespace System.Management.Automation
{
/// <summary>
/// Holds the state of a Monad Shell session.
/// </summary>
internal sealed partial class SessionStateInternal
{
#region aliases
/// <summary>
/// Add a new alias entry to this session state object...
/// </summary>
/// <param name="entry">The entry to add.</param>
/// <param name="scopeID">
/// A scope identifier that is either one of the "special" scopes like
/// "global", "script", "local", or "private, or a numeric ID of a relative scope
/// to the current scope.
/// </param>
internal void AddSessionStateEntry(SessionStateAliasEntry entry, string scopeID)
{
AliasInfo alias = new AliasInfo(entry.Name, entry.Definition, this.ExecutionContext, entry.Options)
{
Visibility = entry.Visibility,
Module = entry.Module,
Description = entry.Description
};
// Create alias in the global scope...
this.SetAliasItemAtScope(alias, scopeID, true, CommandOrigin.Internal);
}
/// <summary>
/// Gets an IEnumerable for the alias table.
/// </summary>
internal IDictionary<string, AliasInfo> GetAliasTable()
{
// On 7.0 version we have 132 aliases so we set a larger number to reduce re-allocations.
const int InitialAliasCount = 150;
Dictionary<string, AliasInfo> result =
new Dictionary<string, AliasInfo>(InitialAliasCount, StringComparer.OrdinalIgnoreCase);
SessionStateScopeEnumerator scopeEnumerator =
new SessionStateScopeEnumerator(_currentScope);
foreach (SessionStateScope scope in scopeEnumerator)
{
foreach (AliasInfo entry in scope.AliasTable)
{
if (!result.ContainsKey(entry.Name))
{
// Make sure the alias isn't private or if it is that the current
// scope is the same scope the alias was retrieved from.
if ((entry.Options & ScopedItemOptions.Private) == 0 ||
scope == _currentScope)
{
result.Add(entry.Name, entry);
}
}
}
}
return result;
}
/// <summary>
/// Gets an IEnumerable for the alias table for a given scope.
/// </summary>
/// <param name="scopeID">
/// A scope identifier that is either one of the "special" scopes like
/// "global", "script", "local", or "private, or a numeric ID of a relative scope
/// to the current scope.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="scopeID"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
internal IDictionary<string, AliasInfo> GetAliasTableAtScope(string scopeID)
{
Dictionary<string, AliasInfo> result =
new Dictionary<string, AliasInfo>(StringComparer.OrdinalIgnoreCase);
SessionStateScope scope = GetScopeByID(scopeID);
foreach (AliasInfo entry in scope.AliasTable)
{
// Make sure the alias isn't private or if it is that the current
// scope is the same scope the alias was retrieved from.
if ((entry.Options & ScopedItemOptions.Private) == 0 ||
scope == _currentScope)
{
result.Add(entry.Name, entry);
}
}
return result;
}
/// <summary>
/// List of aliases to export from this session state object...
/// </summary>
internal List<AliasInfo> ExportedAliases { get; } = new List<AliasInfo>();
/// <summary>
/// Gets the value of the specified alias from the alias table.
/// </summary>
/// <param name="aliasName">
/// The name of the alias value to retrieve.
/// </param>
/// <param name="origin">
/// The origin of the command calling this API.
/// </param>
/// <returns>
/// The AliasInfo representing the alias.
/// </returns>
internal AliasInfo GetAlias(string aliasName, CommandOrigin origin)
{
AliasInfo result = null;
if (string.IsNullOrEmpty(aliasName))
{
return null;
}
// Use the scope enumerator to find the alias using the
// appropriate scoping rules
SessionStateScopeEnumerator scopeEnumerator =
new SessionStateScopeEnumerator(_currentScope);
foreach (SessionStateScope scope in scopeEnumerator)
{
result = scope.GetAlias(aliasName);
if (result != null)
{
// Now check the visibility of the variable...
SessionState.ThrowIfNotVisible(origin, result);
// Make sure the alias isn't private or if it is that the current
// scope is the same scope the alias was retrieved from.
if ((result.Options & ScopedItemOptions.Private) != 0 &&
scope != _currentScope)
{
result = null;
}
else
{
break;
}
}
}
return result;
}
/// <summary>
/// Gets the value of the specified alias from the alias table.
/// </summary>
/// <param name="aliasName">
/// The name of the alias value to retrieve.
/// </param>
/// <returns>
/// The AliasInfo representing the alias.
/// </returns>
internal AliasInfo GetAlias(string aliasName)
{
return GetAlias(aliasName, CommandOrigin.Internal);
}
/// <summary>
/// Gets the value of the specified alias from the alias table.
/// </summary>
/// <param name="aliasName">
/// The name of the alias value to retrieve.
/// </param>
/// <param name="scopeID">
/// A scope identifier that is either one of the "special" scopes like
/// "global", "script", "local", or "private, or a numeric ID of a relative scope
/// to the current scope.
/// </param>
/// <returns>
/// The AliasInfo representing the alias.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="scopeID"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
internal AliasInfo GetAliasAtScope(string aliasName, string scopeID)
{
AliasInfo result = null;
if (string.IsNullOrEmpty(aliasName))
{
return null;
}
SessionStateScope scope = GetScopeByID(scopeID);
result = scope.GetAlias(aliasName);
// Make sure the alias isn't private or if it is that the current
// scope is the same scope the alias was retrieved from.
if (result != null &&
(result.Options & ScopedItemOptions.Private) != 0 &&
scope != _currentScope)
{
result = null;
}
return result;
}
/// <summary>
/// Sets the alias with specified name to the specified value in the current scope.
/// </summary>
/// <param name="aliasName">
/// The name of the alias to set.
/// </param>
/// <param name="value">
/// The value to set the alias to.
/// </param>
/// <param name="force">
/// If true, the value will be set even if the alias is ReadOnly.
/// </param>
/// <param name="origin">
/// THe origin of the caller of this API
/// </param>
/// <returns>
/// The resulting AliasInfo for the alias that was set.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="aliasName"/> or <paramref name="value"/> is null or empty.
/// </exception>
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the alias is read-only or constant.
/// </exception>
internal AliasInfo SetAliasValue(string aliasName, string value, bool force, CommandOrigin origin)
{
if (string.IsNullOrEmpty(aliasName))
{
throw PSTraceSource.NewArgumentException(nameof(aliasName));
}
if (string.IsNullOrEmpty(value))
{
throw PSTraceSource.NewArgumentException(nameof(value));
}
AliasInfo info = _currentScope.SetAliasValue(aliasName, value, this.ExecutionContext, force, origin);
return info;
}
/// <summary>
/// Sets the alias with specified name to the specified value in the current scope.
/// BUGBUG: this overload only exists for the test suites. They should be cleaned up
/// and this overload removed.
/// </summary>
/// <param name="aliasName">
/// The name of the alias to set.
/// </param>
/// <param name="value">
/// The value to set the alias to.
/// </param>
/// <param name="force">
/// If true, the value will be set even if the alias is ReadOnly.
/// </param>
/// <returns>
/// The resulting AliasInfo for the alias that was set.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="aliasName"/> or <paramref name="value"/> is null or empty.
/// </exception>
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the alias is read-only or constant.
/// </exception>
internal AliasInfo SetAliasValue(string aliasName, string value, bool force)
{
return SetAliasValue(aliasName, value, force, CommandOrigin.Internal);
}
/// <summary>
/// Sets the alias with specified name to the specified value in the current scope.
/// </summary>
/// <param name="aliasName">
/// The name of the alias to set.
/// </param>
/// <param name="value">
/// The value to set the alias to.
/// </param>
/// <param name="options">
/// The options to set on the alias.
/// </param>
/// <param name="force">
/// If true, the value will be set even if the alias is ReadOnly.
/// </param>
/// <param name="origin">
/// The origin of the caller of this API
/// </param>
/// <returns>
/// The resulting AliasInfo for the alias that was set.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="aliasName"/> or <paramref name="value"/> is null or empty.
/// </exception>
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the alias is read-only or constant.
/// </exception>
internal AliasInfo SetAliasValue(
string aliasName,
string value,
ScopedItemOptions options,
bool force,
CommandOrigin origin)
{
if (string.IsNullOrEmpty(aliasName))
{
throw PSTraceSource.NewArgumentException(nameof(aliasName));
}
if (string.IsNullOrEmpty(value))
{
throw PSTraceSource.NewArgumentException(nameof(value));
}
AliasInfo info = _currentScope.SetAliasValue(aliasName, value, options, this.ExecutionContext, force, origin);
return info;
}
/// <summary>
/// Sets the alias with specified name to the specified value in the current scope.
/// BUGBUG: this api only exists for the test suites. They should be fixed and it should be removed.
/// </summary>
/// <param name="aliasName">
/// The name of the alias to set.
/// </param>
/// <param name="value">
/// The value to set the alias to.
/// </param>
/// <param name="options">
/// The options to set on the alias.
/// </param>
/// <param name="force">
/// If true, the value will be set even if the alias is ReadOnly.
/// </param>
/// <returns>
/// The resulting AliasInfo for the alias that was set.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="aliasName"/> or <paramref name="value"/> is null or empty.
/// </exception>
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the alias is read-only or constant.
/// </exception>
internal AliasInfo SetAliasValue(
string aliasName,
string value,
ScopedItemOptions options,
bool force)
{
return SetAliasValue(aliasName, value, options, force, CommandOrigin.Internal);
}
/// <summary>
/// Sets the alias with specified name to the specified value in the current scope.
/// </summary>
/// <param name="alias">
/// The AliasInfo representing the alias.
/// </param>
/// <param name="force">
/// If true, the alias will be set even if there is an existing ReadOnly
/// alias.
/// </param>
/// <param name="origin">
/// Specifies the origin of the command setting the alias.
/// </param>
/// <returns>
/// The resulting AliasInfo for the alias that was set.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="alias"/> is null.
/// </exception>
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the alias is read-only or constant.
/// </exception>
internal AliasInfo SetAliasItem(AliasInfo alias, bool force, CommandOrigin origin)
{
if (alias == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(alias));
}
AliasInfo info = _currentScope.SetAliasItem(alias, force, origin);
return info;
}
/// <summary>
/// Sets the alias with specified name to the specified value in the current scope.
/// </summary>
/// <param name="alias">
/// The AliasInfo representing the alias.
/// </param>
/// <param name="scopeID">
/// A scope identifier that is either one of the "special" scopes like
/// "global", "script", "local", or "private, or a numeric ID of a relative scope
/// to the current scope.
/// </param>
/// <param name="force">
/// If true, the alias will be set even if there is an existing ReadOnly
/// alias.
/// </param>
/// <param name="origin">
/// Specifies the command origin of the calling command.
/// </param>
/// <returns>
/// The resulting AliasInfo for the alias that was set.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="scopeID"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If <paramref name="alias"/> is null.
/// </exception>
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the alias is read-only or constant.
/// </exception>
internal AliasInfo SetAliasItemAtScope(AliasInfo alias, string scopeID, bool force, CommandOrigin origin)
{
if (alias == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(alias));
}
// If the "private" scope was specified, make sure the options contain
// the Private flag
if (string.Equals(scopeID, StringLiterals.Private, StringComparison.OrdinalIgnoreCase))
{
alias.Options |= ScopedItemOptions.Private;
}
SessionStateScope scope = GetScopeByID(scopeID);
AliasInfo info = scope.SetAliasItem(alias, force, origin);
return info;
}
/// <summary>
/// Sets the alias with specified name to the specified value in the current scope.
/// </summary>
/// <param name="alias">
/// The AliasInfo representing the alias.
/// </param>
/// <param name="scopeID">
/// A scope identifier that is either one of the "special" scopes like
/// "global", "script", "local", or "private, or a numeric ID of a relative scope
/// to the current scope.
/// </param>
/// <param name="force">
/// If true, the alias will be set even if there is an existing ReadOnly
/// alias.
/// </param>
/// <returns>
/// The resulting AliasInfo for the alias that was set.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="scopeID"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If <paramref name="alias"/> is null.
/// </exception>
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the alias is read-only or constant.
/// </exception>
internal AliasInfo SetAliasItemAtScope(AliasInfo alias, string scopeID, bool force)
{
return SetAliasItemAtScope(alias, scopeID, force, CommandOrigin.Internal);
}
/// <summary>
/// Removes the specified alias.
/// </summary>
/// <param name="aliasName">
/// The name of the alias to remove.
/// </param>
/// <param name="force">
/// If true the alias will be removed even if its ReadOnly.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="aliasName"/> is null or empty.
/// </exception>
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the alias is constant.
/// </exception>
internal void RemoveAlias(string aliasName, bool force)
{
if (string.IsNullOrEmpty(aliasName))
{
throw PSTraceSource.NewArgumentException(nameof(aliasName));
}
// Use the scope enumerator to find an existing function
SessionStateScopeEnumerator scopeEnumerator =
new SessionStateScopeEnumerator(_currentScope);
foreach (SessionStateScope scope in scopeEnumerator)
{
AliasInfo alias =
scope.GetAlias(aliasName);
if (alias != null)
{
// Make sure the alias isn't private or if it is that the current
// scope is the same scope the alias was retrieved from.
if ((alias.Options & ScopedItemOptions.Private) != 0 &&
scope != _currentScope)
{
alias = null;
}
else
{
scope.RemoveAlias(aliasName, force);
break;
}
}
}
}
/// <summary>
/// Gets the aliases by command name (used by metadata-driven help)
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
internal IEnumerable<string> GetAliasesByCommandName(string command)
{
SessionStateScopeEnumerator scopeEnumerator =
new SessionStateScopeEnumerator(_currentScope);
foreach (SessionStateScope scope in scopeEnumerator)
{
foreach (string alias in scope.GetAliasesByCommandName(command))
{
yield return alias;
}
}
yield break;
}
#endregion aliases
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public static class RVOExtensions {
public static Vector3 XY(this RVO.Vector2 _this) {
return new Vector3(_this.x(), _this.y(), 0);
}
public static Vector3 XZ(this RVO.Vector2 _this) {
return new Vector3(_this.x(), 0, _this.y());
}
public static RVO.Vector2 XY(this Vector3 _this) {
return new RVO.Vector2(_this.x, _this.y);
}
public static RVO.Vector2 XZ(this Vector3 _this) {
return new RVO.Vector2(_this.x, _this.z);
}
public static Vector3 SafeNormalized(this RVO.Vector2 _this) {
float magSqrd = _this.x() * _this.x() + _this.y() * _this.y();
if (magSqrd > 0.0001f) {
var mag = Mathf.Sqrt(magSqrd);
return new Vector3(_this.x() / mag, 0, _this.y() / mag);
}
return Vector3.zero;
}
}
public class RVOUnityMgr : MonoBehaviour {
public Dictionary<string, RVOUnityInstance> m_instances = new Dictionary<string, RVOUnityInstance>();
void Update() {
foreach (var i in m_instances) {
i.Value.Step();
}
}
//====
public static RVOUnityMgr Me;
public static void CheckMe() {
if (Me == null) {
var go = new GameObject("RVOMgr");
Me = go.AddComponent<RVOUnityMgr>();
}
}
public static RVOUnityInstance GetInstance(string _name) {
CheckMe();
if (_name == null) _name = "";
RVOUnityInstance rc;
if (!Me.m_instances.TryGetValue(_name, out rc)) {
rc = new RVOUnityInstance(_name);
Me.m_instances[_name] = rc;
}
return rc;
}
public static bool InstanceExists(string _name) {
CheckMe();
if (_name == null) _name = "";
return Me.m_instances.ContainsKey(_name);
}
}
public class RVOUnityInstance {
public class RVOObstacle {
static List<RVO.Vector2> s_verts = new List<RVO.Vector2>();
public Vector3 m_position;
public Vector3 m_extents;
public RVOObstacle(Vector3 _pos, Vector3 _extents) {
m_position = _pos;
m_extents = _extents;
}
public Vector3 Corner(int _c) {
switch (_c) {
case 0:
return m_position - m_extents;
case 1:
return m_position + new Vector3(-m_extents.x, m_extents.y, m_extents.z);
case 2:
return m_position + m_extents;
case 3:
return m_position + new Vector3(m_extents.x, -m_extents.y, -m_extents.z);
}
return Vector3.zero;
}
public void Add(RVO.Simulator _sim) {
s_verts.Clear();
for (int i = 0; i < 4; i ++)
s_verts.Add(Corner(i).XZ());
_sim.addObstacle(s_verts);
}
}
//=================
public string m_name;
public Vector3 m_side = Vector3.right;
public Vector3 m_fwd = Vector3.forward; // defaults to XY
public RVO.Simulator m_instance = new RVO.Simulator();
public List<RVOUnity> m_agents = new List<RVOUnity>();
public List<int> m_removes = new List<int>();
public List<RVOObstacle> m_obstacles = new List<RVOObstacle>();
public bool m_forceRefresh = false;
public delegate bool CheckMoveFn(GameObject _who, Vector3 _from, ref Vector3 _to); // returns false if the move is illegal, can override the Up component of the _to vector
public CheckMoveFn m_checkMoveFn;
public RVOUnityInstance(string _name) {
m_name = _name;
Init();
}
float _neighbourDistance = 100.0f;
private int _maxNeighbours = 50;
private float _timeHorizon = 50.0f;//40.0f;
private float _timeHorizonObstacles = 1.0f;//40.0f;
private float _defaultRadius = 0.5f;
private float _maxSpeed = 30.0f;//5.0f;
public void Init() {
m_instance.setAgentDefaults(_neighbourDistance, _maxNeighbours, _timeHorizon,_timeHorizonObstacles, _defaultRadius, _maxSpeed, new RVO.Vector2());
}
public bool CheckMove(GameObject _go, Vector3 _from, ref Vector3 _to) {
if (m_checkMoveFn == null) return true;
return m_checkMoveFn(_go, _from, ref _to);
}
public void ExecuteRemoves() {
if (m_removes.Count > 0 || m_forceRefresh) {
if (m_removes.Count > 0) {
m_removes.Sort();
for (int i = m_removes.Count-1; i >= 0; i --)
m_agents.RemoveAt(m_removes[i]);
m_removes.Clear();
}
m_instance.Clear();
Init();
for (int i = 0; i < m_obstacles.Count; i ++)
m_obstacles[i].Add(m_instance);
m_instance.processObstacles();
for (int i = 0; i < m_agents.Count; i ++) {
m_agents[i].Add();
if (m_agents[i].Id != i)
Debug.LogErrorFormat("RVO instance mismatch [rebuild] {0} {1}", i, m_agents[i].Id);
}
}
}
public Vector3 GetAgentPosition(int _id) {
var pos = m_instance.getAgentPosition(_id);
return pos.x() * m_side + pos.y() * m_fwd;
}
public void SetAgentPosition(int _id, Vector3 _pos) {
m_instance.setAgentPosition(_id, new RVO.Vector2(Vector3.Dot(_pos, m_side), Vector3.Dot(_pos, m_fwd)));
}
public float DistanceSquaredInPlane(Vector3 _a, Vector3 _b) {
Vector3 d = _b - _a;
float side = Vector3.Dot(d, m_side), fwd = Vector3.Dot(d, m_fwd);
return side*side + fwd*fwd;
}
public void SetCheckMoveFn(CheckMoveFn _fn) {
m_checkMoveFn = _fn;
}
float m_nextTimeStep = 1.0f/30.0f;
public float NextTimeStep { get { return m_nextTimeStep; } }
public void Step() {
m_nextTimeStep = Mathf.Clamp(Time.deltaTime, 1.0f/100.0f, 1.0f/15.0f);
ExecuteRemoves();
foreach (var i in m_agents)
i.PreUpdate ();
m_instance.setTimeStep(m_nextTimeStep);
m_instance.doStepST();
foreach (var i in m_agents)
i.Sync();
}
}
[DisallowMultipleComponent]
public class RVOUnity : MonoBehaviour {
public static Color s_gizmoColour = new Color(0.7f, 0.8f, 1.0f, 0.75f);
public static void SetupSim(string _instanceName, Vector3 _side, Vector3 _fwd) {
var inst = RVOUnityMgr.GetInstance(_instanceName);
inst.m_side = _side;
inst.m_fwd = _fwd;
}
public static void SetSimDefaults(string _instanceName, float _neighbourDistance, int _maxNeighbours, float _defaultRadius, float _maxSpeed) {
var inst = RVOUnityMgr.GetInstance(_instanceName);
inst.m_instance.setAgentDefaults(_neighbourDistance, _maxNeighbours, 10.0f,10.0f, _defaultRadius, _maxSpeed, new RVO.Vector2());
}
public static void SetMoveCheck(string _instanceName, RVOUnityInstance.CheckMoveFn _fn) {
var inst = RVOUnityMgr.GetInstance(_instanceName);
inst.SetCheckMoveFn(_fn);
}
public static void AddAgent(GameObject _go, string _instance = "", float _radius = -1, bool _static = false) {
var rvo = _go.AddComponent<RVOUnity>();
rvo.SetInstance(_instance);
rvo.SetStatic(_static);
if (_radius != -1)
rvo.SetRadius(_radius);
}
public static bool InstanceExists(string _instanceName) {
return RVOUnityMgr.InstanceExists(_instanceName);
}
public static int NumObstacles(string _instanceName) {
var inst = RVOUnityMgr.GetInstance(_instanceName);
return inst.m_obstacles.Count;
}
public static void AddObstacle(string _instanceName, Vector3 _pos, Vector3 _extents) {
var inst = RVOUnityMgr.GetInstance(_instanceName);
inst.m_obstacles.Add(new RVOUnityInstance.RVOObstacle(_pos, _extents));
inst.m_forceRefresh = true;
}
private RVOUnityInstance m_instance;
public Vector3 m_pos;
private Vector3 m_expectedDirection;
public string m_instanceName;
public float m_radius;
public bool m_static;
public bool m_drawGizmos;
private int m_id;
private bool m_lastMoveSuccessful;
private WNS_AnimationControllerScript m_animationScript;
private MovementScript m_WNSScript;
public int Id { get { return m_id; } }
void Start() {
Add();
if (m_id != m_instance.m_agents.Count)
Debug.LogErrorFormat("RVO instance mismatch {0} {1}", m_instance.m_agents.Count, m_id);
m_instance.m_agents.Add(this);
m_animationScript = gameObject.GetComponent<WNS_AnimationControllerScript> ();
m_WNSScript = gameObject.GetComponent<MovementScript> ();
m_pos = m_instance.GetAgentPosition (m_id);
}
public void Add() {
if (m_instance == null) {
m_instance = RVOUnityMgr.GetInstance(m_instanceName);
}
m_id = m_instance.m_instance.addAgent(transform.position.XZ());
if (m_radius != 0)
m_instance.m_instance.setAgentRadius(m_id, m_radius);
ClearVelocity();
}
public static Vector3 RotateVectorAboutVector(Vector3 _v, Vector3 _axis, float _radians) {
float cos = Mathf.Cos(_radians), sin = Mathf.Sin(_radians);
return _v * cos + Vector3.Cross(_axis, _v) * sin + _axis * (Vector3.Dot(_axis, _v) * (1-cos));
}
public static RVO.Vector2 RotateVector(RVO.Vector2 _v, float _radians) {
float cos = Mathf.Cos(_radians), sin = Mathf.Sin(_radians);
return _v * cos + new RVO.Vector2(_v.y(), -_v.x()) * sin;
}
public void UpdatePosition() {
if (m_radius != m_instance.m_instance.getAgentRadius (m_id))
m_instance.m_instance.setAgentRadius (m_id, m_radius);
var newPos = transform.position.XZ();
var oldPos = m_instance.GetAgentPosition(m_id).XZ();
var velocity = (newPos - oldPos) / m_instance.NextTimeStep;
float randomness = 0;//0.3f;
float smoothness = 0.9f;
float theta = UnityEngine.Random.Range(-1.0f, 1.0f) * randomness;
velocity = RotateVector(velocity, theta);
var smoothVelocity = m_instance.m_instance.getAgentVelocity(m_id) * smoothness + velocity * (1-smoothness);
m_instance.m_instance.setAgentVelocity (m_id, smoothVelocity);
m_instance.m_instance.setAgentPrefVelocity (m_id, velocity);
m_expectedDirection = velocity.SafeNormalized();
}
public void PreUpdate() {
UpdatePosition ();
}
void ClearVelocity() {
m_instance.m_instance.setAgentVelocity(m_id, new RVO.Vector2());
m_instance.m_instance.setAgentPrefVelocity(m_id, new RVO.Vector2());
}
float GetAngleBetweenVectors(Vector3 first, Vector3 second)
{
float dot = Vector3.Dot (first, second) / (first.magnitude * second.magnitude);
var acos = Mathf.Acos(dot);
return(acos*180/Mathf.PI);
}
private Vector3 m_goalDirection;
private Vector3 m_rvoDirection;
private float m_rvoAngle;
public void Sync() {
var pos = m_instance.GetAgentPosition(m_id);
pos.y = transform.position.y;
m_lastMoveSuccessful = !(m_static || !m_instance.CheckMove(gameObject, m_pos, ref pos) || float.IsNaN(pos.sqrMagnitude));
if (!m_lastMoveSuccessful)
m_instance.SetAgentPosition(m_id, transform.position);
else {
m_goalDirection = GetDirectionFromOnePointToAnother(m_pos, pos);
m_rvoDirection = GetDirectionFromOnePointToAnother (m_pos,transform.position);
m_rvoAngle = Mathf.Abs (GetAngleBetweenVectors (m_goalDirection, m_rvoDirection));
//UpdateImpatience_v2(m_rvoAngle);
if (GlobalScript.GetDistance (m_pos, pos) < 0.01f)
m_impatience += 0.01f;
else
m_impatience -= 0.01f;
m_impatience = Mathf.Clamp01 (m_impatience);
if (m_impatience > 0)
{
pos = transform.position * m_impatience + pos * (1-m_impatience);
m_instance.SetAgentPosition(m_id, pos);
}
//
// if (m_WNSScript)
// m_WNSScript.HandlePushBack (ref pos, m_pos);
//
// if (m_animationScript)
// m_animationScript.HandleSpeedChange (pos, transform.position, m_pos);
transform.position = pos;
m_instance.SetAgentPosition(m_id, pos);
}
m_pos = m_instance.GetAgentPosition(m_id);
}
private float m_impatience;
//Mode
public enum ImpatienceMode { Disabled, Light, Medium, Strong};
public ImpatienceMode m_impatienceMode;
private float m_rvoDisposition;
private float m_rvoDispOverflow;
private float m_impAngle_Threshold;
private float m_impAngle_SmallThreshold = 90;
private float m_impAngle_HighThreshold = 120f;
private float m_impAngle_Coeff;
private float m_impAngle_SmallCoeff = 0.00005f;
private float m_impAngle_HighCoeff = 0.0001f;
void UpdateImpatience_v2(float angle)
{
if (m_impatienceMode != ImpatienceMode.Disabled)
{
if (m_impatience < 0.3f)
{
m_impAngle_Coeff = m_impAngle_SmallCoeff;
m_impAngle_Threshold = m_impAngle_SmallThreshold;
}
else
{
m_impAngle_Coeff = m_impAngle_HighCoeff;
m_impAngle_Threshold = m_impAngle_HighThreshold;
}
m_rvoDispOverflow = angle - m_impAngle_Threshold;
m_impatience += m_impAngle_Coeff * m_rvoDispOverflow;
m_impatience = Mathf.Max (m_impatience, 0);
m_impatience = Mathf.Min (m_impatience, 1);
}
}
void OnDestroy() {
if (m_instance != null)
{
m_instance.m_removes.Add (m_id);
m_id = -1;
}
}
public RVOUnity SetImpatience(float _imp) {
m_impatience = _imp;
return this;
}
public RVOUnity SetRadius(float _rad) {
m_radius = _rad;
if (m_id != -1)
m_instance.m_instance.setAgentRadius(m_id, m_radius);
return this;
}
public RVOUnity SetStatic(bool _static) {
m_static = _static;
return this;
}
public RVOUnity SetInstance(string _instanceName) {
m_instanceName = _instanceName;
return this;
}
#if UNITY_EDITOR
void OnDrawGizmos() {
if (m_drawGizmos)
{
if (m_id == -1 || m_instance == null)
return;
if (m_id == 0)
{
Gizmos.color = Color.black;
foreach (var o in m_instance.m_obstacles)
{
Gizmos.DrawSphere (o.m_position, 0.15f);
for (int i = 0; i < 4; i++)
{
Gizmos.DrawSphere (o.Corner (i), 0.05f);
Gizmos.DrawLine (o.Corner (i), o.Corner ((i + 1) & 3));
}
}
}
var pos = m_instance.m_instance.getAgentPosition (m_id).XZ ();
pos.y = transform.position.y;
var rad = m_instance.m_instance.getAgentRadius (m_id);
var imp = m_impatience;
var clr = s_gizmoColour;
clr.g *= Mathf.Max (0, 1 - imp * 10);
clr.b *= 1 - imp;
Gizmos.color = clr;
Gizmos.DrawSphere (pos, rad);
Gizmos.color = Color.red;
Gizmos.DrawLine (pos, pos + m_instance.m_instance.getAgentVelocity (m_id).XZ ());
Gizmos.color = Color.yellow;
Gizmos.DrawLine (pos, pos + m_instance.m_instance.getAgentPrefVelocity (m_id).XZ ());
Gizmos.color = m_static ? Color.red : (m_lastMoveSuccessful ? Color.green : Color.blue);
Gizmos.DrawSphere (pos, rad * 0.1f);
}
}
#endif
//Nick's addition
static float GetDistanceBetweenPoints(Vector3 p1, Vector3 p2){
Vector2 diff = p2 - p1;
diff.y = 0;
return (p2 - p1).magnitude;
}
Vector3 GetDirectionFromOnePointToAnother(Vector3 from, Vector3 to)
{
Vector3 result = (to - from).normalized;
result.y = 0;
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:
** This class is used to represent a Dynamic TimeZone. It
** has methods for converting a DateTime between TimeZones
**
**
============================================================*/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System
{
sealed public partial class TimeZoneInfo
{
// use for generating multi-year DST periods
private static readonly TransitionTime s_transition5_15 = TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1), 05, 15);
private static readonly TransitionTime s_transition7_15 = TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1), 07, 15);
private static readonly TransitionTime s_transition10_15 = TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1), 10, 15);
private static readonly TransitionTime s_transition12_15 = TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1), 12, 15);
private TimeZoneInfo(Byte[] data, Boolean dstDisabled)
{
TZifHead t;
DateTime[] dts;
Byte[] typeOfLocalTime;
TZifType[] transitionType;
String zoneAbbreviations;
Boolean[] StandardTime;
Boolean[] GmtTime;
// parse the raw TZif bytes; this method can throw ArgumentException when the data is malformed.
TZif_ParseRaw(data, out t, out dts, out typeOfLocalTime, out transitionType, out zoneAbbreviations, out StandardTime, out GmtTime);
_id = c_localId;
_displayName = c_localId;
_baseUtcOffset = TimeSpan.Zero;
// find the best matching baseUtcOffset and display strings based on the current utcNow value
DateTime utcNow = DateTime.UtcNow;
for (int i = 0; i < dts.Length && dts[i] <= utcNow; i++)
{
int type = typeOfLocalTime[i];
if (!transitionType[type].IsDst)
{
_baseUtcOffset = transitionType[type].UtcOffset;
_standardDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex);
}
else
{
_daylightDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex);
}
}
if (dts.Length == 0)
{
// time zones like Africa/Bujumbura and Etc/GMT* have no transition times but still contain
// TZifType entries that may contain a baseUtcOffset and display strings
for (int i = 0; i < transitionType.Length; i++)
{
if (!transitionType[i].IsDst)
{
_baseUtcOffset = transitionType[i].UtcOffset;
_standardDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex);
}
else
{
_daylightDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex);
}
}
}
_id = _standardDisplayName;
_displayName = _standardDisplayName;
// TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns
// with DateTimeOffset, SQL Server, and the W3C XML Specification
if (_baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
{
_baseUtcOffset = new TimeSpan(_baseUtcOffset.Hours, _baseUtcOffset.Minutes, 0);
}
if (!dstDisabled)
{
// only create the adjustment rule if DST is enabled
TZif_GenerateAdjustmentRules(out _adjustmentRules, dts, typeOfLocalTime, transitionType, StandardTime, GmtTime);
}
ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
}
// ---- SECTION: public methods --------------*
//
// GetAdjustmentRules -
//
// returns a cloned array of AdjustmentRule objects
//
public AdjustmentRule[] GetAdjustmentRules()
{
if (_adjustmentRules == null)
{
return Array.Empty<AdjustmentRule>();
}
// The rules we use in Unix cares mostly about the start and end dates but doesn't fill the transition start and end info.
// as the rules now is public, we should fill it properly so the caller doesn't have to know how we use it internally
// and can use it as it is used in Windows
AdjustmentRule[] rules = new AdjustmentRule[_adjustmentRules.Length];
for (int i = 0; i < _adjustmentRules.Length; i++)
{
var rule = _adjustmentRules[i];
var start = rule.DateStart.Kind == DateTimeKind.Utc ?
new DateTime(TimeZoneInfo.ConvertTime(rule.DateStart, this).Ticks, DateTimeKind.Unspecified) :
rule.DateStart;
var end = rule.DateEnd.Kind == DateTimeKind.Utc ?
new DateTime(TimeZoneInfo.ConvertTime(rule.DateEnd, this).Ticks - 1, DateTimeKind.Unspecified) :
rule.DateEnd;
var startTransition = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, start.Hour, start.Minute, start.Second), start.Month, start.Day);
var endTransition = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, end.Hour, end.Minute, end.Second), end.Month, end.Day);
rules[i] = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(start.Date, end.Date, rule.DaylightDelta, startTransition, endTransition);
}
return rules;
}
public static TimeZoneInfo FindSystemTimeZoneById(string id)
{
// UNIXTODO
throw new NotImplementedException();
}
private static void PopulateAllSystemTimeZones(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
// UNIXTODO
throw new NotImplementedException();
}
internal static Byte[] GetLocalTzFile()
{
// UNIXTODO
throw new NotImplementedException();
}
private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
{
Byte[] rawData = GetLocalTzFile();
if (rawData != null)
{
try
{
return new TimeZoneInfo(rawData, false); // create a TimeZoneInfo instance from the TZif data w/ DST support
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
try
{
return new TimeZoneInfo(rawData, true); // create a TimeZoneInfo instance from the TZif data w/o DST support
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
}
// the data returned from the PAL is completely bogus; return a dummy entry
return CreateCustomTimeZone(c_localId, TimeSpan.Zero, c_localId, c_localId);
}
// TZFILE(5) BSD File Formats Manual TZFILE(5)
//
// NAME
// tzfile -- timezone information
//
// SYNOPSIS
// #include "/usr/src/lib/libc/stdtime/tzfile.h"
//
// DESCRIPTION
// The time zone information files used by tzset(3) begin with the magic
// characters ``TZif'' to identify them as time zone information files, fol-
// lowed by sixteen bytes reserved for future use, followed by four four-
// byte values written in a ``standard'' byte order (the high-order byte of
// the value is written first). These values are, in order:
//
// tzh_ttisgmtcnt The number of UTC/local indicators stored in the file.
// tzh_ttisstdcnt The number of standard/wall indicators stored in the
// file.
// tzh_leapcnt The number of leap seconds for which data is stored in
// the file.
// tzh_timecnt The number of ``transition times'' for which data is
// stored in the file.
// tzh_typecnt The number of ``local time types'' for which data is
// stored in the file (must not be zero).
// tzh_charcnt The number of characters of ``time zone abbreviation
// strings'' stored in the file.
//
// The above header is followed by tzh_timecnt four-byte values of type
// long, sorted in ascending order. These values are written in ``stan-
// dard'' byte order. Each is used as a transition time (as returned by
// time(3)) at which the rules for computing local time change. Next come
// tzh_timecnt one-byte values of type unsigned char; each one tells which
// of the different types of ``local time'' types described in the file is
// associated with the same-indexed transition time. These values serve as
// indices into an array of ttinfo structures that appears next in the file;
// these structures are defined as follows:
//
// struct ttinfo {
// long tt_gmtoff;
// int tt_isdst;
// unsigned int tt_abbrind;
// };
//
// Each structure is written as a four-byte value for tt_gmtoff of type
// long, in a standard byte order, followed by a one-byte value for tt_isdst
// and a one-byte value for tt_abbrind. In each structure, tt_gmtoff gives
// the number of seconds to be added to UTC, tt_isdst tells whether t_isdst
// should be set by localtime(3) and tt_abbrind serves as an index into the
// array of time zone abbreviation characters that follow the ttinfo struc-
// ture(s) in the file.
//
// Then there are tzh_leapcnt pairs of four-byte values, written in standard
// byte order; the first value of each pair gives the time (as returned by
// time(3)) at which a leap second occurs; the second gives the total number
// of leap seconds to be applied after the given time. The pairs of values
// are sorted in ascending order by time.b
//
// Then there are tzh_ttisstdcnt standard/wall indicators, each stored as a
// one-byte value; they tell whether the transition times associated with
// local time types were specified as standard time or wall clock time, and
// are used when a time zone file is used in handling POSIX-style time zone
// environment variables.
//
// Finally there are tzh_ttisgmtcnt UTC/local indicators, each stored as a
// one-byte value; they tell whether the transition times associated with
// local time types were specified as UTC or local time, and are used when a
// time zone file is used in handling POSIX-style time zone environment
// variables.
//
// localtime uses the first standard-time ttinfo structure in the file (or
// simply the first ttinfo structure in the absence of a standard-time
// structure) if either tzh_timecnt is zero or the time argument is less
// than the first transition time recorded in the file.
//
// SEE ALSO
// ctime(3), time2posix(3), zic(8)
//
// BSD September 13, 1994 BSD
//
//
//
// TIME(3) BSD Library Functions Manual TIME(3)
//
// NAME
// time -- get time of day
//
// LIBRARY
// Standard C Library (libc, -lc)
//
// SYNOPSIS
// #include <time.h>
//
// time_t
// time(time_t *tloc);
//
// DESCRIPTION
// The time() function returns the value of time in seconds since 0 hours, 0
// minutes, 0 seconds, January 1, 1970, Coordinated Universal Time, without
// including leap seconds. If an error occurs, time() returns the value
// (time_t)-1.
//
// The return value is also stored in *tloc, provided that tloc is non-null.
//
// ERRORS
// The time() function may fail for any of the reasons described in
// gettimeofday(2).
//
// SEE ALSO
// gettimeofday(2), ctime(3)
//
// STANDARDS
// The time function conforms to IEEE Std 1003.1-2001 (``POSIX.1'').
//
// BUGS
// Neither ISO/IEC 9899:1999 (``ISO C99'') nor IEEE Std 1003.1-2001
// (``POSIX.1'') requires time() to set errno on failure; thus, it is impos-
// sible for an application to distinguish the valid time value -1 (repre-
// senting the last UTC second of 1969) from the error return value.
//
// Systems conforming to earlier versions of the C and POSIX standards
// (including older versions of FreeBSD) did not set *tloc in the error
// case.
//
// HISTORY
// A time() function appeared in Version 6 AT&T UNIX.
//
// BSD July 18, 2003 BSD
//
//
//
// TZif_CalculateTransitionTime -
//
// Example inputs:
// -----------------
// utc = 1918-03-31T10:00:00.0000000Z
// transitionType = {-08:00:00 DST=False, Index 4}
// standardTime = False
// gmtTime = False
//
private static TransitionTime TZif_CalculateTransitionTime(DateTime utc, TimeSpan offset,
TZifType transitionType, Boolean standardTime,
Boolean gmtTime, out DateTime ruleDate)
{
// convert from UTC to local clock time
Int64 ticks = utc.Ticks + offset.Ticks;
if (ticks > DateTime.MaxValue.Ticks)
{
utc = DateTime.MaxValue;
}
else if (ticks < DateTime.MinValue.Ticks)
{
utc = DateTime.MinValue;
}
else
{
utc = new DateTime(ticks);
}
DateTime timeOfDay = new DateTime(1, 1, 1, utc.Hour, utc.Minute, utc.Second, utc.Millisecond);
int month = utc.Month;
int day = utc.Day;
ruleDate = new DateTime(utc.Year, month, day);
// FUTURE: take standardTime/gmtTime into account
return TransitionTime.CreateFixedDateRule(timeOfDay, month, day);
}
private static void TZif_GenerateAdjustmentRules(out AdjustmentRule[] rules, DateTime[] dts, Byte[] typeOfLocalTime,
TZifType[] transitionType, Boolean[] StandardTime, Boolean[] GmtTime)
{
rules = null;
int index = 0;
List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
bool succeeded = true;
while (succeeded && index < dts.Length)
{
succeeded = TZif_GenerateAdjustmentRule(ref index, ref rulesList, dts, typeOfLocalTime, transitionType, StandardTime, GmtTime);
}
rules = rulesList.ToArray();
if (rules != null && rules.Length == 0)
{
rules = null;
}
}
private static bool TZif_GenerateAdjustmentRule(ref int startIndex, ref List<AdjustmentRule> rulesList, DateTime[] dts, Byte[] typeOfLocalTime,
TZifType[] transitionType, Boolean[] StandardTime, Boolean[] GmtTime)
{
int index = startIndex;
bool Dst = false;
int DstStartIndex = -1;
int DstEndIndex = -1;
DateTime startDate = DateTime.MinValue.Date;
DateTime endDate = DateTime.MaxValue.Date;
// find the next DST transition start time index
while (!Dst && index < typeOfLocalTime.Length)
{
int typeIndex = typeOfLocalTime[index];
if (typeIndex < transitionType.Length && transitionType[typeIndex].IsDst)
{
// found the next DST transition start time
Dst = true;
DstStartIndex = index;
}
else
{
index++;
}
}
// find the next DST transition end time index
while (Dst && index < typeOfLocalTime.Length)
{
int typeIndex = typeOfLocalTime[index];
if (typeIndex < transitionType.Length && !transitionType[typeIndex].IsDst)
{
// found the next DST transition end time
Dst = false;
DstEndIndex = index;
}
else
{
index++;
}
}
//
// construct the adjustment rule from the two indices
//
if (DstStartIndex >= 0)
{
DateTime startTransitionDate = dts[DstStartIndex];
DateTime endTransitionDate;
if (DstEndIndex == -1)
{
// we found a DST start but no DST end; in this case use the
// prior non-DST entry if it exists, else use the current entry for both start and end (e.g., zero daylightDelta)
if (DstStartIndex > 0)
{
DstEndIndex = DstStartIndex - 1;
}
else
{
DstEndIndex = DstStartIndex;
}
endTransitionDate = DateTime.MaxValue;
}
else
{
endTransitionDate = dts[DstEndIndex];
}
int dstStartTypeIndex = typeOfLocalTime[DstStartIndex];
int dstEndTypeIndex = typeOfLocalTime[DstEndIndex];
TimeSpan daylightBias = transitionType[dstStartTypeIndex].UtcOffset - transitionType[dstEndTypeIndex].UtcOffset;
// TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns
// with DateTimeOffset, SQL Server, and the W3C XML Specification
if (daylightBias.Ticks % TimeSpan.TicksPerMinute != 0)
{
daylightBias = new TimeSpan(daylightBias.Hours, daylightBias.Minutes, 0);
}
//
// the normal case is less than 12 months between transition times. However places like America/Catamarca
// have DST from 1946-1963 straight without a gap. In that case we need to create a series of Adjustment
// Rules to fudge the multi-year DST period
//
if ((endTransitionDate - startTransitionDate).Ticks <= TimeSpan.TicksPerDay * 364)
{
TransitionTime dstStart;
TransitionTime dstEnd;
TimeSpan startTransitionOffset = (DstStartIndex > 0 ? transitionType[typeOfLocalTime[DstStartIndex - 1]].UtcOffset : transitionType[dstEndTypeIndex].UtcOffset);
TimeSpan endTransitionOffset = (DstEndIndex > 0 ? transitionType[typeOfLocalTime[DstEndIndex - 1]].UtcOffset : transitionType[dstStartTypeIndex].UtcOffset);
dstStart = TZif_CalculateTransitionTime(startTransitionDate,
startTransitionOffset,
transitionType[dstStartTypeIndex],
StandardTime[dstStartTypeIndex],
GmtTime[dstStartTypeIndex],
out startDate);
dstEnd = TZif_CalculateTransitionTime(endTransitionDate,
endTransitionOffset,
transitionType[dstEndTypeIndex],
StandardTime[dstEndTypeIndex],
GmtTime[dstEndTypeIndex],
out endDate);
// calculate the AdjustmentRule end date
if (DstStartIndex >= DstEndIndex)
{
// we found a DST start but no DST end
endDate = DateTime.MaxValue.Date;
}
AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(startDate, endDate, daylightBias, dstStart, dstEnd);
rulesList.Add(r);
}
else
{
// create the multi-year DST rule series:
//
// For example America/Catamarca:
// 1946-10-01T04:00:00.0000000Z {-03:00:00 DST=True}
// 1963-10-01T03:00:00.0000000Z {-04:00:00 DST=False}
//
// gets converted into a series of overlapping 5/7month adjustment rules:
//
// [AdjustmentRule #0] // start rule
// [1946/09/31 - 1947/06/15] // * starts 1 day prior to startTransitionDate
// [start: 10/01 @4:00 ] // * N months long, stopping at month 6 or 11
// [end : 07/15 ] // notice how the _end_ is outside the range
//
// [AdjustmentRule #1] // middle-year all-DST rule
// [1947/06/16 - 1947/11/15] // * starts 1 day after last day in previous rule
// [start: 05/15 ] // * 5 months long, stopping at month 6 or 11
// [end : 12/15 ] // notice how the _start and end_ are outside the range
//
// [AdjustmentRule #2] // middle-year all-DST rule
// [1947/11/16 - 1947/06/15] // * starts 1 day after last day in previous rule
// [start: 10/01 ] // * 7 months long, stopping at month 6 or 11
// [end : 07/15 ] // notice how the _start and end_ are outside the range
//
// .........................
//
// [AdjustmentRule #N] // end rule
// [1963/06/16 - 1946/10/02] // * starts 1 day after last day in previous rule
// [start: 05/15 ] // * N months long, stopping 1 day after endTransitionDate
// [end : 10/01 ] // notice how the _start_ is outside the range
//
// create the first rule from N to either 06/15 or 11/15
TZif_CreateFirstMultiYearRule(ref rulesList, daylightBias, startTransitionDate, DstStartIndex, dstStartTypeIndex, dstEndTypeIndex,
dts, transitionType, typeOfLocalTime, StandardTime, GmtTime);
// create the filler rules
TZif_CreateMiddleMultiYearRules(ref rulesList, daylightBias, endTransitionDate);
// create the last rule
TZif_CreateLastMultiYearRule(ref rulesList, daylightBias, endTransitionDate, DstStartIndex, dstStartTypeIndex, DstEndIndex, dstEndTypeIndex,
dts, transitionType, typeOfLocalTime, StandardTime, GmtTime);
}
startIndex = index + 1;
return true;
}
// setup the start values for the next call to TZif_GenerateAdjustmentRule(...)
startIndex = index + 1;
return false; // did not create a new AdjustmentRule
}
private static void TZif_CreateFirstMultiYearRule(ref List<AdjustmentRule> rulesList, TimeSpan daylightBias, DateTime startTransitionDate,
int DstStartIndex, int dstStartTypeIndex, int dstEndTypeIndex, DateTime[] dts, TZifType[] transitionType,
Byte[] typeOfLocalTime, bool[] StandardTime, bool[] GmtTime)
{
// [AdjustmentRule #0] // start rule
// [1946/09/31 - 1947/06/15] // * starts 1 day prior to startTransitionDate
// [start: 10/01 @4:00 ] // * N months long, stopping at month 6 or 11
// [end : 07/15 ] // notice how the _end_ is outside the range
DateTime startDate;
DateTime endDate;
TransitionTime dstStart;
TransitionTime dstEnd;
TimeSpan startTransitionOffset = (DstStartIndex > 0 ? transitionType[typeOfLocalTime[DstStartIndex - 1]].UtcOffset : transitionType[dstEndTypeIndex].UtcOffset);
dstStart = TZif_CalculateTransitionTime(startTransitionDate,
startTransitionOffset,
transitionType[dstStartTypeIndex],
StandardTime[dstStartTypeIndex],
GmtTime[dstStartTypeIndex],
out startDate);
//
// Choosing the endDate based on the startDate:
//
// startTransitionDate.Month -> end
// 1 4|5 8|9 12
// [-> 06/15]|[-> 11/15]|[-> 06/15]
//
int startDateMonth = startDate.Month;
int startDateYear = startDate.Year;
if (startDateMonth <= 4)
{
endDate = new DateTime(startDateYear, 06, 15);
dstEnd = s_transition7_15;
}
else if (startDateMonth <= 8)
{
endDate = new DateTime(startDateYear, 11, 15);
dstEnd = s_transition12_15;
}
else if (startDateYear < 9999)
{
endDate = new DateTime(startDateYear + 1, 06, 15);
dstEnd = s_transition7_15;
}
else
{
endDate = DateTime.MaxValue;
dstEnd = s_transition7_15;
}
AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(startDate, endDate, daylightBias, dstStart, dstEnd);
rulesList.Add(r);
}
private static void TZif_CreateLastMultiYearRule(ref List<AdjustmentRule> rulesList, TimeSpan daylightBias, DateTime endTransitionDate,
int DstStartIndex, int dstStartTypeIndex, int DstEndIndex, int dstEndTypeIndex, DateTime[] dts, TZifType[] transitionType,
Byte[] typeOfLocalTime, bool[] StandardTime, bool[] GmtTime)
{
// [AdjustmentRule #N] // end rule
// [1963/06/16 - 1946/10/02] // * starts 1 day after last day in previous rule
// [start: 05/15 ] // * N months long, stopping 1 day after endTransitionDate
// [end : 10/01 ] // notice how the _start_ is outside the range
DateTime endDate;
TransitionTime dstEnd;
TimeSpan endTransitionOffset = (DstEndIndex > 0 ? transitionType[typeOfLocalTime[DstEndIndex - 1]].UtcOffset : transitionType[dstStartTypeIndex].UtcOffset);
dstEnd = TZif_CalculateTransitionTime(endTransitionDate,
endTransitionOffset,
transitionType[dstEndTypeIndex],
StandardTime[dstEndTypeIndex],
GmtTime[dstEndTypeIndex],
out endDate);
if (DstStartIndex >= DstEndIndex)
{
// we found a DST start but no DST end
endDate = DateTime.MaxValue.Date;
}
AdjustmentRule prevRule = rulesList[rulesList.Count - 1]; // grab the last element of the MultiYearRule sequence
int y = prevRule.DateEnd.Year;
if (prevRule.DateEnd.Month <= 6)
{
// create a rule from 06/16/YYYY to endDate
AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(new DateTime(y, 06, 16), endDate, daylightBias, s_transition5_15, dstEnd);
rulesList.Add(r);
}
else
{
// create a rule from 11/16/YYYY to endDate
AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(new DateTime(y, 11, 16), endDate, daylightBias, s_transition10_15, dstEnd);
rulesList.Add(r);
}
}
private static void TZif_CreateMiddleMultiYearRules(ref List<AdjustmentRule> rulesList, TimeSpan daylightBias, DateTime endTransitionDate)
{
//
// [AdjustmentRule #1] // middle-year all-DST rule
// [1947/06/16 - 1947/11/15] // * starts 1 day after last day in previous rule
// [start: 05/15 ] // * 5 months long, stopping at month 6 or 11
// [end : 12/15 ] // notice how the _start and end_ are outside the range
//
// [AdjustmentRule #2] // middle-year all-DST rule
// [1947/11/16 - 1947/06/15] // * starts 1 day after last day in previous rule
// [start: 10/01 ] // * 7 months long, stopping at month 6 or 11
// [end : 07/15 ] // notice how the _start and end_ are outside the range
//
// .........................
AdjustmentRule prevRule = rulesList[rulesList.Count - 1]; // grab the first element of the MultiYearRule sequence
DateTime endDate;
//
// Choosing the last endDate based on the endTransitionDate
//
// endTransitionDate.Month -> end
// 1 4|5 8|9 12
// [11/15 <-]|[11/15 <-]|[06/15 <-]
//
if (endTransitionDate.Month <= 8)
{
// set the end date to 11/15/YYYY-1
endDate = new DateTime(endTransitionDate.Year - 1, 11, 15);
}
else
{
// set the end date to 06/15/YYYY
endDate = new DateTime(endTransitionDate.Year, 06, 15);
}
while (prevRule.DateEnd < endDate)
{
// the last endDate will be on either 06/15 or 11/15
int y = prevRule.DateEnd.Year;
if (prevRule.DateEnd.Month <= 6)
{
// create a rule from 06/16/YYYY to 11/15/YYYY
AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(new DateTime(y, 06, 16), new DateTime(y, 11, 15),
daylightBias, s_transition5_15, s_transition12_15);
prevRule = r;
rulesList.Add(r);
}
else
{
// create a rule from 11/16/YYYY to 06/15/YYYY+1
AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(new DateTime(y, 11, 16), new DateTime(y + 1, 06, 15),
daylightBias, s_transition10_15, s_transition7_15);
prevRule = r;
rulesList.Add(r);
}
}
}
// Returns the Substring from zoneAbbreviations starting at index and ending at '\0'
// zoneAbbreviations is expected to be in the form: "PST\0PDT\0PWT\0\PPT"
private static String TZif_GetZoneAbbreviation(String zoneAbbreviations, int index)
{
int lastIndex = zoneAbbreviations.IndexOf('\0', index);
if (lastIndex > 0)
{
return zoneAbbreviations.Substring(index, lastIndex - index);
}
else
{
return zoneAbbreviations.Substring(index);
}
}
// verify the 'index' is referenced from the typeOfLocalTime byte array.
//
private static Boolean TZif_ValidTransitionType(int index, Byte[] typeOfLocalTime)
{
Boolean result = false;
if (typeOfLocalTime != null)
{
for (int i = 0; !result && i < typeOfLocalTime.Length; i++)
{
if (index == typeOfLocalTime[i])
{
result = true;
}
}
}
return result;
}
// Converts an array of bytes into an int - always using standard byte order (Big Endian)
// per TZif file standard
private static int TZif_ToInt32(byte[] value, int startIndex)
{
return (value[startIndex] << 24) | (value[startIndex + 1] << 16) | (value[startIndex + 2] << 8) | value[startIndex + 3];
}
private static void TZif_ParseRaw(Byte[] data, out TZifHead t, out DateTime[] dts, out Byte[] typeOfLocalTime, out TZifType[] transitionType,
out String zoneAbbreviations, out Boolean[] StandardTime, out Boolean[] GmtTime)
{
// initialize the out parameters in case the TZifHead ctor throws
dts = null;
typeOfLocalTime = null;
transitionType = null;
zoneAbbreviations = String.Empty;
StandardTime = null;
GmtTime = null;
// read in the 44-byte TZ header containing the count/length fields
//
t = new TZifHead(data, 0);
int index = TZifHead.Length;
// initialize the containers for the rest of the TZ data
dts = new DateTime[t.TimeCount];
typeOfLocalTime = new Byte[t.TimeCount];
transitionType = new TZifType[t.TypeCount];
zoneAbbreviations = String.Empty;
StandardTime = new Boolean[t.TypeCount];
GmtTime = new Boolean[t.TypeCount];
// read in the 4-byte UTC transition points and convert them to Windows
//
for (int i = 0; i < t.TimeCount; i++)
{
int unixTime = TZif_ToInt32(data, index);
dts[i] = TZif_UnixTimeToWindowsTime(unixTime);
index += 4;
}
// read in the Type Indices; there is a 1:1 mapping of UTC transition points to Type Indices
// these indices directly map to the array index in the transitionType array below
//
for (int i = 0; i < t.TimeCount; i++)
{
typeOfLocalTime[i] = data[index];
index += 1;
}
// read in the Type table. Each 6-byte entry represents
// {UtcOffset, IsDst, AbbreviationIndex}
//
// each AbbreviationIndex is a character index into the zoneAbbreviations string below
//
for (int i = 0; i < t.TypeCount; i++)
{
transitionType[i] = new TZifType(data, index);
index += 6;
}
// read in the Abbreviation ASCII string. This string will be in the form:
// "PST\0PDT\0PWT\0\PPT"
//
System.Text.Encoding enc = new System.Text.UTF8Encoding();
zoneAbbreviations = enc.GetString(data, index, (int)t.CharCount);
index += (int)t.CharCount;
// skip ahead of the Leap-Seconds Adjustment data. In a future release, consider adding
// support for Leap-Seconds
//
index += (int)(t.LeapCount * 8); // skip the leap second transition times
// read in the Standard Time table. There should be a 1:1 mapping between Type-Index and Standard
// Time table entries.
//
// TRUE = transition time is standard time
// FALSE = transition time is wall clock time
// ABSENT = transition time is wall clock time
//
for (int i = 0; i < t.IsStdCount && i < t.TypeCount && index < data.Length; i++)
{
StandardTime[i] = (data[index++] != 0);
}
// read in the GMT Time table. There should be a 1:1 mapping between Type-Index and GMT Time table
// entries.
//
// TRUE = transition time is UTC
// FALSE = transition time is local time
// ABSENT = transition time is local time
//
for (int i = 0; i < t.IsGmtCount && i < t.TypeCount && index < data.Length; i++)
{
GmtTime[i] = (data[index++] != 0);
}
}
// Windows NT time is specified as the number of 100 nanosecond intervals since January 1, 1601.
// UNIX time is specified as the number of seconds since January 1, 1970. There are 134,774 days
// (or 11,644,473,600 seconds) between these dates.
//
private static DateTime TZif_UnixTimeToWindowsTime(int unixTime)
{
// Add 11,644,473,600 and multiply by 10,000,000.
Int64 ntTime = (((Int64)unixTime) + 11644473600) * 10000000;
return DateTime.FromFileTimeUtc(ntTime);
}
private struct TZifType
{
private const int c_len = 6;
public static int Length
{
get
{
return c_len;
}
}
public TimeSpan UtcOffset;
public Boolean IsDst;
public Byte AbbreviationIndex;
public TZifType(Byte[] data, Int32 index)
{
if (data == null || data.Length < index + c_len)
{
throw new ArgumentException(SR.Argument_TimeZoneInfoInvalidTZif, nameof(data));
}
UtcOffset = new TimeSpan(0, 0, TZif_ToInt32(data, index + 00));
IsDst = (data[index + 4] != 0);
AbbreviationIndex = data[index + 5];
}
}
private struct TZifHead
{
private const int c_len = 44;
public static int Length
{
get
{
return c_len;
}
}
public TZifHead(Byte[] data, Int32 index)
{
if (data == null || data.Length < c_len)
{
throw new ArgumentException("bad data", nameof(data));
}
Magic = (uint)TZif_ToInt32(data, index + 00);
if (Magic != 0x545A6966)
{
// 0x545A6966 = {0x54, 0x5A, 0x69, 0x66} = "TZif"
throw new ArgumentException(SR.Argument_TimeZoneInfoBadTZif, nameof(data));
}
// don't use the BitConverter class which parses data
// based on the Endianess of the machine architecture.
// this data is expected to always be in "standard byte order",
// regardless of the machine it is being processed on.
IsGmtCount = (uint)TZif_ToInt32(data, index + 20);
// skip the 16 byte reserved field
IsStdCount = (uint)TZif_ToInt32(data, index + 24);
LeapCount = (uint)TZif_ToInt32(data, index + 28);
TimeCount = (uint)TZif_ToInt32(data, index + 32);
TypeCount = (uint)TZif_ToInt32(data, index + 36);
CharCount = (uint)TZif_ToInt32(data, index + 40);
}
public UInt32 Magic; // TZ_MAGIC "TZif"
// public Byte[16] Reserved; // reserved for future use
public UInt32 IsGmtCount; // number of transition time flags
public UInt32 IsStdCount; // number of transition time flags
public UInt32 LeapCount; // number of leap seconds
public UInt32 TimeCount; // number of transition times
public UInt32 TypeCount; // number of local time types
public UInt32 CharCount; // number of abbreviated characters
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using SIL.Lift.Options;
using SIL.TestUtilities;
using SIL.WritingSystems;
using SIL.WritingSystems.Tests;
namespace SIL.Lift.Tests.Options
{
[TestFixture]
public class WritingSystemsInOptionsListFileHelperTests
{
private class TestEnvironment : IDisposable
{
private readonly TemporaryFolder _folder;
private readonly IO.TempFile _optionListFile;
public TestEnvironment(string rfctag)
: this(rfctag, "x-dontcare")
{
}
public TestEnvironment(string rfctag, string rfctag2)
{
_folder = new TemporaryFolder("WritingSystemsInoptionListFileHelper");
var pathtoOptionsListFile1 = Path.Combine(_folder.Path, "test1.xml");
_optionListFile = new IO.TempFile(String.Format(_optionListFileContent, rfctag, rfctag2));
_optionListFile.MoveTo(pathtoOptionsListFile1);
}
#region LongFileContent
private readonly string _optionListFileContent =
@"<?xml version='1.0' encoding='utf-8'?>
<optionsList>
<options>
<option>
<key>Verb</key>
<name>
<form lang='{0}'>verb</form>
<form lang='{1}'>verbe</form>
</name>
<abbreviation>
<form lang='{0}'>verb</form>
</abbreviation>
<description>
<form lang='{1}'>verbe</form>
</description>
</option>
<option>
<key>Noun</key>
<name>
<form lang='{0}'>noun</form>
<form lang='{1}'>nom</form>
</name>
<abbreviation>
<form lang='{0}'>noun</form>
<form lang='{1}'>nom</form>
</abbreviation>
<description>
<form lang='{0}'>noun</form>
<form lang='{1}'>nom</form>
</description>
</option>
</options>
</optionsList>".Replace("'", "\"");
private WritingSystemsInOptionsListFileHelper _helper;
#endregion
private void CreateWritingSystemRepository()
{
WritingSystemRepository = new TestLdmlInFolderWritingSystemRepository(WritingSystemsPath);
}
private string ProjectPath
{
get { return _folder.Path; }
}
public WritingSystemsInOptionsListFileHelper Helper {
get
{
if (_helper == null)
{
if (WritingSystemRepository == null)
{
CreateWritingSystemRepository();
}
_helper = new WritingSystemsInOptionsListFileHelper(WritingSystemRepository, _optionListFile.Path);
}
return _helper;
}
}
public void Dispose()
{
_optionListFile.Dispose();
_folder.Dispose();
}
private IWritingSystemRepository WritingSystemRepository { get; set; }
public string WritingSystemsPath
{
get { return Path.Combine(ProjectPath, "WritingSystems"); }
}
public string PathToOptionsListFile
{
get { return _optionListFile.Path; }
}
public string GetLdmlFileforWs(string id)
{
return Path.Combine(WritingSystemsPath, String.Format("{0}.ldml", id));
}
}
[Test]
public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsNonConformantRfcTag_CreatesConformingWritingSystem()
{
using (var e = new TestEnvironment("en", "fr"))
{
e.Helper.CreateNonExistentWritingSystemsFoundInFile();
Assert.That(File.Exists(e.GetLdmlFileforWs("en")));
Assert.That(File.Exists(e.GetLdmlFileforWs("fr")));
}
}
[Test]
public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsNonConformantRfcTag_WsIdChangeLogUpdated()
{
using (var e = new TestEnvironment("x-bogusws1", "audio"))
{
e.Helper.CreateNonExistentWritingSystemsFoundInFile();
Assert.That(File.Exists(e.GetLdmlFileforWs("qaa-x-bogusws1")));
Assert.That(File.Exists(e.GetLdmlFileforWs("qaa-Zxxx-x-audio")));
string idChangeLogFilePath = Path.Combine(e.WritingSystemsPath, "idchangelog.xml");
AssertThatXmlIn.File(idChangeLogFilePath).HasAtLeastOneMatchForXpath("/WritingSystemChangeLog/Changes[Add/Id/text()='qaa-x-bogusws1' and Add/Id/text()='qaa-Zxxx-x-audio']");
}
}
[Test]
public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsNonConformantRfcTag_UpdatesRfcTagInOptionsListFile()
{
using (var environment = new TestEnvironment("Zxxx-x-bogusws1", "audio"))
{
environment.Helper.CreateNonExistentWritingSystemsFoundInFile();
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-Zxxx-bogusws1']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-Zxxx-x-audio']");
}
}
[Test]
public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsNonConformantRfcTagWithDuplicates_UpdatesRfcTagInOptionsListFile()
{
using (var environment = new TestEnvironment("wee", "x-wee"))
{
environment.Helper.CreateNonExistentWritingSystemsFoundInFile();
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-wee-dupl0']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-wee']");
}
}
[Test]
public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsConformantRfcTagWithNoCorrespondingLdml_CreatesLdml()
{
using (var e = new TestEnvironment("de", "x-dontcare"))
{
e.Helper.CreateNonExistentWritingSystemsFoundInFile();
AssertThatXmlIn.File(e.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='de']");
Assert.That(File.Exists(e.GetLdmlFileforWs("de")), Is.True);
AssertThatXmlIn.File(e.GetLdmlFileforWs("de")).HasAtLeastOneMatchForXpath("/ldml/identity/language[@type='de']");
AssertThatXmlIn.File(e.GetLdmlFileforWs("de")).HasNoMatchForXpath("/ldml/identity/script");
AssertThatXmlIn.File(e.GetLdmlFileforWs("de")).HasNoMatchForXpath("/ldml/identity/territory");
AssertThatXmlIn.File(e.GetLdmlFileforWs("de")).HasNoMatchForXpath("/ldml/identity/variant");
}
}
[Test]
public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsEntirelyPrivateUseRfcTagThatDoesNotExistInRepo_RfcTagIsMigrated()
{
using (var e = new TestEnvironment("x-blah"))
{
e.Helper.CreateNonExistentWritingSystemsFoundInFile();
Assert.That(File.Exists(e.GetLdmlFileforWs("qaa-x-blah")), Is.True);
AssertThatXmlIn.File(e.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-blah']");
}
}
[Test]
//This test makes sure that nonexisting private use tags are migrated if necessary
public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsAudioTagThatDoesNotExistInRepo_RfcTagIsMigrated()
{
using (var e = new TestEnvironment("x-audio"))
{
e.Helper.CreateNonExistentWritingSystemsFoundInFile();
Assert.That(File.Exists(e.GetLdmlFileforWs("x-audio")), Is.False);
Assert.That(File.Exists(e.GetLdmlFileforWs("qaa-Zxxx-x-audio")), Is.True);
AssertThatXmlIn.File(e.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/name/form[@lang='x-audio']");
AssertThatXmlIn.File(e.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-Zxxx-x-audio']");
}
}
[Test]
public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsNonConformantRfcTagWithDuplicatesContainingduplicateMarker_UpdatesRfcTagInOptionsListFile()
{
using (var environment = new TestEnvironment("wee-dupl1", "x-wee-dupl1"))
{
environment.Helper.CreateNonExistentWritingSystemsFoundInFile();
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-wee-dupl1']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-wee-dupl1-dupl0']");
}
}
[Test]
public void Ctr_FileIsNotXml_MethodsBehave()
{
using (var environment = new TestEnvironment("wee-dupl1", "x-wee-dupl1"))
{
File.WriteAllText(environment.PathToOptionsListFile, "text");
environment.Helper.CreateNonExistentWritingSystemsFoundInFile();
environment.Helper.ReplaceWritingSystemId("text", "test");
Assert.That(environment.Helper.WritingSystemsInUse.Count(), Is.EqualTo(0));
Assert.That(File.ReadAllText(environment.PathToOptionsListFile), Is.EqualTo("text"));
}
}
[Test]
public void Ctr_FileIsXmlButNotOptionList_MethodsBehave()
{
using (var environment = new TestEnvironment("wee-dupl1", "x-wee-dupl1"))
{
File.WriteAllText(environment.PathToOptionsListFile, "<?xml version='1.0' encoding='utf-8'?>\r\n<form>yo</form>".Replace("'", "\""));
environment.Helper.CreateNonExistentWritingSystemsFoundInFile();
environment.Helper.ReplaceWritingSystemId("text", "test");
Assert.That(environment.Helper.WritingSystemsInUse.Count(), Is.EqualTo(0));
Assert.That(File.ReadAllText(environment.PathToOptionsListFile), Is.EqualTo("<?xml version='1.0' encoding='utf-8'?>\r\n<form>yo</form>".Replace("'", "\"")));
}
}
[Test]
public void ReplaceWritingSystemId_FormForNewWritingSystemAlreadyExists_RemoveOldWritingSystemForm()
{
using (var environment = new TestEnvironment("th", "de"))
{
environment.Helper.CreateNonExistentWritingSystemsFoundInFile();
environment.Helper.ReplaceWritingSystemId("th", "de");
Assert.That(environment.Helper.WritingSystemsInUse.Count(), Is.EqualTo(1));
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("//form[@lang='th']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/name/form[@lang='de'][text()='verb']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/name/form[@lang='de'][text()='verbe']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/abbreviation/form[@lang='de'][text()='verb']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/description/form[@lang='de'][text()='verbe']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/name/form[@lang='de'][text()='nom']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/name/form[@lang='de'][text()='noun']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/abbreviation/form[@lang='de'][text()='nom']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/abbreviation/form[@lang='de'][text()='noun']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/description/form[@lang='de'][text()='nom']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/description/form[@lang='de'][text()='noun']");
}
}
[Test]
public void DeleteWritingSystemId_FormForNewWritingSystemAlreadyExists_RemoveOldWritingSystemForm()
{
using (var environment = new TestEnvironment("th", "de"))
{
environment.Helper.CreateNonExistentWritingSystemsFoundInFile();
environment.Helper.DeleteWritingSystemId("th");
Assert.That(environment.Helper.WritingSystemsInUse.Count(), Is.EqualTo(1));
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("//form[@lang='th']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/name/form[@lang='th'][text()='verb']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/name/form[@lang='de'][text()='verbe']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/abbreviation/form[@lang='th'][text()='verb']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/description/form[@lang='de'][text()='verbe']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/name/form[@lang='de'][text()='nom']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/name/form[@lang='th'][text()='noun']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/abbreviation/form[@lang='de'][text()='nom']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/abbreviation/form[@lang='th'][text()='noun']");
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/description/form[@lang='de'][text()='nom']", 1);
AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/description/form[@lang='th'][text()='noun']");
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A wholesale store.
/// </summary>
public class WholesaleStore_Core : TypeCore, IStore
{
public WholesaleStore_Core()
{
this._TypeId = 295;
this._Id = "WholesaleStore";
this._Schema_Org_Url = "http://schema.org/WholesaleStore";
string label = "";
GetLabel(out label, "WholesaleStore", typeof(WholesaleStore_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,252};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{252};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
namespace Ioke.Math {
using System;
class Primality {
private Primality() {}
private static readonly int[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167,
173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239,
241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467,
479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569,
571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643,
647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823,
827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009,
1013, 1019, 1021 };
private static readonly BigInteger[] BIprimes = new BigInteger[primes.Length];
private static readonly int[] BITS = { 0, 0, 1854, 1233, 927, 747, 627, 543,
480, 431, 393, 361, 335, 314, 295, 279, 265, 253, 242, 232, 223,
216, 181, 169, 158, 150, 145, 140, 136, 132, 127, 123, 119, 114,
110, 105, 101, 96, 92, 87, 83, 78, 73, 69, 64, 59, 54, 49, 44, 38,
32, 26, 1 };
private static readonly int[][] offsetPrimes;
static Primality() {// To initialize the dual table of BigInteger primes
for(int i = 0; i < primes.Length; i++) {
BIprimes[i] = BigInteger.valueOf(primes[i]);
}
offsetPrimes = new int[][] { null, null, new int[] { 0, 2 },
new int[] { 2, 2 }, new int[] { 4, 2 }, new int[] { 6, 5 }, new int[] { 11, 7 }, new int[] { 18, 13 }, new int[] { 31, 23 },
new int[] { 54, 43 }, new int[] { 97, 75 } };
}
internal static BigInteger nextProbablePrime(BigInteger n) {
// PRE: n >= 0
int i, j;
int certainty;
int gapSize = 1024; // for searching of the next probable prime number
int[] modules = new int[primes.Length];
bool[] isDivisible = new bool[gapSize];
BigInteger startPoint;
BigInteger probPrime;
// If n < "last prime of table" searches next prime in the table
if ((n.numberLength == 1) && (n.digits[0] >= 0)
&& (n.digits[0] < primes[primes.Length - 1])) {
for (i = 0; n.digits[0] >= primes[i]; i++) {
;
}
return BIprimes[i];
}
/*
* Creates a "N" enough big to hold the next probable prime Note that: N <
* "next prime" < 2*N
*/
startPoint = new BigInteger(1, n.numberLength,
new int[n.numberLength + 1]);
Array.Copy(n.digits, startPoint.digits, n.numberLength);
// To fix N to the "next odd number"
if (n.testBit(0)) {
Elementary.inplaceAdd(startPoint, 2);
} else {
startPoint.digits[0] |= 1;
}
// To set the improved certainly of Miller-Rabin
j = startPoint.bitLength();
for (certainty = 2; j < BITS[certainty]; certainty++) {
;
}
// To calculate modules: N mod p1, N mod p2, ... for first primes.
for (i = 0; i < primes.Length; i++) {
modules[i] = Division.remainder(startPoint, primes[i]) - gapSize;
}
while (true) {
// At this point, all numbers in the gap are initialized as
// probably primes
Array.Clear(isDivisible, 0, isDivisible.Length);
// To discard multiples of first primes
for (i = 0; i < primes.Length; i++) {
modules[i] = (modules[i] + gapSize) % primes[i];
j = (modules[i] == 0) ? 0 : (primes[i] - modules[i]);
for (; j < gapSize; j += primes[i]) {
isDivisible[j] = true;
}
}
// To execute Miller-Rabin for non-divisible numbers by all first
// primes
for (j = 0; j < gapSize; j++) {
if (!isDivisible[j]) {
probPrime = startPoint.copy();
Elementary.inplaceAdd(probPrime, j);
if (millerRabin(probPrime, certainty)) {
return probPrime;
}
}
}
Elementary.inplaceAdd(startPoint, gapSize);
}
}
internal static BigInteger consBigInteger(int bitLength, int certainty, Random rnd) {
// PRE: bitLength >= 2;
// For small numbers get a random prime from the prime table
if (bitLength <= 10) {
int[] rp = offsetPrimes[bitLength];
return BIprimes[rp[0] + rnd.Next(rp[1])];
}
int shiftCount = (-bitLength) & 31;
int last = (bitLength + 31) >> 5;
BigInteger n = new BigInteger(1, last, new int[last]);
last--;
do {// To fill the array with random integers
for (int i = 0; i < n.numberLength; i++) {
n.digits[i] = rnd.Next();
}
// To fix to the correct bitLength
n.digits[last] = (int)((uint)n.digits[last] | 0x80000000);
n.digits[last] = (int)(((uint)n.digits[last]) >> shiftCount);
// To create an odd number
n.digits[0] |= 1;
} while (!isProbablePrime(n, certainty));
return n;
}
internal static bool isProbablePrime(BigInteger n, int certainty) {
// PRE: n >= 0;
if ((certainty <= 0) || ((n.numberLength == 1) && (n.digits[0] == 2))) {
return true;
}
// To discard all even numbers
if (!n.testBit(0)) {
return false;
}
// To check if 'n' exists in the table (it fit in 10 bits)
if ((n.numberLength == 1) && ((n.digits[0] & 0XFFFFFC00) == 0)) {
return (Array.BinarySearch(primes, n.digits[0]) >= 0);
}
// To check if 'n' is divisible by some prime of the table
for (int i = 1; i < primes.Length; i++) {
if (Division.remainderArrayByInt(n.digits, n.numberLength,
primes[i]) == 0) {
return false;
}
}
// To set the number of iterations necessary for Miller-Rabin test
int ix;
int bitLength = n.bitLength();
for (ix = 2; bitLength < BITS[ix]; ix++) {
;
}
certainty = Math.Min(ix, 1 + ((certainty - 1) >> 1));
return millerRabin(n, certainty);
}
private static bool millerRabin(BigInteger n, int t) {
// PRE: n >= 0, t >= 0
BigInteger x; // x := UNIFORM{2...n-1}
BigInteger y; // y := x^(q * 2^j) mod n
BigInteger n_minus_1 = n.subtract(BigInteger.ONE); // n-1
int bitLength = n_minus_1.bitLength(); // ~ log2(n-1)
// (q,k) such that: n-1 = q * 2^k and q is odd
int k = n_minus_1.getLowestSetBit();
BigInteger q = n_minus_1.shiftRight(k);
Random rnd = new Random();
for (int i = 0; i < t; i++) {
// To generate a witness 'x', first it use the primes of table
if (i < primes.Length) {
x = BIprimes[i];
} else {/*
* It generates random witness only if it's necesssary. Note
* that all methods would call Miller-Rabin with t <= 50 so
* this part is only to do more robust the algorithm
*/
do {
x = new BigInteger(bitLength, rnd);
} while ((x.compareTo(n) >= BigInteger.EQUALS) || (x.sign == 0)
|| x.isOne());
}
y = x.modPow(q, n);
if (y.isOne() || y.Equals(n_minus_1)) {
continue;
}
for (int j = 1; j < k; j++) {
if (y.Equals(n_minus_1)) {
continue;
}
y = y.multiply(y).mod(n);
if (y.isOne()) {
return false;
}
}
if (!y.Equals(n_minus_1)) {
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.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Internal;
namespace System.Reflection.Metadata.Ecma335
{
/// <summary>
/// Provides extension methods for working with certain raw elements of the ECMA-335 metadata tables and heaps.
/// </summary>
public static class MetadataReaderExtensions
{
/// <summary>
/// Returns the number of rows in the specified table.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception>
public static int GetTableRowCount(this MetadataReader reader, TableIndex tableIndex)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
if ((int)tableIndex >= MetadataTokens.TableCount)
{
Throw.TableIndexOutOfRange();
}
return reader.TableRowCounts[(int)tableIndex];
}
/// <summary>
/// Returns the size of a row in the specified table.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception>
public static int GetTableRowSize(this MetadataReader reader, TableIndex tableIndex)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
switch (tableIndex)
{
case TableIndex.Module: return reader.ModuleTable.RowSize;
case TableIndex.TypeRef: return reader.TypeRefTable.RowSize;
case TableIndex.TypeDef: return reader.TypeDefTable.RowSize;
case TableIndex.FieldPtr: return reader.FieldPtrTable.RowSize;
case TableIndex.Field: return reader.FieldTable.RowSize;
case TableIndex.MethodPtr: return reader.MethodPtrTable.RowSize;
case TableIndex.MethodDef: return reader.MethodDefTable.RowSize;
case TableIndex.ParamPtr: return reader.ParamPtrTable.RowSize;
case TableIndex.Param: return reader.ParamTable.RowSize;
case TableIndex.InterfaceImpl: return reader.InterfaceImplTable.RowSize;
case TableIndex.MemberRef: return reader.MemberRefTable.RowSize;
case TableIndex.Constant: return reader.ConstantTable.RowSize;
case TableIndex.CustomAttribute: return reader.CustomAttributeTable.RowSize;
case TableIndex.FieldMarshal: return reader.FieldMarshalTable.RowSize;
case TableIndex.DeclSecurity: return reader.DeclSecurityTable.RowSize;
case TableIndex.ClassLayout: return reader.ClassLayoutTable.RowSize;
case TableIndex.FieldLayout: return reader.FieldLayoutTable.RowSize;
case TableIndex.StandAloneSig: return reader.StandAloneSigTable.RowSize;
case TableIndex.EventMap: return reader.EventMapTable.RowSize;
case TableIndex.EventPtr: return reader.EventPtrTable.RowSize;
case TableIndex.Event: return reader.EventTable.RowSize;
case TableIndex.PropertyMap: return reader.PropertyMapTable.RowSize;
case TableIndex.PropertyPtr: return reader.PropertyPtrTable.RowSize;
case TableIndex.Property: return reader.PropertyTable.RowSize;
case TableIndex.MethodSemantics: return reader.MethodSemanticsTable.RowSize;
case TableIndex.MethodImpl: return reader.MethodImplTable.RowSize;
case TableIndex.ModuleRef: return reader.ModuleRefTable.RowSize;
case TableIndex.TypeSpec: return reader.TypeSpecTable.RowSize;
case TableIndex.ImplMap: return reader.ImplMapTable.RowSize;
case TableIndex.FieldRva: return reader.FieldRvaTable.RowSize;
case TableIndex.EncLog: return reader.EncLogTable.RowSize;
case TableIndex.EncMap: return reader.EncMapTable.RowSize;
case TableIndex.Assembly: return reader.AssemblyTable.RowSize;
case TableIndex.AssemblyProcessor: return reader.AssemblyProcessorTable.RowSize;
case TableIndex.AssemblyOS: return reader.AssemblyOSTable.RowSize;
case TableIndex.AssemblyRef: return reader.AssemblyRefTable.RowSize;
case TableIndex.AssemblyRefProcessor: return reader.AssemblyRefProcessorTable.RowSize;
case TableIndex.AssemblyRefOS: return reader.AssemblyRefOSTable.RowSize;
case TableIndex.File: return reader.FileTable.RowSize;
case TableIndex.ExportedType: return reader.ExportedTypeTable.RowSize;
case TableIndex.ManifestResource: return reader.ManifestResourceTable.RowSize;
case TableIndex.NestedClass: return reader.NestedClassTable.RowSize;
case TableIndex.GenericParam: return reader.GenericParamTable.RowSize;
case TableIndex.MethodSpec: return reader.MethodSpecTable.RowSize;
case TableIndex.GenericParamConstraint: return reader.GenericParamConstraintTable.RowSize;
// debug tables
case TableIndex.Document: return reader.DocumentTable.RowSize;
case TableIndex.MethodDebugInformation: return reader.MethodDebugInformationTable.RowSize;
case TableIndex.LocalScope: return reader.LocalScopeTable.RowSize;
case TableIndex.LocalVariable: return reader.LocalVariableTable.RowSize;
case TableIndex.LocalConstant: return reader.LocalConstantTable.RowSize;
case TableIndex.ImportScope: return reader.ImportScopeTable.RowSize;
case TableIndex.StateMachineMethod: return reader.StateMachineMethodTable.RowSize;
case TableIndex.CustomDebugInformation: return reader.CustomDebugInformationTable.RowSize;
default:
throw new ArgumentOutOfRangeException(nameof(tableIndex));
}
}
/// <summary>
/// Returns the offset from the start of metadata to the specified table.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception>
public static unsafe int GetTableMetadataOffset(this MetadataReader reader, TableIndex tableIndex)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return (int)(reader.GetTableMetadataBlock(tableIndex).Pointer - reader.Block.Pointer);
}
private static MemoryBlock GetTableMetadataBlock(this MetadataReader reader, TableIndex tableIndex)
{
Debug.Assert(reader != null);
switch (tableIndex)
{
case TableIndex.Module: return reader.ModuleTable.Block;
case TableIndex.TypeRef: return reader.TypeRefTable.Block;
case TableIndex.TypeDef: return reader.TypeDefTable.Block;
case TableIndex.FieldPtr: return reader.FieldPtrTable.Block;
case TableIndex.Field: return reader.FieldTable.Block;
case TableIndex.MethodPtr: return reader.MethodPtrTable.Block;
case TableIndex.MethodDef: return reader.MethodDefTable.Block;
case TableIndex.ParamPtr: return reader.ParamPtrTable.Block;
case TableIndex.Param: return reader.ParamTable.Block;
case TableIndex.InterfaceImpl: return reader.InterfaceImplTable.Block;
case TableIndex.MemberRef: return reader.MemberRefTable.Block;
case TableIndex.Constant: return reader.ConstantTable.Block;
case TableIndex.CustomAttribute: return reader.CustomAttributeTable.Block;
case TableIndex.FieldMarshal: return reader.FieldMarshalTable.Block;
case TableIndex.DeclSecurity: return reader.DeclSecurityTable.Block;
case TableIndex.ClassLayout: return reader.ClassLayoutTable.Block;
case TableIndex.FieldLayout: return reader.FieldLayoutTable.Block;
case TableIndex.StandAloneSig: return reader.StandAloneSigTable.Block;
case TableIndex.EventMap: return reader.EventMapTable.Block;
case TableIndex.EventPtr: return reader.EventPtrTable.Block;
case TableIndex.Event: return reader.EventTable.Block;
case TableIndex.PropertyMap: return reader.PropertyMapTable.Block;
case TableIndex.PropertyPtr: return reader.PropertyPtrTable.Block;
case TableIndex.Property: return reader.PropertyTable.Block;
case TableIndex.MethodSemantics: return reader.MethodSemanticsTable.Block;
case TableIndex.MethodImpl: return reader.MethodImplTable.Block;
case TableIndex.ModuleRef: return reader.ModuleRefTable.Block;
case TableIndex.TypeSpec: return reader.TypeSpecTable.Block;
case TableIndex.ImplMap: return reader.ImplMapTable.Block;
case TableIndex.FieldRva: return reader.FieldRvaTable.Block;
case TableIndex.EncLog: return reader.EncLogTable.Block;
case TableIndex.EncMap: return reader.EncMapTable.Block;
case TableIndex.Assembly: return reader.AssemblyTable.Block;
case TableIndex.AssemblyProcessor: return reader.AssemblyProcessorTable.Block;
case TableIndex.AssemblyOS: return reader.AssemblyOSTable.Block;
case TableIndex.AssemblyRef: return reader.AssemblyRefTable.Block;
case TableIndex.AssemblyRefProcessor: return reader.AssemblyRefProcessorTable.Block;
case TableIndex.AssemblyRefOS: return reader.AssemblyRefOSTable.Block;
case TableIndex.File: return reader.FileTable.Block;
case TableIndex.ExportedType: return reader.ExportedTypeTable.Block;
case TableIndex.ManifestResource: return reader.ManifestResourceTable.Block;
case TableIndex.NestedClass: return reader.NestedClassTable.Block;
case TableIndex.GenericParam: return reader.GenericParamTable.Block;
case TableIndex.MethodSpec: return reader.MethodSpecTable.Block;
case TableIndex.GenericParamConstraint: return reader.GenericParamConstraintTable.Block;
// debug tables
case TableIndex.Document: return reader.DocumentTable.Block;
case TableIndex.MethodDebugInformation: return reader.MethodDebugInformationTable.Block;
case TableIndex.LocalScope: return reader.LocalScopeTable.Block;
case TableIndex.LocalVariable: return reader.LocalVariableTable.Block;
case TableIndex.LocalConstant: return reader.LocalConstantTable.Block;
case TableIndex.ImportScope: return reader.ImportScopeTable.Block;
case TableIndex.StateMachineMethod: return reader.StateMachineMethodTable.Block;
case TableIndex.CustomDebugInformation: return reader.CustomDebugInformationTable.Block;
default:
throw new ArgumentOutOfRangeException(nameof(tableIndex));
}
}
/// <summary>
/// Returns the size of the specified heap.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception>
public static int GetHeapSize(this MetadataReader reader, HeapIndex heapIndex)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return reader.GetMetadataBlock(heapIndex).Length;
}
/// <summary>
/// Returns the offset from the start of metadata to the specified heap.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception>
public static unsafe int GetHeapMetadataOffset(this MetadataReader reader, HeapIndex heapIndex)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return (int)(reader.GetMetadataBlock(heapIndex).Pointer - reader.Block.Pointer);
}
/// <summary>
/// Returns the size of the specified heap.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception>
private static MemoryBlock GetMetadataBlock(this MetadataReader reader, HeapIndex heapIndex)
{
Debug.Assert(reader != null);
switch (heapIndex)
{
case HeapIndex.UserString:
return reader.UserStringStream.Block;
case HeapIndex.String:
return reader.StringStream.Block;
case HeapIndex.Blob:
return reader.BlobStream.Block;
case HeapIndex.Guid:
return reader.GuidStream.Block;
default:
throw new ArgumentOutOfRangeException(nameof(heapIndex));
}
}
/// <summary>
/// Returns the a handle to the UserString that follows the given one in the UserString heap or a nil handle if it is the last one.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
public static UserStringHandle GetNextHandle(this MetadataReader reader, UserStringHandle handle)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return reader.UserStringStream.GetNextHandle(handle);
}
/// <summary>
/// Returns the a handle to the Blob that follows the given one in the Blob heap or a nil handle if it is the last one.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
public static BlobHandle GetNextHandle(this MetadataReader reader, BlobHandle handle)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return reader.BlobStream.GetNextHandle(handle);
}
/// <summary>
/// Returns the a handle to the String that follows the given one in the String heap or a nil handle if it is the last one.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
public static StringHandle GetNextHandle(this MetadataReader reader, StringHandle handle)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return reader.StringStream.GetNextHandle(handle);
}
/// <summary>
/// Enumerates entries of EnC log.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
public static IEnumerable<EditAndContinueLogEntry> GetEditAndContinueLogEntries(this MetadataReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
for (int rid = 1; rid <= reader.EncLogTable.NumberOfRows; rid++)
{
yield return new EditAndContinueLogEntry(
new EntityHandle(reader.EncLogTable.GetToken(rid)),
reader.EncLogTable.GetFuncCode(rid));
}
}
/// <summary>
/// Enumerates entries of EnC map.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
public static IEnumerable<EntityHandle> GetEditAndContinueMapEntries(this MetadataReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
for (int rid = 1; rid <= reader.EncMapTable.NumberOfRows; rid++)
{
yield return new EntityHandle(reader.EncMapTable.GetToken(rid));
}
}
/// <summary>
/// Enumerate types that define one or more properties.
/// </summary>
/// <returns>
/// The resulting sequence corresponds exactly to entries in PropertyMap table,
/// i.e. n-th returned <see cref="TypeDefinitionHandle"/> is stored in n-th row of PropertyMap.
/// </returns>
public static IEnumerable<TypeDefinitionHandle> GetTypesWithProperties(this MetadataReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
for (int rid = 1; rid <= reader.PropertyMapTable.NumberOfRows; rid++)
{
yield return reader.PropertyMapTable.GetParentType(rid);
}
}
/// <summary>
/// Enumerate types that define one or more events.
/// </summary>
/// <returns>
/// The resulting sequence corresponds exactly to entries in EventMap table,
/// i.e. n-th returned <see cref="TypeDefinitionHandle"/> is stored in n-th row of EventMap.
/// </returns>
public static IEnumerable<TypeDefinitionHandle> GetTypesWithEvents(this MetadataReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
for (int rid = 1; rid <= reader.EventMapTable.NumberOfRows; rid++)
{
yield return reader.EventMapTable.GetParentType(rid);
}
}
/// <summary>
/// Given a type handle and a raw type kind found in a signature blob determines whether the target type is a value type or a reference type.
/// </summary>
public static SignatureTypeKind ResolveSignatureTypeKind(this MetadataReader reader, EntityHandle typeHandle, byte rawTypeKind)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
var typeKind = (SignatureTypeKind)rawTypeKind;
switch (typeKind)
{
case SignatureTypeKind.Unknown:
return SignatureTypeKind.Unknown;
case SignatureTypeKind.Class:
case SignatureTypeKind.ValueType:
break;
default:
// If read from metadata by the decoder the value would have been checked already.
// So it is the callers error to pass in an invalid value, not bad metadata.
throw new ArgumentOutOfRangeException(nameof(rawTypeKind));
}
switch (typeHandle.Kind)
{
case HandleKind.TypeDefinition:
// WinRT projections don't apply to TypeDefs
return typeKind;
case HandleKind.TypeReference:
var treatment = reader.GetTypeReference((TypeReferenceHandle)typeHandle).SignatureTreatment;
switch (treatment)
{
case TypeRefSignatureTreatment.ProjectedToClass:
return SignatureTypeKind.Class;
case TypeRefSignatureTreatment.ProjectedToValueType:
return SignatureTypeKind.ValueType;
case TypeRefSignatureTreatment.None:
return typeKind;
default:
throw ExceptionUtilities.UnexpectedValue(treatment);
}
case HandleKind.TypeSpecification:
// TODO: https://github.com/dotnet/corefx/issues/8139
// We need more work here in differentiating case because instantiations can project class
// to value type as in IReference<T> -> Nullable<T>. Unblocking Roslyn work where the differentiation
// feature is not used. Note that the use-case of custom-mods will not hit this because there is no
// CLASS | VALUETYPE before the modifier token and so it always comes in unresolved.
return SignatureTypeKind.Unknown;
default:
throw new ArgumentOutOfRangeException(nameof(typeHandle), SR.UnexpectedHandleKind);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Numerics
{
/// <summary>
/// A structure encapsulating two single precision floating point values and provides hardware accelerated methods.
/// </summary>
public partial struct Vector2 : IEquatable<Vector2>, IFormattable
{
#region Public Static Properties
/// <summary>
/// Returns the vector (0,0).
/// </summary>
public static Vector2 Zero { get { return new Vector2(); } }
/// <summary>
/// Returns the vector (1,1).
/// </summary>
public static Vector2 One { get { return new Vector2(1.0f, 1.0f); } }
/// <summary>
/// Returns the vector (1,0).
/// </summary>
public static Vector2 UnitX { get { return new Vector2(1.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,1).
/// </summary>
public static Vector2 UnitY { get { return new Vector2(0.0f, 1.0f); } }
#endregion Public Static Properties
#region Public instance methods
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int hash = this.X.GetHashCode();
hash = HashCodeHelper.CombineHashCodes(hash, this.Y.GetHashCode());
return hash;
}
/// <summary>
/// Returns a boolean indicating whether the given Object is equal to this Vector2 instance.
/// </summary>
/// <param name="obj">The Object to compare against.</param>
/// <returns>True if the Object is equal to this Vector2; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object obj)
{
if (!(obj is Vector2))
return false;
return Equals((Vector2)obj);
}
/// <summary>
/// Returns a String representing this Vector2 instance.
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector2 instance, using the specified format to format individual elements.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <returns>The string representation.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector2 instance, using the specified format to format individual elements
/// and the given IFormatProvider.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <param name="formatProvider">The format provider to use when formatting elements.</param>
/// <returns>The string representation.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
StringBuilder sb = new StringBuilder();
string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
sb.Append('<');
sb.Append(this.X.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(this.Y.ToString(format, formatProvider));
sb.Append('>');
return sb.ToString();
}
/// <summary>
/// Returns the length of the vector.
/// </summary>
/// <returns>The vector's length.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float Length()
{
if (Vector.IsHardwareAccelerated)
{
float ls = Vector2.Dot(this, this);
return (float)Math.Sqrt(ls);
}
else
{
float ls = X * X + Y * Y;
return (float)Math.Sqrt((double)ls);
}
}
/// <summary>
/// Returns the length of the vector squared. This operation is cheaper than Length().
/// </summary>
/// <returns>The vector's length squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float LengthSquared()
{
if (Vector.IsHardwareAccelerated)
{
return Vector2.Dot(this, this);
}
else
{
return X * X + Y * Y;
}
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the Euclidean distance between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Distance(Vector2 value1, Vector2 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector2 difference = value1 - value2;
float ls = Vector2.Dot(difference, difference);
return (float)System.Math.Sqrt(ls);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float ls = dx * dx + dy * dy;
return (float)Math.Sqrt((double)ls);
}
}
/// <summary>
/// Returns the Euclidean distance squared between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DistanceSquared(Vector2 value1, Vector2 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector2 difference = value1 - value2;
return Vector2.Dot(difference, difference);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
return dx * dx + dy * dy;
}
}
/// <summary>
/// Returns a vector with the same direction as the given vector, but with a length of 1.
/// </summary>
/// <param name="value">The vector to normalize.</param>
/// <returns>The normalized vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Normalize(Vector2 value)
{
if (Vector.IsHardwareAccelerated)
{
float length = value.Length();
return value / length;
}
else
{
float ls = value.X * value.X + value.Y * value.Y;
float invNorm = 1.0f / (float)Math.Sqrt((double)ls);
return new Vector2(
value.X * invNorm,
value.Y * invNorm);
}
}
/// <summary>
/// Returns the reflection of a vector off a surface that has the specified normal.
/// </summary>
/// <param name="vector">The source vector.</param>
/// <param name="normal">The normal of the surface being reflected off.</param>
/// <returns>The reflected vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Reflect(Vector2 vector, Vector2 normal)
{
if (Vector.IsHardwareAccelerated)
{
float dot = Vector2.Dot(vector, normal);
return vector - (2 * dot * normal);
}
else
{
float dot = vector.X * normal.X + vector.Y * normal.Y;
return new Vector2(
vector.X - 2.0f * dot * normal.X,
vector.Y - 2.0f * dot * normal.Y);
}
}
/// <summary>
/// Restricts a vector between a min and max value.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max)
{
// This compare order is very important!!!
// We must follow HLSL behavior in the case user specified min value is bigger than max value.
float x = value1.X;
x = (x > max.X) ? max.X : x;
x = (x < min.X) ? min.X : x;
float y = value1.Y;
y = (y > max.Y) ? max.Y : y;
y = (y < min.Y) ? min.Y : y;
return new Vector2(x, y);
}
/// <summary>
/// Linearly interpolates between two vectors based on the given weighting.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param>
/// <returns>The interpolated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount)
{
return new Vector2(
value1.X + (value2.X - value1.X) * amount,
value1.Y + (value2.Y - value1.Y) * amount);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="position">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Transform(Vector2 position, Matrix3x2 matrix)
{
return new Vector2(
position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M31,
position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M32);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="position">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Transform(Vector2 position, Matrix4x4 matrix)
{
return new Vector2(
position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41,
position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42);
}
/// <summary>
/// Transforms a vector normal by the given matrix.
/// </summary>
/// <param name="normal">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 TransformNormal(Vector2 normal, Matrix3x2 matrix)
{
return new Vector2(
normal.X * matrix.M11 + normal.Y * matrix.M21,
normal.X * matrix.M12 + normal.Y * matrix.M22);
}
/// <summary>
/// Transforms a vector normal by the given matrix.
/// </summary>
/// <param name="normal">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 TransformNormal(Vector2 normal, Matrix4x4 matrix)
{
return new Vector2(
normal.X * matrix.M11 + normal.Y * matrix.M21,
normal.X * matrix.M12 + normal.Y * matrix.M22);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Transform(Vector2 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float yy2 = rotation.Y * y2;
float zz2 = rotation.Z * z2;
return new Vector2(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2));
}
#endregion Public Static Methods
#region Public operator methods
// all the below methods should be inlined as they are
// implemented over JIT intrinsics
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Add(Vector2 left, Vector2 right)
{
return left + right;
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Subtract(Vector2 left, Vector2 right)
{
return left - right;
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Multiply(Vector2 left, Vector2 right)
{
return left * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Multiply(Vector2 left, Single right)
{
return left * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Multiply(Single left, Vector2 right)
{
return left * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Divide(Vector2 left, Vector2 right)
{
return left / right;
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="divisor">The scalar value.</param>
/// <returns>The result of the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Divide(Vector2 left, Single divisor)
{
return left / divisor;
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Negate(Vector2 value)
{
return -value;
}
#endregion Public operator methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Entities;
using System.Collections.Concurrent;
using Signum.Engine.Maps;
using Signum.Utilities.Reflection;
using Signum.Engine.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Signum.Utilities;
using System.Data.SqlClient;
using Signum.Engine.Basics;
using System.Threading;
using Signum.Utilities.ExpressionTrees;
using System.Data;
using Signum.Entities.Reflection;
using Signum.Entities.Internal;
using Signum.Engine.Connection;
namespace Signum.Engine.Cache
{
public abstract class CachedTableBase
{
public abstract ITable Table { get; }
public abstract IColumn? ParentColumn { get; set; }
internal List<CachedTableBase>? subTables;
public List<CachedTableBase>? SubTables { get { return subTables; } }
protected SqlPreCommandSimple query = null!;
internal ICacheLogicController controller;
internal CachedTableConstructor Constructor = null!;
internal CachedTableBase(ICacheLogicController controller)
{
this.controller = controller;
}
protected void OnChange(object sender, SqlNotificationEventArgs args)
{
try
{
if (args.Info == SqlNotificationInfo.Invalid &&
args.Source == SqlNotificationSource.Statement &&
args.Type == SqlNotificationType.Subscribe)
throw new InvalidOperationException("Invalid query for SqlDependency") { Data = { { "query", query.PlainSql() } } };
if (args.Info == SqlNotificationInfo.PreviousFire)
throw new InvalidOperationException("The same transaction that loaded the data is invalidating it! Table: {0} SubTables: {1} ".
FormatWith(Table, subTables?.Select(e=>e.Table).ToString(","))) { Data = { { "query", query.PlainSql() } } };
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("Change {0}".FormatWith(GetType().TypeName()));
Reset();
Interlocked.Increment(ref invalidations);
controller.OnChange(this, args);
}
catch (Exception e)
{
e.LogException();
}
}
public void ResetAll(bool forceReset)
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("ResetAll {0}".FormatWith(GetType().TypeName()));
Reset();
if (forceReset)
{
invalidations = 0;
hits = 0;
loads = 0;
sumLoadTime = 0;
}
else
{
Interlocked.Increment(ref invalidations);
}
if (subTables != null)
foreach (var st in subTables)
st.ResetAll(forceReset);
}
public abstract void SchemaCompleted();
internal void LoadAll()
{
Load();
if (subTables != null)
foreach (var st in subTables)
st.LoadAll();
}
protected abstract void Load();
protected abstract void Reset();
public abstract Type Type { get; }
public abstract int? Count { get; }
int invalidations;
public int Invalidations { get { return invalidations; } }
protected int hits;
public int Hits { get { return hits; } }
int loads;
public int Loads { get { return loads; } }
long sumLoadTime;
public TimeSpan SumLoadTime
{
get { return TimeSpan.FromMilliseconds(sumLoadTime / PerfCounter.FrequencyMilliseconds); }
}
protected IDisposable MeasureLoad()
{
long start = PerfCounter.Ticks;
return new Disposable(() =>
{
sumLoadTime += (PerfCounter.Ticks - start);
Interlocked.Increment(ref loads);
});
}
internal static readonly MethodInfo ToStringMethod = ReflectionTools.GetMethodInfo((object o) => o.ToString());
internal abstract bool Contains(PrimaryKey primaryKey);
}
class CachedTable<T> : CachedTableBase where T : Entity
{
Table table;
ResetLazy<Dictionary<PrimaryKey, object>> rows;
public Dictionary<PrimaryKey, object> GetRows()
{
return rows.Value;
}
Func<FieldReader, object> rowReader;
Action<object, IRetriever, T> completer;
Expression<Action<object, IRetriever, T>> completerExpression;
Func<object, PrimaryKey> idGetter;
Expression<Func<PrimaryKey, string>> toStrGetterExpression = null!;
Func<PrimaryKey, string> toStrGetter = null!;
public override IColumn? ParentColumn { get; set; }
SemiCachedController<T>? semiCachedController;
public CachedTable(ICacheLogicController controller, AliasGenerator? aliasGenerator, string? lastPartialJoin, string? remainingJoins)
: base(controller)
{
this.table = Schema.Current.Table(typeof(T));
CachedTableConstructor ctr = this.Constructor = new CachedTableConstructor(this, aliasGenerator);
var isPostgres = Schema.Current.Settings.IsPostgres;
//Query
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
{
string select = "SELECT\r\n{0}\r\nFROM {1} {2}\r\n".FormatWith(
Table.Columns.Values.ToString(c => ctr.currentAlias + "." + c.Name.SqlEscape(isPostgres), ",\r\n"),
table.Name.ToString(),
ctr.currentAlias!.ToString());
ctr.remainingJoins = lastPartialJoin == null ? null : lastPartialJoin + ctr.currentAlias + ".Id\r\n" + remainingJoins;
if (ctr.remainingJoins != null)
select += ctr.remainingJoins;
query = new SqlPreCommandSimple(select);
}
//Reader
{
rowReader = ctr.GetRowReader();
}
//Completer
{
ParameterExpression me = Expression.Parameter(typeof(T), "me");
var block = ctr.MaterializeEntity(me, table);
completerExpression = Expression.Lambda<Action<object, IRetriever, T>>(block, CachedTableConstructor.originObject, CachedTableConstructor.retriever, me);
completer = completerExpression.Compile();
idGetter = ctr.GetPrimaryKeyGetter((IColumn)table.PrimaryKey);
}
rows = new ResetLazy<Dictionary<PrimaryKey, object>>(() =>
{
return SqlServerRetry.Retry(() =>
{
CacheLogic.AssertSqlDependencyStarted();
Table table = Connector.Current.Schema.Table(typeof(T));
Dictionary<PrimaryKey, object> result = new Dictionary<PrimaryKey, object>();
using (MeasureLoad())
using (Connector.Override(Connector.Current.ForDatabase(table.Name.Schema?.Database)))
using (Transaction tr = Transaction.ForceNew(IsolationLevel.ReadCommitted))
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("Load {0}".FormatWith(GetType().TypeName()));
Connector.Current.ExecuteDataReaderOptionalDependency(query, OnChange, fr =>
{
object obj = rowReader(fr);
result[idGetter(obj)] = obj; //Could be repeated joins
});
tr.Commit();
}
return result;
});
}, mode: LazyThreadSafetyMode.ExecutionAndPublication);
if(!CacheLogic.WithSqlDependency && lastPartialJoin.HasText()) //Is semi
{
semiCachedController = new SemiCachedController<T>(this);
}
}
public override void SchemaCompleted()
{
toStrGetterExpression = ToStringExpressionVisitor.GetToString<T>(this.Constructor, s => s.ToString());
toStrGetter = toStrGetterExpression.Compile();
if (this.subTables != null)
foreach (var item in this.subTables)
item.SchemaCompleted();
}
protected override void Reset()
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine((rows.IsValueCreated ? "RESET {0}" : "Reset {0}").FormatWith(GetType().TypeName()));
rows.Reset();
if (this.BackReferenceDictionaries != null)
{
foreach (var item in this.BackReferenceDictionaries.Values)
{
item.Reset();
}
}
}
protected override void Load()
{
rows.Load();
}
public string GetToString(PrimaryKey id)
{
return toStrGetter(id);
}
public object GetRow(PrimaryKey id)
{
Interlocked.Increment(ref hits);
var origin = this.GetRows().TryGetC(id);
if (origin == null)
throw new EntityNotFoundException(typeof(T), id);
return origin;
}
public string? TryGetToString(PrimaryKey id)
{
Interlocked.Increment(ref hits);
var origin = this.GetRows().TryGetC(id);
if (origin == null)
return null;
return toStrGetter(id);
}
public void Complete(T entity, IRetriever retriever)
{
Interlocked.Increment(ref hits);
var origin = this.GetRows().TryGetC(entity.Id);
if (origin == null)
throw new EntityNotFoundException(typeof(T), entity.Id);
completer(origin, retriever, entity);
var additional = Schema.Current.GetAdditionalBindings(typeof(T));
if(additional != null)
{
foreach (var ab in additional)
ab.SetInMemory(entity, retriever);
}
}
internal IEnumerable<PrimaryKey> GetAllIds()
{
Interlocked.Increment(ref hits);
return this.GetRows().Keys;
}
public override int? Count
{
get { return rows.IsValueCreated ? rows.Value.Count : (int?)null; }
}
public override Type Type
{
get { return typeof(T); }
}
public override ITable Table
{
get { return table; }
}
internal override bool Contains(PrimaryKey primaryKey)
{
return this.GetRows().ContainsKey(primaryKey);
}
ConcurrentDictionary<LambdaExpression, ResetLazy<Dictionary<PrimaryKey, List<PrimaryKey>>>> BackReferenceDictionaries =
new ConcurrentDictionary<LambdaExpression, ResetLazy<Dictionary<PrimaryKey, List<PrimaryKey>>>>(ExpressionComparer.GetComparer<LambdaExpression>(false));
internal Dictionary<PrimaryKey, List<PrimaryKey>> GetBackReferenceDictionary<R>(Expression<Func<T, Lite<R>?>> backReference)
where R : Entity
{
var lazy = BackReferenceDictionaries.GetOrAdd(backReference, br =>
{
var column = GetColumn(Reflector.GetMemberList((Expression<Func<T, Lite<R>>>)br));
var idGetter = this.Constructor.GetPrimaryKeyGetter(table.PrimaryKey);
if (column.Nullable.ToBool())
{
var backReferenceGetter = this.Constructor.GetPrimaryKeyNullableGetter(column);
return new ResetLazy<Dictionary<PrimaryKey, List<PrimaryKey>>>(() =>
{
return this.rows.Value.Values
.Where(a => backReferenceGetter(a) != null)
.GroupToDictionary(a => backReferenceGetter(a)!.Value, a => idGetter(a));
}, LazyThreadSafetyMode.ExecutionAndPublication);
}
else
{
var backReferenceGetter = this.Constructor.GetPrimaryKeyGetter(column);
return new ResetLazy<Dictionary<PrimaryKey, List<PrimaryKey>>>(() =>
{
return this.rows.Value.Values
.GroupToDictionary(a => backReferenceGetter(a), a => idGetter(a));
}, LazyThreadSafetyMode.ExecutionAndPublication);
}
});
return lazy.Value;
}
private IColumn GetColumn(MemberInfo[] members)
{
IFieldFinder? current = (Table)this.Table;
Field? field = null;
for (int i = 0; i < members.Length - 1; i++)
{
if (current == null)
throw new InvalidOperationException("{0} does not implement {1}".FormatWith(field, typeof(IFieldFinder).Name));
field = current.GetField(members[i]);
current = field as IFieldFinder;
}
var lastMember = members[members.Length - 1];
if (lastMember is Type t)
return ((FieldImplementedBy)field!).ImplementationColumns.GetOrThrow(t);
else if (current != null)
return (IColumn)current.GetField(lastMember);
else
throw new InvalidOperationException("Unexpected");
}
}
class CachedTableMList<T> : CachedTableBase
{
public override IColumn? ParentColumn { get; set; }
TableMList table;
ResetLazy<Dictionary<PrimaryKey, Dictionary<PrimaryKey, object>>> relationalRows;
static ParameterExpression result = Expression.Parameter(typeof(T));
Func<FieldReader, object> rowReader;
Expression<Func<object, IRetriever, MList<T>.RowIdElement>> activatorExpression;
Func<object, IRetriever, MList<T>.RowIdElement> activator;
Func<object, PrimaryKey> parentIdGetter;
Func<object, PrimaryKey> rowIdGetter;
public CachedTableMList(ICacheLogicController controller, TableMList table, AliasGenerator? aliasGenerator, string lastPartialJoin, string? remainingJoins)
: base(controller)
{
this.table = table;
var isPostgres = Schema.Current.Settings.IsPostgres;
CachedTableConstructor ctr = this.Constructor= new CachedTableConstructor(this, aliasGenerator);
//Query
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
{
string select = "SELECT\r\n{0}\r\nFROM {1} {2}\r\n".FormatWith(
ctr.table.Columns.Values.ToString(c => ctr.currentAlias + "." + c.Name.SqlEscape(isPostgres), ",\r\n"),
table.Name.ToString(),
ctr.currentAlias!.ToString());
ctr.remainingJoins = lastPartialJoin + ctr.currentAlias + "." + table.BackReference.Name.SqlEscape(isPostgres) + "\r\n" + remainingJoins;
query = new SqlPreCommandSimple(select);
}
//Reader
{
rowReader = ctr.GetRowReader();
}
//Completer
{
List<Expression> instructions = new List<Expression>
{
Expression.Assign(ctr.origin, Expression.Convert(CachedTableConstructor.originObject, ctr.tupleType)),
Expression.Assign(result, ctr.MaterializeField(table.Field))
};
var ci = typeof(MList<T>.RowIdElement).GetConstructor(new []{typeof(T), typeof(PrimaryKey), typeof(int?)});
var order = table.Order == null ? Expression.Constant(null, typeof(int?)) :
ctr.GetTupleProperty(table.Order).Nullify();
instructions.Add(Expression.New(ci, result, CachedTableConstructor.NewPrimaryKey(ctr.GetTupleProperty(table.PrimaryKey)), order));
var block = Expression.Block(typeof(MList<T>.RowIdElement), new[] { ctr.origin, result }, instructions);
activatorExpression = Expression.Lambda<Func<object, IRetriever, MList<T>.RowIdElement>>(block, CachedTableConstructor.originObject, CachedTableConstructor.retriever);
activator = activatorExpression.Compile();
parentIdGetter = ctr.GetPrimaryKeyGetter(table.BackReference);
rowIdGetter = ctr.GetPrimaryKeyGetter(table.PrimaryKey);
}
relationalRows = new ResetLazy<Dictionary<PrimaryKey, Dictionary<PrimaryKey, object>>>(() =>
{
return SqlServerRetry.Retry(() =>
{
CacheLogic.AssertSqlDependencyStarted();
Dictionary<PrimaryKey, Dictionary<PrimaryKey, object>> result = new Dictionary<PrimaryKey, Dictionary<PrimaryKey, object>>();
using (MeasureLoad())
using (Connector.Override(Connector.Current.ForDatabase(table.Name.Schema?.Database)))
using (Transaction tr = Transaction.ForceNew(IsolationLevel.ReadCommitted))
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("Load {0}".FormatWith(GetType().TypeName()));
Connector.Current.ExecuteDataReaderOptionalDependency(query, OnChange, fr =>
{
object obj = rowReader(fr);
PrimaryKey parentId = parentIdGetter(obj);
var dic = result.TryGetC(parentId);
if (dic == null)
result[parentId] = dic = new Dictionary<PrimaryKey, object>();
dic[rowIdGetter(obj)] = obj;
});
tr.Commit();
}
return result;
});
}, mode: LazyThreadSafetyMode.ExecutionAndPublication);
}
protected override void Reset()
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine((relationalRows.IsValueCreated ? "RESET {0}" : "Reset {0}").FormatWith(GetType().TypeName()));
relationalRows.Reset();
}
protected override void Load()
{
relationalRows.Load();
}
public MList<T> GetMList(PrimaryKey id, IRetriever retriever)
{
Interlocked.Increment(ref hits);
MList<T> result;
var dic = relationalRows.Value.TryGetC(id);
if (dic == null)
result = new MList<T>();
else
{
result = new MList<T>(dic.Count);
var innerList = ((IMListPrivate<T>)result).InnerList;
foreach (var obj in dic.Values)
{
innerList.Add(activator(obj, retriever));
}
((IMListPrivate)result).ExecutePostRetrieving(null!);
}
CachedTableConstructor.resetModifiedAction(retriever, result);
return result;
}
public override int? Count
{
get { return relationalRows.IsValueCreated ? relationalRows.Value.Count : (int?)null; }
}
public override Type Type
{
get { return typeof(MList<T>); }
}
public override ITable Table
{
get { return table; }
}
internal override bool Contains(PrimaryKey primaryKey)
{
throw new InvalidOperationException("CacheMListTable does not implements contains");
}
public override void SchemaCompleted()
{
if (this.subTables != null)
foreach (var item in this.subTables)
item.SchemaCompleted();
}
}
class CachedLiteTable<T> : CachedTableBase where T : Entity
{
public override IColumn? ParentColumn { get; set; }
Table table;
Alias currentAlias;
string lastPartialJoin;
string? remainingJoins;
Func<FieldReader, KeyValuePair<PrimaryKey, string>> rowReader = null!;
ResetLazy<Dictionary<PrimaryKey, string>> toStrings = null!;
SemiCachedController<T>? semiCachedController;
public CachedLiteTable(ICacheLogicController controller, AliasGenerator aliasGenerator, string lastPartialJoin, string? remainingJoins)
: base(controller)
{
this.table = Schema.Current.Table(typeof(T));
this.lastPartialJoin = lastPartialJoin;
this.remainingJoins = remainingJoins;
this.currentAlias = aliasGenerator.NextTableAlias(table.Name.Name);
if (!CacheLogic.WithSqlDependency)
{
semiCachedController = new SemiCachedController<T>(this);
}
}
public override void SchemaCompleted()
{
List<IColumn> columns = new List<IColumn> { table.PrimaryKey };
ParameterExpression reader = Expression.Parameter(typeof(FieldReader));
var expression = ToStringExpressionVisitor.GetToString(table, reader, columns);
var isPostgres = Schema.Current.Settings.IsPostgres;
//Query
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
{
string select = "SELECT {0}\r\nFROM {1} {2}\r\n".FormatWith(
columns.ToString(c => currentAlias + "." + c.Name.SqlEscape(isPostgres), ", "),
table.Name.ToString(),
currentAlias.ToString());
select += this.lastPartialJoin + currentAlias + "." + table.PrimaryKey.Name.SqlEscape(isPostgres) + "\r\n" + this.remainingJoins;
query = new SqlPreCommandSimple(select);
}
//Reader
{
var kvpConstructor = Expression.New(CachedTableConstructor.ciKVPIntString,
CachedTableConstructor.NewPrimaryKey(FieldReader.GetExpression(reader, 0, this.table.PrimaryKey.Type)),
expression);
rowReader = Expression.Lambda<Func<FieldReader, KeyValuePair<PrimaryKey, string>>>(kvpConstructor, reader).Compile();
}
toStrings = new ResetLazy<Dictionary<PrimaryKey, string>>(() =>
{
return SqlServerRetry.Retry(() =>
{
CacheLogic.AssertSqlDependencyStarted();
Dictionary<PrimaryKey, string> result = new Dictionary<PrimaryKey, string>();
using (MeasureLoad())
using (Connector.Override(Connector.Current.ForDatabase(table.Name.Schema?.Database)))
using (Transaction tr = Transaction.ForceNew(IsolationLevel.ReadCommitted))
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("Load {0}".FormatWith(GetType().TypeName()));
Connector.Current.ExecuteDataReaderOptionalDependency(query, OnChange, fr =>
{
var kvp = rowReader(fr);
result[kvp.Key] = kvp.Value;
});
tr.Commit();
}
return result;
});
}, mode: LazyThreadSafetyMode.ExecutionAndPublication);
if (this.subTables != null)
foreach (var item in this.subTables)
item.SchemaCompleted();
}
protected override void Reset()
{
if (toStrings == null)
return;
if (CacheLogic.LogWriter != null )
CacheLogic.LogWriter.WriteLine((toStrings.IsValueCreated ? "RESET {0}" : "Reset {0}").FormatWith(GetType().TypeName()));
toStrings.Reset();
}
protected override void Load()
{
if (toStrings == null)
return;
toStrings.Load();
}
public Lite<T> GetLite(PrimaryKey id, IRetriever retriever)
{
Interlocked.Increment(ref hits);
var lite = (LiteImp<T>)Lite.Create<T>(id, toStrings.Value[id]);
return retriever.ModifiablePostRetrieving(lite)!;
}
public override int? Count
{
get { return toStrings.IsValueCreated ? toStrings.Value.Count : (int?)null; }
}
public override Type Type
{
get { return typeof(Lite<T>); }
}
public override ITable Table
{
get { return table; }
}
class ToStringExpressionVisitor : ExpressionVisitor
{
ParameterExpression param;
ParameterExpression reader;
List<IColumn> columns;
Table table;
public ToStringExpressionVisitor(ParameterExpression param, ParameterExpression reader, List<IColumn> columns, Table table)
{
this.param = param;
this.reader = reader;
this.columns = columns;
this.table = table;
}
public static Expression GetToString(Table table, ParameterExpression reader, List<IColumn> columns)
{
LambdaExpression lambda = ExpressionCleaner.GetFieldExpansion(table.Type, CachedTableBase.ToStringMethod)!;
if (lambda == null)
{
columns.Add(table.ToStrColumn!);
return FieldReader.GetExpression(reader, columns.Count - 1, typeof(string));
}
ToStringExpressionVisitor toStr = new ToStringExpressionVisitor(
lambda.Parameters.SingleEx(),
reader,
columns,
table
);
var result = toStr.Visit(lambda.Body);
return result;
}
protected override Expression VisitUnary(UnaryExpression node)
{
if (node.NodeType == ExpressionType.Convert)
{
var obj = Visit(node.Operand);
return Expression.Convert(obj, node.Type);
}
return base.VisitUnary(node);
}
static MethodInfo miMixin = ReflectionTools.GetMethodInfo((Entity e) => e.Mixin<MixinEntity>()).GetGenericMethodDefinition();
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression == param)
{
var field = table.GetField(node.Member);
var column = GetColumn(field);
columns.Add(column);
return FieldReader.GetExpression(reader, columns.Count - 1, column.Type);
}
if (node.Expression is MethodCallExpression me && me.Method.IsInstantiationOf(miMixin))
{
var type = me.Method.GetGenericArguments()[0];
var mixin = table.Mixins!.GetOrThrow(type);
var field = mixin.GetField(node.Member);
var column = GetColumn(field);
columns.Add(column);
return FieldReader.GetExpression(reader, columns.Count - 1, column.Type);
}
return base.VisitMember(node);
}
private IColumn GetColumn(Field field)
{
if (field is FieldPrimaryKey || field is FieldValue || field is FieldTicks)
return (IColumn)field;
throw new InvalidOperationException("{0} not supported when caching the ToString for a Lite of a transacional entity ({1})".FormatWith(field.GetType().TypeName(), this.table.Type.TypeName()));
}
}
internal override bool Contains(PrimaryKey primaryKey)
{
return this.toStrings.Value.ContainsKey(primaryKey);
}
}
public class SemiCachedController<T> where T : Entity
{
CachedTableBase cachedTable;
public SemiCachedController(CachedTableBase cachedTable)
{
this.cachedTable = cachedTable;
CacheLogic.semiControllers.GetOrCreate(typeof(T)).Add(cachedTable);
var ee = Schema.Current.EntityEvents<T>();
ee.Saving += ident =>
{
if (ident.IsGraphModified && !ident.IsNew)
{
cachedTable.LoadAll();
if (cachedTable.Contains(ident.Id))
DisableAndInvalidate();
}
};
//ee.PreUnsafeDelete += query => DisableAndInvalidate();
ee.PreUnsafeUpdate += (update, entityQuery) => { DisableAndInvalidateMassive(); return null; };
ee.PreUnsafeInsert += (query, constructor, entityQuery) =>
{
if (constructor.Body.Type.IsInstantiationOf(typeof(MListElement<,>)))
DisableAndInvalidateMassive();
return constructor;
};
ee.PreUnsafeMListDelete += (mlistQuery, entityQuery) => { DisableAndInvalidateMassive(); return null; };
ee.PreBulkInsert += inMListTable =>
{
if (inMListTable)
DisableAndInvalidateMassive();
};
}
void DisableAndInvalidateMassive()
{
if (CacheLogic.IsAssumedMassiveChangeAsInvalidation<T>())
DisableAndInvalidate();
}
void DisableAndInvalidate()
{
CacheLogic.DisableAllConnectedTypesInTransaction(this.cachedTable.controller.Type);
Transaction.PostRealCommit -= Transaction_PostRealCommit;
Transaction.PostRealCommit += Transaction_PostRealCommit;
}
void Transaction_PostRealCommit(Dictionary<string, object> obj)
{
cachedTable.ResetAll(forceReset: false);
CacheLogic.NotifyInvalidateAllConnectedTypes(this.cachedTable.controller.Type);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using CrystalDecisions.Shared;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmEmergencyProcedures.
/// </summary>
public partial class frmProfileServiceTypes : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
protected System.Web.UI.WebControls.Label Label2;
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (Session["ProfileType"].ToString() == "Producer")
{
lblTitle.Text = "Business Models";
lblBusProfiles.Text = "Business: " + Session["ProfilesName"].ToString();
lblContent3.Text = "As indicated earlier, a business model"
+ " identifies the various services that are delivered for a given industry or function and,"
+ " For each service, it then identifies key service"
+ " deliverables, as well as related delivery procedures, staffing and other resource requirements, clients and service standards.";
lblContent1.Text="Thus, the list of services below provides a first look at the business"
+ " indicated above."
+ " Use the 'Add Services' button to add to this list as needed.";
lblContent2.Text="Once the list of services is complete, proceed to add details for each service listed below"
+ " by clicking on the"
+ " pushbutton titled 'Deliverables' to the right of each given service.";
}
/*else
{
lblTitle.Text = "EcoSys: Individual/Household Characteristics";
lblBusProfiles.Text = "Type of Characteristic: " + Session["ProfilesName"].ToString();
lblContent3.Text = "To continue, click on 'Events' for the appropriate stage in the list below.";
lblContent1.Visible = false;
lblContent2.Visible = false;
DataGrid1.Columns[3].HeaderText = "Stages";
DataGrid1.Columns[5].HeaderText = "";
lblOverview.Visible = false;
btnRpt1.Visible = false;
btnRpt2.Visible = false;
btnRpt3.Visible = false;
btnRpt4.Visible = false;
btnRpt5.Visible = false;
if (Session["startForm"].ToString() == "frmMainProfileMgr")
{
btnAdd.Visible = false;
}
}*/
if (!IsPostBack)
{
Load_Procedures();
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
}
#endregion
private void Load_Procedures()
{
/*lblProfilesName.Text = "Business Profile for: " + Session["ProfilesName"].ToString();
lblProcs.Text = "To review key procedures involved in generating one of more of the various service"
+ " deliverables, ";
lblStaff.Text = "To review various staff roles involved in executing key processes above, ";
lblOther.Text = "To review various types of goods and services involved in executing key processes above, ";*/
loadData();
}
private void loadData ()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_RetrieveProfileServiceTypes";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=Session["ProfilesId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"ProfileServices");
if (ds.Tables["ProfileServices"].Rows.Count == 0)
{
DataGrid1.Visible = false;
lblContent3.Text = "There are no services identified as yet for this business.";
}
else
{
Session["ds"] = ds;
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
refreshGrid();
}
}
private void refreshGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tb = (TextBox) (i.Cells[1].FindControl("txtSeq"));
Button btnD = (Button)(i.Cells[5].FindControl("btnDeliver"));
Button btnR = (Button)(i.Cells[5].FindControl("btnRemove"));
if (i.Cells[6].Text == " ")
{
tb.Text="99";
}
else tb.Text=i.Cells[6].Text;
/*if (Session["startForm"].ToString() == "frmMainProfileMgr")
{
if (Session["ProfileType"].ToString() == "Consumer")
{
btnD.Text = "Events";
btnR.Visible = false;
}
}*/
}
}
protected void btnAdd_Click(object sender, System.EventArgs e)
{
updateGrid();
Session["CServiceTypes"] = "frmProfileServiceTypes";
Response.Redirect (strURL + "frmServiceTypes.aspx?");
}
protected void btnExit_Click(object sender, System.EventArgs e)
{
updateGrid();
Exit();
}
private void updateGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tb = (TextBox) (i.Cells[1].FindControl("txtSeq"));
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_UpdatePSSeqNo";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@Id", SqlDbType.Int);
cmd.Parameters ["@Id"].Value=i.Cells[0].Text;
cmd.Parameters.Add("@Seq", SqlDbType.Int);
cmd.Parameters ["@Seq"].Value=Int32.Parse(tb.Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
private void Exit()
{
Response.Redirect (strURL + Session["CPSTypes"].ToString() + ".aspx?");
}
protected void btnRpt1_Click(object sender, System.EventArgs e)
{
}
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "Deliver")
{
Session["CPSEvents"]="frmProfileServiceTypes";
Session["ProfileServicesId"]=e.Item.Cells[0].Text;
Session["ServicesId"]=e.Item.Cells[2].Text;
Session["ServiceName"]=e.Item.Cells[3].Text;
Response.Redirect(strURL + "frmProfileServiceEvents.aspx?");
}
else if (e.CommandName == "Clients")
{
Session["CPSEPC"] = "frmProfileServiceTypes";
Session["ProfileServicesId"] = e.Item.Cells[0].Text;
Session["ServicesId"] = e.Item.Cells[2].Text;
Session["ServiceName"] = e.Item.Cells[3].Text;
Response.Redirect(strURL + "frmPSEPClient.aspx?");
}
/*else if (e.CommandName == "Services")
{
Session["CPSResources"] = "frmProfileServiceTypes";
Session["ProfileServicesId"] = e.Item.Cells[0].Text;
Session["RType"] = "0";
Response.Redirect(strURL + "frmProfileServiceResources.aspx?");
}
else if (e.CommandName == "Other")
{
Session["CPSResources"] = "frmProfileServiceTypes";
Session["ProfileServicesId"] = e.Item.Cells[0].Text;
Session["RType"] = "1";
Response.Redirect(strURL + "frmProfileServiceResources.aspx?");
}*/
else if (e.CommandName == "Remove")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_DeleteProfileService";//eps_DeleteSkillCourses
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Load_Procedures();
}
}
protected void btnRpt2_Click(object sender, EventArgs e)
{
}
protected void btnRpt3_Click(object sender, EventArgs e)
{
}
protected void btnRpt4_Click(object sender, EventArgs e)
{
}
protected void btnRpt5_Click(object sender, EventArgs e)
{
}
/*protected void btnRpt6_Click(object sender, EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "ProfilesId";
discreteval.Value = Session["ProfilesId"].ToString();
paramField.CurrentValues.Add(discreteval);
paramFields.Add(paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "rptProfOutputs.rpt";
rpts();
}*/
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public partial class Int16Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new short();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
short i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFF, short.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((short)0x8000), short.MinValue);
}
[Theory]
[InlineData((short)234, (short)234, 0)]
[InlineData((short)234, short.MinValue, 1)]
[InlineData((short)234, (short)-123, 1)]
[InlineData((short)234, (short)0, 1)]
[InlineData((short)234, (short)123, 1)]
[InlineData((short)234, (short)456, -1)]
[InlineData((short)234, short.MaxValue, -1)]
[InlineData((short)-234, (short)-234, 0)]
[InlineData((short)-234, (short)234, -1)]
[InlineData((short)-234, (short)-432, 1)]
[InlineData((short)234, null, 1)]
public void CompareTo_Other_ReturnsExpected(short i, object value, int expected)
{
if (value is short shortValue)
{
Assert.Equal(expected, Math.Sign(i.CompareTo(shortValue)));
}
Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
[Theory]
[InlineData("a")]
[InlineData(234)]
public void CompareTo_ObjectNotShort_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => ((short)123).CompareTo(value));
}
[Theory]
[InlineData((short)789, (short)789, true)]
[InlineData((short)789, (short)-789, false)]
[InlineData((short)789, (short)0, false)]
[InlineData((short)0, (short)0, true)]
[InlineData((short)-789, (short)-789, true)]
[InlineData((short)-789, (short)789, false)]
[InlineData((short)789, null, false)]
[InlineData((short)789, "789", false)]
[InlineData((short)789, 789, false)]
public static void Equals(short i1, object obj, bool expected)
{
if (obj is short)
{
short i2 = (short)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
[Fact]
public void GetTypeCode_Invoke_ReturnsInt16()
{
Assert.Equal(TypeCode.Int16, ((short)1).GetTypeCode());
}
public static IEnumerable<object[]> ToString_TestData()
{
foreach (NumberFormatInfo defaultFormat in new[] { null, NumberFormatInfo.CurrentInfo })
{
yield return new object[] { short.MinValue, "G", defaultFormat, "-32768" };
yield return new object[] { (short)-4567, "G", defaultFormat, "-4567" };
yield return new object[] { (short)0, "G", defaultFormat, "0" };
yield return new object[] { (short)4567, "G", defaultFormat, "4567" };
yield return new object[] { short.MaxValue, "G", defaultFormat, "32767" };
yield return new object[] { (short)4567, "D", defaultFormat, "4567" };
yield return new object[] { (short)4567, "D99", defaultFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004567" };
yield return new object[] { (short)0x2468, "x", defaultFormat, "2468" };
yield return new object[] { (short)-0x2468, "x", defaultFormat, "db98" };
yield return new object[] { (short)2468, "N", defaultFormat, string.Format("{0:N}", 2468.00) };
}
var customFormat = new NumberFormatInfo()
{
NegativeSign = "#",
NumberDecimalSeparator = "~",
NumberGroupSeparator = "*",
PositiveSign = "&",
NumberDecimalDigits = 2,
PercentSymbol = "@",
PercentGroupSeparator = ",",
PercentDecimalSeparator = ".",
PercentDecimalDigits = 5
};
yield return new object[] { (short)-2468, "N", customFormat, "#2*468~00" };
yield return new object[] { (short)2468, "N", customFormat, "2*468~00" };
yield return new object[] { (short)123, "E", customFormat, "1~230000E&002" };
yield return new object[] { (short)123, "F", customFormat, "123~00" };
yield return new object[] { (short)123, "P", customFormat, "12,300.00000 @" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(short i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
short i = 123;
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo emptyFormat = new NumberFormatInfo();
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
yield return new object[] { "-32768", defaultStyle, null, (short)-32768 };
yield return new object[] { "-123", defaultStyle, null, (short)-123 };
yield return new object[] { "0", defaultStyle, null, (short)0 };
yield return new object[] { "123", defaultStyle, null, (short)123 };
yield return new object[] { "+123", defaultStyle, null, (short)123 };
yield return new object[] { " 123 ", defaultStyle, null, (short)123 };
yield return new object[] { "32767", defaultStyle, null, (short)32767 };
yield return new object[] { "123", NumberStyles.HexNumber, null, (short)0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, (short)0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, (short)0xabc };
yield return new object[] { "1000", NumberStyles.AllowThousands, null, (short)1000 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, (short)-123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyFormat, (short)123 };
yield return new object[] { "123", NumberStyles.Any, emptyFormat, (short)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (short)0x12 };
yield return new object[] { "$1,000", NumberStyles.Currency, customFormat, (short)1000 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string value, NumberStyles style, IFormatProvider provider, short expected)
{
short result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.True(short.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, short.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Equal(expected, short.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.True(short.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Equal(expected, short.Parse(value, style));
}
Assert.Equal(expected, short.Parse(value, style, provider ?? new NumberFormatInfo()));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
customFormat.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", defaultStyle, null, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses
yield return new object[] { 1000.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands
yield return new object[] { 678.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal
yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) }; // Hex value
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal
yield return new object[] { "-32769", defaultStyle, null, typeof(OverflowException) }; // < min value
yield return new object[] { "32768", defaultStyle, null, typeof(OverflowException) }; // > max value
yield return new object[] { "2147483648", defaultStyle, null, typeof(OverflowException) }; // Internally, Parse pretends we are inputting an Int32, so this overflows
yield return new object[] { "FFFFFFFF", NumberStyles.HexNumber, null, typeof(OverflowException) }; // Hex number < 0
yield return new object[] { "10000", NumberStyles.HexNumber, null, typeof(OverflowException) }; // Hex number > max value
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
short result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.False(short.TryParse(value, out result));
Assert.Equal(default(short), result);
Assert.Throws(exceptionType, () => short.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Throws(exceptionType, () => short.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.False(short.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(default(short), result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Throws(exceptionType, () => short.Parse(value, style));
}
Assert.Throws(exceptionType, () => short.Parse(value, style, provider ?? new NumberFormatInfo()));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName)
{
short result = 0;
AssertExtensions.Throws<ArgumentException>(paramName, () => short.TryParse("1", style, null, out result));
Assert.Equal(default(short), result);
AssertExtensions.Throws<ArgumentException>(paramName, () => short.Parse("1", style));
AssertExtensions.Throws<ArgumentException>(paramName, () => short.Parse("1", style, null));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.Globalization;
using System.Windows.Forms;
using System.Windows.Threading;
using System.ComponentModel;
namespace Nixxis.Client
{
public delegate void CommandStateChangedDelegate(ICommand command);
// public delegate void HttpLinkCommandDelegate(
internal struct WellKnownCommands
{
public static WellKnownCommands[] List = new WellKnownCommands[]
{
new WellKnownCommands(CommandCodes.Ready, typeof(WaitForContactCommand), new object[] { null, CommandCodes.Ready } ),
new WellKnownCommands(CommandCodes.WaitForCall, typeof(WaitForContactCommand), new object[] { null, CommandCodes.WaitForCall } ),
new WellKnownCommands(CommandCodes.WaitForMail, typeof(WaitForContactCommand), new object[] { null, CommandCodes.WaitForMail } ),
new WellKnownCommands(CommandCodes.WaitForChat, typeof(WaitForContactCommand), new object[] { null, CommandCodes.WaitForChat } ),
new WellKnownCommands(CommandCodes.Pause, typeof(PauseCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.ExtendWrapup, typeof(WrapupCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.RequestAssistance, typeof(AssistanceCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.VoiceNewCall, typeof(VoiceNewCallCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.VoiceHold, typeof(VoiceHoldCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.VoiceRetrieve, typeof(VoiceRetrieveCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.VoiceTransfer, typeof(VoiceTransferCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.VoiceForward, typeof(VoiceForwardCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.VoiceConference, typeof(VoiceConferenceCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.VoiceHangup, typeof(VoiceHangupCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.VoiceRecord, typeof(VoiceRecordCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.VoiceListen, typeof(VoiceListenCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.MailNewMail, typeof(MailNewMailCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.MailReply, typeof(MailReplyCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.MailReplySender, typeof(MailReplySenderCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.MailForward, typeof(MailForwardCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.ChatNewCall, typeof(ChatNewCallCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.ChatHold, typeof(ChatHoldCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.ChatRetrieve, typeof(ChatRetrieveCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.ChatHangup, typeof(ChatHangupCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.TerminateContact, typeof(TerminateContactCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.PriorityPickup, typeof(PriorityPickupCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.StartScript, typeof(StartScriptCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.ChatForward, typeof(ChatForwardCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.ChatSpy, typeof(ChatSpyCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.SearchMode, typeof(SearchModeCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.SendMessage, typeof(SendMessageCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.ShowHistory, typeof(ShowHistoryCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.SetQualification, typeof(SetQualificationCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.SupervisionSelect, typeof(SupervisionSelectCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.ViewScreen, typeof(ViewScreenCommand), new object[] { null } ),
new WellKnownCommands(CommandCodes.ExternalSpy, typeof(ExternalSpyCommand), new object[] { null } ),
};
public CommandCodes Code;
public Type Type;
public Object[] ActivationData;
private WellKnownCommands(CommandCodes code, Type type, object[] activationData)
{
Code = code;
Type = type;
ActivationData = activationData;
}
}
public interface ICommand : System.Windows.Input.ICommand
{
HttpLink Link { get; }
CommandCodes Code { get; }
bool Authorized { get; }
bool Active { get; }
ToolStripItem LinkedItem { get; set; }
event CommandStateChangedDelegate StateChanged;
ResponseData Execute();
ResponseData Execute(bool parameter);
ResponseData Execute(int parameter);
ResponseData Execute(string parameter);
ResponseData Execute(params string[] parameters);
int LockState();
int ReleaseState();
int ReleaseState(bool changed);
}
public class BaseCommand : System.Windows.DependencyObject, ICommand, INotifyPropertyChanged
{
private HttpLink m_Link;
private CommandCodes m_Code;
private bool? m_Authorized = null;
private bool? m_Active = null;
private int m_StateLockCount;
private bool m_StateChanged;
private ToolStripItem m_LinkedItem;
protected string m_ActionCode;
protected bool m_SomeStateChanged;
public event CommandStateChangedDelegate StateChanged;
private CommandStateChangedDelegate m_InternalStateChanged;
public static readonly System.Windows.DependencyProperty ActiveProperty = System.Windows.DependencyProperty.Register("Active", typeof(bool?), typeof(BaseCommand), new System.Windows.PropertyMetadata(null, new System.Windows.PropertyChangedCallback(OnActiveChanged)));
public static readonly System.Windows.DependencyProperty AuthorizedProperty = System.Windows.DependencyProperty.Register("Authorized", typeof(bool?), typeof(BaseCommand), new System.Windows.PropertyMetadata(null, new System.Windows.PropertyChangedCallback(OnAuthorizedChanged)));
private static void OnActiveChanged(System.Windows.DependencyObject target, System.Windows.DependencyPropertyChangedEventArgs args)
{
}
private static void OnAuthorizedChanged(System.Windows.DependencyObject target, System.Windows.DependencyPropertyChangedEventArgs args)
{
}
private BaseCommand()
{
}
protected BaseCommand(HttpLink link, CommandCodes code)
{
m_Link = link;
m_Code = code;
m_ActionCode = code.ToString().ToLowerInvariant();
m_InternalStateChanged = new CommandStateChangedDelegate(InternalStateChanged);
}
private void InternalStateChanged(ICommand target)
{
if (LinkedItem != null)
{
try
{
LinkedItem.Enabled = target.Authorized;
if (LinkedItem is ToolStripButton)
{
((ToolStripButton)target.LinkedItem).Checked = Active;
}
else if (LinkedItem is ToolStripMenuItem)
{
((ToolStripMenuItem)target.LinkedItem).Checked = Active;
}
}
catch
{
}
}
if (m_Active != (bool?)GetValue(ActiveProperty))
{
Debug.WriteLine(string.Format("{0} {1} active: {2}", this.GetType().Name, this.Code.ToString(), m_Active), "CommandState");
SetValue(ActiveProperty, m_Active);
OnPropertyChanged(new PropertyChangedEventArgs("Active"));
}
if (m_Authorized != (bool?)GetValue(AuthorizedProperty))
{
Debug.WriteLine(string.Format("{0} {1} enabled: {2}", this.GetType().Name, this.Code.ToString(), m_Authorized), "CommandState");
SetValue(AuthorizedProperty, m_Authorized);
OnPropertyChanged(new PropertyChangedEventArgs("Authorized"));
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
if (StateChanged != null)
StateChanged(target);
}
private void FireStateChanged()
{
m_Link.Invoke(new CommandStateChangedDelegate(InternalStateChanged), this);
}
public int LockState()
{
lock (this)
{
return ++m_StateLockCount;
}
}
public int ReleaseState()
{
return ReleaseState(true);
}
public int ReleaseState(bool changed)
{
int NewLockCount;
lock(this)
{
if (changed)
m_StateChanged = true;
NewLockCount = --m_StateLockCount;
}
if (NewLockCount == 0)
{
bool DoFire;
lock (this)
{
DoFire = m_StateChanged;
m_StateChanged = false;
}
if(DoFire)
FireStateChanged();
}
return NewLockCount;
}
internal void SetAuthorized(bool? value)
{
if (m_Authorized != value)
{
LockState();
if (m_Authorized != value)
{
m_Authorized = value;
ReleaseState(true);
}
else
{
ReleaseState(false);
}
}
}
internal void SetActive(bool? value)
{
if (m_Active != value)
{
LockState();
if (m_Active != value)
{
m_Active = value;
ReleaseState(true);
}
else
{
ReleaseState(false);
}
}
}
#region ICommand Members
public HttpLink Link
{
get
{
return m_Link;
}
}
public CommandCodes Code
{
get
{
return m_Code;
}
}
public bool Authorized
{
get
{
return ((m_Authorized.HasValue) ? m_Authorized.Value : false);
}
}
public bool Active
{
get
{
return ((m_Active.HasValue) ? m_Active.Value : false);
}
}
public bool? Active3S
{
get
{
return m_Active;
}
}
public ToolStripItem LinkedItem
{
get
{
return m_LinkedItem;
}
set
{
LockState();
m_LinkedItem = value;
ReleaseState(true);
}
}
public virtual ResponseData ExecuteDirect(string[] urlParameters, string dataParameters)
{
return m_Link.GetResponseData(m_Link.BuildRequest(m_ActionCode, urlParameters, dataParameters));
}
protected virtual ResponseData Execute(string[] urlParameters, string dataParameters)
{
if(!Authorized)
return ResponseData.Forbidden;
return m_Link.GetResponseData(m_Link.BuildRequest(m_ActionCode, urlParameters, dataParameters));
}
public ResponseData Execute(string parameter)
{
return Execute((string[])null, parameter);
}
public ResponseData Execute()
{
return Execute((string[])null, (string)null);
}
public ResponseData Execute(bool parameter)
{
return Execute(parameter ? "1" : "0", null);
}
public ResponseData Execute(int parameter)
{
return Execute(parameter.ToString(), null);
}
public ResponseData Execute(params string[] parameters)
{
return Execute((string[])null, string.Join("\n", parameters));
}
#endregion
public bool CanExecute(object parameter)
{
return Authorized;
}
public event EventHandler CanExecuteChanged;
public event CustomCommandExecuteHandler BeforeExecute;
public void Execute(object parameter)
{
if (BeforeExecute != null && BeforeExecute(parameter))
return;
if (parameter == null)
Execute((string[])null, (string)null);
else if (parameter is string)
Execute((string[])null, (string)parameter);
else if (parameter is string[])
Execute((string[])null, string.Join("\n", (string[])parameter));
else if (parameter is int)
Execute((int)parameter);
else if (parameter is bool)
Execute((bool)parameter);
}
protected void OnPropertyChanged(PropertyChangedEventArgs args)
{
if (PropertyChanged != null)
PropertyChanged(this, args);
}
public event PropertyChangedEventHandler PropertyChanged;
}
public delegate bool CustomCommandExecuteHandler(object parameter);
public class InternalCommand : System.Windows.DependencyObject, ICommand, INotifyPropertyChanged
{
Action<InternalCommand, object> m_Action;
HttpLink m_Link;
bool m_Authorized;
bool m_Active;
ICommand m_LinkedCommand;
public InternalCommand(HttpLink link, Action<InternalCommand, object> action)
{
m_Link = link;
m_Action = action;
}
public HttpLink Link
{
get
{
return m_Link;
}
}
public ICommand LinkedCommand
{
get
{
return m_LinkedCommand;
}
set
{
if (m_LinkedCommand != null)
m_LinkedCommand.StateChanged -= new CommandStateChangedDelegate(LinkedCommand_StateChanged);
m_LinkedCommand = value;
if (m_LinkedCommand != null)
m_LinkedCommand.StateChanged += new CommandStateChangedDelegate(LinkedCommand_StateChanged);
}
}
void Sync_LinkedCommand_StateChanged()
{
this.Authorized = m_LinkedCommand.Authorized;
this.Active = m_LinkedCommand.Active;
}
void LinkedCommand_StateChanged(ICommand command)
{
m_Link.Invoke(new HttpLinkEventDelegate(Sync_LinkedCommand_StateChanged), null);
}
public CommandCodes Code
{
get { return (CommandCodes)(-1); }
}
public bool Authorized
{
get
{
return m_Authorized;
}
set
{
if (m_Authorized != value)
{
m_Authorized = value;
OnPropertyChanged(new PropertyChangedEventArgs("Authorized"));
OnCanExecuteChanged();
}
}
}
public bool Active
{
get
{
return m_Active;
}
set
{
if (m_Active != value)
{
m_Active = value;
OnPropertyChanged(new PropertyChangedEventArgs("Active"));
}
}
}
public ToolStripItem LinkedItem
{
get
{
return null;
}
set
{
throw new NotImplementedException();
}
}
public event CommandStateChangedDelegate StateChanged;
public ResponseData Execute()
{
throw new NotImplementedException();
}
public ResponseData Execute(bool parameter)
{
throw new NotImplementedException();
}
public ResponseData Execute(int parameter)
{
throw new NotImplementedException();
}
public ResponseData Execute(string parameter)
{
throw new NotImplementedException();
}
public ResponseData Execute(params string[] parameters)
{
throw new NotImplementedException();
}
public int LockState()
{
throw new NotImplementedException();
}
public int ReleaseState()
{
throw new NotImplementedException();
}
public int ReleaseState(bool changed)
{
throw new NotImplementedException();
}
public bool CanExecute(object parameter)
{
return Authorized;
}
protected void OnCanExecuteChanged()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
m_Action.Invoke(this, parameter);
}
protected void OnPropertyChanged(PropertyChangedEventArgs args)
{
if (PropertyChanged != null)
PropertyChanged(this, args);
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class CustomCommand : BaseCommand
{
public CustomCommand(HttpLink link, string action)
: base(link, CommandCodes.Custom)
{
m_ActionCode = action;
}
}
public class WaitForContactCommand : BaseCommand
{
public WaitForContactCommand(HttpLink link, CommandCodes code)
: base(link, code)
{
}
protected override ResponseData Execute(string[] urlParameters, string dataParameters)
{
if (urlParameters == null || urlParameters.Length == 0)
{
// Force to execute the expected behavior even if transmitting multiple times
urlParameters = new string[] { (this.Active) ? "0" : "1" };
}
return base.Execute(urlParameters, dataParameters);
}
}
public class PauseCommand : BaseCommand
{
public PauseCommand(HttpLink link)
: base(link, CommandCodes.Pause)
{
}
}
public class VoiceHoldCommand : BaseCommand
{
public VoiceHoldCommand(HttpLink link)
: base(link, CommandCodes.VoiceHold)
{
}
}
public class VoiceRetrieveCommand : BaseCommand
{
public VoiceRetrieveCommand(HttpLink link)
: base(link, CommandCodes.VoiceRetrieve)
{
}
}
public class VoiceNewCallCommand : BaseCommand
{
public VoiceNewCallCommand(HttpLink link)
: base(link, CommandCodes.VoiceNewCall)
{
}
}
public class VoiceHangupCommand : BaseCommand
{
public VoiceHangupCommand(HttpLink link)
: base(link, CommandCodes.VoiceHangup)
{
}
}
public class VoiceTransferCommand : BaseCommand
{
public VoiceTransferCommand(HttpLink link)
: base(link, CommandCodes.VoiceTransfer)
{
}
}
public class VoiceForwardCommand : BaseCommand
{
public VoiceForwardCommand(HttpLink link)
: base(link, CommandCodes.VoiceForward)
{
}
}
public class VoiceConferenceCommand : BaseCommand
{
public VoiceConferenceCommand(HttpLink link)
: base(link, CommandCodes.VoiceConference)
{
}
}
public class ExternalSpyCommand : BaseCommand
{
public ExternalSpyCommand(HttpLink link)
: base(link, CommandCodes.ExternalSpy)
{
}
}
public class WrapupCommand : BaseCommand
{
public WrapupCommand(HttpLink link)
: base(link, CommandCodes.ExtendWrapup)
{
}
}
public class AssistanceCommand : BaseCommand
{
public AssistanceCommand(HttpLink link)
: base(link, CommandCodes.RequestAssistance)
{
}
}
public class VoiceRecordCommand : BaseCommand
{
public VoiceRecordCommand(HttpLink link)
: base(link, CommandCodes.VoiceRecord)
{
}
}
public class VoiceListenCommand : BaseCommand
{
public VoiceListenCommand(HttpLink link)
: base(link, CommandCodes.VoiceListen)
{
}
}
public class ViewScreenCommand : BaseCommand
{
public ViewScreenCommand(HttpLink link)
: base(link, CommandCodes.ViewScreen)
{
}
}
public class MailNewMailCommand : BaseCommand
{
public MailNewMailCommand(HttpLink link)
: base(link, CommandCodes.MailNewMail)
{
}
}
public class MailReplyCommand : BaseCommand
{
public MailReplyCommand(HttpLink link)
: base(link, CommandCodes.MailReply)
{
}
}
public class MailReplySenderCommand : BaseCommand
{
public MailReplySenderCommand(HttpLink link)
: base(link, CommandCodes.MailReplySender)
{
}
}
public class MailForwardCommand : BaseCommand
{
public MailForwardCommand(HttpLink link)
: base(link, CommandCodes.MailForward)
{
}
}
public class ChatNewCallCommand : BaseCommand
{
public ChatNewCallCommand(HttpLink link)
: base(link, CommandCodes.ChatNewCall)
{
}
}
public class ChatHoldCommand : BaseCommand
{
public ChatHoldCommand(HttpLink link)
: base(link, CommandCodes.ChatHold)
{
}
}
public class ChatRetrieveCommand : BaseCommand
{
public ChatRetrieveCommand(HttpLink link)
: base(link, CommandCodes.ChatRetrieve)
{
}
}
public class ChatHangupCommand : BaseCommand
{
public ChatHangupCommand(HttpLink link)
: base(link, CommandCodes.ChatHangup)
{
}
}
public class ChatForwardCommand : BaseCommand
{
public ChatForwardCommand(HttpLink link)
: base(link, CommandCodes.ChatForward)
{
}
}
public class TerminateContactCommand : BaseCommand
{
public TerminateContactCommand(HttpLink link)
: base(link, CommandCodes.TerminateContact)
{
}
}
public class PriorityPickupCommand : BaseCommand
{
public PriorityPickupCommand(HttpLink link)
: base(link, CommandCodes.PriorityPickup)
{
}
}
public class StartScriptCommand : BaseCommand
{
public StartScriptCommand(HttpLink link)
: base(link, CommandCodes.StartScript)
{
}
}
public class ChatSpyCommand : BaseCommand
{
public ChatSpyCommand(HttpLink link)
: base(link, CommandCodes.ChatSpy)
{
}
}
public class SearchModeCommand : BaseCommand
{
public SearchModeCommand(HttpLink link)
: base(link, CommandCodes.SearchMode)
{
}
}
public class SendMessageCommand : BaseCommand
{
public SendMessageCommand(HttpLink link)
: base(link, CommandCodes.SendMessage)
{
}
}
public class RequestAssistanceCommand : BaseCommand
{
public RequestAssistanceCommand(HttpLink link)
: base(link, CommandCodes.RequestAssistance)
{
}
}
public class ShowHistoryCommand : BaseCommand
{
public ShowHistoryCommand(HttpLink link)
: base(link, CommandCodes.ShowHistory)
{
}
}
public class SetQualificationCommand : BaseCommand
{
public SetQualificationCommand(HttpLink link)
: base(link, CommandCodes.SetQualification)
{
}
}
public class SupervisionSelectCommand : BaseCommand
{
public SupervisionSelectCommand(HttpLink link)
: base(link, CommandCodes.SupervisionSelect)
{
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for OriginsOperations.
/// </summary>
public static partial class OriginsOperationsExtensions
{
/// <summary>
/// Lists all of the existing origins within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static IPage<Origin> ListByEndpoint(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
return operations.ListByEndpointAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the existing origins within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Origin>> ListByEndpointAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByEndpointWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets an existing origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
public static Origin Get(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName)
{
return operations.GetAsync(resourceGroupName, profileName, endpointName, originName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets an existing origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Origin> GetAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, originName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
/// <param name='originUpdateProperties'>
/// Origin properties
/// </param>
public static Origin Update(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties)
{
return operations.UpdateAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
/// <param name='originUpdateProperties'>
/// Origin properties
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Origin> UpdateAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
/// <param name='originUpdateProperties'>
/// Origin properties
/// </param>
public static Origin BeginUpdate(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties)
{
return operations.BeginUpdateAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
/// <param name='originUpdateProperties'>
/// Origin properties
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Origin> BeginUpdateAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the existing origins within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Origin> ListByEndpointNext(this IOriginsOperations operations, string nextPageLink)
{
return operations.ListByEndpointNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the existing origins within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Origin>> ListByEndpointNextAsync(this IOriginsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByEndpointNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using MatterHackers.Agg.Image;
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// scanline_u8 class
//
//----------------------------------------------------------------------------
using System;
namespace MatterHackers.Agg
{
public interface IAlphaMask
{
byte pixel(int x, int y);
byte combine_pixel(int x, int y, byte val);
void fill_hspan(int x, int y, byte[] dst, int dstIndex, int num_pix);
void fill_vspan(int x, int y, byte[] dst, int dstIndex, int num_pix);
void combine_hspanFullCover(int x, int y, byte[] dst, int dstIndex, int num_pix);
void combine_hspan(int x, int y, byte[] dst, int dstIndex, int num_pix);
void combine_vspan(int x, int y, byte[] dst, int dstIndex, int num_pix);
};
public sealed class AlphaMaskByteUnclipped : IAlphaMask
{
private IImageByte m_rbuf;
private uint m_Step;
private uint m_Offset;
public static readonly int cover_shift = 8;
public static readonly int cover_none = 0;
public static readonly int cover_full = 255;
public AlphaMaskByteUnclipped(IImageByte rbuf, uint Step, uint Offset)
{
m_Step = Step;
m_Offset = Offset;
m_rbuf = rbuf;
}
public void attach(IImageByte rbuf)
{
m_rbuf = rbuf;
}
//--------------------------------------------------------------------
public byte pixel(int x, int y)
{
int bufferIndex = m_rbuf.GetBufferOffsetXY(x, y);
byte[] buffer = m_rbuf.GetBuffer();
return buffer[bufferIndex];
}
//--------------------------------------------------------------------
public byte combine_pixel(int x, int y, byte val)
{
unchecked
{
int bufferIndex = m_rbuf.GetBufferOffsetXY(x, y);
byte[] buffer = m_rbuf.GetBuffer();
return (byte)((255 + val * buffer[bufferIndex]) >> 8);
}
}
public void fill_hspan(int x, int y, byte[] dst, int dstIndex, int num_pix)
{
throw new NotImplementedException();
#if false
byte[] mask = m_rbuf.GetPixelPointerY(y) + x * m_Step + m_Offset;
do
{
*dst++ = *mask;
mask += m_Step;
}
while (--num_pix != 0);
#endif
}
public void combine_hspanFullCover(int x, int y, byte[] covers, int coversIndex, int count)
{
int maskIndex = m_rbuf.GetBufferOffsetXY(x, y);
byte[] mask = m_rbuf.GetBuffer();
do
{
covers[coversIndex++] = mask[maskIndex++];
}
while (--count != 0);
}
public void combine_hspan(int x, int y, byte[] covers, int coversIndex, int count)
{
int maskIndex = m_rbuf.GetBufferOffsetXY(x, y);
byte[] mask = m_rbuf.GetBuffer();
do
{
covers[coversIndex] = (byte)((255 + (covers[coversIndex]) * mask[maskIndex]) >> 8);
coversIndex++;
maskIndex++;
}
while (--count != 0);
}
public void fill_vspan(int x, int y, byte[] buffer, int bufferIndex, int num_pix)
{
throw new NotImplementedException();
#if false
byte[] mask = m_rbuf.GetPixelPointerY(y) + x * m_Step + m_Offset;
do
{
*dst++ = *mask;
mask += m_rbuf.StrideInBytes();
}
while (--num_pix != 0);
#endif
}
public void combine_vspan(int x, int y, byte[] dst, int dstIndex, int num_pix)
{
throw new NotImplementedException();
#if false
byte[] mask = m_rbuf.GetPixelPointerY(y) + x * m_Step + m_Offset;
do
{
*dst = (byte)((cover_full + (*dst) * (*mask)) >> cover_shift);
++dst;
mask += m_rbuf.StrideInBytes();
}
while (--num_pix != 0);
#endif
}
};
public sealed class AlphaMaskByteClipped : IAlphaMask
{
private IImageByte m_rbuf;
private uint m_Step;
private uint m_Offset;
public static readonly int cover_shift = 8;
public static readonly int cover_none = 0;
public static readonly int cover_full = 255;
public AlphaMaskByteClipped(IImageByte rbuf, uint Step, uint Offset)
{
m_Step = Step;
m_Offset = Offset;
m_rbuf = rbuf;
}
public void attach(IImageByte rbuf)
{
m_rbuf = rbuf;
}
//--------------------------------------------------------------------
public byte pixel(int x, int y)
{
unchecked
{
if ((uint)x < (uint)m_rbuf.Width
&& (uint)y < (uint)m_rbuf.Height)
{
int bufferIndex = m_rbuf.GetBufferOffsetXY(x, y);
byte[] buffer = m_rbuf.GetBuffer();
return buffer[bufferIndex];
}
}
return 0;
}
public byte combine_pixel(int x, int y, byte val)
{
unchecked
{
if ((uint)x < (uint)m_rbuf.Width
&& (uint)y < (uint)m_rbuf.Height)
{
int bufferIndex = m_rbuf.GetBufferOffsetXY(x, y);
byte[] buffer = m_rbuf.GetBuffer();
return (byte)((val * buffer[bufferIndex] + 255) >> 8);
}
}
return 0;
}
public void fill_hspan(int x, int y, byte[] dst, int dstIndex, int num_pix)
{
throw new NotImplementedException();
#if false
int xmax = (int)m_rbuf.Width() - 1;
int ymax = (int)m_rbuf.Height() - 1;
int count = num_pix;
byte[] covers = dst;
if (y < 0 || y > ymax)
{
agg_basics.MemClear(dst, num_pix);
return;
}
if (x < 0)
{
count += x;
if (count <= 0)
{
agg_basics.MemClear(dst, num_pix);
return;
}
agg_basics.MemClear(covers, -x);
covers -= x;
x = 0;
}
if (x + count > xmax)
{
int rest = x + count - xmax - 1;
count -= rest;
if (count <= 0)
{
agg_basics.MemClear(dst, num_pix);
return;
}
agg_basics.MemClear(covers + count, rest);
}
byte[] mask = m_rbuf.GetPixelPointerY(y) + x * m_Step + m_Offset;
do
{
*covers++ = *(mask);
mask += m_Step;
}
while (--count != 0);
#endif
}
public void combine_hspanFullCover(int x, int y, byte[] covers, int coversIndex, int num_pix)
{
int xmax = (int)m_rbuf.Width - 1;
int ymax = (int)m_rbuf.Height - 1;
int count = num_pix;
if (y < 0 || y > ymax)
{
agg_basics.MemClear(covers, coversIndex, num_pix);
return;
}
if (x < 0)
{
count += x;
if (count <= 0)
{
agg_basics.MemClear(covers, coversIndex, num_pix);
return;
}
agg_basics.MemClear(covers, coversIndex, -x);
coversIndex -= x;
x = 0;
}
if (x + count > xmax)
{
int rest = x + count - xmax - 1;
count -= rest;
if (count <= 0)
{
agg_basics.MemClear(covers, coversIndex, num_pix);
return;
}
agg_basics.MemClear(covers, coversIndex + count, rest);
}
int maskIndex = m_rbuf.GetBufferOffsetXY(x, y);
byte[] mask = m_rbuf.GetBuffer();
do
{
covers[coversIndex++] = mask[maskIndex++];
}
while (--count != 0);
}
public void combine_hspan(int x, int y, byte[] buffer, int bufferIndex, int num_pix)
{
int xmax = (int)m_rbuf.Width - 1;
int ymax = (int)m_rbuf.Height - 1;
int count = num_pix;
byte[] covers = buffer;
int coversIndex = bufferIndex;
if (y < 0 || y > ymax)
{
agg_basics.MemClear(buffer, bufferIndex, num_pix);
return;
}
if (x < 0)
{
count += x;
if (count <= 0)
{
agg_basics.MemClear(buffer, bufferIndex, num_pix);
return;
}
agg_basics.MemClear(covers, coversIndex, -x);
coversIndex -= x;
x = 0;
}
if (x + count > xmax)
{
int rest = x + count - xmax - 1;
count -= rest;
if (count <= 0)
{
agg_basics.MemClear(buffer, bufferIndex, num_pix);
return;
}
agg_basics.MemClear(covers, coversIndex + count, rest);
}
int maskIndex = m_rbuf.GetBufferOffsetXY(x, y);
byte[] mask = m_rbuf.GetBuffer();
do
{
covers[coversIndex] = (byte)(((covers[coversIndex]) * mask[maskIndex] + 255) >> 8);
coversIndex++;
maskIndex++;
}
while (--count != 0);
}
public void fill_vspan(int x, int y, byte[] buffer, int bufferIndex, int num_pix)
{
throw new NotImplementedException();
#if false
int xmax = (int)m_rbuf.Width() - 1;
int ymax = (int)m_rbuf.Height() - 1;
int count = num_pix;
byte[] covers = dst;
if (x < 0 || x > xmax)
{
agg_basics.MemClear(dst, num_pix);
return;
}
if (y < 0)
{
count += y;
if (count <= 0)
{
agg_basics.MemClear(dst, num_pix);
return;
}
agg_basics.MemClear(covers, -y);
covers -= y;
y = 0;
}
if (y + count > ymax)
{
int rest = y + count - ymax - 1;
count -= rest;
if (count <= 0)
{
agg_basics.MemClear(dst, num_pix);
return;
}
agg_basics.MemClear(covers + count, rest);
}
byte[] mask = m_rbuf.GetPixelPointerY(y) + x * m_Step + m_Offset;
do
{
*covers++ = *mask;
mask += m_rbuf.StrideInBytes();
}
while (--count != 0);
#endif
}
public void combine_vspan(int x, int y, byte[] buffer, int bufferIndex, int num_pix)
{
throw new NotImplementedException();
#if false
int xmax = (int)m_rbuf.Width() - 1;
int ymax = (int)m_rbuf.Height() - 1;
int count = num_pix;
byte[] covers = dst;
if (x < 0 || x > xmax)
{
agg_basics.MemClear(dst, num_pix);
return;
}
if (y < 0)
{
count += y;
if (count <= 0)
{
agg_basics.MemClear(dst, num_pix);
return;
}
agg_basics.MemClear(covers, -y);
covers -= y;
y = 0;
}
if (y + count > ymax)
{
int rest = y + count - ymax - 1;
count -= rest;
if (count <= 0)
{
agg_basics.MemClear(dst, num_pix);
return;
}
agg_basics.MemClear(covers + count, rest);
}
byte[] mask = m_rbuf.GetPixelPointerY(y) + x * m_Step + m_Offset;
do
{
*covers = (byte)((cover_full + (*covers) * (*mask)) >> cover_shift);
++covers;
mask += m_rbuf.StrideInBytes();
}
while (--count != 0);
#endif
}
};
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Adxstudio.Xrm.Web.Mvc.Html;
using Adxstudio.Xrm.Web.UI.JsonConfiguration;
using Adxstudio.Xrm.Web.UI.WebControls;
using Adxstudio.Xrm.Resources;
namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView
{
public static class FormActionControls
{
private static readonly string DefaultModalDeleteTitle = "<span class='fa fa-trash-o' aria-hidden='true'></span> " + ResourceManager.GetString("Delete_Button_Text");
private static readonly string DefaultModalDeleteBody = ResourceManager.GetString("Record_Deletion_Confirmation_Message");
private static readonly string DefaultModalDeletePrimaryButtonText = ResourceManager.GetString("Delete_Button_Text");
private static readonly string DefaultModalDeleteCancelButtonText = ResourceManager.GetString("Cancel_DefaultText");
private static readonly string DefaultModalDismissButtonSrText = ResourceManager.GetString("Close_DefaultText");
private static readonly string DefaultModalProcessingText = ResourceManager.GetString("Default_Modal_Processing_Text");
public static PlaceHolder FormActionLinkListItem(HtmlHelper html, ViewActionLink viewActionLink, ActionButtonStyle actionButtonStyle, bool autoGenerateSteps = false,
string submitButtonID = "SubmitButton", string submitButtonCommandName = "", string validationGroup = null, string submitButtonBusyText = null,
string actionNavbarCssClass = null, string nextButtonId = "NextButton", string previousButtonId = "PreviousButton")
{
submitButtonBusyText = submitButtonBusyText == null ? DefaultModalProcessingText : submitButtonBusyText;
var placeHolder = new PlaceHolder();
if (actionButtonStyle == ActionButtonStyle.DropDown)
{
placeHolder.Controls.Add(
new LiteralControl("<li>"));
}
switch (viewActionLink.Type)
{
case LinkActionType.Submit:
var control = FormActionSubmit(viewActionLink, submitButtonID, submitButtonCommandName, validationGroup, submitButtonBusyText, actionButtonStyle);
placeHolder.Controls.Add(control);
break;
case LinkActionType.Next:
var nextcontrol = FormActionNext(viewActionLink, nextButtonId, validationGroup, actionButtonStyle);
placeHolder.Controls.Add(nextcontrol);
break;
case LinkActionType.Previous:
var previouscontrol = FormActionPrevious(viewActionLink, previousButtonId, validationGroup, actionButtonStyle);
placeHolder.Controls.Add(previouscontrol);
break;
default:
var link = html.FormActionLink(viewActionLink, actionButtonStyle);
placeHolder.Controls.Add(new LiteralControl(link.ToString()));
break;
}
if (actionButtonStyle == ActionButtonStyle.DropDown)
{
placeHolder.Controls.Add(new LiteralControl("</li>"));
}
placeHolder.Controls.Add(new LiteralControl("\r\n")); // ensures proper whitespace between buttons
return placeHolder;
}
public static Button FormActionSubmit(ViewActionLink viewActionLink, string submitButtonID = "SubmitButton",
string submitButtonCommandName = "", string validationGroup = null, string submitButtonBusyText = null,
ActionButtonStyle actionButtonStyle = ActionButtonStyle.ButtonGroup)
{
submitButtonBusyText = submitButtonBusyText ?? DefaultModalProcessingText;
if (!string.IsNullOrEmpty(viewActionLink.BusyText))
{
submitButtonBusyText = viewActionLink.BusyText;
}
if (actionButtonStyle == ActionButtonStyle.DropDown) //This will no longer be a form-wdie setting in a future version
{
if (string.IsNullOrEmpty(viewActionLink.ButtonCssClass) || viewActionLink.ButtonCssClass == "btn btn-primary")
{
viewActionLink.ButtonCssClass = "submit-btn-link submit-btn";
}
else
{
viewActionLink.ButtonCssClass = "submit-btn-link submit-btn " + viewActionLink.ButtonCssClass;
}
}
else if (string.IsNullOrEmpty(viewActionLink.ButtonCssClass) || viewActionLink.ButtonCssClass == "button submit"
|| viewActionLink.ButtonCssClass == "btn btn-primary" || viewActionLink.ButtonCssClass == "btn-primary")
{
viewActionLink.ButtonCssClass = "btn btn-primary button submit-btn";
}
else
{
viewActionLink.ButtonCssClass = viewActionLink.ButtonCssClass + " submit-btn";
}
var submitButton = new Button
{
ID = submitButtonID,
CommandName = submitButtonCommandName,
Text = viewActionLink.Label,
ValidationGroup = validationGroup,
CssClass = viewActionLink.ButtonCssClass,
CausesValidation = true,
OnClientClick =
"javascript:if(typeof entityFormClientValidate === 'function'){if(entityFormClientValidate()){if(typeof Page_ClientValidate === 'function'){if(Page_ClientValidate('" +
validationGroup + "')){clearIsDirty();disableButtons();this.value = '" +
submitButtonBusyText + "';}}else{clearIsDirty();disableButtons();this.value = '" +
submitButtonBusyText +
"';}}else{return false;}}else{if(typeof Page_ClientValidate === 'function'){if(Page_ClientValidate('" +
validationGroup + "')){clearIsDirty();disableButtons();this.value = '" +
submitButtonBusyText + "';}}else{clearIsDirty();disableButtons();this.value = '" +
submitButtonBusyText + "';}}",
UseSubmitBehavior = false,
ToolTip = viewActionLink.Tooltip
};
return submitButton;
}
public static Button FormActionNext(ViewActionLink viewActionLink, string nextButtonID = "NextButton",
string validationGroup = null, ActionButtonStyle actionButtonStyle = ActionButtonStyle.ButtonGroup)
{
if (actionButtonStyle == ActionButtonStyle.DropDown) //This will no longer be a form-wide setting in a future version
{
if (string.IsNullOrEmpty(viewActionLink.ButtonCssClass) || viewActionLink.ButtonCssClass == "btn btn-primary")
{
viewActionLink.ButtonCssClass = "submit-btn-link next-btn";
}
else
{
viewActionLink.ButtonCssClass = "submit-btn-link next-btn " + viewActionLink.ButtonCssClass;
}
}
else if (string.IsNullOrEmpty(viewActionLink.ButtonCssClass) || viewActionLink.ButtonCssClass == "button next"
|| viewActionLink.ButtonCssClass == "btn btn-primary" || viewActionLink.ButtonCssClass == "btn-primary")
{
viewActionLink.ButtonCssClass = "btn btn-primary button next next-btn";
}
else
{
viewActionLink.ButtonCssClass = viewActionLink.ButtonCssClass + " next-btn";
}
var nextButton = new Button
{
ID = nextButtonID,
CommandName = "Next",
Text = string.IsNullOrWhiteSpace(viewActionLink.Label) ? viewActionLink.Label : "Next",
ValidationGroup = validationGroup,
CausesValidation = true,
CssClass = viewActionLink.ButtonCssClass
};
return nextButton;
}
public static Button FormActionPrevious(ViewActionLink viewActionLink, string previousButtonID = "PreviousButton",
string validationGroup = null, ActionButtonStyle actionButtonStyle = ActionButtonStyle.ButtonGroup)
{
if (actionButtonStyle == ActionButtonStyle.DropDown) //This will no longer be a form-wide setting in a future version
{
if (string.IsNullOrEmpty(viewActionLink.ButtonCssClass) || viewActionLink.ButtonCssClass == "btn btn-default")
{
viewActionLink.ButtonCssClass = "submit-btn-link previous-btn";
}
else
{
viewActionLink.ButtonCssClass = "submit-btn-link previous-btn " + viewActionLink.ButtonCssClass;
}
}
else if (string.IsNullOrEmpty(viewActionLink.ButtonCssClass) || viewActionLink.ButtonCssClass == "button next" || viewActionLink.ButtonCssClass == "button previous"
|| viewActionLink.ButtonCssClass == "btn btn-default" || viewActionLink.ButtonCssClass == "btn-default")
{
viewActionLink.ButtonCssClass = "btn btn-default button previous previous-btn";
}
else
{
viewActionLink.ButtonCssClass = viewActionLink.ButtonCssClass + " previous-btn";
}
var previousButton = new Button
{
ID = previousButtonID,
CommandName = "Previous",
Text = string.IsNullOrWhiteSpace(viewActionLink.Label) ? viewActionLink.Label : "Previous",
ValidationGroup = validationGroup,
CausesValidation = false,
CssClass = viewActionLink.ButtonCssClass,
UseSubmitBehavior = false
};
return previousButton;
}
public static WebControl FormActionDropDownMenuControl()
{
var dropDownMenu = new WebControl(HtmlTextWriterTag.Ul);
dropDownMenu.AddClass("dropdown-menu");
dropDownMenu.Attributes.Add("role", "menu");
return dropDownMenu;
}
public static WebControl FormActionDefaultNavBar(HtmlHelper html, FormConfiguration formConfiguration, WebControl leftContainer, WebControl rightContainer,
ActionButtonPlacement actionButtonPlacement, string submitButtonID = "SubmitButton", string submitButtonCommandName = "", string validationGroup = null,
string submitButtonBusyText = null, string nextButtonId = "NextButton", string previousButtonId = "PreviousButton")
{
submitButtonBusyText = submitButtonBusyText == null ? DefaultModalProcessingText : submitButtonBusyText;
var dropDownLeft = FormActions(html, formConfiguration, leftContainer, actionButtonPlacement, ActionButtonAlignment.Left, submitButtonID, submitButtonCommandName, validationGroup, submitButtonBusyText, nextButtonId, previousButtonId);
var dropDownRight = FormActions(html, formConfiguration, rightContainer, actionButtonPlacement, ActionButtonAlignment.Right, submitButtonID, submitButtonCommandName, validationGroup, submitButtonBusyText, nextButtonId, previousButtonId);
var containerFluid = FormActionNavbarInnerHtml(html, dropDownLeft, dropDownRight, formConfiguration, actionButtonPlacement);
var navBar = FormActionNavbarContainerControl(formConfiguration);
navBar.Controls.Add(containerFluid);
AddActionModalWindows(html, formConfiguration, navBar, actionButtonPlacement);
return navBar;
}
public static WebControl FormActionNoNavBar(HtmlHelper html, FormConfiguration formConfiguration, WebControl leftContainer, WebControl rightContainer,
ActionButtonPlacement actionButtonPlacement, string submitButtonID = "SubmitButton", string submitButtonCommandName = "", string validationGroup = null,
string submitButtonBusyText = null, string nextButtonId = "NextButton", string previousButtonId = "PreviousButton")
{
submitButtonBusyText = submitButtonBusyText == null ? DefaultModalProcessingText : submitButtonBusyText;
var dropDownLeft = FormActions(html, formConfiguration, leftContainer, actionButtonPlacement, ActionButtonAlignment.Left, submitButtonID, submitButtonCommandName, validationGroup, submitButtonBusyText, nextButtonId, previousButtonId);
var dropDownRight = FormActions(html, formConfiguration, rightContainer, actionButtonPlacement, ActionButtonAlignment.Right, submitButtonID, submitButtonCommandName, validationGroup, submitButtonBusyText, nextButtonId, previousButtonId);
var navBar = FormActionNavbarContainerControl(formConfiguration);
navBar.Controls.Add(dropDownLeft);
navBar.Controls.Add(dropDownRight);
AddActionModalWindows(html, formConfiguration, navBar, actionButtonPlacement);
return navBar;
}
public static WebControl FormActions(HtmlHelper html, FormConfiguration formConfiguration, WebControl container,
ActionButtonPlacement actionButtonPlacement, ActionButtonAlignment actionButtonAlignment, string submitButtonID = "SubmitButton",
string submitButtonCommandName = "", string validationGroup = null, string submitButtonBusyText = null,
string nextButtonId = "NextButton", string previousButtonId = "PreviousButton")
{
submitButtonBusyText = submitButtonBusyText == null ? DefaultModalProcessingText : submitButtonBusyText;
var buttonActionLinks = new List<Control>();
var dropdownActionLinks = new List<Control>();
var actionLinks = (actionButtonPlacement == ActionButtonPlacement.AboveForm)
? formConfiguration.TopFormActionLinks
: formConfiguration.BottomFormActionLinks;
foreach (var action in actionLinks)
{
if (action is WorkflowActionLink && action.Enabled && (action.ActionButtonAlignment ?? ActionButtonAlignment.Left) == actionButtonAlignment)
{
if ((action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup) == ActionButtonStyle.DropDown)
{
var workflowHtml = FormActionLinkListItem(html, action as WorkflowActionLink,
action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup);
dropdownActionLinks.Add(workflowHtml);
}
else
{
var workflowHtml = FormActionLinkListItem(html, action as WorkflowActionLink,
action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup);
buttonActionLinks.Add(workflowHtml);
}
}
else if (action is SubmitActionLink && action.Enabled && (action.ActionButtonAlignment ?? ActionButtonAlignment.Left) == actionButtonAlignment)
{
if ((action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup) == ActionButtonStyle.DropDown)
{
var submitHtml = FormActionLinkListItem(html, action as SubmitActionLink,
action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup,
formConfiguration.AutoGenerateSteps, submitButtonID, submitButtonCommandName, validationGroup,
submitButtonBusyText, formConfiguration.ActionNavbarCssClass);
dropdownActionLinks.Add(submitHtml);
}
else
{
var submitHtml = FormActionLinkListItem(html, action as SubmitActionLink,
action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup,
formConfiguration.AutoGenerateSteps, submitButtonID, submitButtonCommandName, validationGroup,
submitButtonBusyText, formConfiguration.ActionNavbarCssClass);
buttonActionLinks.Add(submitHtml);
}
}
else if (action is PreviousActionLink && action.Enabled && (action.ActionButtonAlignment ?? ActionButtonAlignment.Left) == actionButtonAlignment)
{
if ((action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup) == ActionButtonStyle.DropDown)
{
var previousHtml = FormActionLinkListItem(html, action as PreviousActionLink,
action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup,
formConfiguration.AutoGenerateSteps, null, null, validationGroup, null, formConfiguration.ActionNavbarCssClass,
null, previousButtonId);
dropdownActionLinks.Add(previousHtml);
}
else
{
var previousHtml = FormActionLinkListItem(html, action as PreviousActionLink,
action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup,
formConfiguration.AutoGenerateSteps, null, null, validationGroup, null, formConfiguration.ActionNavbarCssClass,
null, previousButtonId);
buttonActionLinks.Add(previousHtml);
}
}
else if (action is NextActionLink && action.Enabled && (action.ActionButtonAlignment ?? ActionButtonAlignment.Left) == actionButtonAlignment)
{
if ((action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup) == ActionButtonStyle.DropDown)
{
var nextHtml = FormActionLinkListItem(html, action as NextActionLink,
action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup,
formConfiguration.AutoGenerateSteps, null, null, validationGroup, null, formConfiguration.ActionNavbarCssClass,
nextButtonId);
dropdownActionLinks.Add(nextHtml);
}
else
{
var nextHtml = FormActionLinkListItem(html, action as NextActionLink, action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup, formConfiguration.AutoGenerateSteps, null, null, validationGroup, null, formConfiguration.ActionNavbarCssClass, nextButtonId);
buttonActionLinks.Add(nextHtml);
}
}
else if (action.Enabled && (action.ActionButtonAlignment ?? ActionButtonAlignment.Left) == actionButtonAlignment)
{
if ((action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup) == ActionButtonStyle.DropDown)
{
var actionHtml = FormActionLinkListItem(html, action, action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup);
dropdownActionLinks.Add(actionHtml);
}
else
{
var actionHtml = FormActionLinkListItem(html, action, action.ActionButtonStyle ?? formConfiguration.ActionButtonStyle ?? ActionButtonStyle.ButtonGroup);
buttonActionLinks.Add(actionHtml);
}
}
}
var buttonContainer = new WebControl(HtmlTextWriterTag.Div);
buttonContainer.AddClass(actionButtonAlignment == ActionButtonAlignment.Left
? "form-action-container-left"
: "form-action-container-right");
container.Controls.Add(buttonContainer);
if (buttonActionLinks.Any())
{
foreach (var link in buttonActionLinks)
{
buttonContainer.Controls.Add(link);
}
}
if (dropdownActionLinks.Any())
{
var dropDownMenu = FormActionDropDownMenuControl();
foreach (var link in dropdownActionLinks) dropDownMenu.Controls.Add(link);
var dropDown = FormActionDropDownControl(formConfiguration);
dropDown.Controls.Add(dropDownMenu);
dropDown.Controls.Add(new LiteralControl("</div>"));
buttonContainer.Controls.Add(dropDown);
}
return container;
}
public static Control FormActionDropDownControl(IFormConfiguration formConfiguration)
{
var placeHolder = new PlaceHolder();
placeHolder.Controls.Add(new LiteralControl("<div role=\"group\" class=\"btn-group\">"));
var linkButton = new HtmlGenericControl("button");
linkButton.AddClass("dropdown-toggle");
linkButton.AddClass("btn");
linkButton.AddClass("btn-default");
linkButton.Attributes.Add("aria-haspopup", "true");
linkButton.Attributes.Add("data-toggle", "dropdown");
linkButton.Attributes.Add("role", "button");
linkButton.Attributes.Add("aria-expanded", "false");
linkButton.InnerHtml += !string.IsNullOrEmpty(formConfiguration.ActionButtonDropDownLabel) ? formConfiguration.ActionButtonDropDownLabel : "<span class='fa fa-bars fa-fw' aria-hidden='true'></span> Actions ";
var buttonInner = new TagBuilder("span");
buttonInner.AddCssClass("caret");
linkButton.InnerHtml += buttonInner.ToString();
placeHolder.Controls.Add(linkButton);
return placeHolder;
}
public static WebControl ActionNavBarControl(ActionButtonAlignment? actionButtonAlignment)
{
var container = new WebControl(HtmlTextWriterTag.Div);
container.AddClass("col-sm-6");
container.AddClass("clearfix");
return container;
}
public static WebControl FormActionNavbarInnerHtml(HtmlHelper html, WebControl containerLeft, WebControl containerRight, IFormConfiguration formConfiguration,
ActionButtonPlacement actionButtonPlacement)
{
var collapsedNavbar = new Panel { ID = "form-navbar-collapse" + actionButtonPlacement.ToString() };
collapsedNavbar.AddClass("collapse");
collapsedNavbar.AddClass("navbar-collapse");
var status = new HtmlGenericControl("p");
status.AddClass("navbar-text");
status.AddClass("pull-right");
status.AddClass("action-status");
status.AddClass("hidden");
status.Attributes.Add("style", "margin-right:0;");
var statusIcon = new TagBuilder("span");
statusIcon.Attributes.Add("aria-hidden", "true");
statusIcon.AddCssClass("fa fa-fw");
status.InnerHtml += statusIcon.ToString();
collapsedNavbar.Controls.Add(status);
collapsedNavbar.Controls.Add(containerLeft);
collapsedNavbar.Controls.Add(containerRight);
var navbarHeader = new HtmlGenericControl("div");
navbarHeader.AddClass("navbar-header");
var collapseButton = new TagBuilder("button");
collapseButton.AddCssClass("navbar-toggle");
collapseButton.AddCssClass("collapsed");
collapseButton.Attributes["type"] = "button";
collapseButton.Attributes["data-toggle"] = "collapse";
collapseButton.Attributes["data-target"] = "#form-navbar-collapse" + actionButtonPlacement.ToString();
var srOnly = new TagBuilder("span");
srOnly.AddCssClass("sr-only");
collapseButton.InnerHtml += srOnly;
var collapseButtonBar = new TagBuilder("span");
collapseButtonBar.AddCssClass("icon-bar");
collapseButton.InnerHtml += collapseButtonBar;
collapseButton.InnerHtml += collapseButtonBar;
collapseButton.InnerHtml += collapseButtonBar;
navbarHeader.InnerHtml += collapseButton.ToString();
var containerFluid = new Panel();
containerFluid.AddClass("container-fluid");
containerFluid.Controls.Add(navbarHeader);
containerFluid.Controls.Add(collapsedNavbar);
return containerFluid;
}
public static WebControl FormActionNavbarContainerControl(FormConfiguration formConfiguration)
{
var navBar = new Panel();
navBar.AddClass("row");
navBar.AddClass("form-custom-actions");
return navBar;
}
public static void AddActionModalWindows(HtmlHelper html, FormConfiguration formConfiguration, WebControl container,
ActionButtonPlacement actionButtonPlacement)
{
var deleteActionLink = formConfiguration.DeleteActionLink;
var closeCaseActionLink = formConfiguration.CloseIncidentActionLink;
var resolveCaseActionLink = formConfiguration.ResolveCaseActionLink;
var reopenCaseActionLink = formConfiguration.ReopenCaseActionLink;
var cancelCaseActionLink = formConfiguration.CancelCaseActionLink;
var qualifyLeadActionLink = formConfiguration.QualifyLeadActionLink;
var convertQuoteActionLink = formConfiguration.ConvertQuoteToOrderActionLink;
var convertOrderActionLink = formConfiguration.ConvertOrderToInvoiceActionLink;
var calculateOpportunityActionLink = formConfiguration.CalculateOpportunityActionLink;
var deactivateActionLink = formConfiguration.DeactivateActionLink;
var activateActionLink = formConfiguration.ActivateActionLink;
var activateQuoteActionLink = formConfiguration.ActivateQuoteActionLink;
var opportunityOnHoldActionLink = formConfiguration.SetOpportunityOnHoldActionLink;
var reopenOpportunityActionLink = formConfiguration.ReopenOpportunityActionLink;
var winOpportunityActionLink = formConfiguration.WinOpportunityActionLink;
var loseOpportunityActionLink = formConfiguration.LoseOpportunityActionLink;
var generateQuoteFromOpportunityActionLink = formConfiguration.GenerateQuoteFromOpportunityActionLink;
var createRelatedRecordActionLink = formConfiguration.CreateRelatedRecordActionLink;
DisassociateActionLink disassociateAction = null;
var actionLinks = (actionButtonPlacement == ActionButtonPlacement.AboveForm)
? formConfiguration.TopFormActionLinks
: formConfiguration.BottomFormActionLinks;
WorkflowActionLink firstWorkflow = actionLinks.OfType<WorkflowActionLink>().Select(action => action).FirstOrDefault();
if (deleteActionLink != null && deleteActionLink.Enabled)
{
container.Controls.Add(new LiteralControl(html.DeleteModal(deleteActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
deleteActionLink.Modal.CssClass, deleteActionLink.Modal.Title.GetValueOrDefault(DefaultModalDeleteTitle),
deleteActionLink.Confirmation.GetValueOrDefault(DefaultModalDeleteBody),
deleteActionLink.Modal.DismissButtonSrText.GetValueOrDefault(DefaultModalDismissButtonSrText),
deleteActionLink.Modal.PrimaryButtonText.GetValueOrDefault(DefaultModalDeletePrimaryButtonText),
deleteActionLink.Modal.CloseButtonText.GetValueOrDefault(DefaultModalDeleteCancelButtonText),
deleteActionLink.Modal.TitleCssClass, deleteActionLink.Modal.PrimaryButtonCssClass,
deleteActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (qualifyLeadActionLink != null && qualifyLeadActionLink.Enabled && (qualifyLeadActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.QualifyLeadModal(qualifyLeadActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
qualifyLeadActionLink.Modal.CssClass, qualifyLeadActionLink.Modal.Title, qualifyLeadActionLink.Confirmation,
qualifyLeadActionLink.Modal.DismissButtonSrText, qualifyLeadActionLink.Modal.PrimaryButtonText,
qualifyLeadActionLink.Modal.CloseButtonText, qualifyLeadActionLink.Modal.TitleCssClass,
qualifyLeadActionLink.Modal.PrimaryButtonCssClass, qualifyLeadActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (closeCaseActionLink != null && closeCaseActionLink.Enabled && (closeCaseActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.CloseCaseModal(closeCaseActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
closeCaseActionLink.Modal.CssClass, closeCaseActionLink.Modal.Title, closeCaseActionLink.Confirmation,
null, null, closeCaseActionLink.Modal.DismissButtonSrText, closeCaseActionLink.Modal.PrimaryButtonText,
closeCaseActionLink.Modal.CloseButtonText, closeCaseActionLink.Modal.TitleCssClass,
closeCaseActionLink.Modal.PrimaryButtonCssClass, closeCaseActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (resolveCaseActionLink != null && resolveCaseActionLink.Enabled)
{
container.Controls.Add(new LiteralControl(html.ResolveCaseModal(resolveCaseActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
resolveCaseActionLink.Modal.CssClass, resolveCaseActionLink.Modal.Title, resolveCaseActionLink.Confirmation,
resolveCaseActionLink.SubjectLabel, resolveCaseActionLink.DescriptionLabel,
resolveCaseActionLink.Modal.DismissButtonSrText, resolveCaseActionLink.Modal.PrimaryButtonText,
resolveCaseActionLink.Modal.CloseButtonText, resolveCaseActionLink.Modal.TitleCssClass,
resolveCaseActionLink.Modal.PrimaryButtonCssClass, resolveCaseActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (reopenCaseActionLink != null && reopenCaseActionLink.Enabled && (reopenCaseActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.ReopenCaseModal(reopenCaseActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
reopenCaseActionLink.Modal.CssClass, reopenCaseActionLink.Modal.Title, reopenCaseActionLink.Confirmation,
null, null, reopenCaseActionLink.Modal.DismissButtonSrText, reopenCaseActionLink.Modal.PrimaryButtonText,
reopenCaseActionLink.Modal.CloseButtonText, reopenCaseActionLink.Modal.TitleCssClass,
reopenCaseActionLink.Modal.PrimaryButtonCssClass, reopenCaseActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (cancelCaseActionLink != null && cancelCaseActionLink.Enabled && (cancelCaseActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.CancelCaseModal(cancelCaseActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
cancelCaseActionLink.Modal.CssClass, cancelCaseActionLink.Modal.Title, cancelCaseActionLink.Confirmation,
null, null, cancelCaseActionLink.Modal.DismissButtonSrText, cancelCaseActionLink.Modal.PrimaryButtonText,
cancelCaseActionLink.Modal.CloseButtonText, cancelCaseActionLink.Modal.TitleCssClass,
cancelCaseActionLink.Modal.PrimaryButtonCssClass, cancelCaseActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (convertQuoteActionLink != null && convertQuoteActionLink.Enabled && (convertQuoteActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.ConvertQuoteModal(convertQuoteActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
convertQuoteActionLink.Modal.CssClass, convertQuoteActionLink.Modal.Title, convertQuoteActionLink.Confirmation,
convertQuoteActionLink.Modal.DismissButtonSrText, convertQuoteActionLink.Modal.PrimaryButtonText,
convertQuoteActionLink.Modal.CloseButtonText, convertQuoteActionLink.Modal.TitleCssClass,
convertQuoteActionLink.Modal.PrimaryButtonCssClass, convertQuoteActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (convertOrderActionLink != null && convertOrderActionLink.Enabled && (convertOrderActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.ConvertOrderModal(closeCaseActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
convertOrderActionLink.Modal.CssClass, convertOrderActionLink.Modal.Title, convertOrderActionLink.Confirmation,
convertOrderActionLink.Modal.DismissButtonSrText, convertOrderActionLink.Modal.PrimaryButtonText,
convertOrderActionLink.Modal.CloseButtonText, convertOrderActionLink.Modal.TitleCssClass,
convertOrderActionLink.Modal.PrimaryButtonCssClass, convertOrderActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (calculateOpportunityActionLink != null && calculateOpportunityActionLink.Enabled && (calculateOpportunityActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.CalculateOpportunityModal(
calculateOpportunityActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
calculateOpportunityActionLink.Modal.CssClass, calculateOpportunityActionLink.Modal.Title,
calculateOpportunityActionLink.Confirmation, calculateOpportunityActionLink.Modal.DismissButtonSrText,
calculateOpportunityActionLink.Modal.PrimaryButtonText, calculateOpportunityActionLink.Modal.CloseButtonText,
calculateOpportunityActionLink.Modal.TitleCssClass, calculateOpportunityActionLink.Modal.PrimaryButtonCssClass,
calculateOpportunityActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (deactivateActionLink != null && deactivateActionLink.Enabled && (deactivateActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.DeactivateModal(deactivateActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
deactivateActionLink.Modal.CssClass, deactivateActionLink.Modal.Title, deactivateActionLink.Confirmation,
deactivateActionLink.Modal.DismissButtonSrText, deactivateActionLink.Modal.PrimaryButtonText,
deactivateActionLink.Modal.CloseButtonText,
deactivateActionLink.Modal.TitleCssClass, deactivateActionLink.Modal.PrimaryButtonCssClass,
deactivateActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (activateActionLink != null && activateActionLink.Enabled && (activateActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.ActivateModal(activateActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
activateActionLink.Modal.CssClass, activateActionLink.Modal.Title, activateActionLink.Confirmation,
activateActionLink.Modal.DismissButtonSrText, activateActionLink.Modal.PrimaryButtonText,
activateActionLink.Modal.CloseButtonText,
activateActionLink.Modal.TitleCssClass, activateActionLink.Modal.PrimaryButtonCssClass,
activateActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (activateQuoteActionLink != null && activateQuoteActionLink.Enabled && (activateQuoteActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.ActivateQuoteModal(activateQuoteActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
activateQuoteActionLink.Modal.CssClass, activateQuoteActionLink.Modal.Title, activateQuoteActionLink.Confirmation,
activateQuoteActionLink.Modal.DismissButtonSrText, activateQuoteActionLink.Modal.PrimaryButtonText,
activateQuoteActionLink.Modal.CloseButtonText,
activateQuoteActionLink.Modal.TitleCssClass, activateQuoteActionLink.Modal.PrimaryButtonCssClass,
activateQuoteActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (opportunityOnHoldActionLink != null && opportunityOnHoldActionLink.Enabled && (opportunityOnHoldActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.SetOpportunityOnHoldModal(
opportunityOnHoldActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
opportunityOnHoldActionLink.Modal.CssClass, opportunityOnHoldActionLink.Modal.Title,
opportunityOnHoldActionLink.Confirmation, opportunityOnHoldActionLink.Modal.DismissButtonSrText,
opportunityOnHoldActionLink.Modal.PrimaryButtonText, opportunityOnHoldActionLink.Modal.CloseButtonText,
opportunityOnHoldActionLink.Modal.TitleCssClass, opportunityOnHoldActionLink.Modal.PrimaryButtonCssClass,
opportunityOnHoldActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (reopenOpportunityActionLink != null && reopenOpportunityActionLink.Enabled && (reopenOpportunityActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.ReopenOpportunityModal(reopenOpportunityActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
reopenOpportunityActionLink.Modal.CssClass, reopenOpportunityActionLink.Modal.Title,
reopenOpportunityActionLink.Confirmation, reopenOpportunityActionLink.Modal.DismissButtonSrText,
reopenOpportunityActionLink.Modal.PrimaryButtonText, reopenOpportunityActionLink.Modal.CloseButtonText,
reopenOpportunityActionLink.Modal.TitleCssClass, reopenOpportunityActionLink.Modal.PrimaryButtonCssClass,
reopenOpportunityActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (winOpportunityActionLink != null && winOpportunityActionLink.Enabled && (winOpportunityActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.WinOpportunityModal(winOpportunityActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
winOpportunityActionLink.Modal.CssClass, winOpportunityActionLink.Modal.Title, winOpportunityActionLink.Confirmation,
winOpportunityActionLink.Modal.DismissButtonSrText, winOpportunityActionLink.Modal.PrimaryButtonText,
winOpportunityActionLink.Modal.CloseButtonText,
winOpportunityActionLink.Modal.TitleCssClass, winOpportunityActionLink.Modal.PrimaryButtonCssClass,
winOpportunityActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (loseOpportunityActionLink != null && loseOpportunityActionLink.Enabled && (loseOpportunityActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.LoseOpportunityModal(loseOpportunityActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
loseOpportunityActionLink.Modal.CssClass, loseOpportunityActionLink.Modal.Title,
loseOpportunityActionLink.Confirmation, loseOpportunityActionLink.Modal.DismissButtonSrText,
loseOpportunityActionLink.Modal.PrimaryButtonText, loseOpportunityActionLink.Modal.CloseButtonText,
loseOpportunityActionLink.Modal.TitleCssClass, loseOpportunityActionLink.Modal.PrimaryButtonCssClass,
loseOpportunityActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (generateQuoteFromOpportunityActionLink != null && generateQuoteFromOpportunityActionLink.Enabled &&
(generateQuoteFromOpportunityActionLink.ShowModal == ShowModal.Yes))
{
container.Controls.Add(new LiteralControl(html.GenerateQuoteFromOpportunityModal(
generateQuoteFromOpportunityActionLink.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
generateQuoteFromOpportunityActionLink.Modal.CssClass, generateQuoteFromOpportunityActionLink.Modal.Title,
generateQuoteFromOpportunityActionLink.Confirmation,
generateQuoteFromOpportunityActionLink.Modal.DismissButtonSrText,
generateQuoteFromOpportunityActionLink.Modal.PrimaryButtonText,
generateQuoteFromOpportunityActionLink.Modal.CloseButtonText,
generateQuoteFromOpportunityActionLink.Modal.TitleCssClass,
generateQuoteFromOpportunityActionLink.Modal.PrimaryButtonCssClass,
generateQuoteFromOpportunityActionLink.Modal.CloseButtonCssClass).ToString()));
}
if (firstWorkflow != null && firstWorkflow.Enabled)
{
container.Controls.Add(new LiteralControl(html.WorkflowModal(firstWorkflow.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
firstWorkflow.Modal.CssClass, firstWorkflow.Modal.Title, firstWorkflow.Confirmation,
firstWorkflow.Modal.DismissButtonSrText, firstWorkflow.Modal.PrimaryButtonText, firstWorkflow.Modal.CloseButtonText,
firstWorkflow.Modal.TitleCssClass, firstWorkflow.Modal.PrimaryButtonCssClass, firstWorkflow.Modal.CloseButtonCssClass).ToString()));
}
if (disassociateAction != null && disassociateAction.Enabled)
{
container.Controls.Add(new LiteralControl(html.DissassociateModal(disassociateAction.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
disassociateAction.Modal.CssClass, disassociateAction.Modal.Title, disassociateAction.Confirmation,
disassociateAction.Modal.DismissButtonSrText, disassociateAction.Modal.PrimaryButtonText,
disassociateAction.Modal.CloseButtonText, disassociateAction.Modal.TitleCssClass,
disassociateAction.Modal.PrimaryButtonCssClass, disassociateAction.Modal.CloseButtonCssClass).ToString()));
}
var createRelatedRecordActionLinks = actionLinks.OfType<CreateRelatedRecordActionLink>().Select(action => action);
foreach (var createRelatedRecordAction in createRelatedRecordActionLinks)
{
var htmlAttributes = new Dictionary<string, string>
{
{ "data-filtercriteriaid", createRelatedRecordAction.FilterCriteriaId.ToString() }
};
if (createRelatedRecordAction.ShowModal != ShowModal.Yes)
{
container.Controls.Add(
new LiteralControl(
html.CreateRelatedRecordModal(
createRelatedRecordAction.Modal.Size ?? BootstrapExtensions.BootstrapModalSize.Default,
createRelatedRecordAction.Modal.CssClass, createRelatedRecordAction.Modal.Title,
createRelatedRecordAction.Confirmation,
createRelatedRecordAction.Modal.DismissButtonSrText, createRelatedRecordAction.Modal.PrimaryButtonText,
createRelatedRecordAction.Modal.CloseButtonText,
createRelatedRecordAction.Modal.TitleCssClass, createRelatedRecordAction.Modal.PrimaryButtonCssClass,
createRelatedRecordAction.Modal.CloseButtonCssClass, htmlAttributes).ToString()));
}
else
{
container.Controls.Add(
new LiteralControl(html.CreateRelatedRecordModal(BootstrapExtensions.BootstrapModalSize.Large,
createRelatedRecordAction.Modal.CssClass, createRelatedRecordAction.Modal.Title,
createRelatedRecordAction.Modal.DismissButtonSrText, createRelatedRecordAction.Modal.TitleCssClass,
null, htmlAttributes, null).ToString()));
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
internal static partial class ProcessManager
{
/// <summary>Gets process infos for each process on the specified machine.</summary>
/// <param name="machineName">The target machine.</param>
/// <returns>An array of process infos, one per found process.</returns>
public static ProcessInfo[] GetProcessInfos(string machineName)
{
return IsRemoteMachine(machineName) ?
NtProcessManager.GetProcessInfos(machineName, true) :
NtProcessInfoHelper.GetProcessInfos(); // Do not use performance counter for local machine
}
/// <summary>Gets the IDs of all processes on the specified machine.</summary>
/// <param name="machineName">The machine to examine.</param>
/// <returns>An array of process IDs from the specified machine.</returns>
public static int[] GetProcessIds(string machineName)
{
// Due to the lack of support for EnumModules() on coresysserver, we rely
// on PerformanceCounters to get the ProcessIds for both remote desktop
// and the local machine, unlike Desktop on which we rely on PCs only for
// remote machines.
return IsRemoteMachine(machineName) ?
NtProcessManager.GetProcessIds(machineName, true) :
GetProcessIds();
}
/// <summary>Gets the IDs of all processes on the current machine.</summary>
public static int[] GetProcessIds()
{
return NtProcessManager.GetProcessIds();
}
/// <summary>Gets the ID of a process from a handle to the process.</summary>
/// <param name="processHandle">The handle.</param>
/// <returns>The process ID.</returns>
public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
{
return NtProcessManager.GetProcessIdFromHandle(processHandle);
}
/// <summary>Gets an array of module infos for the specified process.</summary>
/// <param name="processId">The ID of the process whose modules should be enumerated.</param>
/// <returns>The array of modules.</returns>
public static ModuleInfo[] GetModuleInfos(int processId)
{
return NtProcessManager.GetModuleInfos(processId);
}
/// <summary>Gets whether the named machine is remote or local.</summary>
/// <param name="machineName">The machine name.</param>
/// <returns>true if the machine is remote; false if it's local.</returns>
public static bool IsRemoteMachine(string machineName)
{
if (machineName == null)
throw new ArgumentNullException("machineName");
if (machineName.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidParameter, "machineName", machineName));
string baseName;
if (machineName.StartsWith("\\", StringComparison.Ordinal))
baseName = machineName.Substring(2);
else
baseName = machineName;
if (baseName.Equals(".")) return false;
if (String.Compare(Interop.mincore.GetComputerName(), baseName, StringComparison.OrdinalIgnoreCase) == 0) return false;
return true;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
static ProcessManager()
{
// In order to query information (OpenProcess) on some protected processes
// like csrss, we need SeDebugPrivilege privilege.
// After removing the depenecy on Performance Counter, we don't have a chance
// to run the code in CLR performance counter to ask for this privilege.
// So we will try to get the privilege here.
// We could fail if the user account doesn't have right to do this, but that's fair.
Interop.LUID luid = new Interop.LUID();
if (!Interop.mincore.LookupPrivilegeValue(null, Interop.SeDebugPrivilege, out luid))
{
return;
}
SafeTokenHandle tokenHandle = null;
try
{
if (!Interop.mincore.OpenProcessToken(
Interop.mincore.GetCurrentProcess(),
Interop.TOKEN_ADJUST_PRIVILEGES,
out tokenHandle))
{
return;
}
Interop.TokenPrivileges tp = new Interop.TokenPrivileges();
tp.Luid = luid;
tp.Attributes = Interop.SE_PRIVILEGE_ENABLED;
// AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned).
Interop.mincore.AdjustTokenPrivileges(tokenHandle, false, tp, 0, IntPtr.Zero, IntPtr.Zero);
}
finally
{
if (tokenHandle != null)
{
tokenHandle.Dispose();
}
}
}
public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited)
{
SafeProcessHandle processHandle = Interop.mincore.OpenProcess(access, false, processId);
int result = Marshal.GetLastWin32Error();
if (!processHandle.IsInvalid)
{
return processHandle;
}
if (processId == 0)
{
throw new Win32Exception(5);
}
// If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true.
if (!IsProcessRunning(processId))
{
if (throwIfExited)
{
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture)));
}
else
{
return SafeProcessHandle.InvalidHandle;
}
}
throw new Win32Exception(result);
}
public static SafeThreadHandle OpenThread(int threadId, int access)
{
SafeThreadHandle threadHandle = Interop.mincore.OpenThread(access, false, threadId);
int result = Marshal.GetLastWin32Error();
if (threadHandle.IsInvalid)
{
if (result == Interop.ERROR_INVALID_PARAMETER)
throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture)));
throw new Win32Exception(result);
}
return threadHandle;
}
}
/// <devdoc>
/// This static class provides the process api for the WinNt platform.
/// We use the performance counter api to query process and thread
/// information. Module information is obtained using PSAPI.
/// </devdoc>
/// <internalonly/>
internal static class NtProcessManager
{
private const int ProcessPerfCounterId = 230;
private const int ThreadPerfCounterId = 232;
private const string PerfCounterQueryString = "230 232";
internal const int IdleProcessID = 0;
private static Dictionary<String, ValueId> s_valueIds;
static NtProcessManager()
{
s_valueIds = new Dictionary<String, ValueId>();
s_valueIds.Add("Handle Count", ValueId.HandleCount);
s_valueIds.Add("Pool Paged Bytes", ValueId.PoolPagedBytes);
s_valueIds.Add("Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes);
s_valueIds.Add("Elapsed Time", ValueId.ElapsedTime);
s_valueIds.Add("Virtual Bytes Peak", ValueId.VirtualBytesPeak);
s_valueIds.Add("Virtual Bytes", ValueId.VirtualBytes);
s_valueIds.Add("Private Bytes", ValueId.PrivateBytes);
s_valueIds.Add("Page File Bytes", ValueId.PageFileBytes);
s_valueIds.Add("Page File Bytes Peak", ValueId.PageFileBytesPeak);
s_valueIds.Add("Working Set Peak", ValueId.WorkingSetPeak);
s_valueIds.Add("Working Set", ValueId.WorkingSet);
s_valueIds.Add("ID Thread", ValueId.ThreadId);
s_valueIds.Add("ID Process", ValueId.ProcessId);
s_valueIds.Add("Priority Base", ValueId.BasePriority);
s_valueIds.Add("Priority Current", ValueId.CurrentPriority);
s_valueIds.Add("% User Time", ValueId.UserTime);
s_valueIds.Add("% Privileged Time", ValueId.PrivilegedTime);
s_valueIds.Add("Start Address", ValueId.StartAddress);
s_valueIds.Add("Thread State", ValueId.ThreadState);
s_valueIds.Add("Thread Wait Reason", ValueId.ThreadWaitReason);
}
internal static int SystemProcessID
{
get
{
const int systemProcessIDOnXP = 4;
return systemProcessIDOnXP;
}
}
public static int[] GetProcessIds(string machineName, bool isRemoteMachine)
{
ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine);
int[] ids = new int[infos.Length];
for (int i = 0; i < infos.Length; i++)
ids[i] = infos[i]._processId;
return ids;
}
public static int[] GetProcessIds()
{
int[] processIds = new int[256];
int size;
for (; ; )
{
if (!Interop.mincore.EnumProcesses(processIds, processIds.Length * 4, out size))
throw new Win32Exception();
if (size == processIds.Length * 4)
{
processIds = new int[processIds.Length * 2];
continue;
}
break;
}
int[] ids = new int[size / 4];
Array.Copy(processIds, ids, ids.Length);
return ids;
}
public static ModuleInfo[] GetModuleInfos(int processId)
{
return GetModuleInfos(processId, false);
}
public static ModuleInfo GetFirstModuleInfo(int processId)
{
ModuleInfo[] moduleInfos = GetModuleInfos(processId, true);
if (moduleInfos.Length == 0)
{
return null;
}
else
{
return moduleInfos[0];
}
}
private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly)
{
Contract.Ensures(Contract.Result<ModuleInfo[]>().Length >= 1);
// preserving Everett behavior.
if (processId == SystemProcessID || processId == IdleProcessID)
{
// system process and idle process doesn't have any modules
throw new Win32Exception(Interop.EFail, SR.EnumProcessModuleFailed);
}
SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle;
try
{
processHandle = ProcessManager.OpenProcess(processId, Interop.PROCESS_QUERY_INFORMATION | Interop.PROCESS_VM_READ, true);
IntPtr[] moduleHandles = new IntPtr[64];
GCHandle moduleHandlesArrayHandle = new GCHandle();
int moduleCount = 0;
for (; ; )
{
bool enumResult = false;
try
{
moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned);
enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount);
// The API we need to use to enumerate process modules differs on two factors:
// 1) If our process is running in WOW64.
// 2) The bitness of the process we wish to introspect.
//
// If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process
// we can call psapi!EnumProcessModules.
//
// If we are running in WOW64 and we want to inspect the modules of a 64 bit process then
// psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't
// do the enumeration at all. So we'll detect this case and bail out.
//
// Also, EnumProcessModules is not a reliable method to get the modules for a process.
// If OS loader is touching module information, this method might fail and copy part of the data.
// This is no easy solution to this problem. The only reliable way to fix this is to
// suspend all the threads in target process. Of course we don't want to do this in Process class.
// So we just to try avoid the race by calling the same method 50 (an arbitary number) times.
//
if (!enumResult)
{
bool sourceProcessIsWow64 = false;
bool targetProcessIsWow64 = false;
SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle;
try
{
hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.mincore.GetCurrentProcessId()), Interop.PROCESS_QUERY_INFORMATION, true);
bool wow64Ret;
wow64Ret = Interop.mincore.IsWow64Process(hCurProcess, ref sourceProcessIsWow64);
if (!wow64Ret)
{
throw new Win32Exception();
}
wow64Ret = Interop.mincore.IsWow64Process(processHandle, ref targetProcessIsWow64);
if (!wow64Ret)
{
throw new Win32Exception();
}
if (sourceProcessIsWow64 && !targetProcessIsWow64)
{
// Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user.
throw new Win32Exception(Interop.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow);
}
}
finally
{
if (hCurProcess != SafeProcessHandle.InvalidHandle)
{
hCurProcess.Dispose();
}
}
// If the failure wasn't due to Wow64, try again.
for (int i = 0; i < 50; i++)
{
enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount);
if (enumResult)
{
break;
}
Thread.Sleep(1);
}
}
}
finally
{
moduleHandlesArrayHandle.Free();
}
if (!enumResult)
{
throw new Win32Exception();
}
moduleCount /= IntPtr.Size;
if (moduleCount <= moduleHandles.Length) break;
moduleHandles = new IntPtr[moduleHandles.Length * 2];
}
List<ModuleInfo> moduleInfos = new List<ModuleInfo>();
int ret;
for (int i = 0; i < moduleCount; i++)
{
try
{
ModuleInfo moduleInfo = new ModuleInfo();
IntPtr moduleHandle = moduleHandles[i];
Interop.NtModuleInfo ntModuleInfo = new Interop.NtModuleInfo();
if (!Interop.mincore.GetModuleInformation(processHandle, moduleHandle, ntModuleInfo, Marshal.SizeOf(ntModuleInfo)))
throw new Win32Exception();
moduleInfo._sizeOfImage = ntModuleInfo.SizeOfImage;
moduleInfo._entryPoint = ntModuleInfo.EntryPoint;
moduleInfo._baseOfDll = ntModuleInfo.BaseOfDll;
StringBuilder baseName = new StringBuilder(1024);
ret = Interop.mincore.GetModuleBaseName(processHandle, moduleHandle, baseName, baseName.Capacity * 2);
if (ret == 0) throw new Win32Exception();
moduleInfo._baseName = baseName.ToString();
StringBuilder fileName = new StringBuilder(1024);
ret = Interop.mincore.GetModuleFileNameEx(processHandle, moduleHandle, fileName, fileName.Capacity * 2);
if (ret == 0) throw new Win32Exception();
moduleInfo._fileName = fileName.ToString();
if (moduleInfo._fileName != null
&& moduleInfo._fileName.Length >= 4
&& moduleInfo._fileName.StartsWith(@"\\?\", StringComparison.Ordinal))
{
moduleInfo._fileName = moduleInfo._fileName.Substring(4);
}
moduleInfos.Add(moduleInfo);
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == Interop.ERROR_INVALID_HANDLE || e.NativeErrorCode == Interop.ERROR_PARTIAL_COPY)
{
// It's possible that another thread casued this module to become
// unloaded (e.g FreeLibrary was called on the module). Ignore it and
// move on.
}
else
{
throw;
}
}
//
// If the user is only interested in the main module, break now.
// This avoid some waste of time. In addition, if the application unloads a DLL
// we will not get an exception.
//
if (firstModuleOnly) { break; }
}
ModuleInfo[] temp = new ModuleInfo[moduleInfos.Count];
moduleInfos.CopyTo(temp, 0);
return temp;
}
finally
{
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)");
#endif
if (!processHandle.IsInvalid)
{
processHandle.Dispose();
}
}
}
public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
{
Interop.NtProcessBasicInfo info = new Interop.NtProcessBasicInfo();
int status = Interop.mincore.NtQueryInformationProcess(processHandle, Interop.NtQueryProcessBasicInfo, info, (int)Marshal.SizeOf(info), null);
if (status != 0)
{
throw new InvalidOperationException(SR.CantGetProcessId, new Win32Exception(status));
}
// We should change the signature of this function and ID property in process class.
return info.UniqueProcessId.ToInt32();
}
public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine)
{
PerformanceCounterLib library = null;
try
{
library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en"));
return GetProcessInfos(library);
}
catch (Exception e)
{
if (isRemoteMachine)
{
throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e);
}
else
{
throw e;
}
}
// We don't want to call library.Close() here because that would cause us to unload all of the perflibs.
// On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW!
}
static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library)
{
ProcessInfo[] processInfos;
int retryCount = 5;
do
{
try
{
byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString);
processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.CouldntGetProcessInfos, e);
}
--retryCount;
}
while (processInfos.Length == 0 && retryCount != 0);
if (processInfos.Length == 0)
throw new InvalidOperationException(SR.ProcessDisabled);
return processInfos;
}
static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data)
{
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()");
#endif
Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>();
List<ThreadInfo> threadInfos = new List<ThreadInfo>();
GCHandle dataHandle = new GCHandle();
try
{
dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject();
Interop.PERF_DATA_BLOCK dataBlock = new Interop.PERF_DATA_BLOCK();
Marshal.PtrToStructure(dataBlockPtr, dataBlock);
IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength);
Interop.PERF_INSTANCE_DEFINITION instance = new Interop.PERF_INSTANCE_DEFINITION();
Interop.PERF_COUNTER_BLOCK counterBlock = new Interop.PERF_COUNTER_BLOCK();
for (int i = 0; i < dataBlock.NumObjectTypes; i++)
{
Interop.PERF_OBJECT_TYPE type = new Interop.PERF_OBJECT_TYPE();
Marshal.PtrToStructure(typePtr, type);
IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength);
IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength);
List<Interop.PERF_COUNTER_DEFINITION> counterList = new List<Interop.PERF_COUNTER_DEFINITION>();
for (int j = 0; j < type.NumCounters; j++)
{
Interop.PERF_COUNTER_DEFINITION counter = new Interop.PERF_COUNTER_DEFINITION();
Marshal.PtrToStructure(counterPtr, counter);
string counterName = library.GetCounterName(counter.CounterNameTitleIndex);
if (type.ObjectNameTitleIndex == processIndex)
counter.CounterNameTitlePtr = (int)GetValueId(counterName);
else if (type.ObjectNameTitleIndex == threadIndex)
counter.CounterNameTitlePtr = (int)GetValueId(counterName);
counterList.Add(counter);
counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength);
}
Interop.PERF_COUNTER_DEFINITION[] counters = new Interop.PERF_COUNTER_DEFINITION[counterList.Count];
counterList.CopyTo(counters, 0);
for (int j = 0; j < type.NumInstances; j++)
{
Marshal.PtrToStructure(instancePtr, instance);
IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset);
string instanceName = Marshal.PtrToStringUni(namePtr);
if (instanceName.Equals("_Total")) continue;
IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength);
Marshal.PtrToStructure(counterBlockPtr, counterBlock);
if (type.ObjectNameTitleIndex == processIndex)
{
ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
if (processInfo._processId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0)
{
// Sometimes we'll get a process structure that is not completely filled in.
// We can catch some of these by looking for non-"idle" processes that have id 0
// and ignoring those.
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring.");
#endif
}
else
{
if (processInfos.ContainsKey(processInfo._processId))
{
// We've found two entries in the perfcounters that claim to be the
// same process. We throw an exception. Is this really going to be
// helpfull to the user? Should we just ignore?
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id");
#endif
}
else
{
// the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe",
// if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe"
// at the end. If instanceName ends in ".", ".e", or ".ex" we remove it.
string processName = instanceName;
if (processName.Length == 15)
{
if (instanceName.EndsWith(".", StringComparison.Ordinal)) processName = instanceName.Substring(0, 14);
else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) processName = instanceName.Substring(0, 13);
else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12);
}
processInfo._processName = processName;
processInfos.Add(processInfo._processId, processInfo);
}
}
}
else if (type.ObjectNameTitleIndex == threadIndex)
{
ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
if (threadInfo._threadId != 0) threadInfos.Add(threadInfo);
}
instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength);
}
typePtr = (IntPtr)((long)typePtr + type.TotalByteLength);
}
}
finally
{
if (dataHandle.IsAllocated) dataHandle.Free();
}
for (int i = 0; i < threadInfos.Count; i++)
{
ThreadInfo threadInfo = (ThreadInfo)threadInfos[i];
ProcessInfo processInfo;
if (processInfos.TryGetValue(threadInfo._processId, out processInfo))
{
processInfo._threadInfoList.Add(threadInfo);
}
}
ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
processInfos.Values.CopyTo(temp, 0);
return temp;
}
static ThreadInfo GetThreadInfo(Interop.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.PERF_COUNTER_DEFINITION[] counters)
{
ThreadInfo threadInfo = new ThreadInfo();
for (int i = 0; i < counters.Length; i++)
{
Interop.PERF_COUNTER_DEFINITION counter = counters[i];
long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset));
switch ((ValueId)counter.CounterNameTitlePtr)
{
case ValueId.ProcessId:
threadInfo._processId = (int)value;
break;
case ValueId.ThreadId:
threadInfo._threadId = (int)value;
break;
case ValueId.BasePriority:
threadInfo._basePriority = (int)value;
break;
case ValueId.CurrentPriority:
threadInfo._currentPriority = (int)value;
break;
case ValueId.StartAddress:
threadInfo._startAddress = (IntPtr)value;
break;
case ValueId.ThreadState:
threadInfo._threadState = (ThreadState)value;
break;
case ValueId.ThreadWaitReason:
threadInfo._threadWaitReason = GetThreadWaitReason((int)value);
break;
}
}
return threadInfo;
}
internal static ThreadWaitReason GetThreadWaitReason(int value)
{
switch (value)
{
case 0:
case 7: return ThreadWaitReason.Executive;
case 1:
case 8: return ThreadWaitReason.FreePage;
case 2:
case 9: return ThreadWaitReason.PageIn;
case 3:
case 10: return ThreadWaitReason.SystemAllocation;
case 4:
case 11: return ThreadWaitReason.ExecutionDelay;
case 5:
case 12: return ThreadWaitReason.Suspended;
case 6:
case 13: return ThreadWaitReason.UserRequest;
case 14: return ThreadWaitReason.EventPairHigh; ;
case 15: return ThreadWaitReason.EventPairLow;
case 16: return ThreadWaitReason.LpcReceive;
case 17: return ThreadWaitReason.LpcReply;
case 18: return ThreadWaitReason.VirtualMemory;
case 19: return ThreadWaitReason.PageOut;
default: return ThreadWaitReason.Unknown;
}
}
static ProcessInfo GetProcessInfo(Interop.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.PERF_COUNTER_DEFINITION[] counters)
{
ProcessInfo processInfo = new ProcessInfo();
for (int i = 0; i < counters.Length; i++)
{
Interop.PERF_COUNTER_DEFINITION counter = counters[i];
long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset));
switch ((ValueId)counter.CounterNameTitlePtr)
{
case ValueId.ProcessId:
processInfo._processId = (int)value;
break;
case ValueId.HandleCount:
processInfo._handleCount = (int)value;
break;
case ValueId.PoolPagedBytes:
processInfo._poolPagedBytes = value;
break;
case ValueId.PoolNonpagedBytes:
processInfo._poolNonpagedBytes = value;
break;
case ValueId.VirtualBytes:
processInfo._virtualBytes = value;
break;
case ValueId.VirtualBytesPeak:
processInfo._virtualBytesPeak = value;
break;
case ValueId.WorkingSetPeak:
processInfo._workingSetPeak = value;
break;
case ValueId.WorkingSet:
processInfo._workingSet = value;
break;
case ValueId.PageFileBytesPeak:
processInfo._pageFileBytesPeak = value;
break;
case ValueId.PageFileBytes:
processInfo._pageFileBytes = value;
break;
case ValueId.PrivateBytes:
processInfo._privateBytes = value;
break;
case ValueId.BasePriority:
processInfo._basePriority = (int)value;
break;
}
}
return processInfo;
}
static ValueId GetValueId(string counterName)
{
if (counterName != null)
{
ValueId id;
if (s_valueIds.TryGetValue(counterName, out id))
return id;
}
return ValueId.Unknown;
}
static long ReadCounterValue(int counterType, IntPtr dataPtr)
{
if ((counterType & Interop.NtPerfCounterSizeLarge) != 0)
return Marshal.ReadInt64(dataPtr);
else
return (long)Marshal.ReadInt32(dataPtr);
}
enum ValueId
{
Unknown = -1,
HandleCount,
PoolPagedBytes,
PoolNonpagedBytes,
ElapsedTime,
VirtualBytesPeak,
VirtualBytes,
PrivateBytes,
PageFileBytes,
PageFileBytesPeak,
WorkingSetPeak,
WorkingSet,
ThreadId,
ProcessId,
BasePriority,
CurrentPriority,
UserTime,
PrivilegedTime,
StartAddress,
ThreadState,
ThreadWaitReason
}
}
internal static class NtProcessInfoHelper
{
private static int GetNewBufferSize(int existingBufferSize, int requiredSize)
{
if (requiredSize == 0)
{
//
// On some old OS like win2000, requiredSize will not be set if the buffer
// passed to NtQuerySystemInformation is not enough.
//
int newSize = existingBufferSize * 2;
if (newSize < existingBufferSize)
{
// In reality, we should never overflow.
// Adding the code here just in case it happens.
throw new OutOfMemoryException();
}
return newSize;
}
else
{
// allocating a few more kilo bytes just in case there are some new process
// kicked in since new call to NtQuerySystemInformation
int newSize = requiredSize + 1024 * 10;
if (newSize < requiredSize)
{
throw new OutOfMemoryException();
}
return newSize;
}
}
public static ProcessInfo[] GetProcessInfos()
{
// On a normal machine, 30k to 40K will be enough.
// We use 128K here to tolerate mutilple connections to a machine.
int bufferSize = 128 * 1024;
#if DEBUG
// on debug build, use a smaller buffer size to make sure we hit the retrying code path
bufferSize = 1024;
#endif
int requiredSize = 0;
int status;
ProcessInfo[] processInfos;
GCHandle bufferHandle = new GCHandle();
try
{
// Retry until we get all the data
do
{
// Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned.
long[] buffer = new long[(bufferSize + 7) / 8];
bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
status = Interop.mincore.NtQuerySystemInformation(
Interop.NtQuerySystemProcessInformation,
bufferHandle.AddrOfPinnedObject(),
bufferSize,
out requiredSize);
if ((uint)status == Interop.STATUS_INFO_LENGTH_MISMATCH)
{
if (bufferHandle.IsAllocated) bufferHandle.Free();
bufferSize = GetNewBufferSize(bufferSize, requiredSize);
}
} while ((uint)status == Interop.STATUS_INFO_LENGTH_MISMATCH);
if (status < 0)
{ // see definition of NT_SUCCESS(Status) in SDK
throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status));
}
// Parse the data block to get process information
processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject());
}
finally
{
if (bufferHandle.IsAllocated) bufferHandle.Free();
}
return processInfos;
}
static ProcessInfo[] GetProcessInfos(IntPtr dataPtr)
{
// 60 is a reasonable number for processes on a normal machine.
Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60);
long totalOffset = 0;
while (true)
{
IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset);
SystemProcessInformation pi = new SystemProcessInformation();
Marshal.PtrToStructure(currentPtr, pi);
// get information for a process
ProcessInfo processInfo = new ProcessInfo();
// Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD.
processInfo._processId = pi.UniqueProcessId.ToInt32();
processInfo._handleCount = (int)pi.HandleCount;
processInfo._sessionId = (int)pi.SessionId;
processInfo._poolPagedBytes = (long)pi.QuotaPagedPoolUsage; ;
processInfo._poolNonpagedBytes = (long)pi.QuotaNonPagedPoolUsage;
processInfo._virtualBytes = (long)pi.VirtualSize;
processInfo._virtualBytesPeak = (long)pi.PeakVirtualSize;
processInfo._workingSetPeak = (long)pi.PeakWorkingSetSize;
processInfo._workingSet = (long)pi.WorkingSetSize;
processInfo._pageFileBytesPeak = (long)pi.PeakPagefileUsage;
processInfo._pageFileBytes = (long)pi.PagefileUsage;
processInfo._privateBytes = (long)pi.PrivatePageCount;
processInfo._basePriority = pi.BasePriority;
if (pi.NamePtr == IntPtr.Zero)
{
if (processInfo._processId == NtProcessManager.SystemProcessID)
{
processInfo._processName = "System";
}
else if (processInfo._processId == NtProcessManager.IdleProcessID)
{
processInfo._processName = "Idle";
}
else
{
// for normal process without name, using the process ID.
processInfo._processName = processInfo._processId.ToString(CultureInfo.InvariantCulture);
}
}
else
{
string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.NamePtr, pi.NameLength / sizeof(char)));
processInfo._processName = processName;
}
// get the threads for current process
processInfos[processInfo._processId] = processInfo;
currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi));
int i = 0;
while (i < pi.NumberOfThreads)
{
SystemThreadInformation ti = new SystemThreadInformation();
Marshal.PtrToStructure(currentPtr, ti);
ThreadInfo threadInfo = new ThreadInfo();
threadInfo._processId = (int)ti.UniqueProcess;
threadInfo._threadId = (int)ti.UniqueThread;
threadInfo._basePriority = ti.BasePriority;
threadInfo._currentPriority = ti.Priority;
threadInfo._startAddress = ti.StartAddress;
threadInfo._threadState = (ThreadState)ti.ThreadState;
threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason);
processInfo._threadInfoList.Add(threadInfo);
currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti));
i++;
}
if (pi.NextEntryOffset == 0)
{
break;
}
totalOffset += pi.NextEntryOffset;
}
ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
processInfos.Values.CopyTo(temp, 0);
return temp;
}
// This function generates the short form of process name.
//
// This is from GetProcessShortName in NT code base.
// Check base\screg\winreg\perfdlls\process\perfsprc.c for details.
internal static string GetProcessShortName(String name)
{
if (String.IsNullOrEmpty(name))
{
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName");
#endif
return String.Empty;
}
int slash = -1;
int period = -1;
for (int i = 0; i < name.Length; i++)
{
if (name[i] == '\\')
slash = i;
else if (name[i] == '.')
period = i;
}
if (period == -1)
period = name.Length - 1; // set to end of string
else
{
// if a period was found, then see if the extension is
// .EXE, if so drop it, if not, then use end of string
// (i.e. include extension in name)
String extension = name.Substring(period);
if (String.Equals(".exe", extension, StringComparison.OrdinalIgnoreCase))
period--; // point to character before period
else
period = name.Length - 1; // set to end of string
}
if (slash == -1)
slash = 0; // set to start of string
else
slash++; // point to character next to slash
// copy characters between period (or end of string) and
// slash (or start of string) to make image name
return name.Substring(slash, period - slash + 1);
}
// native struct defined in ntexapi.h
[StructLayout(LayoutKind.Sequential)]
internal class SystemProcessInformation
{
internal uint NextEntryOffset;
internal uint NumberOfThreads;
private long _SpareLi1;
private long _SpareLi2;
private long _SpareLi3;
private long _CreateTime;
private long _UserTime;
private long _KernelTime;
internal ushort NameLength; // UNICODE_STRING
internal ushort MaximumNameLength;
internal IntPtr NamePtr; // This will point into the data block returned by NtQuerySystemInformation
internal int BasePriority;
internal IntPtr UniqueProcessId;
internal IntPtr InheritedFromUniqueProcessId;
internal uint HandleCount;
internal uint SessionId;
internal UIntPtr PageDirectoryBase;
internal UIntPtr PeakVirtualSize; // SIZE_T
internal UIntPtr VirtualSize;
internal uint PageFaultCount;
internal UIntPtr PeakWorkingSetSize;
internal UIntPtr WorkingSetSize;
internal UIntPtr QuotaPeakPagedPoolUsage;
internal UIntPtr QuotaPagedPoolUsage;
internal UIntPtr QuotaPeakNonPagedPoolUsage;
internal UIntPtr QuotaNonPagedPoolUsage;
internal UIntPtr PagefileUsage;
internal UIntPtr PeakPagefileUsage;
internal UIntPtr PrivatePageCount;
private long _ReadOperationCount;
private long _WriteOperationCount;
private long _OtherOperationCount;
private long _ReadTransferCount;
private long _WriteTransferCount;
private long _OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
internal class SystemThreadInformation
{
private long _KernelTime;
private long _UserTime;
private long _CreateTime;
private uint _WaitTime;
internal IntPtr StartAddress;
internal IntPtr UniqueProcess;
internal IntPtr UniqueThread;
internal int Priority;
internal int BasePriority;
internal uint ContextSwitches;
internal uint ThreadState;
internal uint WaitReason;
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.IO;
using System.Text;
using OpenADK.Library.Global;
using OpenADK.Library.Infra;
using OpenADK.Util;
namespace OpenADK.Library.Impl
{
/// <summary> An implementation of the DataObjectOutputStream interface that packetizes
/// SIF_Response packets to the agent work directory.
///
/// </summary>
/// <author> Eric Petersen
/// </author>
/// <version> Adk 1.0
/// </version>
public class DataObjectOutputFileStream : DataObjectOutputStreamImpl
{
private FileInfo fFile;
private Query fQuery;
private IElementDef[] fQueryRestrictions;
private String fWorkDir;
private long fCurSize;
private long fMaxSize;
private long fEnvSize;
private int fCurPacket = 0;
private SIF_Error fError;
private ZoneImpl fZone;
private SifVersion fRenderAsVersion;
private Stream fCurrentOutputStream;
private bool fDeferResponses;
/// <summary>
/// The Query filter used to filter data. If set, each call to write() makes an evaluation
/// of the data based on this filter. It the data does not meet the conditions of the query,
/// the object is not written to the output stream.
/// </summary>
private Query fFilter;
/// <summary>
/// This field is set to true in certain cases by SIFResposeSender. If it is set to true,
/// the final packet that is written by this class will have the SIF_MorePackets flag set to 'Yes'
/// </summary>
private bool fMorePackets = false;
/// <summary> Initialize the output stream. This method must be called after creating
/// a new instance of this class and before writing any SIFDataObjects to
/// the stream.
/// </summary>
/// <param name="zone">The Zone associated with messages that will be written to the stream
/// </param>
/// <param name="query">The Query from the SIF_Request message
/// </param>
/// <param name="requestSourceId">The SourceId of the associated SIF_Request message
/// </param>
/// <param name="requestMsgId">The MsgId of the associated SIF_Request message
/// </param>
/// <param name="requestSIFVersion">The version of the SIF_Message envelope of the
/// SIF_Request message (if specified and different than the SIF_Message
/// version, the SIF_Request/SIF_Version element takes precedence).
/// SIF_Responses will be encapsulated in a message envelope matching
/// this version and SifDataObject contents will be rendered in this
/// version
/// </param>
/// <param name="maxSize">The maximum size of rendered SifDataObject that will be
/// accepted by this stream. If a SifDataObject is written to the stream
/// and its size exceeds this value after rendering the object to an XML
/// stream, an ObjectTooLargeException will be thrown by the <i>write</i>
/// method
/// </param>
public override void Initialize(
IZone zone,
Query query,
String requestSourceId,
String requestMsgId,
SifVersion requestSIFVersion,
int maxSize )
{
fQuery = query;
Initialize( zone, query == null ? null : query.FieldRestrictions, requestSourceId, requestMsgId,
requestSIFVersion, maxSize );
}
/// <summary> Initialize the output stream. This method must be called after creating
/// a new instance of this class and before writing any SIFDataObjects to
/// the stream.
/// </summary>
/// <param name="zone">The Zone associated with messages that will be written to the stream
/// </param>
/// <param name="queryRestrictions">The fields that should be returned according to the Query
/// that was specified in the SIF_Request message
/// </param>
/// <param name="requestSourceId">The SourceId of the associated SIF_Request message
/// </param>
/// <param name="requestMsgId">The MsgId of the associated SIF_Request message
/// </param>
/// <param name="requestSIFVersion">The version of the SIF_Message envelope of the
/// SIF_Request message (if specified and different than the SIF_Message
/// version, the SIF_Request/SIF_Version element takes precedence).
/// SIF_Responses will be encapsulated in a message envelope matching
/// this version and SifDataObject contents will be rendered in this
/// version
/// </param>
/// <param name="maxSize">The maximum size of rendered SifDataObject that will be
/// accepted by this stream. If a SifDataObject is written to the stream
/// and its size exceeds this value after rendering the object to an XML
/// stream, an ObjectTooLargeException will be thrown by the <i>write</i>
/// method
/// </param>
public override void Initialize(
IZone zone,
IElementDef[] queryRestrictions,
String requestSourceId,
String requestMsgId,
SifVersion requestSIFVersion,
int maxSize )
{
fZone = (ZoneImpl) zone;
fQueryRestrictions = queryRestrictions;
fReqId = requestMsgId;
fDestId = requestSourceId;
fMaxSize = maxSize;
fCurPacket = 0;
fRenderAsVersion = requestSIFVersion;
//
// Messages written to this stream are stored in the directory
// "%adk.home%/work/%zoneId%_%zoneHost%/responses". One or more files
// are written to this directory, where each file has the name
// "destId.requestId.{packet}.pkt". As messages are written to the
// stream, the maxSize property is checked to determine if the size of
// the current file will be larger than the maxSize. If so, the file is
// closed and the packet number incremented. A new file is then created
// for the message and all subsequent messages until maxSize is again
// exceeded.
// Ensure work directory exists
fWorkDir = ResponseDelivery.GetSourceDirectory( DeliveryType, zone );
DirectoryInfo dir = new DirectoryInfo( fWorkDir );
if ( !dir.Exists )
{
dir.Create();
}
// Get the size of the SIF_Message envelope to determine the actual
// packet size we're producing
fEnvSize = CalcEnvelopeSize( fZone );
}
/// <summary> Start writing messages to a new packet file. The current packet file
/// stream is closed, the packet number incremented by one, and a new packet
/// file created. All subsequent calls to the <i>write</i> method will render
/// messages to the newly-created packet file.
/// </summary>
private void NewPacket()
{
Close();
fCurPacket++;
fCurSize = fEnvSize;
// Create output file and stream
fFile = CreateOutputFile();
fCurrentOutputStream = CreateOutputStream();
}
/// <summary> Create a File descriptor of the current output file</summary>
private FileInfo CreateOutputFile()
{
StringBuilder builder = new StringBuilder();
builder.Append( fWorkDir );
builder.Append( Path.DirectorySeparatorChar );
ResponseDelivery.SerializeResponsePacketFileName( builder, fDestId, fReqId, fCurPacket, fRenderAsVersion,
(fError != null) );
return new FileInfo( builder.ToString() );
}
/// <summary> Create the underlying output stream</summary>
private Stream CreateOutputStream()
{
Close();
return new FileStream( fFile.FullName, FileMode.Create );
}
/// <summary> Write a SifDataObject to the stream</summary>
public override void Write( SifDataObject data )
{
// Check to see if the data object is null or if the
// deferResponses() property has been set
if ( data == null || fDeferResponses )
{
return;
}
// Check to see if a SIF_Error has already been written
if ( fError != null )
{
throw new AdkException
( "A SIF_Error has already been written to the stream", fZone );
}
// If the autoFilter property has been set, determine if this object meets the
// conditions of the filter
if ( fFilter != null )
{
if ( !fFilter.Evaluate( data ) )
{
// TODO: Perhaps this feature should log any objects not written to the output
// stream if extended logging is enabled
return;
}
}
try
{
if ( fCurrentOutputStream == null || fZone.Properties.OneObjectPerResponse )
{
NewPacket();
}
using ( MemoryStream buffer = new MemoryStream() )
{
// Write to memory stream first so we can determine if the resulting
// message will fit in the current packet
WriteObject( data, buffer, fRenderAsVersion, fQueryRestrictions );
if ( (buffer.Length + fCurSize) > fMaxSize )
{
// If the current packet size is equal to the envelope size (e.g. no objects
// have been written), we have exceeded the size of the buffer and need to abort
if ( buffer.Length == fEnvSize )
{
String errorMessage = "Publisher result data in packet " + fCurPacket + " too large (" +
buffer.Length + " [Data] + " + fEnvSize + " [Sif Envelope] > " +
fMaxSize + ")";
if ( fZone.Properties.OneObjectPerResponse )
{
errorMessage += " [1 Object per Response Packet]";
}
throw new AdkException( errorMessage, fZone );
}
else
{
// Create new packet for this object
NewPacket();
}
}
if ( (Adk.Debug & AdkDebugFlags.Message_Content) != 0 )
{
buffer.Seek( 0, SeekOrigin.Begin );
StreamReader reader = new StreamReader( buffer, SifIOFormatter.ENCODING );
string message = reader.ReadToEnd();
fZone.Log.Debug
( "Writing object to SIF_Response packet #" + fCurPacket + ":\r\n" +
message );
}
buffer.Seek( 0, SeekOrigin.Begin );
Streams.CopyStream( buffer, fCurrentOutputStream );
fCurSize += buffer.Length;
buffer.Close();
}
}
catch ( Exception ioe )
{
throw new AdkException
(
"Failed to write Publisher result data (packet " + fCurPacket + ") to " +
fFile.FullName + ": " +
ioe, fZone );
}
}
/// <summary>
/// Commits the writing of all objects and sends the objects
/// </summary>
public override void Commit()
{
try
{
if ( fDeferResponses )
{
Abort();
}
else
{
// If no objects or SIF_Errors have been written to the stream, we still
// need to return an empty SIF_Response to the ZIS.
if ( fCurrentOutputStream == null )
{
try
{
NewPacket();
Close();
}
catch ( IOException ioe )
{
throw new AdkException
(
"Could not commit the stream because of an IO error writing an empty SIF_Response packet: " +
ioe, fZone );
}
}
String responseFileName = ResponseDelivery.SerializeResponseHeaderFileName(fDestId, fReqId, fMorePackets);
// Write out "destId.requestId." file to signal the Publisher has finished
// writing all responses successfully. This file will hang around until
// all "requestId.{packet}.pkt" files have been sent to the ZIS by the Adk,
// a process that could occur over several agent sessions if the agent
// is abruptly terminated.
//
String fileName = fWorkDir + Path.DirectorySeparatorChar + responseFileName;
try
{
FileInfo publisherFile = new FileInfo( fileName );
using ( Stream publisherFileStream = publisherFile.Create() )
{
publisherFileStream.Close();
}
}
catch ( IOException ioe )
{
fZone.Log.Warn("Unable to create SIF_Response header file: " + fileName + ". " + ioe.Message, ioe);
}
OnCommitted();
}
}
finally
{
fZone = null;
}
}
protected virtual void OnCommitted()
{
fZone.GetResponseDelivery().Process();
}
/// <summary> Called when the Publisher.OnQuery method has thrown a SifException,
/// indicating an error should be returned in the SIF_Response body
/// </summary>
public override void SetError( SIF_Error error )
{
fError = error;
//
// Write a SIF_Response packet that contains only this SIF_Error
//
try
{
NewPacket();
SifWriter writer = new SifWriter( fCurrentOutputStream );
writer.SuppressNamespace( true );
writer.Write( error, fRenderAsVersion );
writer.Close();
}
catch ( IOException ioe )
{
throw new AdkException
(
"Failed to write Publisher SIF_Error data (packet " + fCurPacket + ") to " +
fFile.FullName + ": " +
ioe, fZone );
}
}
/// <summary>
/// Aborts the current write, closes the string, and deletes all files created during this operations
/// </summary>
public override void Abort()
{
Close();
string filter = fDestId + "." + fReqId + "*";
DirectoryInfo dir = new DirectoryInfo( fWorkDir );
foreach ( FileInfo file in dir.GetFiles( filter ) )
{
file.Delete();
}
fZone = null;
}
/// <summary>
/// Defer sending SIF_Response messages and ignore any objects written to this stream.
/// </summary>
/// <remarks>
/// See the <see cref="OpenADK.Library.SifResponseSender"/> class comments for more
/// information about using this method.
/// <seealso cref="OpenADK.Library.SifResponseSender"/>
/// </remarks>
/// <since>ADK 1.5.1</since>
public override void DeferResponse()
{
fDeferResponses = true;
}
/// <summary>
/// Closes the current stream
/// </summary>
public override void Close()
{
if ( fCurrentOutputStream != null )
{
fCurrentOutputStream.Close();
}
}
/// <summary>
/// The zone that is currently in scope
/// </summary>
protected ZoneImpl Zone
{
get { return fZone; }
}
/// <summary>
/// Recalculates the envelope size
/// </summary>
protected void RecalcEnvSize()
{
fEnvSize = CalcEnvelopeSize( fZone );
}
/// <summary>
/// Returns the type of delivery stream this is
/// </summary>
protected virtual ResponseDeliveryType DeliveryType
{
get { return ResponseDeliveryType.Generic; }
}
/// <summary>
/// Returns whether Responses are being deferred
/// </summary>
protected bool ResponsesDeferred
{
get { return fDeferResponses; }
}
/// <summary>
/// The directory where responses are being queued until they are sent
/// </summary>
protected string WorkDir
{
get { return fWorkDir; }
}
/// <summary>
/// Writes the object to the outgoing data stream
/// </summary>
/// <param name="data"></param>
/// <param name="buffer"></param>
/// <param name="version"></param>
/// <param name="fieldRestrictions"></param>
protected virtual void WriteObject( SifDataObject data,
Stream buffer,
SifVersion version,
IElementDef[] fieldRestrictions )
{
SifWriter writer = new SifWriter( buffer );
writer.SuppressNamespace( true );
if ( fQuery != null )
{
fQuery.SetRenderingRestrictionsTo( data );
}
else if ( fQueryRestrictions != null )
{
writer.Filter = fQueryRestrictions;
}
writer.Write( data, version );
writer.Flush();
}
/// <summary>
/// Tells the DataObjectOutputStream to automatically filter out any SIFDataObjects that do
/// not match the conditions specified in the provided Query object.
/// </summary>
/// <remarks>Any SIFDataObject that does not meet the conditions specified in the Query will not be
/// written to the underlying data stream.
/// </remarks>
/// <value>The Query object to use when filtering data or <c>null</c> to remove the filter </value>
public override Query Filter
{
get { return fFilter; }
set { fFilter = value; }
}
/// <summary>
/// Gets or sets the value that will be set to the SIF_MorePackets element in the message
/// after this DataObjectOutputStream is closed
/// </summary>
public override YesNo SIF_MorePackets
{
get { return fMorePackets ? YesNo.YES : YesNo.NO; }
set { fMorePackets = value == YesNo.YES; }
}
/// <summary>
/// Sets the value that will be used for the number of the first packet created by the output stream
/// </summary>
/// <exception cref="InvalidOperationException">thrown if setting the value after an object has
/// already been written to the output stream</exception>
public override int SIF_PacketNumber
{
get
{ // Special case: If newPacket() has not been called yet,
// fWriter will be null, in which case, we need to add one to fCurPacket
// to get the actual value of the packet
if (fCurrentOutputStream == null)
{
return fCurPacket + 1;
}
else
{
return fCurPacket;
}
}
set
{ // If fWriter is not initialized, set the fCurPacket value to
// 1 value less (allows it to be properly incremented in newPacket())
if (fCurrentOutputStream == null)
{
fCurPacket = value - 1;
}
else
{
throw new InvalidOperationException("Cannot set the packet number after objects have already been written");
}
}
}
#region Cleanup and Disposal
/// <summary>
/// Cleans up the resources held on to by this object
/// </summary>
public override void Dispose()
{
Dispose( true );
}
private void Dispose( bool disposing )
{
Close();
}
#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 Xunit;
namespace System.Numerics.Tests
{
public class op_multiplyTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunMultiplyPositive()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One Large BigInteger
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + "u*");
}
// Multiply Method - Two Large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
try
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
catch (IndexOutOfRangeException)
{
// TODO: Refactor this
Console.WriteLine("Array1: " + Print(tempByteArray1));
Console.WriteLine("Array2: " + Print(tempByteArray2));
throw;
}
}
}
[Fact]
public static void RunMultiplyPositiveWith0()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
}
[Fact]
public static void RunMultiplyAxiomXmult1()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X*1 = X
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " b*", Int32.MaxValue.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.One + " b*", Int64.MaxValue.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.One + " b*", randBigInt + "u+");
}
}
[Fact]
public static void RunMultiplyAxiomXmult0()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X*0 = 0
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
}
}
[Fact]
public static void RunMultiplyAxiomComm()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*");
// 32 bit boundary n1=0 n2=1
VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*");
}
[Fact]
public static void RunMultiplyBoundary()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*");
// 32 bit boundary n1=0 n2=1
VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*");
}
[Fact]
public static void RunMultiplyTests()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One Large BigInteger
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + "u*");
}
// Multiply Method - Two Large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
try
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
catch (IndexOutOfRangeException)
{
// TODO: Refactor this
Console.WriteLine("Array1: " + Print(tempByteArray1));
Console.WriteLine("Array2: " + Print(tempByteArray2));
throw;
}
}
// Multiply Method - One large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Axiom: X*1 = X
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " b*", Int32.MaxValue.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.One + " b*", Int64.MaxValue.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.One + " b*", randBigInt + "u+");
}
// Axiom: X*0 = 0
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
}
// Axiom: a*b = b*a
VerifyIdentityString(Int32.MaxValue + " " + Int64.MaxValue + " b*", Int64.MaxValue + " " + Int32.MaxValue + " b*");
for (int i = 0; i < s_samples; i++)
{
String randBigInt1 = Print(GetRandomByteArray(s_random));
String randBigInt2 = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt1 + randBigInt2 + "b*", randBigInt2 + randBigInt1 + "b*");
}
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*");
// 32 bit boundary n1=0 n2=1
VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*");
}
private static void VerifyMultiplyString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static void VerifyIdentityString(string opstring1, string opstring2)
{
StackCalc sc1 = new StackCalc(opstring1);
while (sc1.DoNextOperation())
{
//Run the full calculation
sc1.DoNextOperation();
}
StackCalc sc2 = new StackCalc(opstring2);
while (sc2.DoNextOperation())
{
//Run the full calculation
sc2.DoNextOperation();
}
Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString());
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 100));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Linq;
namespace Test
{
public class FirstLastSingleDefaultIfEmptyTests
{
#region DefaultIfEmpty / First / Last / Single Tests
//
// DefaultIfEmpty
//
[Fact]
public static void RunDefaultIfEmptyTest1()
{
for (int i = 0; i <= 33; i++)
{
RunDefaultIfEmptyTest1Core(i);
}
RunDefaultIfEmptyTest1Core(1024);
RunDefaultIfEmptyTest1Core(1024 * 1024);
}
[Fact]
public static void RunDefaultIfEmptyOrderByTest1()
{
RunDefaultIfEmptyOrderByTest1Core(0);
RunDefaultIfEmptyOrderByTest1Core(1024);
RunDefaultIfEmptyOrderByTest2(0);
RunDefaultIfEmptyOrderByTest2(1024);
}
private static void RunDefaultIfEmptyTest1Core(int size)
{
string methodInf = string.Format("RunDefaultIfEmptyTest1(size={0})", size);
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i;
ParallelQuery<int> q = ints.AsParallel().DefaultIfEmpty();
int cnt = 0;
foreach (int x in q)
{
if (size == 0 && x != default(int))
{
Assert.True(false, string.Format(methodInf + " > FAILED. Only element should be {0} for empty inputs: saw {1}", default(int), x));
}
cnt++;
}
int expect = size == 0 ? 1 : size;
if (cnt != expect)
{
Assert.True(false, string.Format(methodInf + " > Expect: {0}, real: {1}", expect, cnt));
}
}
private static void RunDefaultIfEmptyOrderByTest1Core(int size)
{
string methodInf = string.Format("RunDefaultIfEmptyOrderByTest1(size={0})", size);
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i;
ParallelQuery<int> q = ints.AsParallel().OrderBy<int, int>(x => x).DefaultIfEmpty();
int cnt = 0;
int last = -1;
foreach (int x in q)
{
if (size == 0 && x != default(int))
{
Assert.True(false, string.Format(methodInf + " > FAILED. Only element should be {0} for empty inputs: saw {1}", default(int), x));
}
if (x < last)
{
Assert.True(false, string.Format(methodInf + " > FAILED. Sort wasn't processed correctly: curr = {0}, but last = {1}", x, last));
}
last = x;
cnt++;
}
int expect = size == 0 ? 1 : size;
if (cnt != expect)
{
Assert.True(false, string.Format(methodInf + " > Expect: {0}, real: {1}", expect, cnt));
}
}
private static void RunDefaultIfEmptyOrderByTest2(int size)
{
string methodInf = string.Format("RunDefaultIfEmptyOrderByTest2(size={0})", size);
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i;
ParallelQuery<int> q = ints.AsParallel().DefaultIfEmpty().
OrderBy<int, int>(e => e);
int cnt = 0;
int last = -1;
foreach (int x in q)
{
if (size == 0 && x != default(int))
{
Assert.True(false, string.Format(methodInf + " > FAILED. Only element should be {0} for empty inputs: saw {1}", default(int), x));
}
if (x < last)
{
Assert.True(false, string.Format(methodInf + " > FAILED. Sort wasn't processed correctly: curr = {0}, but last = {1}", x, last));
}
last = x;
cnt++;
}
int expect = size == 0 ? 1 : size;
if (cnt != expect)
{
Assert.True(false, string.Format(methodInf + " > FAILED. Expect: {0}, real: {1}", expect, cnt));
}
}
//
// First and FirstOrDefault
//
[Fact]
public static void RunFirstTest1()
{
RunFirstTest1Core(0, false);
RunFirstTest1Core(1024, false);
RunFirstTest1Core(1024 * 1024, false);
RunFirstTest1Core(0, true);
RunFirstTest1Core(1024, true);
RunFirstTest1Core(1024 * 1024, true);
}
[Fact]
public static void RunFirstOrDefaultTest1()
{
RunFirstOrDefaultTest1Core(0, false);
RunFirstOrDefaultTest1Core(1024, false);
RunFirstOrDefaultTest1Core(1024 * 1024, false);
RunFirstOrDefaultTest1Core(0, true);
RunFirstOrDefaultTest1Core(1024, true);
RunFirstOrDefaultTest1Core(1024 * 1024, true);
}
private static void RunFirstTest1Core(int size, bool usePredicate)
{
string method = string.Format("RunFirstTest1(size={0}, usePredicate={1})", size, usePredicate);
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i;
int predSearch = 1033;
bool expectExcept = (size == 0 || (usePredicate && size <= predSearch));
try
{
int q;
if (usePredicate)
{
Func<int, bool> pred = delegate (int x) { return (x >= predSearch); };
q = ints.AsParallel().First(pred);
}
else
{
q = ints.AsParallel().First();
}
if (expectExcept)
{
Assert.True(false, string.Format(method + " > Failure: Expected an exception, but didn't get one"));
}
int expectReturn = usePredicate ? predSearch : 0;
if (q != expectReturn)
{
Assert.True(false, string.Format(method + " > Failed. Expected return value of {0}, saw {1} instead", expectReturn, q));
}
}
catch (InvalidOperationException ioex)
{
if (!expectExcept)
{
Assert.True(false, string.Format(method + " > Failure: Got exception, but didn't expect it {0}", ioex));
}
}
}
private static void RunFirstOrDefaultTest1Core(int size, bool usePredicate)
{
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i + 1;
int predSearch = 1033;
bool expectDefault = (size == 0 || (usePredicate && size <= predSearch));
int q;
if (usePredicate)
{
Func<int, bool> pred = delegate (int x) { return (x >= predSearch); };
q = ints.AsParallel().FirstOrDefault(pred);
}
else
{
q = ints.AsParallel().FirstOrDefault();
}
int expectReturn = expectDefault ? 0 : (usePredicate ? predSearch : 1);
if (q != expectReturn)
{
string method = string.Format("RunFirstOrDefaultTest1(size={0}, usePredicate={1})", size, usePredicate);
Assert.True(false, string.Format(method + " > FAILED. Expected return value of {0}, saw {1} instead", expectReturn, q));
}
}
//
// Last and LastOrDefault
//
[Fact]
public static void RunLastTest1()
{
RunLastTest1Core(0, false);
RunLastTest1Core(1024, false);
RunLastTest1Core(1024 * 1024, false);
RunLastTest1Core(0, true);
RunLastTest1Core(1024, true);
RunLastTest1Core(1024 * 1024, true);
}
[Fact]
public static void RunLastOrDefaultTest1()
{
RunLastOrDefaultTest1Core(0, false);
RunLastOrDefaultTest1Core(1024, false);
RunLastOrDefaultTest1Core(1024 * 1024, false);
RunLastOrDefaultTest1Core(0, true);
RunLastOrDefaultTest1Core(1024, true);
RunLastOrDefaultTest1Core(1024 * 1024, true);
}
private static void RunLastTest1Core(int size, bool usePredicate)
{
string methodInf = string.Format("RunLastTest1(size={0}, usePredicate={1})", size, usePredicate);
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i;
int predLo = 1033;
int predHi = 1050;
bool expectExcept = (size == 0 || (usePredicate && size <= predLo));
try
{
int q;
if (usePredicate)
{
Func<int, bool> pred = delegate (int x) { return (x >= predLo && x <= predHi); };
q = ints.AsParallel().Last(pred);
}
else
{
q = ints.AsParallel().Last();
}
if (expectExcept)
{
Assert.True(false, string.Format(methodInf + " > Failure: Expected an exception, but didn't get one"));
}
int sizeLessOne = size - 1;
int minPredHiSize = predHi >= sizeLessOne ? sizeLessOne : predHi;
int expectReturn = usePredicate ? minPredHiSize : sizeLessOne;
if (q != expectReturn)
{
Assert.True(false, string.Format(methodInf + " > FAILED. Expected return value of {0}, saw {1} instead", expectReturn, q));
}
}
catch (InvalidOperationException ioex)
{
if (!expectExcept)
{
Assert.True(false, string.Format(methodInf + " > Failure: Got exception, but didn't expect it {0}", ioex));
}
}
}
private static void RunLastOrDefaultTest1Core(int size, bool usePredicate)
{
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i + 1;
int predLo = 1033;
int predHi = 1050;
bool expectDefault = (size == 0 || (usePredicate && size <= (predLo + 1)));
int q;
if (usePredicate)
{
Func<int, bool> pred = delegate (int x) { return (x >= predLo && x <= predHi); };
q = ints.AsParallel().LastOrDefault(pred);
}
else
{
q = ints.AsParallel().LastOrDefault();
}
int minPredHiSize = predHi >= size ? size : predHi;
int expectReturn = expectDefault ? 0 : (usePredicate ? minPredHiSize : size);
if (q != expectReturn)
{
string methodInf = string.Format("RunLastOrDefaultTest1(size={0}, usePredicate={1})", size, usePredicate);
Assert.True(false, string.Format(methodInf + " > Expected return value of {0}, saw {1} instead", expectReturn, q));
}
}
//
// Single and SingleOrDefault
//
[Fact]
public static void RunSingleTest1()
{
RunSingleTest1Core(0, false);
RunSingleTest1Core(1, false);
RunSingleTest1Core(1024, false);
RunSingleTest1Core(1024 * 1024, false);
RunSingleTest1Core(0, true);
RunSingleTest1Core(1, true);
RunSingleTest1Core(1024, true);
RunSingleTest1Core(1024 * 1024, true);
}
[Fact]
public static void RunSingleOrDefaultTest1()
{
RunSingleOrDefaultTest1Core(0, false);
RunSingleOrDefaultTest1Core(1, false);
RunSingleOrDefaultTest1Core(1024, false);
RunSingleOrDefaultTest1Core(1024 * 1024, false);
RunSingleOrDefaultTest1Core(0, true);
RunSingleOrDefaultTest1Core(1, true);
RunSingleOrDefaultTest1Core(1024, true);
RunSingleOrDefaultTest1Core(1024 * 1024, true);
}
private static void RunSingleTest1Core(int size, bool usePredicate)
{
string methodInfo = string.Format("RunSingleTest1(size={0}, usePredicate={1})", size, usePredicate);
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i;
int predNum = 1023;
bool expectExcept = usePredicate ? predNum != (size - 1) : size != 1;
try
{
int q;
if (usePredicate)
{
Func<int, bool> pred = delegate (int x) { return x >= predNum; };
q = ints.AsParallel().Single(pred);
}
else
{
q = ints.AsParallel().Single();
}
if (expectExcept)
{
Assert.True(false, string.Format(methodInfo + " > Failure: Expected an exception, but didn't get one"));
}
else
{
int expectReturn = usePredicate ? predNum : 0;
if (q != expectReturn)
{
Assert.True(false, string.Format(methodInfo + " > FAILED. Expected return value of {0}, saw {1} instead", expectReturn, q));
}
}
}
catch (InvalidOperationException ioex)
{
if (!expectExcept)
{
Assert.True(false, string.Format(methodInfo + " > Failure: Got exception, but didn't expect it {0}", ioex));
}
}
}
private static void RunSingleOrDefaultTest1Core(int size, bool usePredicate)
{
string methodInfo = string.Format("RunSingleOrDefaultTest1(size={0}, usePredicate={1})", size, usePredicate);
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i + 1;
int predNum = 1023;
bool expectDefault = usePredicate ? predNum >= (size + 1) : size == 0;
bool expectExcept = usePredicate ? predNum < size : size > 1;
try
{
int q;
if (usePredicate)
{
Func<int, bool> pred = delegate (int x) { return x >= predNum; };
q = ints.AsParallel().SingleOrDefault(pred);
}
else
{
q = ints.AsParallel().SingleOrDefault();
}
if (expectExcept)
{
Assert.True(false, string.Format(methodInfo + " > Failure: Expected an exception, but didn't get one"));
}
else
{
int expectReturn = expectDefault ? 0 : (usePredicate ? predNum : 1);
if (q != expectReturn)
{
Assert.True(false, string.Format(methodInfo + " > FAILED. Expected return value of {0}, saw {1} instead", expectReturn, q));
}
}
}
catch (InvalidOperationException ioex)
{
if (!expectExcept)
{
Assert.True(false, string.Format(methodInfo + " > Failure: Got exception, but didn't expect it {0}", ioex));
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class PartitionerStaticTests
{
[Fact]
public static void TestStaticPartitioningIList()
{
RunTestWithAlgorithm(dataSize: 11, partitionCount: 8, algorithm: 0);
RunTestWithAlgorithm(dataSize: 999, partitionCount: 1, algorithm: 0);
RunTestWithAlgorithm(dataSize: 10000, partitionCount: 11, algorithm: 0);
}
[Fact]
public static void TestStaticPartitioningArray()
{
RunTestWithAlgorithm(dataSize: 7, partitionCount: 4, algorithm: 1);
RunTestWithAlgorithm(dataSize: 123, partitionCount: 1, algorithm: 1);
RunTestWithAlgorithm(dataSize: 1000, partitionCount: 7, algorithm: 1);
}
[Fact]
public static void TestLoadBalanceIList()
{
RunTestWithAlgorithm(dataSize: 7, partitionCount: 4, algorithm: 2);
RunTestWithAlgorithm(dataSize: 123, partitionCount: 1, algorithm: 2);
RunTestWithAlgorithm(dataSize: 1000, partitionCount: 7, algorithm: 2);
}
[Fact]
public static void TestLoadBalanceArray()
{
RunTestWithAlgorithm(dataSize: 11, partitionCount: 8, algorithm: 3);
RunTestWithAlgorithm(dataSize: 999, partitionCount: 1, algorithm: 3);
RunTestWithAlgorithm(dataSize: 10000, partitionCount: 11, algorithm: 3);
}
[Fact]
public static void TestLoadBalanceEnumerator()
{
RunTestWithAlgorithm(dataSize: 7, partitionCount: 4, algorithm: 4);
RunTestWithAlgorithm(dataSize: 123, partitionCount: 1, algorithm: 4);
RunTestWithAlgorithm(dataSize: 1000, partitionCount: 7, algorithm: 4);
}
#region Dispose tests. The dispose logic of PartitionerStatic
// In the official dev unit test run, this test should be commented out
// - Each time we call GetDynamicPartitions method, we create an internal "reader enumerator" to read the
// source data, and we need to make sure that whenever the object returned by GetDynamicPartitions is disposed,
// the "reader enumerator" is also disposed.
[Fact]
public static void TestDisposeException()
{
var data = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var enumerable = new DisposeTrackingEnumerable<int>(data);
var partitioner = Partitioner.Create(enumerable);
var partition = partitioner.GetDynamicPartitions();
IDisposable d = partition as IDisposable;
Assert.NotNull(d);
d.Dispose();
Assert.Throws<ObjectDisposedException>(() => { var enum1 = partition.GetEnumerator(); });
}
/// <summary>
/// Race in Partitioner's dynamic partitioning Dispose logic
/// After the fix, the partitioner created through Partitioner.Create(IEnumerable) has the following behavior:
/// 1. reference counting in static partitioning. All partitions need to be disposed explicitly
/// 2. no reference counting in dynamic partitioning. The partitioner need to be disposed explicitly
/// </summary>
/// <returns></returns>
[Fact]
public static void RunDynamicPartitioningDispose()
{
var p = Partitioner.Create(new int[] { 0, 1 });
var d = p.GetDynamicPartitions();
using (var e = d.GetEnumerator())
{
while (e.MoveNext()) { }
}
// should not throw
using (var e = d.GetEnumerator()) { };
}
#endregion
[Fact]
public static void TestExceptions()
{
// Testing ArgumentNullException with data==null
// Test ArgumentNullException of source data
OrderablePartitioner<int> partitioner;
for (int algorithm = 0; algorithm < 5; algorithm++)
{
Assert.Throws<ArgumentNullException>(() => { partitioner = PartitioningWithAlgorithm<int>(null, algorithm); });
}
// Test NotSupportedException of Reset: already tested in RunTestWithAlgorithm
// Test InvalidOperationException: already tested in TestPartitioningCore
// Test ArgumentOutOfRangeException of partitionCount == 0
int[] data = new int[10000];
for (int i = 0; i < 10000; i++)
data[i] = i;
//test GetOrderablePartitions method for 0-4 algorithms, try to catch ArgumentOutOfRangeException
for (int algorithm = 0; algorithm < 5; algorithm++)
{
partitioner = PartitioningWithAlgorithm<int>(data, algorithm);
Assert.Throws<ArgumentOutOfRangeException>(() => { var partitions1 = partitioner.GetOrderablePartitions(0); });
}
}
[Fact]
public static void TestEmptyPartitions()
{
int[] data = new int[0];
// Test ArgumentNullException of source data
OrderablePartitioner<int> partitioner;
for (int algorithm = 0; algorithm < 5; algorithm++)
{
partitioner = PartitioningWithAlgorithm<int>(data, algorithm);
//test GetOrderablePartitions
var partitions1 = partitioner.GetOrderablePartitions(4);
//verify all partitions are empty
for (int i = 0; i < 4; i++)
{
Assert.False(partitions1[i].MoveNext(), "Should not be able to move next in an empty partition.");
}
//test GetOrderableDynamicPartitions
try
{
var partitions2 = partitioner.GetOrderableDynamicPartitions();
//verify all partitions are empty
var newPartition = partitions2.GetEnumerator();
Assert.False(newPartition.MoveNext(), "Should not be able to move next in an empty partition.");
}
catch (NotSupportedException)
{
Assert.True(IsStaticPartition(algorithm), "TestEmptyPartitions: IsStaticPartition(algorithm) should have been true.");
}
}
}
private static void RunTestWithAlgorithm(int dataSize, int partitionCount, int algorithm)
{
//we set up the KeyValuePair in the way that keys and values should always be the same
//for all partitioning algorithms. So that we can use a bitmap (boolarray) to check whether
//any elements are missing in the end.
int[] data = new int[dataSize];
for (int i = 0; i < dataSize; i++)
data[i] = i;
IEnumerator<KeyValuePair<long, int>>[] partitionsUnderTest = new IEnumerator<KeyValuePair<long, int>>[partitionCount];
//step 1: test GetOrderablePartitions
OrderablePartitioner<int> partitioner = PartitioningWithAlgorithm<int>(data, algorithm);
var partitions1 = partitioner.GetOrderablePartitions(partitionCount);
//convert it to partition array for testing
for (int i = 0; i < partitionCount; i++)
partitionsUnderTest[i] = partitions1[i];
Assert.Equal(partitionCount, partitions1.Count);
TestPartitioningCore(dataSize, partitionCount, data, IsStaticPartition(algorithm), partitionsUnderTest);
//step 2: test GetOrderableDynamicPartitions
bool gotException = false;
try
{
var partitions2 = partitioner.GetOrderableDynamicPartitions();
for (int i = 0; i < partitionCount; i++)
partitionsUnderTest[i] = partitions2.GetEnumerator();
TestPartitioningCore(dataSize, partitionCount, data, IsStaticPartition(algorithm), partitionsUnderTest);
}
catch (NotSupportedException)
{
//swallow this exception: static partitioning doesn't support GetOrderableDynamicPartitions
gotException = true;
}
Assert.False(IsStaticPartition(algorithm) && !gotException, "TestLoadBalanceIList: Failure: didn't catch \"NotSupportedException\" for static partitioning");
}
private static OrderablePartitioner<T> PartitioningWithAlgorithm<T>(T[] data, int algorithm)
{
switch (algorithm)
{
//static partitioning through IList
case (0):
return Partitioner.Create((IList<T>)data, false);
//static partitioning through Array
case (1):
return Partitioner.Create(data, false);
//dynamic partitioning through IList
case (2):
return Partitioner.Create((IList<T>)data, true);
//dynamic partitioning through Array
case (3):
return Partitioner.Create(data, true);
//dynamic partitioning through IEnumerator
case (4):
return Partitioner.Create((IEnumerable<T>)data);
default:
throw new InvalidOperationException("PartitioningWithAlgorithm: no such partitioning algorithm");
}
}
private static void TestPartitioningCore(int dataSize, int partitionCount, int[] data, bool staticPartitioning,
IEnumerator<KeyValuePair<long, int>>[] partitions)
{
bool[] boolarray = new bool[dataSize];
bool keysOrderedWithinPartition = true,
keysOrderedAcrossPartitions = true;
int enumCount = 0; //count how many elements are enumerated by all partitions
Task[] threadArray = new Task[partitionCount];
for (int i = 0; i < partitionCount; i++)
{
int my_i = i;
threadArray[i] = Task.Run(() =>
{
int localOffset = 0;
int lastElement = -1;
//variables to compute key/value consistency for static partitioning.
int quotient, remainder;
quotient = dataSize / partitionCount;
remainder = dataSize % partitionCount;
Assert.Throws<InvalidOperationException>(() => { var temp = partitions[my_i].Current; });
while (partitions[my_i].MoveNext())
{
int key = (int)partitions[my_i].Current.Key,
value = partitions[my_i].Current.Value;
Assert.Equal(key, value);
boolarray[key] = true;
Interlocked.Increment(ref enumCount);
//todo: check if keys are ordered increasingly within each partition.
keysOrderedWithinPartition &= (lastElement >= key);
lastElement = key;
//Only check this with static partitioning
//check keys are ordered across the partitions
if (staticPartitioning)
{
int originalPosition;
if (my_i < remainder)
originalPosition = localOffset + my_i * (quotient + 1);
else
originalPosition = localOffset + remainder * (quotient + 1) + (my_i - remainder) * quotient;
keysOrderedAcrossPartitions &= originalPosition == value;
}
localOffset++;
}
}
);
}
Task.WaitAll(threadArray);
if (keysOrderedWithinPartition)
Console.WriteLine("TestPartitioningCore: Keys are not strictly ordered within each partition");
// Only check this with static partitioning
//check keys are ordered across the partitions
Assert.False(staticPartitioning && !keysOrderedAcrossPartitions, "TestPartitioningCore: Keys are not strictly ordered across partitions");
//check data count
Assert.Equal(enumCount, dataSize);
//check if any elements are missing
foreach (var item in boolarray)
{
Assert.True(item);
}
}
//
// Try calling MoveNext on a Partitioner enumerator after that enumerator has already returned false.
//
[Fact]
public static void TestExtraMoveNext()
{
Partitioner<int>[] partitioners = new[]
{
Partitioner.Create(new int[] { 0 , 1, 2, 3, 4, 5}),
Partitioner.Create(new int[] { 0 , 1, 2, 3, 4, 5}, false),
Partitioner.Create(new int[] { 0 , 1, 2, 3, 4, 5}, true),
Partitioner.Create(new int[] { 0 }),
Partitioner.Create(new int[] { 0 }, false),
Partitioner.Create(new int[] { 0 }, true),
};
for (int i = 0; i < partitioners.Length; i++)
{
using (var ee = partitioners[i].GetPartitions(1)[0])
{
while (ee.MoveNext()) { }
Assert.False(ee.MoveNext(), "TestExtraMoveNext: FAILED. Partitioner " + i + ": First extra MoveNext expected to return false.");
Assert.False(ee.MoveNext(), "TestExtraMoveNext: FAILED. Partitioner " + i + ": Second extra MoveNext expected to return false.");
Assert.False(ee.MoveNext(), "TestExtraMoveNext: FAILED. Partitioner " + i + ": Third extra MoveNext expected to return false.");
}
}
}
#region Helper Methods / Classes
private class DisposeTrackingEnumerable<T> : IEnumerable<T>
{
protected IEnumerable<T> m_data;
List<DisposeTrackingEnumerator<T>> s_enumerators = new List<DisposeTrackingEnumerator<T>>();
public DisposeTrackingEnumerable(IEnumerable<T> enumerable)
{
m_data = enumerable;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
DisposeTrackingEnumerator<T> walker = new DisposeTrackingEnumerator<T>(m_data.GetEnumerator());
lock (s_enumerators)
{
s_enumerators.Add(walker);
}
return walker;
}
public IEnumerator<T> GetEnumerator()
{
DisposeTrackingEnumerator<T> walker = new DisposeTrackingEnumerator<T>(m_data.GetEnumerator());
lock (s_enumerators)
{
s_enumerators.Add(walker);
}
return walker;
}
public void AreEnumeratorsDisposed(string scenario)
{
for (int i = 0; i < s_enumerators.Count; i++)
{
Assert.True(s_enumerators[i].IsDisposed(),
String.Format("AreEnumeratorsDisposed: FAILED. enumerator {0} was not disposed for SCENARIO: {1}.", i, scenario));
}
}
}
/// <summary>
/// This is the Enumerator that DisposeTrackingEnumerable generates when GetEnumerator is called.
/// We are simply wrapping an Enumerator and tracking whether Dispose had been called or not.
/// </summary>
/// <typeparam name="T">The type of the element</typeparam>
private class DisposeTrackingEnumerator<T> : IEnumerator<T>
{
IEnumerator<T> m_elements;
bool disposed;
public DisposeTrackingEnumerator(IEnumerator<T> enumerator)
{
m_elements = enumerator;
disposed = false;
}
public Boolean MoveNext()
{
return m_elements.MoveNext();
}
public T Current
{
get { return m_elements.Current; }
}
Object System.Collections.IEnumerator.Current
{
get { return m_elements.Current; }
}
/// <summary>
/// Dispose the underlying Enumerator, and suppresses finalization
/// so that we will not throw.
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
m_elements.Dispose();
disposed = true;
}
public void Reset()
{
m_elements.Reset();
}
public bool IsDisposed()
{
return disposed;
}
}
private static bool IsStaticPartition(int algorithm)
{
return algorithm < 2;
}
#endregion
}
}
| |
namespace OpenTemplate_Runner
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.assemblyPathText = new System.Windows.Forms.TextBox();
this.assemblyBrowseButton = new System.Windows.Forms.Button();
this.assemblyOpenDialog = new System.Windows.Forms.OpenFileDialog();
this.label2 = new System.Windows.Forms.Label();
this.templateTypeCombo = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.templatePropertyGrid = new System.Windows.Forms.PropertyGrid();
this.runButton = new System.Windows.Forms.Button();
this.closeButton = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.outputFileText = new System.Windows.Forms.TextBox();
this.outputBrowseButton = new System.Windows.Forms.Button();
this.outputSaveDialog = new System.Windows.Forms.SaveFileDialog();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(294, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Enter the path to Assembly containing the compiled template:";
//
// assemblyPathText
//
this.assemblyPathText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.assemblyPathText.Location = new System.Drawing.Point(12, 26);
this.assemblyPathText.Name = "assemblyPathText";
this.assemblyPathText.Size = new System.Drawing.Size(398, 20);
this.assemblyPathText.TabIndex = 1;
//
// assemblyBrowseButton
//
this.assemblyBrowseButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.assemblyBrowseButton.Location = new System.Drawing.Point(419, 23);
this.assemblyBrowseButton.Name = "assemblyBrowseButton";
this.assemblyBrowseButton.Size = new System.Drawing.Size(75, 23);
this.assemblyBrowseButton.TabIndex = 2;
this.assemblyBrowseButton.Text = "Browse...";
this.assemblyBrowseButton.UseVisualStyleBackColor = true;
this.assemblyBrowseButton.Click += new System.EventHandler(this.assemblyBrowseButton_Click);
//
// assemblyOpenDialog
//
this.assemblyOpenDialog.Filter = "Assemblies|*.dll;*.exe";
this.assemblyOpenDialog.Title = "Template Assembly";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(9, 49);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(135, 13);
this.label2.TabIndex = 3;
this.label2.Text = "Select the Template to run:";
//
// templateTypeCombo
//
this.templateTypeCombo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.templateTypeCombo.FormattingEnabled = true;
this.templateTypeCombo.Location = new System.Drawing.Point(12, 65);
this.templateTypeCombo.Name = "templateTypeCombo";
this.templateTypeCombo.Size = new System.Drawing.Size(482, 21);
this.templateTypeCombo.TabIndex = 4;
this.templateTypeCombo.SelectedIndexChanged += new System.EventHandler(this.templateTypeCombo_SelectedIndexChanged);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(9, 89);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(201, 13);
this.label3.TabIndex = 5;
this.label3.Text = "Enter values for the template Parameters:";
//
// templatePropertyGrid
//
this.templatePropertyGrid.Location = new System.Drawing.Point(12, 105);
this.templatePropertyGrid.Name = "templatePropertyGrid";
this.templatePropertyGrid.Size = new System.Drawing.Size(482, 339);
this.templatePropertyGrid.TabIndex = 6;
//
// runButton
//
this.runButton.Location = new System.Drawing.Point(419, 490);
this.runButton.Name = "runButton";
this.runButton.Size = new System.Drawing.Size(75, 23);
this.runButton.TabIndex = 8;
this.runButton.Text = "Run!";
this.runButton.UseVisualStyleBackColor = true;
this.runButton.Click += new System.EventHandler(this.runButton_Click);
//
// closeButton
//
this.closeButton.Location = new System.Drawing.Point(338, 490);
this.closeButton.Name = "closeButton";
this.closeButton.Size = new System.Drawing.Size(75, 23);
this.closeButton.TabIndex = 9;
this.closeButton.Text = "Close";
this.closeButton.UseVisualStyleBackColor = true;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(9, 447);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(187, 13);
this.label4.TabIndex = 0;
this.label4.Text = "Enter the file to output the template to:";
//
// outputFileText
//
this.outputFileText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.outputFileText.Location = new System.Drawing.Point(12, 464);
this.outputFileText.Name = "outputFileText";
this.outputFileText.Size = new System.Drawing.Size(398, 20);
this.outputFileText.TabIndex = 1;
//
// outputBrowseButton
//
this.outputBrowseButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.outputBrowseButton.Location = new System.Drawing.Point(419, 461);
this.outputBrowseButton.Name = "outputBrowseButton";
this.outputBrowseButton.Size = new System.Drawing.Size(75, 23);
this.outputBrowseButton.TabIndex = 2;
this.outputBrowseButton.Text = "Browse...";
this.outputBrowseButton.UseVisualStyleBackColor = true;
this.outputBrowseButton.Click += new System.EventHandler(this.outputBrowseButton_Click);
//
// outputSaveDialog
//
this.outputSaveDialog.Filter = "All Files|*.*";
this.outputSaveDialog.Title = "Template Output";
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(506, 525);
this.Controls.Add(this.closeButton);
this.Controls.Add(this.runButton);
this.Controls.Add(this.templatePropertyGrid);
this.Controls.Add(this.label3);
this.Controls.Add(this.templateTypeCombo);
this.Controls.Add(this.label2);
this.Controls.Add(this.outputBrowseButton);
this.Controls.Add(this.assemblyBrowseButton);
this.Controls.Add(this.outputFileText);
this.Controls.Add(this.label4);
this.Controls.Add(this.assemblyPathText);
this.Controls.Add(this.label1);
this.Name = "MainForm";
this.Text = "OpenTemplate Runner v0.1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox assemblyPathText;
private System.Windows.Forms.Button assemblyBrowseButton;
private System.Windows.Forms.OpenFileDialog assemblyOpenDialog;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox templateTypeCombo;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.PropertyGrid templatePropertyGrid;
private System.Windows.Forms.Button runButton;
private System.Windows.Forms.Button closeButton;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox outputFileText;
private System.Windows.Forms.Button outputBrowseButton;
private System.Windows.Forms.SaveFileDialog outputSaveDialog;
}
}
| |
/* 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.Collections;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Principal;
using System.Threading;
using Belikov.GenuineChannels.BroadcastEngine;
using Belikov.GenuineChannels.Connection;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.GenuineHttp;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Messaging;
using Belikov.GenuineChannels.Parameters;
using Belikov.GenuineChannels.Security;
using Belikov.GenuineChannels.TransportContext;
using Belikov.GenuineChannels.Utilities;
using Zyan.SafeDeserializationHelpers;
namespace Belikov.GenuineChannels.Receiving
{
/// <summary>
/// Manages a number of message handlers processing incoming messages:
/// wait cells, multiple response catchers, custom stream handlers,
/// broadcast court interceptors, IClientChannelSinks and
/// sync response catchers.
/// </summary>
public class GenuineReceivingHandler : MarshalByRefObject, IIncomingStreamHandler, ITimerConsumer
{
/// <summary>
/// Constructs an instance of the GenuineReceivingHandler class.
/// </summary>
/// <param name="iTransportContext">Transport context.</param>
/// <param name="defaultTransportUser">Default transport user.</param>
public GenuineReceivingHandler(ITransportContext iTransportContext, ITransportUser defaultTransportUser)
{
this.ITransportContext = iTransportContext;
this.DefaultTransportUser = defaultTransportUser;
this._waitCallback_InternalExecuteMessagewaitCallback = new WaitCallback(this.InternalExecuteMessage);
TimerProvider.Attach(this);
}
/// <summary>
/// Callback invoking InternalExecuteMessage method.
/// </summary>
private WaitCallback _waitCallback_InternalExecuteMessagewaitCallback;
/// <summary>
/// Transport Context.
/// </summary>
public readonly ITransportContext ITransportContext;
/// <summary>
/// The default transport user.
/// </summary>
public readonly ITransportUser DefaultTransportUser;
/// <summary>
/// All messages with such reply id will be ignored.
/// </summary>
public const int PING_MESSAGE_REPLYID = -3;
/// <summary>
/// Processes incoming requests and responses.
/// </summary>
/// <param name="stream">The stream containing a request or a response.</param>
/// <param name="remote">The remote host.</param>
/// <param name="genuineConnectionType">The type of the connection.</param>
/// <param name="connectionName">Connection id to send a response through.</param>
/// <param name="dbgConnectionId">The identifier of the connection, which is used for debugging purposes only.</param>
/// <param name="useThisThread">True to invoke the target in the current thread.</param>
/// <param name="iMessageRegistrator">The message registrator.</param>
/// <param name="connectionLevelSecuritySession">Connection Level Security Session.</param>
/// <param name="httpServerRequestResult">The HTTP request through which the message was received.</param>
/// <returns>True if it's a one-way message.</returns>
public bool HandleMessage(Stream stream, HostInformation remote, GenuineConnectionType genuineConnectionType, string connectionName, int dbgConnectionId, bool useThisThread, IMessageRegistrator iMessageRegistrator, SecuritySession connectionLevelSecuritySession, HttpServerRequestResult httpServerRequestResult)
{
// read the Security Session name
BinaryReader binaryReader = new BinaryReader(stream);
string sessionName = binaryReader.ReadString();
Message message = null;
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
// and decode the packet
SecuritySession securitySession = remote.GetSecuritySession(sessionName, this.ITransportContext.IKeyStore);
if (securitySession == null)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Security] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Security, "GenuineReceivingHandler.HandleMessage",
LogMessageType.SecuritySessionApplied, GenuineExceptions.Get_Security_ContextNotFound(sessionName),
message, remote,
null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
securitySession, sessionName, dbgConnectionId,
0, 0, 0, null, null, null, null,
"The requested Security Session can not be constructed or established. The name of Security Session: {0}.",
sessionName);
}
this.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.SecuritySessionWasNotFound, GenuineExceptions.Get_Security_ContextNotFound(sessionName),
remote, null));
return true;
}
// decode the stream and roll back if it was a Security Session's message
stream = securitySession.Decrypt(stream);
if (stream == null)
return true;
// read the message
message = MessageCoder.Deserialize(stream, sessionName);
message.ConnectionName = connectionName;
message.SecuritySessionParameters._connectionName = connectionName;
message.SecuritySessionParameters._genuineConnectionType = genuineConnectionType;
message.Sender = remote;
message.ITransportContext = this.ITransportContext;
message.ConnectionLevelSecuritySession = connectionLevelSecuritySession;
message.HttpServerRequestResult = httpServerRequestResult;
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Security] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Security, "GenuineReceivingHandler.HandleMessage",
LogMessageType.SecuritySessionApplied, null, message, remote,
null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
securitySession, sessionName, dbgConnectionId,
0, 0, 0, null, null, null, null,
"The Security Session has been used for decrypting the message.");
}
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
{
bool readContent = this.ITransportContext.BinaryLogWriter[LogCategory.MessageProcessing] > 1;
if (readContent)
{
GenuineChunkedStream streamClone = new GenuineChunkedStream();
GenuineUtility.CopyStreamToStream(message.Stream, streamClone);
message.Stream = streamClone;
}
binaryLogWriter.WriteMessageCreatedEvent("GenuineReceivingHandler.HandleMessage",
LogMessageType.MessageReceived, null, message, message.ReplyToId > 0, remote,
readContent ? message.Stream : null,
message.ITransportHeaders[Message.TransportHeadersInvocationTarget] as string, message.ITransportHeaders[Message.TransportHeadersMethodName] as string,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, connectionName, dbgConnectionId,
connectionLevelSecuritySession == null ? -1 : connectionLevelSecuritySession.SecuritySessionId,
connectionLevelSecuritySession == null ? null : connectionLevelSecuritySession.Name,
securitySession == null ? -1 : securitySession.SecuritySessionId,
securitySession.Name,
"The message has been received.");
}
if (message.ReplyToId == PING_MESSAGE_REPLYID)
return true;
if (iMessageRegistrator != null && iMessageRegistrator.WasRegistered(remote.Uri, message.MessageId, message.ReplyToId))
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineReceivingHandler.HandleMessage",
LogMessageType.MessageDispatched, GenuineExceptions.Get_Debugging_GeneralWarning("The message has been already processed."), message, remote,
null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, securitySession, securitySession.Name,
dbgConnectionId,
GenuineUtility.TickCount, 0, message.SeqNo, null, null, null, null,
"The message has been already processed. Therefore, this message is ignored.");
return true;
}
// if it's a response, then direct the message to the response handler
if (message.ReplyToId > 0)
{
message.IsOneWay = true;
IResponseProcessor iResponseProcessor = GenuineReceivingHandler._responseHandlers[message.ReplyToId] as IResponseProcessor;
// nothing waits for this request
if (iResponseProcessor == null)
return true;
// 2.5.1: set the answer flag
if (iResponseProcessor.Message != null)
iResponseProcessor.Message.HasBeenAsnwered = true;
if (iResponseProcessor.IsShortInProcessing)
{
iResponseProcessor.ProcessRespose(message);
#if TRIAL
#else
if (iResponseProcessor.IsExpired(GenuineUtility.TickCount))
GenuineReceivingHandler._responseHandlers.Remove(message.ReplyToId);
#endif
return true;
}
}
// take care about the thread and call context
if (useThisThread)
InternalExecuteMessage(message);
else
GenuineThreadPool.QueueUserWorkItem(this._waitCallback_InternalExecuteMessagewaitCallback, message, false);
return message.IsOneWay;
}
/// <summary>
/// Processes the message.
/// </summary>
/// <param name="messageAsObject">An instance of the Message class.</param>
private void InternalExecuteMessage(object messageAsObject)
{
Message message = null;
try
{
message = (Message) messageAsObject;
if (message.ConnectionLevelSecuritySession == null)
HandleMessage_AfterCLSS(message);
else
message.ConnectionLevelSecuritySession.Invoke(message, true);
}
catch(Exception ex)
{
// LOG:
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineReceivingHandler.InternalExecuteMessage",
LogMessageType.SecuritySessionApplied, ex, message, message.Sender,
null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, message.ConnectionLevelSecuritySession, null,
-1, 0, 0, 0, null, null, null, null,
"An exception occurred while executing the request.");
}
}
/// <summary>
/// Processes the message.
/// </summary>
/// <param name="message">The message.</param>
public void HandleMessage_AfterCLSS(Message message)
{
SecuritySession securitySession = message.Sender.GetSecuritySession(message.SecuritySessionParameters.Name, this.ITransportContext.IKeyStore);
if (securitySession == null)
{
// LOG:
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineReceivingHandler.HandleMessage_AfterCLSS",
LogMessageType.SecuritySessionApplied, GenuineExceptions.Get_Security_ContextNotFound(message.SecuritySessionParameters.Name),
message, message.Sender,
null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, message.SecuritySessionParameters.Name,
-1, 0, 0, 0, null, null, null, null,
"The message can not be processed due to the raised exception.");
return ;
}
// initialize all the necessary info
using(new ThreadDataSlotKeeper(OccupiedThreadSlots.CurrentMessage, message))
{
if (message.HttpServerRequestResult != null &&
(bool) message.ITransportContext.IParameterProvider[GenuineParameter.HttpAuthentication] &&
message.HttpServerRequestResult.IPrincipal != null &&
message.HttpServerRequestResult.IPrincipal.Identity is WindowsIdentity &&
((WindowsIdentity) message.HttpServerRequestResult.IPrincipal.Identity).Token != IntPtr.Zero )
{
// impersonate authenticated security context
WindowsImpersonationContext windowsImpersonationContext = null;
IPrincipal previousPrincipal = null;
previousPrincipal = Thread.CurrentPrincipal;
try
{
windowsImpersonationContext = ((WindowsIdentity) message.HttpServerRequestResult.IPrincipal.Identity).Impersonate();
Thread.CurrentPrincipal = message.HttpServerRequestResult.IPrincipal;
securitySession.Invoke(message, false);
}
finally
{
Thread.CurrentPrincipal = previousPrincipal;
windowsImpersonationContext.Undo();
}
}
else
{
securitySession.Invoke(message, false);
}
}
}
/// <summary>
/// Invokes the target or dispatches the response according to message content.
/// Throws the exception on any errors.
/// </summary>
/// <param name="message">The message being processed.</param>
public void HandleMessage_Final(Message message)
{
// get the specified transport user
ITransportUser iTransportUser = null;
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
if (message.SecuritySessionParameters.RemoteTransportUser.Length > 0)
iTransportUser = this._transportUsers[message.SecuritySessionParameters.RemoteTransportUser] as ITransportUser;
if (iTransportUser == null)
iTransportUser = this.DefaultTransportUser;
// direct the response to the response handler
if (message.ReplyToId > 0)
{
IResponseProcessor iResponseProcessor = GenuineReceivingHandler._responseHandlers[message.ReplyToId] as IResponseProcessor;
// check whether it's OK
if (iResponseProcessor == null)
{
#if TRIAL
#else
GenuineReceivingHandler._responseHandlers.Remove(message.ReplyToId);
#endif
return ;
}
if (! iResponseProcessor.IsExpired(GenuineUtility.TickCount))
iResponseProcessor.ProcessRespose(message);
#if TRIAL
#else
if (iResponseProcessor.IsExpired(GenuineUtility.TickCount))
GenuineReceivingHandler._responseHandlers.Remove(message.ReplyToId);
#endif
return ;
}
// if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Security] > 0 )
// binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineReceivingHandler.HandleMessage_Final",
// LogMessageType.MessageDispatched, null, message, message.Recipient, null,
// GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
// null, message.SecuritySessionParameters.Name, -1, 0, 0, 0, null, null, null, null,
// "The message is dispatched.");
// dispatch it
switch (message.GenuineMessageType)
{
case GenuineMessageType.Ordinary:
// dispatch the message to the sink
iTransportUser.HandleMessage(message);
break;
case GenuineMessageType.TrueBroadcast:
case GenuineMessageType.BroadcastEngine:
// get the string
var binaryFormatter = new BinaryFormatter().Safe();
IMessage iMessage = null;
try
{
iMessage = (IMessage) binaryFormatter.Deserialize(message.Stream);
IMethodReturnMessage ret = null;
if (message.DestinationMarshalByRef is string)
{
// message come via true multicast channel to the specific court
MarshalByRefObject receiver, sender;
// get the court info
CourtCollection.Find( (string) message.DestinationMarshalByRef,
out receiver, out sender);
if (receiver == null)
{
// message to the unregistered court has been received
this.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.BroadcastUnknownCourtReceived, null,
message.Sender, message.DestinationMarshalByRef));
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.BroadcastEngine, "GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageRequestInvoking, GenuineExceptions.Get_Debugging_GeneralWarning("No objects are associated with the \"{0}\" court.", (string) message.DestinationMarshalByRef),
message, message.Sender, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"The message is ignored because no objects are associated with the \"{0}\" court.", (string) message.DestinationMarshalByRef);
}
return ;
}
if (message.ITransportHeaders[Message.TransportHeadersBroadcastSendGuid] is string
&& UniqueCallTracer.Instance.WasGuidRegistered( RemotingServices.GetObjectUri(receiver) + (string) message.ITransportHeaders[Message.TransportHeadersBroadcastSendGuid]))
{
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.BroadcastEngine, "GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageRequestInvoking, GenuineExceptions.Get_Broadcast_CallHasAlreadyBeenMade(),
message, message.Sender, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"This message is ignored because this call has been already processed.");
}
// this call has been already processed
ret = new ReturnMessage(GenuineExceptions.Get_Broadcast_CallHasAlreadyBeenMade(), (IMethodCallMessage) iMessage);
}
else
{
// perform the call
try
{
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.BroadcastEngine, "GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageRequestInvoking, null,
message, message.Sender, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"The multicast message is being invoked on court \"{0}\".", (string) message.DestinationMarshalByRef);
}
ret = RemotingServices.ExecuteMessage(receiver, (IMethodCallMessage) iMessage);
}
catch(Exception ex)
{
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.BroadcastEngine, "GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageRequestInvoking, ex,
message, message.Sender, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"An exception occurred while the message was being processed. The exception is dispatched back.");
}
ret = new ReturnMessage(ex, (IMethodCallMessage) iMessage);
}
}
// if (sender != null)
// message.Sender = this.ITransportContext.KnownHosts[GenuineUtility.FetchChannelUriFromMbr(sender)];
// set correct remote guid
ITransportContext iTransportContext = this.ITransportContext;
if (sender != null)
{
string uri;
GenuineUtility.FetchChannelUriFromMbr(sender, out uri, out iTransportContext);
if (uri == null || iTransportContext == null)
iTransportContext = this.ITransportContext;
else
message.Sender = iTransportContext.KnownHosts[uri];
}
Message reply = CreateResponseToBroadcastMessage(message, ret, binaryFormatter);
reply.DestinationMarshalByRef = GenuineUtility.FetchDotNetUriFromMbr(receiver);
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
this.PutDownRecordAboutResponseCreation(binaryLogWriter, reply, ret, "The response to the \"true\" broadcast message has been created.");
iTransportContext.ConnectionManager.Send(reply);
}
else
{
MarshalByRefObject marshalByRefObject = null;
if ((message.DestinationMarshalByRef is MarshalByRefObject))
marshalByRefObject = (MarshalByRefObject) message.DestinationMarshalByRef;
else
{
Exception exception = GenuineExceptions.Get_Debugging_GeneralWarning("Can't process the object with type {0}", message.DestinationMarshalByRef == null ? "<null!>" : message.DestinationMarshalByRef.GetType().ToString());
if (binaryLogWriter != null)
{
binaryLogWriter.WriteImplementationWarningEvent("GenuineReceivingHandler.HandleMessage_Final",
LogMessageType.CriticalError, exception,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
"The response with the {0} type cannot be processed.", message.DestinationMarshalByRef.GetType());
}
throw exception;
}
if (message.ITransportHeaders[Message.TransportHeadersBroadcastSendGuid] is string
&& UniqueCallTracer.Instance.WasGuidRegistered( RemotingServices.GetObjectUri( marshalByRefObject ) + (string) message.ITransportHeaders[Message.TransportHeadersBroadcastSendGuid]))
{
Exception exception = GenuineExceptions.Get_Broadcast_CallHasAlreadyBeenMade();
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.BroadcastEngine, "GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageRequestInvoking, exception,
message, message.Sender, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"This message is ignored because this call has been already processed.");
}
ret = new ReturnMessage(exception, (IMethodCallMessage) iMessage);
}
else
{
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.BroadcastEngine, "GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageRequestInvoking, null,
message, message.Sender, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"The usual broadcast message is being invoked.");
}
ret = RemotingServices.ExecuteMessage(marshalByRefObject, (IMethodCallMessage) iMessage);
}
Message reply = CreateResponseToBroadcastMessage(message, ret, binaryFormatter);
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
this.PutDownRecordAboutResponseCreation(binaryLogWriter, reply, ret, "The response to the usual broadcast invocation has been created.");
reply.ITransportHeaders[Message.TransportHeadersMbrUriName] = message.ITransportHeaders[Message.TransportHeadersMbrUriName];
this.ITransportContext.ConnectionManager.Send(reply);
}
}
catch(Exception ex)
{
try
{
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.BroadcastEngine, "GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageRequestInvoking, ex,
message, message.Sender, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"An exception occurred while the usual broadcast message was being processed. The exception is dispatched back.");
}
ReturnMessage returnMessage = new ReturnMessage(ex, (IMethodCallMessage) iMessage);
Message reply = CreateResponseToBroadcastMessage(message, returnMessage, binaryFormatter);
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
this.PutDownRecordAboutResponseCreation(binaryLogWriter, reply, returnMessage, "The response to the usual broadcast invocation has been created.");
this.ITransportContext.ConnectionManager.Send(reply);
}
catch(Exception internalException)
{
// it's a destiny not to reply to this message
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.BroadcastEngine, "GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageRequestInvoking, internalException,
message, message.Sender, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"An exception occurred again while the previous exception was being serialized. This request is ignored.");
}
}
}
break;
case GenuineMessageType.ExternalStreamConsumer:
// direct the response to response handler
if (message.ReplyToId > 0)
{
IResponseProcessor iResponseProcessor = GenuineReceivingHandler._responseHandlers[message.ReplyToId] as IResponseProcessor;
if (! iResponseProcessor.IsExpired(GenuineUtility.TickCount))
iResponseProcessor.ProcessRespose(message);
#if TRIAL
#else
if (iResponseProcessor.IsExpired(GenuineUtility.TickCount))
GenuineReceivingHandler._responseHandlers.Remove(message.ReplyToId);
#endif
break;
}
string entryName = message.DestinationMarshalByRef as string;
if (entryName != null)
{
if (message.IsOneWay)
{
this.ITransportContext.DirectExchangeManager.HandleRequest(message);
return ;
}
Stream response = null;
Message reply;
try
{
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.DXM] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.BroadcastEngine, "GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageRequestInvoking, null,
message, message.Sender, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"The DXM message is being dispatched to the \"{0}\" entry.", entryName);
}
response = this.ITransportContext.DirectExchangeManager.HandleRequest(message);
if (response == null)
response = Stream.Null;
reply = new Message(message, new TransportHeaders(), response);
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
{
if (this.ITransportContext.BinaryLogWriter[LogCategory.MessageProcessing] > 1)
{
// make a copy of the source stream
GenuineChunkedStream copy = new GenuineChunkedStream(false);
GenuineUtility.CopyStreamToStream(reply.Stream, copy);
reply.Stream = copy;
}
binaryLogWriter.WriteMessageCreatedEvent("AsyncSinkStackResponseProcessor.ProcessRespose",
LogMessageType.MessageCreated, null, reply, false, reply.Recipient,
this.ITransportContext.BinaryLogWriter[LogCategory.MessageProcessing] > 1 ? reply.Stream : null,
entryName, entryName,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, -1, -1, null, -1, null,
"A response to DXM request has been created.");
message.ITransportHeaders[Message.TransportHeadersInvocationTarget] = entryName;
message.ITransportHeaders[Message.TransportHeadersMethodName] = entryName;
binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "AsyncSinkStackResponseProcessor.ProcessRespose",
LogMessageType.MessageRequestInvoked, null, reply, reply.Recipient, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1,
GenuineUtility.TickCount, 0, message.SeqNo, null, null, null, null,
"The DXM invocation has been completed.");
}
message.ITransportContext.ConnectionManager.Send(reply);
}
catch(Exception ex)
{
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.DXM] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.BroadcastEngine, "GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageRequestInvoking, ex,
message, message.Sender, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"The invocation of the DXM message directed to the \"{0}\" entry has resulted in exception.", entryName);
}
// return this exception as a result
var binaryFormatter2 = new BinaryFormatter().Safe();
GenuineChunkedStream serializedException = new GenuineChunkedStream(false);
binaryFormatter2.Serialize(serializedException, ex);
reply = new Message(message, new TransportHeaders(), serializedException);
reply.ContainsSerializedException = true;
// LOG: put down the log record
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
string invocationTarget = entryName;
string methodName = null;
object service = this.ITransportContext.DirectExchangeManager.GetServerService(entryName);
if (service != null)
methodName = service.GetType().FullName;
binaryLogWriter.WriteMessageCreatedEvent("GenuineReceivingHanlder.HandleMessage_Final",
LogMessageType.MessageCreated, null, reply, false, reply.Recipient,
this.ITransportContext.BinaryLogWriter[LogCategory.MessageProcessing] > 1 ? reply.Stream : null,
invocationTarget, methodName,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, -1, -1, null, -1, null,
"The response to DXM message directed to the \"{0}\" court has been created.", entryName);
reply.ITransportHeaders[Message.TransportHeadersInvocationTarget] = invocationTarget;
reply.ITransportHeaders[Message.TransportHeadersMethodName] = methodName;
}
this.ITransportContext.ConnectionManager.Send(reply);
}
}
break;
default:
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineReceivingHandler.HandleMessage_Final",
LogMessageType.MessageDispatched, GenuineExceptions.Get_Debugging_GeneralWarning("Unknown message type."),
message, message.Sender,
null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, message.SecuritySessionParameters.Name,
-1, 0, 0, 0, null, null, null, null,
"A message has an unknown type and can not be processed. Type: {0}", (int) message.GenuineMessageType);
break;
}
}
/// <summary>
/// Puts down a record describing the creation of the response message.
/// </summary>
/// <param name="binaryLogWriter">The binary log writer.</param>
/// <param name="reply">The response message.</param>
/// <param name="ret">The response.</param>
/// <param name="message">The text of the message.</param>
/// <param name="parameters">Parameters to the message text.</param>
internal void PutDownRecordAboutResponseCreation(BinaryLogWriter binaryLogWriter, Message reply, IMessage ret, string message, params object[] parameters)
{
string invocationTarget = ret.Properties["__Uri"] as string;
string methodName = BinaryLogWriter.ParseInvocationMethod(ret.Properties["__MethodName"] as string, ret.Properties["__TypeName"] as string);
binaryLogWriter.WriteMessageCreatedEvent("GenuineReceivingHanlder.PutDownRecordAboutResponseCreation",
LogMessageType.MessageCreated, null, reply, false, reply.Recipient,
this.ITransportContext.BinaryLogWriter[LogCategory.MessageProcessing] > 1 ? reply.Stream : null,
invocationTarget, methodName,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, -1, -1, null, -1, null,
message, parameters);
reply.ITransportHeaders[Message.TransportHeadersInvocationTarget] = invocationTarget;
reply.ITransportHeaders[Message.TransportHeadersMethodName] = methodName;
}
/// <summary>
/// Packs and returns a message that contains back response to the broadcast message.
/// </summary>
/// <param name="message">The source message.</param>
/// <param name="returnMessage">IMethodReturnMessage response.</param>
/// <param name="binaryFormatter">Just to prevent creating addition instance.</param>
/// <returns>The reply message.</returns>
private Message CreateResponseToBroadcastMessage(Message message, object returnMessage, BinaryFormatter binaryFormatter)
{
// serialize the reply
GenuineChunkedStream stream = new GenuineChunkedStream(false);
binaryFormatter.Serialize(stream, returnMessage);
// and wrap it into the message
return new Message(message, new TransportHeaders(), stream);
}
/// <summary>
/// Contains a set of response handlers awaiting for the messages with the specific
/// reply id.
/// </summary>
private static Hashtable _responseHandlers = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Registers a response processor that waits for messages containing a response to the
/// message with the specified identifier.
/// </summary>
/// <param name="replyId">ID of the source message.</param>
/// <param name="iResponseProcessor">A response processor instance.</param>
public void RegisterResponseProcessor(int replyId, IResponseProcessor iResponseProcessor)
{
GenuineReceivingHandler._responseHandlers[replyId] = iResponseProcessor;
}
/// <summary>
/// True if there is a handler awaiting for the response to the message with the specified id.
/// </summary>
/// <param name="replyId">The id of the source message.</param>
/// <returns>True if there is a handler awaiting for the response to the message with the specified id.</returns>
public bool IsHandlerAlive(int replyId)
{
IResponseProcessor iResponseProcessor = GenuineReceivingHandler._responseHandlers[replyId] as IResponseProcessor;
if (iResponseProcessor == null)
return false;
return ! iResponseProcessor.IsExpired(GenuineUtility.TickCount);
}
/// <summary>
/// Keeps a set of associative links between strings and transport users.
/// </summary>
private Hashtable _transportUsers = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Associates the specified transport user with the specified name.
/// </summary>
/// <param name="name">The name to associate the transport user with.</param>
/// <param name="transportUser">The transport user.</param>
public void RegisterTransportUser(string name, ITransportUser transportUser)
{
this._transportUsers[name] = transportUser;
}
/// <summary>
/// Dispatches the exception to all response processors awaiting something from the specific remote host.
/// </summary>
/// <param name="hostInformation">The remote host.</param>
/// <param name="exception">The exception.</param>
public void DispatchException(HostInformation hostInformation, Exception exception)
{
// LOG:
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineReceivingHandler.DispatchException",
LogMessageType.ExceptionDispatched, exception,
null, hostInformation,
null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
-1, 0, 0, 0, null, null, null, null,
"The exception is being dispatched back to the caller context.");
Hashtable expiredHandlers = new Hashtable();
lock (GenuineReceivingHandler._responseHandlers.SyncRoot)
{
foreach (DictionaryEntry entry in GenuineReceivingHandler._responseHandlers)
{
IResponseProcessor iResponseProcessor = entry.Value as IResponseProcessor;
// 2.5.2 fix; fixed in 2.5.6 again
bool hostsEqual = (iResponseProcessor.Remote == hostInformation);
if (! hostsEqual && iResponseProcessor.Remote != null && hostInformation != null)
hostsEqual = (iResponseProcessor.Remote.Url == hostInformation.Url && hostInformation.Url != null)
|| (iResponseProcessor.Remote.Uri == hostInformation.Uri && hostInformation.Uri != null);
if (hostsEqual)
expiredHandlers[entry.Key] = iResponseProcessor;
}
foreach (DictionaryEntry entry in expiredHandlers)
{
IResponseProcessor iResponseProcessor = entry.Value as IResponseProcessor;
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineReceivingHandler.DispatchException",
LogMessageType.ExceptionDispatched, exception,
iResponseProcessor.Message, hostInformation,
null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
-1, 0, 0, 0, null, null, null, null,
"The exception is being dispatched back to the caller context.");
iResponseProcessor.DispatchException(OperationException.WrapException(exception));
#if TRIAL
#else
GenuineReceivingHandler._responseHandlers.Remove(entry.Key);
#endif
}
}
}
/// <summary>
/// Dispatches the exception to the response processor specified by the replyId value.
/// </summary>
/// <param name="sourceMessage">The source message.</param>
/// <param name="exception">The exception</param>
public void DispatchException(Message sourceMessage, Exception exception)
{
// LOG:
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineReceivingHandler.DispatchException2",
LogMessageType.ExceptionDispatched, exception,
sourceMessage, sourceMessage.Recipient,
null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
-1, 0, 0, 0, null, null, null, null,
"The exception is being dispatched back to the caller context.");
IResponseProcessor iResponseProcessor = GenuineReceivingHandler._responseHandlers[sourceMessage.MessageId] as IResponseProcessor;
if (iResponseProcessor != null)
{
iResponseProcessor.DispatchException(OperationException.WrapException(exception));
#if TRIAL
#else
if (iResponseProcessor.IsExpired(GenuineUtility.TickCount))
GenuineReceivingHandler._responseHandlers.Remove(sourceMessage.ReplyToId);
#endif
}
}
/// <summary>
/// Invokes ScanForExpiredHandlers method in the separate thread.
/// </summary>
public void TimerCallback()
{
ArrayList expiredResponses = new ArrayList();
Exception exception = GenuineExceptions.Get_Send_ServerDidNotReply();
int now = GenuineUtility.TickCount;
// remove expired elements from the collection
lock (GenuineReceivingHandler._responseHandlers.SyncRoot)
{
foreach (DictionaryEntry entry in GenuineReceivingHandler._responseHandlers)
{
IResponseProcessor iResponseProcessor = (IResponseProcessor) entry.Value;
if (iResponseProcessor.IsExpired(now))
expiredResponses.Add(entry);
}
}
#if TRIAL
#else
// first, get rid of expired handlers
foreach (DictionaryEntry entry in expiredResponses)
GenuineReceivingHandler._responseHandlers.Remove(entry.Key);
#endif
// then dispatch exceptions
foreach (DictionaryEntry entry in expiredResponses)
{
IResponseProcessor iResponseProcessor = (IResponseProcessor) entry.Value;
GenuineThreadPool.QueueUserWorkItem(new WaitCallback(iResponseProcessor.DispatchException), exception, false);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace MGTK.Controls
{
public class TreeListBox : Control
{
private ListBox lstBox;
private List<TreeListBoxItem> items;
public List<TreeListBoxItem> Items
{
get
{
return items;
}
set
{
if (items != value)
{
items = value;
TranslateToLstBox();
}
}
}
public object SelectedValue
{
get
{
return lstBox.SelectedValue;
}
set
{
lstBox.SelectedValue = value;
}
}
public int SelectedIndex
{
get
{
if (Items != null && lstBox.Items != null && lstBox.Items.Count > 0 &&
lstBox.SelectedIndex >= 0 &&
lstBox.SelectedIndex < lstBox.Items.Count)
{
for (int i = 0; i < Items.Count; i++)
{
if (lstBox.Items[lstBox.SelectedIndex].tag is TreeListBoxItem &&
lstBox.Items[lstBox.SelectedIndex].tag == Items[i])
return i;
}
}
return -1;
}
}
public bool UseVerticalScrollBar
{
get
{
return lstBox.UseVerticalScrollBar;
}
set
{
lstBox.UseVerticalScrollBar = value;
lstBox.ConfigureCoordinatesAndSizes();
}
}
public bool UseHorizontalScrollBar
{
get
{
return lstBox.UseHorizontalScrollBar;
}
set
{
lstBox.UseHorizontalScrollBar = value;
lstBox.ConfigureCoordinatesAndSizes();
}
}
public event EventHandler SelectedIndexChanged;
public TreeListBox(Form formowner)
: base(formowner)
{
lstBox = new ListBox(formowner) { Parent = this, Width = Width, Height = Height };
lstBox.SelectedIndexChanged += new EventHandler(lstBox_SelectedIndexChanged);
Controls.Add(lstBox);
this.WidthChanged += new EventHandler(TreeListBox_SizeChanged);
this.HeightChanged += new EventHandler(TreeListBox_SizeChanged);
}
void lstBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (SelectedIndexChanged != null)
SelectedIndexChanged(this, new EventArgs());
}
void TreeListBox_SizeChanged(object sender, EventArgs e)
{
lstBox.Width = Width;
lstBox.Height = Height;
lstBox.ConfigureCoordinatesAndSizes();
}
private void TranslateToLstBox()
{
lstBox.Items = GetListBoxItems(Items, null, 4);
lstBox.ConfigureCoordinatesAndSizes();
}
private Control GetExpandCollapseButton(TreeListBoxItem tLBIOwner)
{
CheckBox chkExpCol = null;
if (Items.Exists(li => li.Parent == tLBIOwner))
{
chkExpCol = new CheckBox(Owner) { Width = 12, Height = 12, Tag = tLBIOwner, Parent = lstBox.innerListBox };
chkExpCol.CheckBoxUnchecked = Theme.TreeListBoxExpand;
chkExpCol.CheckBoxChecked = Theme.TreeListBoxCollapse;
chkExpCol.Checked = tLBIOwner.Expanded;
chkExpCol.CheckStateChanged += new EventHandler(chkExpCol_CheckStateChanged);
}
return chkExpCol;
}
void chkExpCol_CheckStateChanged(object sender, EventArgs e)
{
if ((sender as CheckBox).Tag != null && (sender as CheckBox).Tag is TreeListBoxItem)
{
TreeListBoxItem tLBI = ((sender as CheckBox).Tag as TreeListBoxItem);
tLBI.Expanded = !tLBI.Expanded;
TranslateToLstBox();
}
}
private List<ListBoxItem> GetListBoxItems(List<TreeListBoxItem> treeItems, TreeListBoxItem parent, int textXPadding)
{
List<ListBoxItem> lstItems = new List<ListBoxItem>();
foreach (TreeListBoxItem treeItem in treeItems)
{
if (treeItem.Parent == parent)
{
lstItems.Add(new ListBoxItem(treeItem.Value, treeItem.Text, textXPadding, GetExpandCollapseButton(treeItem)));
lstItems[lstItems.Count - 1].tag = treeItem;
if (treeItem.Expanded)
{
List<ListBoxItem> lstSub = GetListBoxItems(treeItems, treeItem, textXPadding + textXPadding +
lstItems[lstItems.Count - 1].Ctrl.Width);
lstItems.AddRange(lstSub);
}
}
}
return lstItems;
}
public void AddItem(TreeListBoxItem item)
{
Items.Add(item);
TranslateToLstBox();
lstBox.ConfigureCoordinatesAndSizes();
}
public void RemoveItem(TreeListBoxItem item)
{
Items.Remove(item);
lstBox.Items.Remove(lstBox.Items.Find(li => li.tag == item));
lstBox.ConfigureCoordinatesAndSizes();
}
}
public class TreeListBoxItem : ListBoxItem
{
private TreeListBoxItem _parent;
public bool Expanded = false;
public TreeListBoxItem Parent
{
get
{
return _parent;
}
set
{
if (_parent != value)
_parent = value;
}
}
public TreeListBoxItem(object value, string text, TreeListBoxItem parent, bool expanded)
{
Value = value;
Text = text;
Parent = parent;
Expanded = expanded;
}
}
}
| |
// Copyright 2014 Jacob Trimble
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using ModMaker.Lua.Compiler;
using ModMaker.Lua.Parser;
using ModMaker.Lua.Runtime.LuaValues;
namespace ModMaker.Lua.Runtime {
/// <summary>
/// A dynamic object that is used to convert implicitly to numeric types.
/// </summary>
sealed class NumberProxy : DynamicObject {
// TODO: Consider removing.
public double Value;
public NumberProxy(double value) {
Value = value;
}
public override bool TryConvert(ConvertBinder binder, out object result) {
Type t1 = binder.Type;
if (t1 == typeof(SByte) || t1 == typeof(Int16) || t1 == typeof(Int32) ||
t1 == typeof(Int64) || t1 == typeof(Single) || t1 == typeof(Double) ||
t1 == typeof(UInt16) || t1 == typeof(UInt32) || t1 == typeof(UInt64) ||
t1 == typeof(Byte) || t1 == typeof(Decimal)) {
result = Helpers.DynamicInvoke(
typeof(Convert).GetMethod("To" + t1.Name, new[] { typeof(double) }),
null, new object[] { Value });
return true;
}
return base.TryConvert(binder, out result);
}
public static object Create(object o) {
if (o is double d) {
o = new NumberProxy(d);
}
return o;
}
}
/// <summary>
/// Defines the environment that Lua operates in.
/// </summary>
[LuaIgnore]
public class LuaEnvironmentNet : DynamicObject, ILuaEnvironmentNet {
IModuleBinder _modules;
ILuaTable _globals;
ICodeCompiler _compiler;
IParser _parser;
ILuaRuntime _runtime;
/// <summary>
/// Creates a new LuaEnvironment without initializing the state, for use with a derived type.
/// </summary>
protected LuaEnvironmentNet() {
Settings = new LuaSettings().AsReadOnly();
_compiler = new CodeCompiler(Settings);
_parser = new PlainParser();
_runtime = new LuaRuntimeNet(this);
_globals = new LuaValues.LuaTable();
_modules = new ModuleBinder();
}
/// <summary>
/// Creates a new environment with the given settings.
/// </summary>
/// <param name="settings">The settings to give the Environment.</param>
/// <exception cref="System.ArgumentNullException">If settings is null.</exception>
public LuaEnvironmentNet(LuaSettings settings) {
if (settings == null) {
throw new ArgumentNullException(nameof(settings));
}
Settings = settings.AsReadOnly();
_globals = new LuaTable();
_runtime = new LuaRuntimeNet(this);
_compiler = new CodeCompiler(Settings);
_parser = new PlainParser();
_modules = new ModuleBinder();
// initialize the global variables.
LuaStaticLibraries.Initialize(this);
_initializeTypes();
}
/// <summary>
/// Registers all the primitive types to the globals table.
/// </summary>
protected void _initializeTypes() {
RegisterType(typeof(bool), "bool");
RegisterType(typeof(byte), "byte");
RegisterType(typeof(sbyte), "sbyte");
RegisterType(typeof(short), "short");
RegisterType(typeof(int), "int");
RegisterType(typeof(long), "long");
RegisterType(typeof(ushort), "ushort");
RegisterType(typeof(uint), "uint");
RegisterType(typeof(ulong), "ulong");
RegisterType(typeof(float), "float");
RegisterType(typeof(double), "double");
RegisterType(typeof(decimal), "decimal");
RegisterType(typeof(Int16), "Int16");
RegisterType(typeof(Int32), "Int32");
RegisterType(typeof(Int64), "Int64");
RegisterType(typeof(UInt16), "UInt16");
RegisterType(typeof(UInt32), "UInt32");
RegisterType(typeof(UInt64), "UInt64");
RegisterType(typeof(Single), "Single");
RegisterType(typeof(Double), "Double");
RegisterType(typeof(Decimal), "Decimal");
RegisterType(typeof(String), "String");
RegisterType(typeof(Byte), "Byte");
RegisterType(typeof(SByte), "SByte");
RegisterType(typeof(Boolean), "Boolean");
}
public virtual ILuaValue this[string name] {
get {
return _globals.GetIndex(new LuaString(name));
}
set {
_globals.SetIndex(new LuaString(name), value);
}
}
public LuaSettings Settings { get; protected set; }
public ILuaRuntime Runtime {
get { return _runtime; }
set {
if (value == null) {
throw new ArgumentNullException(nameof(value));
}
lock (this) {
_runtime = value;
}
}
}
public ILuaTable GlobalsTable {
get { return _globals; }
protected set {
if (value == null) {
throw new ArgumentNullException(nameof(value));
}
lock (this) {
_globals = value;
}
}
}
public ICodeCompiler CodeCompiler {
get { return _compiler; }
set {
if (value == null) {
throw new ArgumentNullException(nameof(value));
}
lock (this) {
_compiler = value;
}
}
}
public IParser Parser {
get { return _parser; }
set {
if (value == null) {
throw new ArgumentNullException(nameof(value));
}
lock (this) {
_parser = value;
}
}
}
public IModuleBinder ModuleBinder {
get { return _modules; }
set {
if (value == null) {
throw new ArgumentNullException(nameof(value));
}
_modules = value;
}
}
public virtual void RegisterDelegate(Delegate d, string name) {
if (d == null) {
throw new ArgumentNullException(nameof(d));
}
if (name == null) {
throw new ArgumentNullException(nameof(name));
}
lock (this) {
object o = GlobalsTable.GetItemRaw(new LuaString(name));
if (o != LuaNil.Nil) {
LuaOverloadFunction meth = o as LuaOverloadFunction;
if (meth == null) {
throw new ArgumentException(string.Format(Resources.AlreadyRegistered, name));
}
meth.AddOverload(d);
} else {
GlobalsTable.SetItemRaw(
new LuaString(name),
new LuaOverloadFunction(name, new[] { d.Method }, new[] { d.Target }));
}
}
}
public virtual void RegisterType(Type t, string name) {
if (t == null) {
throw new ArgumentNullException(nameof(t));
}
if (name == null) {
throw new ArgumentNullException(nameof(name));
}
lock (this) {
var n = new LuaString(name);
ILuaValue o = GlobalsTable.GetItemRaw(n);
if (o != LuaNil.Nil) {
throw new ArgumentException(string.Format(Resources.AlreadyRegistered, name));
} else {
GlobalsTable.SetItemRaw(n, new LuaType(t));
}
}
}
public override IEnumerable<string> GetDynamicMemberNames() {
foreach (var item in GlobalsTable) {
if (item.Key.ValueType == LuaValueType.String) {
yield return (string)item.Key.GetValue();
}
}
}
public override bool TryConvert(ConvertBinder binder, out object result) {
if (typeof(ILuaEnvironment) == binder.Type) {
result = this;
return true;
}
return base.TryConvert(binder, out result);
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) {
if (indexes != null && indexes.Length == 1) {
ILuaValue o;
lock (this) {
o = GlobalsTable.GetItemRaw(LuaValueBase.CreateValue(indexes[0]));
}
MethodInfo asMethod =
typeof(ILuaValue).GetMethod(nameof(ILuaValue.As)).MakeGenericMethod(binder.ReturnType);
result = Helpers.DynamicInvoke(asMethod, o, null);
if (result is double d) {
result = new NumberProxy(d);
}
return true;
} else {
return base.TryGetIndex(binder, indexes, out result);
}
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) {
if (indexes != null && indexes.Length == 1) {
lock (this) {
GlobalsTable.SetItemRaw(
LuaValueBase.CreateValue(indexes[0]), LuaValueBase.CreateValue(value));
}
return true;
} else {
return base.TrySetIndex(binder, indexes, value);
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
ILuaValue o;
lock (this) {
o = GlobalsTable.GetItemRaw(new LuaString(binder.Name));
}
MethodInfo asMethod =
typeof(ILuaValue).GetMethod(nameof(ILuaValue.As)).MakeGenericMethod(binder.ReturnType);
result = Helpers.DynamicInvoke(asMethod, o, null);
if (result is double d) {
result = new NumberProxy(d);
}
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value) {
lock (this) {
GlobalsTable.SetItemRaw(new LuaString(binder.Name), LuaValueBase.CreateValue(value));
}
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.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
// Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary
// to separately Dispose (or have a 'using' statement) for the handler.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "dotnet/corefx #20010")]
public class PostScenarioTest : HttpClientTestBase
{
private const string ExpectedContent = "Test contest";
private const string UserName = "user1";
private const string Password = "password1";
private static readonly Uri BasicAuthServerUri =
Configuration.Http.BasicAuthUriForCreds(false, UserName, Password);
private static readonly Uri SecureBasicAuthServerUri =
Configuration.Http.BasicAuthUriForCreds(true, UserName, Password);
private readonly ITestOutputHelper _output;
public static readonly object[][] EchoServers = Configuration.Http.EchoServers;
public static readonly object[][] BasicAuthEchoServers =
new object[][]
{
new object[] { BasicAuthServerUri },
new object[] { SecureBasicAuthServerUri }
};
public PostScenarioTest(ITestOutputHelper output)
{
_output = output;
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostNoContentUsingContentLengthSemantics_Success(Uri serverUri)
{
await PostHelper(serverUri, string.Empty, null,
useContentLengthUpload: true, useChunkedEncodingUpload: false);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostEmptyContentUsingContentLengthSemantics_Success(Uri serverUri)
{
await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
useContentLengthUpload: true, useChunkedEncodingUpload: false);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostEmptyContentUsingChunkedEncoding_Success(Uri serverUri)
{
await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
useContentLengthUpload: false, useChunkedEncodingUpload: true);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostEmptyContentUsingConflictingSemantics_Success(Uri serverUri)
{
await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
useContentLengthUpload: true, useChunkedEncodingUpload: true);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostUsingContentLengthSemantics_Success(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
useContentLengthUpload: true, useChunkedEncodingUpload: false);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostUsingChunkedEncoding_Success(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
useContentLengthUpload: false, useChunkedEncodingUpload: true);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostSyncBlockingContentUsingChunkedEncoding_Success(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new SyncBlockingContent(ExpectedContent),
useContentLengthUpload: false, useChunkedEncodingUpload: true);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostRepeatedFlushContentUsingChunkedEncoding_Success(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new RepeatedFlushContent(ExpectedContent),
useContentLengthUpload: false, useChunkedEncodingUpload: true);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostUsingUsingConflictingSemantics_UsesChunkedSemantics(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
useContentLengthUpload: true, useChunkedEncodingUpload: true);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx behaves differently and will buffer content and use 'Content-Length' semantics")]
public async Task PostUsingNoSpecifiedSemantics_UsesChunkedSemantics(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
useContentLengthUpload: false, useChunkedEncodingUpload: false);
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(5 * 1024)]
[InlineData(63 * 1024)]
public async Task PostLongerContentLengths_UsesChunkedSemantics(int contentLength)
{
var rand = new Random(42);
var sb = new StringBuilder(contentLength);
for (int i = 0; i < contentLength; i++)
{
sb.Append((char)(rand.Next(0, 26) + 'a'));
}
string content = sb.ToString();
await PostHelper(Configuration.Http.RemoteEchoServer, content, new StringContent(content),
useContentLengthUpload: true, useChunkedEncodingUpload: false);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(BasicAuthEchoServers))]
public async Task PostRewindableContentUsingAuth_NoPreAuthenticate_Success(Uri serverUri)
{
HttpContent content = CustomContent.Create(ExpectedContent, true);
var credential = new NetworkCredential(UserName, Password);
await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, false);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(BasicAuthEchoServers))]
public async Task PostNonRewindableContentUsingAuth_NoPreAuthenticate_ThrowsHttpRequestException(Uri serverUri)
{
HttpContent content = CustomContent.Create(ExpectedContent, false);
var credential = new NetworkCredential(UserName, Password);
await Assert.ThrowsAsync<HttpRequestException>(() =>
PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: false));
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(BasicAuthEchoServers))]
[ActiveIssue(9228, TestPlatforms.Windows)]
public async Task PostNonRewindableContentUsingAuth_PreAuthenticate_Success(Uri serverUri)
{
HttpContent content = CustomContent.Create(ExpectedContent, false);
var credential = new NetworkCredential(UserName, Password);
await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: true);
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_EmptyContent_ContentTypeHeaderNotSent(Uri serverUri)
{
using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.PostAsync(serverUri, null))
{
string responseContent = await response.Content.ReadAsStringAsync();
bool sentContentType = TestHelper.JsonMessageContainsKey(responseContent, "Content-Type");
Assert.False(sentContentType);
}
}
private async Task PostHelper(
Uri serverUri,
string requestBody,
HttpContent requestContent,
bool useContentLengthUpload,
bool useChunkedEncodingUpload)
{
using (HttpClient client = CreateHttpClient())
{
if (requestContent != null)
{
if (useContentLengthUpload)
{
// Ensure that Content-Length is populated (see issue #27245)
requestContent.Headers.ContentLength = requestContent.Headers.ContentLength;
}
else
{
requestContent.Headers.ContentLength = null;
}
}
if (useChunkedEncodingUpload)
{
client.DefaultRequestHeaders.TransferEncodingChunked = true;
}
using (HttpResponseMessage response = await client.PostAsync(serverUri, requestContent))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
if (!useContentLengthUpload && !useChunkedEncodingUpload)
{
useChunkedEncodingUpload = true;
}
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
useChunkedEncodingUpload,
requestBody);
}
}
}
private async Task PostUsingAuthHelper(
Uri serverUri,
string requestBody,
HttpContent requestContent,
NetworkCredential credential,
bool preAuthenticate)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.PreAuthenticate = preAuthenticate;
handler.Credentials = credential;
using (var client = new HttpClient(handler))
{
// Send HEAD request to help bypass the 401 auth challenge for the latter POST assuming
// that the authentication will be cached and re-used later when PreAuthenticate is true.
var request = new HttpRequestMessage(HttpMethod.Head, serverUri);
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
// Now send POST request.
request = new HttpRequestMessage(HttpMethod.Post, serverUri);
request.Content = requestContent;
requestContent.Headers.ContentLength = null;
request.Headers.TransferEncodingChunked = true;
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
true,
requestBody);
}
}
}
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_142 : MapLoop
{
public M_142() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_N1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 4 },
new L_LX(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new L_TDS(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
//1000
public class L_N1 : MapLoop
{
public L_N1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
});
}
}
//2000
public class L_LX : MapLoop
{
public L_LX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_N9(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new L_LIN(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_PRR(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new L_REP(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new L_AMT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2100
public class L_N9 : MapLoop
{
public L_N9(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2200
public class L_LIN : MapLoop
{
public L_LIN(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LIN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new LOC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PSC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new SSS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2300
public class L_LM : MapLoop
{
public L_LM(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2400
public class L_N1_1 : MapLoop
{
public L_N1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
});
}
}
//2500
public class L_PRR : MapLoop
{
public L_PRR(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new PRR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LOC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new RC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PSC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new SSS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_CID(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2510
public class L_CID : MapLoop
{
public L_CID(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new CID() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new TMD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_MEA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2511
public class L_MEA : MapLoop
{
public L_MEA(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new MEA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2600
public class L_REP : MapLoop
{
public L_REP(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new REP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new RC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new ITA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PRT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LM_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_MEA_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_IT1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2610
public class L_LM_1 : MapLoop
{
public L_LM_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2620
public class L_MEA_1 : MapLoop
{
public L_MEA_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new MEA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2630
public class L_IT1 : MapLoop
{
public L_IT1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new IT1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PRT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new ITA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2700
public class L_AMT : MapLoop
{
public L_AMT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//3000
public class L_TDS : MapLoop
{
public L_TDS(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new TDS() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
}
}
| |
// Copyright 2008-2009 Louis DeJardin - http://whereslou.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Spark.Parser.Markup;
namespace Spark.Parser.Code
{
public class CodeGrammar : CharGrammar
{
public CodeGrammar()
{
Func<IList<char>, string> bs = hit => new string(hit.ToArray());
Func<IList<string>, string> js = hit => string.Concat(hit.ToArray());
var escapeSequence = Ch('\\').And(Ch(c => true)).Build(hit => "\\" + hit.Down);
var quotHunks =
Rep1(ChNot('\"', '\\')).Build(bs)
.Or(escapeSequence);
var quotStringLiteral = Snip(Ch('\"').And(Rep(quotHunks)).And(Ch('\"')), hit => "\"" + js(hit.Left.Down) + "\"");
var quotVerbatimPiece =
Ch("\"\"").Or(ChNot('\"').Build(ch => new string(ch, 1)));
var quotVerbatimLiteral = Snip(Ch("@\"").And(Rep(quotVerbatimPiece)).And(Ch('"')), hit => "@\"" + js(hit.Left.Down) + "\"");
var aposHunks =
Snip(Rep1(ChNot('\'', '\\', '\"')))
.Or(Snip(escapeSequence))
.Or(Swap(Ch('\"'), "\\\""));
var aposStringLiteral = Snip(Swap(Ch('\''), "\"").And(Snip(Rep(aposHunks))).And(Swap(Ch('\''), "\"")));
// @' " '' ' becomes @" "" ' "
var aposVerbatimPiece =
Swap(Ch("''"), "'")
.Or(Swap(Ch('\"'), "\"\""))
.Or(Snip(ChNot('\'')));
var aposVerbatimLiteral = Snip(Swap(Ch("@'"), "@\"").And(Snip(Rep(aposVerbatimPiece))).And(Swap(Ch('\''), "\"")));
var stringLiteral = TkStr(quotStringLiteral.Or(quotVerbatimLiteral).Or(aposStringLiteral).Or(aposVerbatimLiteral));
_stringLiteral = stringLiteral;
var SpecialCharCast = Snip(Ch("(char)'").And(ChNot('\'', '\\').Build(ch => ch.ToString()).Or(escapeSequence)).And(Ch('\'')),
hit => "(char)'" + hit.Left.Down + "'");
var oneLineComment = Snip(Ch("//").And(Rep(ChNot('\r', '\n'))), hit => "//" + bs(hit.Down));
var multiLineComment = Snip(Ch("/*").And(Rep(Ch(c => true).Unless(Ch("*/")))).And(Ch("*/")),
hit => "/*" + bs(hit.Left.Down) + "*/");
// A Unicode character of the class Pc
var connectingCharacter = Ch(c => char.GetUnicodeCategory(c) == UnicodeCategory.ConnectorPunctuation);
// A Unicode character of classes Mn or Mc
var combiningCharacter = Ch(c => char.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark || char.GetUnicodeCategory(c) == UnicodeCategory.SpacingCombiningMark);
// A Unicode character of the class Cf
var formattingCharacter = Ch(c => char.GetUnicodeCategory(c) == UnicodeCategory.Format);
var identifierStartCharacter = Ch(char.IsLetter).Or(Ch('_'));
var identifierPartCharacter = Ch(char.IsLetterOrDigit).Or(connectingCharacter).Or(combiningCharacter).Or(formattingCharacter);
var identifierOrKeyword = identifierStartCharacter.And(Rep(identifierPartCharacter))
.Build(hit => hit.Left + new string(hit.Down.ToArray()));
var keyword = Snip(Ch("abstract").Or(Ch("as")).Or(Ch("base")).Or(Ch("bool")).Or(Ch("break"))
.Or(Ch("byte")).Or(Ch("case")).Or(Ch("catch")).Or(Ch("char")).Or(Ch("checked"))
.Or(Ch("class")).Or(Ch("const")).Or(Ch("continue")).Or(Ch("decimal")).Or(Ch("default"))
.Or(Ch("delegate")).Or(Ch("double")).Or(Ch("do")).Or(Ch("else")).Or(Ch("enum"))
.Or(Ch("event")).Or(Ch("explicit")).Or(Ch("extern")).Or(Ch("false")).Or(Ch("finally"))
.Or(Ch("fixed")).Or(Ch("float")).Or(Ch("foreach")).Or(Ch("for")).Or(Ch("goto"))
.Or(Ch("if")).Or(Ch("implicit")).Or(Ch("int")).Or(Ch("in")).Or(Ch("interface"))
.Or(Ch("internal")).Or(Ch("is")).Or(Ch("lock")).Or(Ch("long")).Or(Ch("namespace"))
.Or(Ch("new")).Or(Ch("null")).Or(Ch("object")).Or(Ch("operator")).Or(Ch("out"))
.Or(Ch("override")).Or(Ch("params")).Or(Ch("private")).Or(Ch("protected")).Or(Ch("public"))
.Or(Ch("readonly")).Or(Ch("ref")).Or(Ch("return")).Or(Ch("sbyte")).Or(Ch("sealed"))
.Or(Ch("short")).Or(Ch("sizeof")).Or(Ch("stackalloc")).Or(Ch("static")).Or(Ch("string"))
.Or(Ch("struct")).Or(Ch("switch")).Or(Ch("this")).Or(Ch("throw")).Or(Ch("true"))
.Or(Ch("try")).Or(Ch("typeof")).Or(Ch("uint")).Or(Ch("ulong")).Or(Ch("unchecked"))
.Or(Ch("unsafe")).Or(Ch("ushort")).Or(Ch("using")).Or(Ch("virtual")).Or(Ch("void"))
.Or(Ch("volatile")).Or(Ch("while"))).NotNext(identifierPartCharacter);
var availableIdentifier = Snip(identifierOrKeyword.Unless(keyword))
.Or(Swap(Ch("class"), "@class"));
var identifier = availableIdentifier
.Or(Snip(Ch('@').And(identifierOrKeyword), hit => "@" + hit.Down));
// parsing late bound properties #a.b.c into Eval("a.b.c")
var dotProperty = Snip(Ch('.').And(identifierOrKeyword),
hit => hit.Left + hit.Down);
var formatAppendage = Swap(Opt(Rep(Ch(' ', '\t')))
.And(Ch('\"').And(Rep1(ChNot('\"'))).And(Ch('\"'))
.Or(Ch('\'').And(Rep1(ChNot('\''))).And(Ch('\'')))),
hit => ", \"{0:" + new string(hit.Down.Left.Down.ToArray()) + "}\"");
var lateBound = Ch('#')
.And(Snip(identifierOrKeyword))
.And(Snip(Rep(dotProperty)))
.And(Opt(formatAppendage))
.Build(hit => (IList<Snippet>) new Snippets("Eval(\"")
.Concat(hit.Left.Left.Down)
.Concat(hit.Left.Down)
.Concat(new Snippets("\""))
.Concat(hit.Down ?? new Snippet[0])
.Concat(new Snippets(")"))
.ToList());
var codeStretch = Snip(Rep1(
Swap(Ch("[["), "<")
.Or(Swap(Ch("]]"), ">"))
.Or(lateBound)
.Or(Snip(ChNot('\"', '\'', '{', '}', '(', ')')))
.Unless(identifier.Or(keyword).Or(SpecialCharCast))
.Unless(Ch("%>").Or(Ch("@\"")).Or(Ch("@'")).Or(Ch("//")).Or(Ch("/*")))));
Func<ParseAction<string>, ParseAction<IList<Snippet>>> limitedCodeStretch = limit => Snip(Rep1(
Swap(Ch("[["), "<")
.Or(Swap(Ch("]]"), ">"))
.Or(lateBound)
.Or(Snip(ChNot('\"', '\'', '{', '}', '(', ')')))
.Unless(identifier.Or(keyword).Or(SpecialCharCast))
.Unless(limit.Or(Ch("@\"")).Or(Ch("@'")).Or(Ch("//")).Or(Ch("/*")))));
// braced ::= '{' + terms + '}'
var braced = Snip(Snip(Ch('{')).And((ParseAction<IList<Snippet>>)FnTerms).And(Snip(Ch('}'))));
// parens ::= '(' + terms + ')'
var parens = Snip(Snip(Ch('(')).And((ParseAction<IList<Snippet>>)FnTerms).And(Snip(Ch(')')))).Unless(SpecialCharCast);
// ExpressionTerms ::= (dquot | aquot | braced | codeStretch | specialCharCast)*
ExpressionTerms = Snip(Rep1(
stringLiteral
.Or(braced)
.Or(parens)
.Or(codeStretch)
.Or(identifier)
.Or(keyword)
.Or(SpecialCharCast)
.Or(oneLineComment)
.Or(multiLineComment)
)).Or(EmptySnip());
LimitedExpressionTerms = limit=>Snip(Rep1(
stringLiteral
.Or(braced)
.Or(parens)
.Or(limitedCodeStretch(limit))
.Or(identifier)
.Or(keyword)
.Or(SpecialCharCast)
.Or(oneLineComment)
.Or(multiLineComment)
)).Or(EmptySnip());
Expression = ExpressionTerms.Build(hit => new Snippets(hit));
LimitedExpression = limit=>LimitedExpressionTerms(limit).Build(hit => new Snippets(hit));
var statementPiece =
Swap(Ch("[["), "<")
.Or(Swap(Ch("]]"), ">"))
.Or(lateBound)
.Or(Snip(ChNot('\"', '\'')))
.Unless(SpecialCharCast)
.Unless(Ch("@\"").Or(Ch("@'")).Or(Ch("//")).Or(Ch("/*")));
var statement1Stretch = Snip(Rep1(statementPiece.Unless(Ch('\r', '\n'))));
var statement2Stretch = Snip(Rep1(statementPiece.Unless(Ch("%>"))));
// Statement1 ::= (dquot | aquot | statement1Stretch | specialCharCast)*
Statement1 = Snip(Rep(
stringLiteral
.Or(statement1Stretch)
.Or(SpecialCharCast)
.Or(oneLineComment)
.Or(multiLineComment)));
// Statement2 ::= (dquot | aquot | statement2Stretch | specialCharCast)*
Statement2 = Snip(Rep(
stringLiteral
.Or(statement2Stretch)
.Or(SpecialCharCast)
.Or(oneLineComment)
.Or(multiLineComment)));
}
static ParseAction<IList<Snippet>> Snip(ParseAction<Chain<Chain<IList<Snippet>, IList<Snippet>>, IList<Snippet>>> parser)
{
return Snip(parser, hit => new[] { hit.Left.Left, hit.Left.Down, hit.Down });
}
static ParseAction<IList<Snippet>> Snip<TValue>(ParseAction<TValue> parser, Func<TValue, IList<IList<Snippet>>> combiner)
{
return position =>
{
var result = parser(position);
if (result == null) return null;
return new ParseResult<IList<Snippet>>(result.Rest, combiner(result.Value).SelectMany(s => s).ToArray());
};
}
static ParseAction<IList<Snippet>> Snip<TValue>(ParseAction<TValue> parser, Func<TValue, string> builder)
{
return position =>
{
var result = parser(position);
if (result == null) return null;
var snippet = new Snippet { Value = builder(result.Value), Begin = position, End = result.Rest };
return new ParseResult<IList<Snippet>>(result.Rest, new[] { snippet });
};
}
static ParseAction<IList<Snippet>> Snip(ParseAction<char> parser)
{
return position =>
{
var result = parser(position);
if (result == null) return null;
var snippet = new Snippet { Value = new string(result.Value, 1), Begin = position, End = result.Rest };
return new ParseResult<IList<Snippet>>(result.Rest, new[] { snippet });
};
}
static ParseAction<IList<Snippet>> Snip(ParseAction<IList<char>> parser)
{
return position =>
{
var result = parser(position);
if (result == null) return null;
var snippet = new Snippet { Value = new string(result.Value.ToArray()), Begin = position, End = result.Rest };
return new ParseResult<IList<Snippet>>(result.Rest, new[] { snippet });
};
}
static ParseAction<IList<Snippet>> Snip(ParseAction<string> parser)
{
return position =>
{
var result = parser(position);
if (result == null) return null;
var snippet = new Snippet { Value = new string(result.Value.ToArray()), Begin = position, End = result.Rest };
return new ParseResult<IList<Snippet>>(result.Rest, new[] { snippet });
};
}
static ParseAction<IList<Snippet>> Snip(ParseAction<IList<string>> parser)
{
return position =>
{
var result = parser(position);
if (result == null) return null;
var snippet = new Snippet { Value = string.Concat(result.Value.ToArray()), Begin = position, End = result.Rest };
return new ParseResult<IList<Snippet>>(result.Rest, new[] { snippet });
};
}
static ParseAction<IList<Snippet>> Snip(ParseAction<IList<Snippet>> parser)
{
return parser;
}
static ParseAction<IList<Snippet>> Snip(ParseAction<IList<IList<Snippet>>> parser)
{
return position =>
{
var result = parser(position);
if (result == null) return null;
return new ParseResult<IList<Snippet>>(result.Rest, result.Value.SelectMany(s => s).ToArray());
};
}
static ParseAction<IList<Snippet>> EmptySnip()
{
return position => new ParseResult<IList<Snippet>>(position, new[] { new Snippet { Value = "", Begin = position, End = position } });
}
static ParseAction<IList<Snippet>> Swap<TValue>(ParseAction<TValue> parser, string replacement)
{
return position =>
{
var result = parser(position);
if (result == null) return null;
var snippet = new Snippet { Value = replacement };
return new ParseResult<IList<Snippet>>(result.Rest, new[] { snippet });
};
}
static ParseAction<IList<Snippet>> Swap<TValue>(ParseAction<TValue> parser, Func<TValue, string> replacement)
{
return position =>
{
var result = parser(position);
if (result == null) return null;
var snippet = new Snippet { Value = replacement(result.Value) };
return new ParseResult<IList<Snippet>>(result.Rest, new[] { snippet });
};
}
public ParseAction<IList<Snippet>> ExpressionTerms;
public ParseAction<Snippets> Expression;
public Func<ParseAction<string>, ParseAction<IList<Snippet>>> LimitedExpressionTerms;
public Func<ParseAction<string>, ParseAction<Snippets>> LimitedExpression;
public ParseAction<IList<Snippet>> Statement1;
public ParseAction<IList<Snippet>> Statement2;
public ParseAction<IList<Snippet>> _stringLiteral;
ParseResult<IList<Snippet>> FnTerms(Position position)
{
return ExpressionTerms(position);
}
protected static ParseAction<TValue> TkTagDelim<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.HtmlTagDelimiter, parser); }
protected static ParseAction<TValue> TkEleNam<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.HtmlElementName, parser); }
protected static ParseAction<TValue> TkAttNam<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.HtmlAttributeName, parser); }
protected static ParseAction<TValue> TkAttDelim<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.HtmlOperator, parser); }
protected static ParseAction<TValue> TkAttQuo<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.HtmlAttributeValue, parser); }
protected static ParseAction<TValue> TkAttVal<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.HtmlAttributeValue, parser); }
protected static ParseAction<TValue> TkEntity<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.HtmlEntity, parser); }
protected static ParseAction<TValue> TkComm<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.HtmlComment, parser); }
protected static ParseAction<TValue> TkCDATA<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.PlainText, parser); }
protected static ParseAction<TValue> TkAspxCode<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.HtmlServerSideScript, parser); }
protected static ParseAction<TValue> TkCode<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.SparkDelimiter, parser); }
protected static ParseAction<TValue> TkStr<TValue>(ParseAction<TValue> parser)
{ return Paint(SparkTokenType.String, parser); }
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols
{
public class AnonymousTypesSemanticsTests : CompilingTestBase
{
[Fact()]
public void AnonymousTypeSymbols_Simple()
{
var source = @"
public class ClassA
{
public struct SSS
{
}
public static void Test1(int x)
{
object v1 = [# new
{
[# aa #] = 1,
[# BB #] = """",
[# CCC #] = new SSS()
} #];
object v2 = [# new
{
[# aa #] = new SSS(),
[# BB #] = 123.456,
[# CCC #] = [# new
{
(new ClassA()).[# aa #],
ClassA.[# BB #],
ClassA.[# CCC #]
} #]
} #];
object v3 = [# new {} #];
var v4 = [# new {} #];
}
public int aa
{
get { return 123; }
}
public const string BB = ""-=-=-"";
public static SSS CCC = new SSS();
}";
var data = Compile(source, 14);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2, 3);
var info1 = GetAnonymousTypeInfoSummary(data, 4,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 3).Span,
5, 6, 7);
var info2 = GetAnonymousTypeInfoSummary(data, 8,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 5).Span,
9, 10, 11);
Assert.Equal(info0.Type, info2.Type);
Assert.NotEqual(info0.Type, info1.Type);
var info3 = GetAnonymousTypeInfoSummary(data, 12,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 7).Span);
var info4 = GetAnonymousTypeInfoSummary(data, 13,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 8).Span);
Assert.Equal(info3.Type, info4.Type);
}
[Fact()]
public void AnonymousTypeSymbols_ContextualKeywordsInFields()
{
var source = @"
class ClassA
{
static void Test1(int x)
{
object v1 = [# new
{
[# var #] = ""var"",
[# get #] = new {},
[# partial #] = [# new
{
(new ClassA()).[# select #],
[# global #]
} #]
} #];
}
public int select
{
get { return 123; }
}
public const string global = ""-=-=-"";
}";
var data = Compile(source, 7);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2, 3);
var info1 = GetAnonymousTypeInfoSummary(data, 4,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 3).Span,
5, 6);
Assert.Equal(
"<anonymous type: System.String var, <empty anonymous type> get, <anonymous type: System.Int32 select, System.String global> partial>",
info0.Type.ToTestDisplayString());
Assert.Equal(
"<anonymous type: System.Int32 select, System.String global>..ctor(System.Int32 select, System.String global)",
info1.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_DelegateMembers()
{
var source = @"
delegate bool D1();
class ClassA
{
void Main()
{
var at1 = [# new { [# module #] = (D1)(() => false)} #].module();
}
}";
var data = Compile(source, 2);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1);
Assert.Equal("<anonymous type: D1 module>", info0.Type.ToTestDisplayString());
Assert.Equal("<anonymous type: D1 module>..ctor(D1 module)", info0.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_BaseAccessInMembers()
{
var source = @"
delegate bool D1();
class ClassB
{
protected System.Func<int, int> F = x => x;
}
class ClassA: ClassB
{
void Main()
{
var at1 = [# [# new { base.[# F #] } #].F(1) #];
}
}";
var data = Compile(source, 3);
var info0 = GetAnonymousTypeInfoSummary(data, 1,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
2);
Assert.Equal("<anonymous type: System.Func<System.Int32, System.Int32> F>", info0.Type.ToTestDisplayString());
var info1 = data.Model.GetSemanticInfoSummary(data.Nodes[0]);
Assert.Equal("System.Int32 System.Func<System.Int32, System.Int32>.Invoke(System.Int32 arg)", info1.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_InFieldInitializer()
{
var source = @"
class ClassA
{
private static object F = [# new { [# F123 #] = typeof(ClassA) } #];
}";
var data = Compile(source, 2);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1);
Assert.Equal("<anonymous type: System.Type F123>", info0.Type.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_Equals()
{
var source = @"
class ClassA
{
static void Test1(int x)
{
bool result = [# new { f1 = 1, f2 = """" }.Equals(new { }) #];
}
}";
var data = Compile(source, 1);
var info = data.Model.GetSemanticInfoSummary(data.Nodes[0]);
var method = info.Symbol;
Assert.NotNull(method);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.Equal("object.Equals(object)", method.ToDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_ToString()
{
var source = @"
class ClassA
{
static void Test1(int x)
{
string result = [# new { f1 = 1, f2 = """" }.ToString() #];
}
}";
var data = Compile(source, 1);
var info = data.Model.GetSemanticInfoSummary(data.Nodes[0]);
var method = info.Symbol;
Assert.NotNull(method);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.Equal("object.ToString()", method.ToDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_GetHashCode()
{
var source = @"
class ClassA
{
static void Test1(int x)
{
int result = [# new { f1 = 1, f2 = """" }.GetHashCode() #];
}
}";
var data = Compile(source, 1);
var info = data.Model.GetSemanticInfoSummary(data.Nodes[0]);
var method = info.Symbol;
Assert.NotNull(method);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.Equal("object.GetHashCode()", method.ToDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_Ctor()
{
var source = @"
class ClassA
{
static void Test1(int x)
{
var result = [# new { f1 = 1, f2 = """" } #];
}
}";
var data = Compile(source, 1);
var info = data.Model.GetSemanticInfoSummary(data.Nodes[0]);
var method = info.Symbol;
Assert.NotNull(method);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.Equal("<anonymous type: int f1, string f2>..ctor(int, string)", method.ToDisplayString());
Assert.Equal("<anonymous type: System.Int32 f1, System.String f2>..ctor(System.Int32 f1, System.String f2)", method.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeTemplateCannotConstruct()
{
var source = @"
class ClassA
{
object F = [# new { [# F123 #] = typeof(ClassA) } #];
}";
var data = Compile(source, 2);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1);
var type = info0.Type;
Assert.Equal("<anonymous type: System.Type F123>", type.ToTestDisplayString());
Assert.True(type.IsDefinition);
AssertCannotConstruct(type);
}
[Fact()]
public void AnonymousTypeTemplateCannotConstruct_Empty()
{
var source = @"
class ClassA
{
object F = [# new { } #];
}";
var data = Compile(source, 1);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span);
var type = info0.Type;
Assert.Equal("<empty anonymous type>", type.ToTestDisplayString());
Assert.True(type.IsDefinition);
AssertCannotConstruct(type);
}
[Fact()]
public void AnonymousTypeFieldDeclarationIdentifier()
{
var source = @"
class ClassA
{
object F = new { [# F123 #] = typeof(ClassA) };
}";
var data = Compile(source, 1);
var info = data.Model.GetSymbolInfo((ExpressionSyntax)data.Nodes[0]);
Assert.NotNull(info.Symbol);
Assert.Equal(SymbolKind.Property, info.Symbol.Kind);
Assert.Equal("System.Type <anonymous type: System.Type F123>.F123 { get; }", info.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeFieldCreatedInQuery()
{
var source = LINQ + @"
class ClassA
{
void m()
{
var o = from x in new List1<int>(1, 2, 3) select [# new { [# x #], [# y #] = x } #];
}
}";
var data = Compile(source, 3);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, NumberOfNewKeywords(LINQ) + 2).Span,
1, 2);
var info1 = data.Model.GetSymbolInfo(((AnonymousObjectMemberDeclaratorSyntax)data.Nodes[1]).Expression);
Assert.NotNull(info1.Symbol);
Assert.Equal(SymbolKind.RangeVariable, info1.Symbol.Kind);
Assert.Equal("x", info1.Symbol.ToDisplayString());
var info2 = data.Model.GetSymbolInfo((ExpressionSyntax)data.Nodes[2]);
Assert.NotNull(info2.Symbol);
Assert.Equal(SymbolKind.Property, info2.Symbol.Kind);
Assert.Equal("System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; }", info2.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeFieldCreatedInQuery2()
{
var source = LINQ + @"
class ClassA
{
void m()
{
var o = from x in new List1<int>(1, 2, 3) let y = """" select [# new { [# x #], [# y #] } #];
}
}";
var data = Compile(source, 3);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, NumberOfNewKeywords(LINQ) + 2).Span,
1, 2);
Assert.Equal("<anonymous type: System.Int32 x, System.String y>", info0.Type.ToTestDisplayString());
var info1 = data.Model.GetSymbolInfo(((AnonymousObjectMemberDeclaratorSyntax)data.Nodes[1]).Expression);
Assert.NotNull(info1.Symbol);
Assert.Equal(SymbolKind.RangeVariable, info1.Symbol.Kind);
Assert.Equal("x", info1.Symbol.ToDisplayString());
var info2 = data.Model.GetSymbolInfo(((AnonymousObjectMemberDeclaratorSyntax)data.Nodes[2]).Expression);
Assert.NotNull(info2.Symbol);
Assert.Equal(SymbolKind.RangeVariable, info2.Symbol.Kind);
Assert.Equal("y", info2.Symbol.ToDisplayString());
}
[Fact()]
public void AnonymousTypeFieldCreatedInLambda()
{
var source = @"
using System;
class ClassA
{
void m()
{
var o = (Action)(() => ( [# new { [# x #] = 1, [# y #] = [# new { } #] } #]).ToString());;
}
}";
var data = Compile(source, 4);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2);
var info1 = GetAnonymousTypeInfoSummary(data, 3,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 2).Span);
Assert.Equal("<anonymous type: System.Int32 x, <empty anonymous type> y>..ctor(System.Int32 x, <empty anonymous type> y)", info0.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeFieldCreatedInLambda2()
{
var source = @"
using System;
class ClassA
{
void m()
{
var o = (Action)
(() =>
((Func<string>) (() => ( [# new { [# x #] = 1, [# y #] = [# new { } #] } #]).ToString())
).Invoke());
}
}";
var data = Compile(source, 4);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2);
var info1 = GetAnonymousTypeInfoSummary(data, 3,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 2).Span);
Assert.Equal("<anonymous type: System.Int32 x, <empty anonymous type> y>..ctor(System.Int32 x, <empty anonymous type> y)", info0.Symbol.ToTestDisplayString());
}
[ClrOnlyFact]
public void AnonymousTypeSymbols_DontCrashIfNameIsQueriedBeforeEmit()
{
var source = @"
public class ClassA
{
public static void Test1(int x)
{
object v1 = [# new { [# aa #] = 1, [# BB #] = 2 } #];
object v2 = [# new { } #];
}
}";
var data = Compile(source, 4);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2);
CheckAnonymousType(info0.Type, "", "");
info0 = GetAnonymousTypeInfoSummary(data, 3,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 2).Span);
CheckAnonymousType(info0.Type, "", "");
// perform emit
CompileAndVerify(
data.Compilation,
symbolValidator: module => CheckAnonymousTypes(module)
);
}
#region "AnonymousTypeSymbols_DontCrashIfNameIsQueriedBeforeEmit"
private void CheckAnonymousType(ITypeSymbol type, string name, string metadataName)
{
Assert.NotNull(type);
Assert.Equal(name, type.Name);
Assert.Equal(metadataName, type.MetadataName);
}
private void CheckAnonymousTypes(ModuleSymbol module)
{
var ns = module.GlobalNamespace;
Assert.NotNull(ns);
CheckAnonymousType(ns.GetMember<NamedTypeSymbol>("<>f__AnonymousType0"), "<>f__AnonymousType0", "<>f__AnonymousType0`2");
CheckAnonymousType(ns.GetMember<NamedTypeSymbol>("<>f__AnonymousType1"), "<>f__AnonymousType1", "<>f__AnonymousType1");
}
#endregion
[Fact()]
public void AnonymousTypeSymbols_Error_Simple()
{
var source = @"
public class ClassA
{
public static void Test1(int x)
{
object v1 = [# new
{
[# aa #] = xyz,
[# BB #] = """",
[# CCC #] = new SSS()
} #];
object v2 = [# new
{
[# aa #] = new SSS(),
[# BB #] = 123.456,
[# CCC #] = [# new
{
(new ClassA()).[# aa #],
ClassA.[# BB #],
ClassA.[# CCC #]
} #]
} #];
}
}";
var data = Compile(source, 12,
// (8,25): error CS0103: The name 'xyz' does not exist in the current context
// aa = xyz,
Diagnostic(ErrorCode.ERR_NameNotInContext, "xyz").WithArguments("xyz"),
// (10,29): error CS0246: The type or namespace name 'SSS' could not be found (are you missing a using directive or an assembly reference?)
// CCC = new SSS()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "SSS").WithArguments("SSS"),
// (15,29): error CS0246: The type or namespace name 'SSS' could not be found (are you missing a using directive or an assembly reference?)
// aa = new SSS(),
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "SSS").WithArguments("SSS"),
// (19,35): error CS1061: 'ClassA' does not contain a definition for 'aa' and no extension method 'aa' accepting a first argument of type 'ClassA' could be found (are you missing a using directive or an assembly reference?)
// (new ClassA()). aa ,
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "aa").WithArguments("ClassA", "aa"),
// (20,27): error CS0117: 'ClassA' does not contain a definition for 'BB'
// ClassA. BB ,
Diagnostic(ErrorCode.ERR_NoSuchMember, "BB").WithArguments("ClassA", "BB"),
// (21,27): error CS0117: 'ClassA' does not contain a definition for 'CCC'
// ClassA. CCC
Diagnostic(ErrorCode.ERR_NoSuchMember, "CCC").WithArguments("ClassA", "CCC")
);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2, 3);
var info1 = GetAnonymousTypeInfoSummary(data, 4,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 3).Span,
5, 6, 7);
var info2 = GetAnonymousTypeInfoSummary(data, 8,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 5).Span,
9, 10, 11);
Assert.Equal("<anonymous type: ? aa, System.String BB, SSS CCC>", info0.Type.ToTestDisplayString());
Assert.Equal("<anonymous type: SSS aa, System.Double BB, <anonymous type: ? aa, ? BB, ? CCC> CCC>", info1.Type.ToTestDisplayString());
Assert.Equal("<anonymous type: ? aa, ? BB, ? CCC>", info2.Type.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_Error_InUsingStatement()
{
var source = @"
public class ClassA
{
public static void Test1(int x)
{
using (var v1 = [# new { } #])
{
}
}
}";
var data = Compile(source, 1,
// (6,16): error CS1674: '<empty anonymous type>': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (var v1 = new { } )
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v1 = new { }").WithArguments("<empty anonymous type>")
);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span);
Assert.Equal("<empty anonymous type>", info0.Type.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_Error_DuplicateName()
{
var source = @"
public class ClassA
{
public static void Test1(int x)
{
object v1 = [# new
{
[# aa #] = 1,
ClassA.[# aa #],
[# bb #] = 1.2
} #];
}
public static string aa = ""-field-aa-"";
}";
var data = Compile(source, 4,
// (9,13): error CS0833: An anonymous type cannot have multiple properties with the same name
// ClassA. aa ,
Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "ClassA. aa")
);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, /*2,*/ 3);
Assert.Equal("<anonymous type: System.Int32 aa, System.String $1, System.Double bb>", info0.Type.ToTestDisplayString());
var properties = (from m in info0.Type.GetMembers() where m.Kind == SymbolKind.Property select m).ToArray();
Assert.Equal(3, properties.Length);
Assert.Equal("System.Int32 <anonymous type: System.Int32 aa, System.String $1, System.Double bb>.aa { get; }", properties[0].ToTestDisplayString());
Assert.Equal("System.String <anonymous type: System.Int32 aa, System.String $1, System.Double bb>.$1 { get; }", properties[1].ToTestDisplayString());
Assert.Equal("System.Double <anonymous type: System.Int32 aa, System.String $1, System.Double bb>.bb { get; }", properties[2].ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_LookupSymbols()
{
var source = @"
public class ClassA
{
public static void Test1(int x)
{
object v1 = [# new
{
[# aa #] = """",
[# abc #] = 123.456
} #];
object v2 = [# new{ } #];
}
}";
var data = Compile(source, 4);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2);
Assert.Equal("<anonymous type: System.String aa, System.Double abc>", info0.Type.ToTestDisplayString());
var pos = data.Nodes[0].Span.End;
var syms = data.Model.LookupSymbols(pos, container: info0.Type).Select(x => x.ToTestDisplayString()).OrderBy(x => x).ToArray();
Assert.Equal(8, syms.Length);
int index = 0;
Assert.Equal("System.Boolean System.Object.Equals(System.Object obj)", syms[index++]);
Assert.Equal("System.Boolean System.Object.Equals(System.Object objA, System.Object objB)", syms[index++]);
Assert.Equal("System.Boolean System.Object.ReferenceEquals(System.Object objA, System.Object objB)", syms[index++]);
Assert.Equal("System.Double <anonymous type: System.String aa, System.Double abc>.abc { get; }", syms[index++]);
Assert.Equal("System.Int32 System.Object.GetHashCode()", syms[index++]);
Assert.Equal("System.String <anonymous type: System.String aa, System.Double abc>.aa { get; }", syms[index++]);
Assert.Equal("System.String System.Object.ToString()", syms[index++]);
Assert.Equal("System.Type System.Object.GetType()", syms[index++]);
info0 = GetAnonymousTypeInfoSummary(data, 3,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 2).Span);
Assert.Equal("<empty anonymous type>", info0.Type.ToTestDisplayString());
pos = data.Nodes[3].Span.End;
syms = data.Model.LookupSymbols(pos, container: info0.Type).Select(x => x.ToTestDisplayString()).OrderBy(x => x).ToArray();
Assert.Equal(6, syms.Length);
index = 0;
Assert.Equal("System.Boolean System.Object.Equals(System.Object obj)", syms[index++]);
Assert.Equal("System.Boolean System.Object.Equals(System.Object objA, System.Object objB)", syms[index++]);
Assert.Equal("System.Boolean System.Object.ReferenceEquals(System.Object objA, System.Object objB)", syms[index++]);
Assert.Equal("System.Int32 System.Object.GetHashCode()", syms[index++]);
Assert.Equal("System.String System.Object.ToString()", syms[index++]);
Assert.Equal("System.Type System.Object.GetType()", syms[index++]);
}
[WorkItem(543189, "DevDiv")]
[Fact()]
public void CheckAnonymousTypeAsConstValue()
{
var source = @"
public class A
{
const int i = /*<bind>*/(new {a = 2}).a/*</bind>*/;
}";
var comp = CreateCompilationWithMscorlib(source);
var tuple = GetBindingNodeAndModel<ExpressionSyntax>(comp);
var info = tuple.Item2.GetSymbolInfo(tuple.Item1);
Assert.NotNull(info.Symbol);
Assert.Equal("<anonymous type: int a>.a", info.Symbol.ToDisplayString());
}
[WorkItem(546416, "DevDiv")]
[ClrOnlyFact]
public void TestAnonymousTypeInsideGroupBy_Queryable()
{
CompileAndVerify(
@"using System.Linq;
public class Product
{
public int ProductID;
public string ProductName;
public int SupplierID;
}
public class DB
{
public IQueryable<Product> Products;
}
public class Program
{
public static void Main()
{
var db = new DB();
var q0 = db.Products.GroupBy(p => new { Conditional = false ? new { p.ProductID, p.ProductName, p.SupplierID } : new { p.ProductID, p.ProductName, p.SupplierID } }).ToList();
}
}", additionalRefs: new[] { SystemCoreRef }).VerifyDiagnostics();
}
[WorkItem(546416, "DevDiv")]
[ClrOnlyFact]
public void TestAnonymousTypeInsideGroupBy_Enumerable()
{
CompileAndVerify(
@"using System.Linq;
using System.Collections.Generic;
public class Product
{
public int ProductID;
public string ProductName;
public int SupplierID;
}
public class DB
{
public IEnumerable<Product> Products;
}
public class Program
{
public static void Main()
{
var db = new DB();
var q0 = db.Products.GroupBy(p => new { Conditional = false ? new { p.ProductID, p.ProductName, p.SupplierID } : new { p.ProductID, p.ProductName, p.SupplierID } }).ToList();
}
}", additionalRefs: new[] { SystemCoreRef }).VerifyDiagnostics();
}
[WorkItem(546416, "DevDiv")]
[ClrOnlyFact]
public void TestAnonymousTypeInsideGroupBy_Enumerable2()
{
CompileAndVerify(
@"using System.Linq;
using System.Collections.Generic;
public class Product
{
public int ProductID;
public int SupplierID;
}
public class DB
{
public IEnumerable<Product> Products;
}
public class Program
{
public static void Main()
{
var db = new DB();
var q0 = db.Products.GroupBy(p => new { Conditional = false ? new { p.ProductID, p.SupplierID } : new { p.ProductID, p.SupplierID } }).ToList();
var q1 = db.Products.GroupBy(p => new { Conditional = false ? new { p.ProductID, p.SupplierID } : new { p.ProductID, p.SupplierID } }).ToList();
}
}", additionalRefs: new[] { SystemCoreRef }).VerifyDiagnostics();
}
#region "Utility methods"
private void AssertCannotConstruct(ISymbol type)
{
var namedType = type as NamedTypeSymbol;
Assert.NotNull(namedType);
var objType = namedType.BaseType;
Assert.NotNull(objType);
Assert.Equal("System.Object", objType.ToTestDisplayString());
TypeSymbol[] args = new TypeSymbol[namedType.Arity];
for (int i = 0; i < namedType.Arity; i++)
{
args[i] = objType;
}
Assert.Throws<InvalidOperationException>(() => namedType.Construct(args));
}
private CompilationUtils.SemanticInfoSummary GetAnonymousTypeInfoSummary(TestData data, int node, TextSpan typeSpan, params int[] fields)
{
var info = data.Model.GetSemanticInfoSummary(data.Nodes[node]);
var type = info.Type;
Assert.True(type.IsAnonymousType);
Assert.False(type.CanBeReferencedByName);
Assert.Equal("System.Object", type.BaseType.ToTestDisplayString());
Assert.Equal(0, type.Interfaces.Length);
Assert.Equal(1, type.Locations.Length);
Assert.Equal(typeSpan, type.Locations[0].SourceSpan);
foreach (int field in fields)
{
CheckFieldNameAndLocation(data, type, data.Nodes[field]);
}
return info;
}
private void CheckFieldNameAndLocation(TestData data, ITypeSymbol type, SyntaxNode identifier)
{
var anonymousType = (NamedTypeSymbol)type;
var current = identifier;
while (current.Span == identifier.Span && !current.IsKind(SyntaxKind.IdentifierName))
{
current = current.ChildNodes().Single();
}
var node = (IdentifierNameSyntax)current;
Assert.NotNull(node);
var span = node.Span;
var fieldName = node.ToString();
var property = anonymousType.GetMember<PropertySymbol>(fieldName);
Assert.NotNull(property);
Assert.Equal(fieldName, property.Name);
Assert.Equal(1, property.Locations.Length);
Assert.Equal(span, property.Locations[0].SourceSpan);
MethodSymbol getter = property.GetMethod;
Assert.NotNull(getter);
Assert.Equal("get_" + fieldName, getter.Name);
}
private struct TestData
{
public CSharpCompilation Compilation;
public SyntaxTree Tree;
public List<SyntaxNode> Nodes;
public SemanticModel Model;
}
private TestData Compile(string source, int expectedIntervals, params DiagnosticDescription[] diagnostics)
{
var intervals = ExtractTextIntervals(ref source);
Assert.Equal(expectedIntervals, intervals.Count);
var compilation = GetCompilationForEmit(
new[] { source },
new MetadataReference[] { },
TestOptions.ReleaseDll,
TestOptions.Regular
);
compilation.VerifyDiagnostics(diagnostics);
var tree = compilation.SyntaxTrees[0];
var nodes = new List<SyntaxNode>();
foreach (var span in intervals)
{
var stack = new Stack<SyntaxNode>();
stack.Push(tree.GetCompilationUnitRoot());
while (stack.Count > 0)
{
var node = stack.Pop();
if (span.Contains(node.Span))
{
nodes.Add(node);
break;
}
foreach (var child in node.ChildNodes())
{
stack.Push(child);
}
}
}
Assert.Equal(expectedIntervals, nodes.Count);
return new TestData()
{
Compilation = compilation,
Tree = tree,
Model = compilation.GetSemanticModel(tree),
Nodes = nodes
};
}
private CSharpCompilation Compile(string source)
{
return GetCompilationForEmit(
new[] { source },
new MetadataReference[] { },
TestOptions.ReleaseDll,
TestOptions.Regular
);
}
private static List<TextSpan> ExtractTextIntervals(ref string source)
{
const string startTag = "[#";
const string endTag = "#]";
List<TextSpan> intervals = new List<TextSpan>();
var all = (from s in FindAll(source, startTag)
select new { start = true, offset = s }).Union(
from s in FindAll(source, endTag)
select new { start = false, offset = s }
).OrderBy(value => value.offset).ToList();
while (all.Count > 0)
{
int i = 1;
bool added = false;
while (i < all.Count)
{
if (all[i - 1].start && !all[i].start)
{
intervals.Add(TextSpan.FromBounds(all[i - 1].offset, all[i].offset));
all.RemoveAt(i);
all.RemoveAt(i - 1);
added = true;
}
else
{
i++;
}
}
Assert.True(added);
}
source = source.Replace(startTag, " ").Replace(endTag, " ");
intervals.Sort((x, y) => x.Start.CompareTo(y.Start));
return intervals;
}
private static IEnumerable<int> FindAll(string source, string what)
{
int index = source.IndexOf(what, StringComparison.Ordinal);
while (index >= 0)
{
yield return index;
index = source.IndexOf(what, index + 1, StringComparison.Ordinal);
}
}
private int NumberOfNewKeywords(string source)
{
int cnt = 0;
foreach (var line in source.Split(new String[] { Environment.NewLine }, StringSplitOptions.None))
{
if (!string.IsNullOrWhiteSpace(line))
{
if (!line.Trim().StartsWith("//", StringComparison.Ordinal))
{
for (int index = line.IndexOf("new ", StringComparison.Ordinal); index >= 0;)
{
cnt++;
index = line.IndexOf("new ", index + 1, StringComparison.Ordinal);
}
}
}
}
return cnt;
}
#endregion
}
}
| |
//
// Copyright (c) 2008 Microsoft Corporation. All rights reserved.
//
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Net;
using System.Management.Automation;
using System.ComponentModel;
using System.Reflection;
using System.Globalization;
using System.Management.Automation.Runspaces;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Security;
using System.Security.Principal;
using System.Resources;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Powershell.Commands.GetCounter.PdhNative;
using Microsoft.PowerShell.Commands.GetCounter;
using Microsoft.PowerShell.Commands.Diagnostics.Common;
namespace Microsoft.PowerShell.Commands
{
///
/// Class that implements the Get-Counter cmdlet.
///
[Cmdlet("Import", "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=138338")]
public sealed class ImportCounterCommand : PSCmdlet
{
//
// Path parameter
//
[Parameter(
Position = 0,
Mandatory = true,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessageBaseName = "GetEventResources")]
[Alias("PSPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Scope = "member",
Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet",
Justification = "A string[] is required here because that is the type Powershell supports")]
public string[] Path
{
get { return _path; }
set { _path = value; }
}
private string[] _path;
private StringCollection _resolvedPaths = new StringCollection();
private List<string> _accumulatedFileNames = new List<string>();
//
// ListSet parameter
//
[Parameter(
Mandatory = true,
ParameterSetName = "ListSetSet",
ValueFromPipeline = false,
ValueFromPipelineByPropertyName = false,
HelpMessageBaseName = "GetEventResources")]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Scope = "member",
Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet",
Justification = "A string[] is required here because that is the type Powershell supports")]
public string[] ListSet
{
get { return _listSet; }
set { _listSet = value; }
}
private string[] _listSet = new string[0];
//
// StartTime parameter
//
[Parameter(
ValueFromPipeline = false,
ValueFromPipelineByPropertyName = false,
ParameterSetName = "GetCounterSet",
HelpMessageBaseName = "GetEventResources")]
public DateTime StartTime
{
get { return _startTime; }
set { _startTime = value; }
}
private DateTime _startTime = DateTime.MinValue;
//
// EndTime parameter
//
[Parameter(
ValueFromPipeline = false,
ValueFromPipelineByPropertyName = false,
ParameterSetName = "GetCounterSet",
HelpMessageBaseName = "GetEventResources")]
public DateTime EndTime
{
get { return _endTime; }
set { _endTime = value; }
}
private DateTime _endTime = DateTime.MaxValue;
//
// Counter parameter
//
[Parameter(
Mandatory = false,
ParameterSetName = "GetCounterSet",
ValueFromPipeline = false,
HelpMessageBaseName = "GetEventResources")]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Scope = "member",
Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet",
Justification = "A string[] is required here because that is the type Powershell supports")]
public string[] Counter
{
get { return _counter; }
set { _counter = value; }
}
private string[] _counter = new string[0];
//
// Summary switch
//
[Parameter(ParameterSetName = "SummarySet")]
public SwitchParameter Summary
{
get { return _summary; }
set { _summary = value; }
}
private SwitchParameter _summary;
//
// MaxSamples parameter
//
private const Int64 KEEP_ON_SAMPLING = -1;
[Parameter(
ParameterSetName = "GetCounterSet",
ValueFromPipeline = false,
ValueFromPipelineByPropertyName = false,
HelpMessageBaseName = "GetEventResources")]
[ValidateRange((Int64)1, Int64.MaxValue)]
public Int64 MaxSamples
{
get { return _maxSamples; }
set { _maxSamples = value; }
}
private Int64 _maxSamples = KEEP_ON_SAMPLING;
private ResourceManager _resourceMgr = null;
private PdhHelper _pdhHelper = null;
private bool _stopping = false;
//
// AccumulatePipelineFileNames() accumulates counter file paths in the pipeline scenario:
// we do not want to construct a Pdh query until all the file names are supplied.
//
private void AccumulatePipelineFileNames()
{
_accumulatedFileNames.AddRange(_path);
}
//
// BeginProcessing() is invoked once per pipeline
//
protected override void BeginProcessing()
{
_resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager();
_pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6);
}
//
// EndProcessing() is invoked once per pipeline
//
protected override void EndProcessing()
{
//
// Resolve and validate the Path argument: present for all parametersets.
//
if (!ResolveFilePaths())
{
return;
}
ValidateFilePaths();
switch (ParameterSetName)
{
case "ListSetSet":
ProcessListSet();
break;
case "GetCounterSet":
ProcessGetCounter();
break;
case "SummarySet":
ProcessSummary();
break;
default:
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName));
break;
}
_pdhHelper.Dispose();
}
//
// Handle Control-C
//
protected override void StopProcessing()
{
_stopping = true;
_pdhHelper.Dispose();
}
//
// ProcessRecord() override.
// This is the main entry point for the cmdlet.
//
protected override void ProcessRecord()
{
AccumulatePipelineFileNames();
}
//
// ProcessSummary().
// Does the work to process Summary parameter set.
//
private void ProcessSummary()
{
uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths);
if (res != 0)
{
ReportPdhError(res, true);
return;
}
CounterFileInfo summaryObj;
res = _pdhHelper.GetFilesSummary(out summaryObj);
if (res != 0)
{
ReportPdhError(res, true);
return;
}
WriteObject(summaryObj);
}
//
// ProcessListSet().
// Does the work to process ListSet parameter set.
//
private void ProcessListSet()
{
uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths);
if (res != 0)
{
ReportPdhError(res, true);
return;
}
StringCollection machineNames = new StringCollection();
res = _pdhHelper.EnumBlgFilesMachines(ref machineNames);
if (res != 0)
{
ReportPdhError(res, true);
return;
}
foreach (string machine in machineNames)
{
StringCollection counterSets = new StringCollection();
res = _pdhHelper.EnumObjects(machine, ref counterSets);
if (res != 0)
{
return;
}
StringCollection validPaths = new StringCollection();
foreach (string pattern in _listSet)
{
bool bMatched = false;
WildcardPattern wildLogPattern = new WildcardPattern(pattern, WildcardOptions.IgnoreCase);
foreach (string counterSet in counterSets)
{
if (!wildLogPattern.IsMatch(counterSet))
{
continue;
}
StringCollection counterSetCounters = new StringCollection();
StringCollection counterSetInstances = new StringCollection();
res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances);
if (res != 0)
{
ReportPdhError(res, false);
continue;
}
string[] instanceArray = new string[counterSetInstances.Count];
int i = 0;
foreach (string instance in counterSetInstances)
{
instanceArray[i++] = instance;
}
Dictionary<string, string[]> counterInstanceMapping = new Dictionary<string, string[]>();
foreach (string counter in counterSetCounters)
{
counterInstanceMapping.Add(counter, instanceArray);
}
PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown;
if (counterSetInstances.Count > 1)
{
categoryType = PerformanceCounterCategoryType.MultiInstance;
}
else //if (counterSetInstances.Count == 1) //???
{
categoryType = PerformanceCounterCategoryType.SingleInstance;
}
string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet);
CounterSet setObj = new CounterSet(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping);
WriteObject(setObj);
bMatched = true;
}
if (!bMatched)
{
string msg = _resourceMgr.GetString("NoMatchingCounterSetsInFile");
Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg,
CommonUtilities.StringArrayToString(_resolvedPaths),
pattern));
WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsInFile", ErrorCategory.ObjectNotFound, null));
}
}
}
}
//
// ProcessGetCounter()
// Does the work to process GetCounterSet parameter set.
//
private void ProcessGetCounter()
{
// Validate StartTime-EndTime, if present
if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue)
{
if (_startTime >= _endTime)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterInvalidDateRange"));
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "CounterInvalidDateRange", ErrorCategory.InvalidArgument, null));
return;
}
}
uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths);
if (res != 0)
{
ReportPdhError(res, true);
return;
}
StringCollection validPaths = new StringCollection();
if (_counter.Length > 0)
{
foreach (string path in _counter)
{
StringCollection expandedPaths;
res = _pdhHelper.ExpandWildCardPath(path, out expandedPaths);
if (res != 0)
{
WriteDebug(path);
ReportPdhError(res, false);
continue;
}
foreach (string expandedPath in expandedPaths)
{
if (!_pdhHelper.IsPathValid(expandedPath))
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathIsInvalid"), path);
Exception exc = new Exception(msg);
WriteError(new ErrorRecord(exc, "CounterPathIsInvalid", ErrorCategory.InvalidResult, null));
continue;
}
validPaths.Add(expandedPath);
}
}
if (validPaths.Count == 0)
{
return;
}
}
else
{
res = _pdhHelper.GetValidPathsFromFiles(ref validPaths);
if (res != 0)
{
ReportPdhError(res, false);
}
}
if (validPaths.Count == 0)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathsInFilesInvalid"));
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "CounterPathsInFilesInvalid", ErrorCategory.InvalidResult, null));
}
res = _pdhHelper.OpenQuery();
if (res != 0)
{
ReportPdhError(res, false);
}
if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue)
{
res = _pdhHelper.SetQueryTimeRange(_startTime, _endTime);
if (res != 0)
{
ReportPdhError(res, true);
}
}
res = _pdhHelper.AddCounters(ref validPaths, true);
if (res != 0)
{
ReportPdhError(res, true);
}
PerformanceCounterSampleSet nextSet;
uint samplesRead = 0;
while (!_stopping)
{
res = _pdhHelper.ReadNextSet(out nextSet, false);
if (res == PdhResults.PDH_NO_MORE_DATA)
{
break;
}
if (res != 0 && res != PdhResults.PDH_INVALID_DATA)
{
ReportPdhError(res, false);
continue;
}
//
// Display data
//
WriteSampleSetObject(nextSet, (samplesRead == 0));
samplesRead++;
if (_maxSamples != KEEP_ON_SAMPLING && samplesRead >= _maxSamples)
{
break;
}
}
}
//
// ValidateFilePaths() helper.
// Validates the _resolvedPaths: present for all parametersets.
// We cannot have more than 32 blg files, or more than one CSV or TSC file.
// Files have to all be of the same type (.blg, .csv, .tsv).
//
private void ValidateFilePaths()
{
Debug.Assert(_resolvedPaths.Count > 0);
string firstExt = System.IO.Path.GetExtension(_resolvedPaths[0]);
foreach (string fileName in _resolvedPaths)
{
WriteVerbose(fileName);
string curExtension = System.IO.Path.GetExtension(fileName);
if (!curExtension.Equals(".blg", StringComparison.CurrentCultureIgnoreCase)
&& !curExtension.Equals(".csv", StringComparison.CurrentCultureIgnoreCase)
&& !curExtension.Equals(".tsv", StringComparison.CurrentCultureIgnoreCase))
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterNotALogFile"), fileName);
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "CounterNotALogFile", ErrorCategory.InvalidResult, null));
return;
}
if (!curExtension.Equals(firstExt, StringComparison.CurrentCultureIgnoreCase))
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterNoMixedLogTypes"), fileName);
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "CounterNoMixedLogTypes", ErrorCategory.InvalidResult, null));
return;
}
}
if (firstExt.Equals(".blg", StringComparison.CurrentCultureIgnoreCase))
{
if (_resolvedPaths.Count > 32)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("Counter32FileLimit"));
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "Counter32FileLimit", ErrorCategory.InvalidResult, null));
return;
}
}
else if (_resolvedPaths.Count > 1)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("Counter1FileLimit"));
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "Counter1FileLimit", ErrorCategory.InvalidResult, null));
return;
}
}
//
// ResolveFilePath helper.
// Returns a string collection of resolved file paths.
// Writes non-terminating errors for invalid paths
// and returns an empty colleciton.
//
private bool ResolveFilePaths()
{
StringCollection retColl = new StringCollection();
foreach (string origPath in _accumulatedFileNames)
{
Collection<PathInfo> resolvedPathSubset = null;
try
{
resolvedPathSubset = SessionState.Path.GetResolvedPSPathFromPSPath(origPath);
}
catch (PSNotSupportedException notSupported)
{
WriteError(new ErrorRecord(notSupported, "", ErrorCategory.ObjectNotFound, origPath));
continue;
}
catch (System.Management.Automation.DriveNotFoundException driveNotFound)
{
WriteError(new ErrorRecord(driveNotFound, "", ErrorCategory.ObjectNotFound, origPath));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(new ErrorRecord(providerNotFound, "", ErrorCategory.ObjectNotFound, origPath));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(new ErrorRecord(pathNotFound, "", ErrorCategory.ObjectNotFound, origPath));
continue;
}
catch (Exception exc)
{
WriteError(new ErrorRecord(exc, "", ErrorCategory.ObjectNotFound, origPath));
continue;
}
foreach (PathInfo pi in resolvedPathSubset)
{
//
// Check the provider: only FileSystem provider paths are acceptable.
//
if (pi.Provider.Name != "FileSystem")
{
string msg = _resourceMgr.GetString("NotAFileSystemPath");
Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, origPath));
WriteError(new ErrorRecord(exc, "NotAFileSystemPath", ErrorCategory.InvalidArgument, origPath));
continue;
}
_resolvedPaths.Add(pi.ProviderPath.ToLower(CultureInfo.InvariantCulture));
}
}
return (_resolvedPaths.Count > 0);
}
private void ReportPdhError(uint res, bool bTerminate)
{
string msg;
uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg);
if (formatRes != 0)
{
msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res);
}
Exception exc = new Exception(msg);
if (bTerminate)
{
ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
}
else
{
WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
}
}
//
// WriteSampleSetObject() helper.
// In addition to writing the PerformanceCounterSampleSet object,
// it writes a single error if one of the samples has an invalid (non-zero) status.
// The only exception is the first set, where we allow for the formatted value to be 0 -
// this is expected for CSV and TSV files.
private void WriteSampleSetObject(PerformanceCounterSampleSet set, bool firstSet)
{
if (!firstSet)
{
foreach (PerformanceCounterSample sample in set.CounterSamples)
{
if (sample.Status != 0)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSampleDataInvalid"));
Exception exc = new Exception(msg);
WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
break;
}
}
}
WriteObject(set);
}
}
}
| |
using JetBrains.DataFlow;
using System;
using System.Collections.Generic;
using System.IO;
using JetBrains.Annotations;
using JetBrains.Application.Infra;
using JetBrains.Application.Threading;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.ProjectImplementation;
using JetBrains.ProjectModel.Properties;
using JetBrains.ProjectModel.Properties.Common;
using JetBrains.ProjectModel.References;
using JetBrains.Util;
using JetBrains.Util.dataStructures;
using JetBrains.Util.Dotnet.TargetFrameworkIds;
namespace GammaJul.ReSharper.ForTea.Psi {
/// <summary>
/// This almost empty implementation of <see cref="IProject"/> has only one purpose: provide a custom <see cref="PlatformID"/>
/// so that the GAC resolver will correctly resolve from the profile we want, which is the full framework.
/// TODO: see with JetBrains if that can be changed, this is really ugly
/// </summary>
internal sealed class T4ResolveProject : IProject {
[NotNull] private readonly IUserDataHolder _dataHolder;
[NotNull] private readonly ISolution _solution;
[NotNull] private readonly IShellLocks _shellLocks;
[NotNull] private readonly TargetFrameworkId _targetFrameworkId;
[NotNull] private readonly IProjectProperties _projectProperties;
[NotNull] private readonly TargetFrameworkReferences _targetFrameworkReferences;
public void PutData<T>(Key<T> key, T val)
where T : class
=> _dataHolder.PutData(key, val);
public T GetOrCreateDataUnderLock<T>(Key<T> key, Func<T> factory)
where T : class
=> _dataHolder.GetOrCreateDataUnderLock(key, factory);
public T GetOrCreateDataUnderLock<T, TState>(Key<T> key, TState state, Func<TState, T> factory)
where T : class
=> _dataHolder.GetOrCreateDataUnderLock(key, state, factory);
public T GetData<T>(Key<T> key)
where T : class
=> _dataHolder.GetData(key);
public IEnumerable<KeyValuePair<object, object>> EnumerateData()
=> _dataHolder.EnumerateData();
public string Name
=> typeof(T4ResolveProject).FullName ?? nameof(T4ResolveProject);
public bool IsValid()
=> _solution.IsValid();
public ISolution GetSolution()
=> _solution;
Type IProjectModelElement.MarshallerType
=> null;
void IProjectModelElement.Accept(ProjectVisitor projectVisitor) {
}
object IProjectModelElement.GetProperty(Key propertyName)
=> _dataHolder.GetData(propertyName);
void IProjectModelElement.SetProperty(Key propertyName, object propertyValue)
=> _dataHolder.PutData(propertyName, propertyValue);
IProject IProjectElement.GetProject()
=> this;
string IProjectElement.GetPersistentID()
=> Name;
void IProjectItem.Dump(TextWriter to, DumpFlags flags) {
}
string IProjectItem.GetPresentableProjectPath()
=> null;
IProjectFolder IProjectItem.ParentFolder
=> null;
FileSystemPath IProjectItem.Location
=> null;
ProjectItemKind IProjectItem.Kind
=> ProjectItemKind.PROJECT;
bool IProjectItem.IsLinked
=> false;
IShellLocks IProjectItem.Locks
=> _shellLocks;
IProjectItem IProjectFolder.FindProjectItemByLocation(FileSystemPath location)
=> null;
IProjectItem IProjectFolder.GetSubItem(string name)
=> null;
ReadOnlyFrugalLocalList<IProjectItem> IProjectFolder.GetSubItems(string name)
=> default;
IList<IProjectItem> IProjectFolder.GetSubItems()
=> EmptyList<IProjectItem>.InstanceList;
ProjectFolderPath IProjectFolder.Path
=> null;
string IModule.Presentation
=> Name;
public void Dispose() {
}
IEnumerable<IProjectToModuleReference> IProject.GetModuleReferences(TargetFrameworkId targetFrameworkId)
=> EmptyList<IProjectToModuleReference>.InstanceList;
bool IProject.HasFlavour<T>()
=> false;
IProjectFile IProject.ProjectFile
=> null;
Guid IProject.Guid { get; } = Guid.NewGuid();
bool IProject.IsOpened { get; set; }
IProjectProperties IProject.ProjectProperties
=> _projectProperties;
FileSystemPath IProject.ProjectFileLocation
=> null;
FileSystemPath IProject.GetOutputDirectory(TargetFrameworkId targetFrameworkId)
=> FileSystemPath.Empty;
FileSystemPath IProject.GetOutputFilePath(TargetFrameworkId targetFrameworkId)
=> FileSystemPath.Empty;
public T GetComponent<T>()
where T : class
=> _solution.GetComponent<T>();
[NotNull]
public IProperty<FileSystemPath> ProjectFileLocationLive { get; }
[NotNull]
public IProperty<FileSystemPath> ProjectLocationLive { get; }
public ProjectTargetFrameworkScope GetTargetFrameworkScope(TargetFrameworkId targetFrameworkId)
=> _targetFrameworkReferences.GetScope(targetFrameworkId);
public IEnumerable<TargetFrameworkScope> GetAllTargetFrameworks()
=> _targetFrameworkReferences.GetAllProjectScopes();
public IReadOnlyList<TargetFrameworkId> TargetFrameworkIds
=> new[] { _targetFrameworkId };
IProjectFolder IProjectFolder.GetSubFolderByPath(ProjectFolderPath projectFolderPath)
=> null;
ICollection<FileSystemPath> IProject.GetOutputDirectories()
=> EmptyList<FileSystemPath>.Instance;
ICollection<FileSystemPath> IProject.GetIntermidiateDirectories()
=> EmptyList<FileSystemPath>.Instance;
public FileSystemPath GetRefOutputFilePath(TargetFrameworkId targetFrameworkId)
=> FileSystemPath.Empty;
private sealed class T4ResolveProjectProperties : ProjectPropertiesBase<UnsupportedProjectConfiguration> {
public override IBuildSettings BuildSettings
=> null;
public override ProjectLanguage DefaultLanguage
=> ProjectLanguage.UNKNOWN;
public override ProjectKind ProjectKind
=> ProjectKind.MISC_FILES_PROJECT;
public T4ResolveProjectProperties([NotNull] TargetFrameworkId targetFrameworkId)
: base(EmptyList<Guid>.InstanceList, Guid.Empty, new[] { targetFrameworkId }, dotNetCoreSDK: null) {
}
}
public T4ResolveProject(
Lifetime lifetime,
[NotNull] ISolution solution,
[NotNull] IShellLocks shellLocks,
[NotNull] TargetFrameworkId targetFrameworkId,
[NotNull] IUserDataHolder dataHolder
) {
_shellLocks = shellLocks;
_targetFrameworkId = targetFrameworkId;
_solution = solution;
_dataHolder = dataHolder;
_projectProperties = new T4ResolveProjectProperties(targetFrameworkId);
ProjectFileLocationLive = new Property<FileSystemPath>(lifetime, "ProjectFileLocationLive");
ProjectLocationLive = new Property<FileSystemPath>(lifetime, "ProjectLocationLive");
_targetFrameworkReferences = new TargetFrameworkReferences(lifetime, shellLocks, this, solution.SolutionOwner.GetComponent<AssemblyInfoDatabase>());
}
}
}
| |
//-----------------------------------------------------------------------------
// PageFlipTracker.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework;
using System.Diagnostics;
namespace UserInterfaceSample.Controls
{
/// <remarks>
/// PageFlipTracker watches the touchpanel for drag and flick gestures, and computes the appropriate
/// offsets for flipping horizontally through a multi-page display. It is used by PageFlipControl
/// to handle the scroll logic. PageFlipTracker is broken out into a separate class so that XNA apps
/// with their own scheme for UI controls can still use it to handle the scroll logic.
///
/// Handling TouchPanel.EnabledGestures
/// --------------------------
/// This class watches for HorizontalDrag, DragComplete, and Flick gestures. However, it cannot just
/// set TouchPanel.EnabledGestures, because that would most likely interfere with gestures needed
/// elsewhere in the application. So it just exposes a const 'HandledGestures' field and relies on
/// the client code to set TouchPanel.EnabledGestures appropriately.
///
/// Handling screen rotation
/// ------------------------
/// This class uses TouchPanel.DisplayWidth to determine the width of the screen. DisplayWidth
/// is automatically updated by the system when the orientation changes.
/// </remarks>
public class PageFlipTracker
{
public const GestureType GesturesNeeded = GestureType.Flick | GestureType.HorizontalDrag | GestureType.DragComplete;
#region Tuning options
public static TimeSpan FlipDuration = TimeSpan.FromSeconds(0.3);
/// <summary>
/// Exponent on curve to make page flips and springbacks start quickly and slow to a stop.
///
/// Interpolation formula is (1-TransitionAlpha)^TransitionExponent, where
/// TransitionAlpha animates uniformly from 0 to 1 over timespan FlipDuration.
/// </summary>
public static double FlipExponent = 3.0;
/// <summary>
/// By default, this many pixels of the next page will be visible
/// on the right-hand edge of the screen, unless the current page's
/// contentWidth is too large.
/// </summary>
public static int PreviewMargin = 20;
/// <summary>
/// How far (as a fraction of the total screen width) you have
/// to drag a screen past its edge to trigger a flip by dragging.
/// </summary>
public static float DragToFlipTheshold = 1.0f / 3.0f;
#endregion
#region Private fields
// Time stamp when transition started
private DateTime flipStartTime;
// Horizontal offset at start of current transition. Target offset is always 0.
private float flipStartOffset;
#endregion
#region Properties
// Current active page. If we're in a transition, this is the page we're transitioning TO.
public int CurrentPage { get; private set; }
// Offset in pixels to render currentPage at. If this is positive, other
// pages may be visible to the left.
//
// This is always relative to the current page.
public float CurrentPageOffset { get; private set; }
public bool IsLeftPageVisible
{
get
{
return PageWidthList.Count >= 2 && CurrentPageOffset > 0;
}
}
public bool IsRightPageVisible
{
get
{
return PageWidthList.Count >= 2 && CurrentPageOffset + EffectivePageWidth(CurrentPage) <= TouchPanel.DisplayWidth;
}
}
// True if we're currently in a transition
public bool InFlip { get; private set; }
// Alpha value that animates from 0 to 1 during a spring. Will be 1 when not springing.
public float FlipAlpha { get; private set; }
// PageWidthList contains the width in pixels of each page. Pages can be added or removed at any time by
// changing this list.
public List<int> PageWidthList = new List<int>();
#endregion
public PageFlipTracker()
{
}
public int EffectivePageWidth(int page)
{
int displayWidth = TouchPanel.DisplayWidth - PreviewMargin;
return Math.Max(displayWidth, PageWidthList[page]);
}
// Update is called once per frame.
public void Update()
{
if (InFlip)
{
TimeSpan transitionClock = DateTime.Now - flipStartTime;
if (transitionClock >= FlipDuration)
{
EndFlip();
}
else
{
double f = transitionClock.TotalSeconds / FlipDuration.TotalSeconds;
f = Math.Max(f, 0.0); // this shouldn't happen, but just in case time goes crazy
FlipAlpha = (float)(1 - Math.Pow(1 - f, FlipExponent));
CurrentPageOffset = flipStartOffset * (1 - FlipAlpha);
}
}
}
public void HandleInput(InputState input)
{
foreach (GestureSample sample in input.Gestures)
{
switch (sample.GestureType)
{
case GestureType.HorizontalDrag:
CurrentPageOffset += sample.Delta.X;
flipStartOffset = CurrentPageOffset;
break;
case GestureType.DragComplete:
if (!InFlip)
{
if (CurrentPageOffset < -TouchPanel.DisplayWidth * DragToFlipTheshold)
{
// flip to next page
BeginFlip(1);
}
else if (CurrentPageOffset + TouchPanel.DisplayWidth * (1 - DragToFlipTheshold) > EffectivePageWidth(CurrentPage))
{
// flip to previous page
BeginFlip(-1);
}
else
{
// "snap back" effect when you drag a little and let go
BeginFlip(0);
}
}
break;
case GestureType.Flick:
// Only respond to mostly-horizontal flicks
if (Math.Abs(sample.Delta.X) > Math.Abs(sample.Delta.Y))
{
if (sample.Delta.X > 0)
{
BeginFlip(-1);
}
else
{
BeginFlip(1);
}
}
break;
}
}
}
void BeginFlip(int pageDelta)
{
if(PageWidthList.Count == 0)
return;
int pageFrom = CurrentPage;
CurrentPage = (CurrentPage + pageDelta + PageWidthList.Count) % PageWidthList.Count;
if (pageDelta > 0)
{
// going to next page; offset starts out large
CurrentPageOffset += EffectivePageWidth(pageFrom);
}
else if(pageDelta < 0)
{
// going to previous page; offset starts out negative
CurrentPageOffset -= EffectivePageWidth(CurrentPage);
}
InFlip = true;
FlipAlpha = 0;
flipStartOffset = CurrentPageOffset;
flipStartTime = DateTime.Now;
}
// FIXME: private
void EndFlip()
{
InFlip = false;
FlipAlpha = 1;
CurrentPageOffset = 0;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Newtonsoft.Json;
using osu.Framework.Bindables;
using osu.Framework.Lists;
using osu.Framework.Utils;
using osu.Game.Screens.Edit;
using osu.Game.Utils;
namespace osu.Game.Beatmaps.ControlPoints
{
[Serializable]
public class ControlPointInfo : IDeepCloneable<ControlPointInfo>
{
/// <summary>
/// All control points grouped by time.
/// </summary>
[JsonProperty]
public IBindableList<ControlPointGroup> Groups => groups;
private readonly BindableList<ControlPointGroup> groups = new BindableList<ControlPointGroup>();
/// <summary>
/// All timing points.
/// </summary>
[JsonProperty]
public IReadOnlyList<TimingControlPoint> TimingPoints => timingPoints;
private readonly SortedList<TimingControlPoint> timingPoints = new SortedList<TimingControlPoint>(Comparer<TimingControlPoint>.Default);
/// <summary>
/// All effect points.
/// </summary>
[JsonProperty]
public IReadOnlyList<EffectControlPoint> EffectPoints => effectPoints;
private readonly SortedList<EffectControlPoint> effectPoints = new SortedList<EffectControlPoint>(Comparer<EffectControlPoint>.Default);
/// <summary>
/// All control points, of all types.
/// </summary>
[JsonIgnore]
public IEnumerable<ControlPoint> AllControlPoints => Groups.SelectMany(g => g.ControlPoints).ToArray();
/// <summary>
/// Finds the effect control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the effect control point at.</param>
/// <returns>The effect control point.</returns>
[NotNull]
public EffectControlPoint EffectPointAt(double time) => BinarySearchWithFallback(EffectPoints, time, EffectControlPoint.DEFAULT);
/// <summary>
/// Finds the timing control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the timing control point at.</param>
/// <returns>The timing control point.</returns>
[NotNull]
public TimingControlPoint TimingPointAt(double time) => BinarySearchWithFallback(TimingPoints, time, TimingPoints.Count > 0 ? TimingPoints[0] : TimingControlPoint.DEFAULT);
/// <summary>
/// Finds the maximum BPM represented by any timing control point.
/// </summary>
[JsonIgnore]
public double BPMMaximum =>
60000 / (TimingPoints.OrderBy(c => c.BeatLength).FirstOrDefault() ?? TimingControlPoint.DEFAULT).BeatLength;
/// <summary>
/// Finds the minimum BPM represented by any timing control point.
/// </summary>
[JsonIgnore]
public double BPMMinimum =>
60000 / (TimingPoints.OrderByDescending(c => c.BeatLength).FirstOrDefault() ?? TimingControlPoint.DEFAULT).BeatLength;
/// <summary>
/// Remove all <see cref="ControlPointGroup"/>s and return to a pristine state.
/// </summary>
public virtual void Clear()
{
groups.Clear();
timingPoints.Clear();
effectPoints.Clear();
}
/// <summary>
/// Add a new <see cref="ControlPoint"/>. Note that the provided control point may not be added if the correct state is already present at the provided time.
/// </summary>
/// <param name="time">The time at which the control point should be added.</param>
/// <param name="controlPoint">The control point to add.</param>
/// <returns>Whether the control point was added.</returns>
public bool Add(double time, ControlPoint controlPoint)
{
if (CheckAlreadyExisting(time, controlPoint))
return false;
GroupAt(time, true).Add(controlPoint);
return true;
}
public ControlPointGroup GroupAt(double time, bool addIfNotExisting = false)
{
var newGroup = new ControlPointGroup(time);
int i = groups.BinarySearch(newGroup);
if (i >= 0)
return groups[i];
if (addIfNotExisting)
{
newGroup.ItemAdded += GroupItemAdded;
newGroup.ItemRemoved += GroupItemRemoved;
groups.Insert(~i, newGroup);
return newGroup;
}
return null;
}
public void RemoveGroup(ControlPointGroup group)
{
foreach (var item in group.ControlPoints.ToArray())
group.Remove(item);
group.ItemAdded -= GroupItemAdded;
group.ItemRemoved -= GroupItemRemoved;
groups.Remove(group);
}
/// <summary>
/// Returns the time on the given beat divisor closest to the given time.
/// </summary>
/// <param name="time">The time to find the closest snapped time to.</param>
/// <param name="beatDivisor">The beat divisor to snap to.</param>
/// <param name="referenceTime">An optional reference point to use for timing point lookup.</param>
public double GetClosestSnappedTime(double time, int beatDivisor, double? referenceTime = null)
{
var timingPoint = TimingPointAt(referenceTime ?? time);
return getClosestSnappedTime(timingPoint, time, beatDivisor);
}
/// <summary>
/// Returns the time on *ANY* valid beat divisor, favouring the divisor closest to the given time.
/// </summary>
/// <param name="time">The time to find the closest snapped time to.</param>
public double GetClosestSnappedTime(double time) => GetClosestSnappedTime(time, GetClosestBeatDivisor(time));
/// <summary>
/// Returns the beat snap divisor closest to the given time. If two are equally close, the smallest divisor is returned.
/// </summary>
/// <param name="time">The time to find the closest beat snap divisor to.</param>
/// <param name="referenceTime">An optional reference point to use for timing point lookup.</param>
public int GetClosestBeatDivisor(double time, double? referenceTime = null)
{
TimingControlPoint timingPoint = TimingPointAt(referenceTime ?? time);
int closestDivisor = 0;
double closestTime = double.MaxValue;
foreach (int divisor in BindableBeatDivisor.PREDEFINED_DIVISORS)
{
double distanceFromSnap = Math.Abs(time - getClosestSnappedTime(timingPoint, time, divisor));
if (Precision.DefinitelyBigger(closestTime, distanceFromSnap))
{
closestDivisor = divisor;
closestTime = distanceFromSnap;
}
}
return closestDivisor;
}
private static double getClosestSnappedTime(TimingControlPoint timingPoint, double time, int beatDivisor)
{
double beatLength = timingPoint.BeatLength / beatDivisor;
int beatLengths = (int)Math.Round((time - timingPoint.Time) / beatLength, MidpointRounding.AwayFromZero);
return timingPoint.Time + beatLengths * beatLength;
}
/// <summary>
/// Binary searches one of the control point lists to find the active control point at <paramref name="time"/>.
/// Includes logic for returning a specific point when no matching point is found.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="time">The time to find the control point at.</param>
/// <param name="fallback">The control point to use when <paramref name="time"/> is before any control points.</param>
/// <returns>The active control point at <paramref name="time"/>, or a fallback <see cref="ControlPoint"/> if none found.</returns>
protected T BinarySearchWithFallback<T>(IReadOnlyList<T> list, double time, T fallback)
where T : ControlPoint
{
return BinarySearch(list, time) ?? fallback;
}
/// <summary>
/// Binary searches one of the control point lists to find the active control point at <paramref name="time"/>.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="time">The time to find the control point at.</param>
/// <returns>The active control point at <paramref name="time"/>.</returns>
protected virtual T BinarySearch<T>(IReadOnlyList<T> list, double time)
where T : ControlPoint
{
if (list == null)
throw new ArgumentNullException(nameof(list));
if (list.Count == 0)
return null;
if (time < list[0].Time)
return null;
if (time >= list[^1].Time)
return list[^1];
int l = 0;
int r = list.Count - 2;
while (l <= r)
{
int pivot = l + ((r - l) >> 1);
if (list[pivot].Time < time)
l = pivot + 1;
else if (list[pivot].Time > time)
r = pivot - 1;
else
return list[pivot];
}
// l will be the first control point with Time > time, but we want the one before it
return list[l - 1];
}
/// <summary>
/// Check whether <paramref name="newPoint"/> should be added.
/// </summary>
/// <param name="time">The time to find the timing control point at.</param>
/// <param name="newPoint">A point to be added.</param>
/// <returns>Whether the new point should be added.</returns>
protected virtual bool CheckAlreadyExisting(double time, ControlPoint newPoint)
{
ControlPoint existing = null;
switch (newPoint)
{
case TimingControlPoint _:
// Timing points are a special case and need to be added regardless of fallback availability.
existing = BinarySearch(TimingPoints, time);
break;
case EffectControlPoint _:
existing = EffectPointAt(time);
break;
}
return newPoint?.IsRedundant(existing) == true;
}
protected virtual void GroupItemAdded(ControlPoint controlPoint)
{
switch (controlPoint)
{
case TimingControlPoint typed:
timingPoints.Add(typed);
break;
case EffectControlPoint typed:
effectPoints.Add(typed);
break;
default:
throw new ArgumentException($"A control point of unexpected type {controlPoint.GetType()} was added to this {nameof(ControlPointInfo)}");
}
}
protected virtual void GroupItemRemoved(ControlPoint controlPoint)
{
switch (controlPoint)
{
case TimingControlPoint typed:
timingPoints.Remove(typed);
break;
case EffectControlPoint typed:
effectPoints.Remove(typed);
break;
}
}
public ControlPointInfo DeepClone()
{
var controlPointInfo = (ControlPointInfo)Activator.CreateInstance(GetType());
foreach (var point in AllControlPoints)
controlPointInfo.Add(point.Time, point.DeepClone());
return controlPointInfo;
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="Item.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the Item class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Represents a generic item. Properties available on items are defined in the ItemSchema class.
/// </summary>
[Attachable]
[ServiceObjectDefinition(XmlElementNames.Item)]
public class Item : ServiceObject
{
private ItemAttachment parentAttachment;
/// <summary>
/// Initializes an unsaved local instance of <see cref="Item"/>. To bind to an existing item, use Item.Bind() instead.
/// </summary>
/// <param name="service">The ExchangeService object to which the item will be bound.</param>
internal Item(ExchangeService service)
: base(service)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Item"/> class.
/// </summary>
/// <param name="parentAttachment">The parent attachment.</param>
internal Item(ItemAttachment parentAttachment)
: this(parentAttachment.Service)
{
EwsUtilities.Assert(
parentAttachment != null,
"Item.ctor",
"parentAttachment is null");
this.parentAttachment = parentAttachment;
}
/// <summary>
/// Binds to an existing item, whatever its actual type is, and loads the specified set of properties.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="service">The service to use to bind to the item.</param>
/// <param name="id">The Id of the item to bind to.</param>
/// <param name="propertySet">The set of properties to load.</param>
/// <returns>An Item instance representing the item corresponding to the specified Id.</returns>
public static Item Bind(
ExchangeService service,
ItemId id,
PropertySet propertySet)
{
return service.BindToItem<Item>(id, propertySet);
}
/// <summary>
/// Binds to an existing item, whatever its actual type is, and loads its first class properties.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="service">The service to use to bind to the item.</param>
/// <param name="id">The Id of the item to bind to.</param>
/// <returns>An Item instance representing the item corresponding to the specified Id.</returns>
public static Item Bind(ExchangeService service, ItemId id)
{
return Item.Bind(
service,
id,
PropertySet.FirstClassProperties);
}
/// <summary>
/// Internal method to return the schema associated with this type of object.
/// </summary>
/// <returns>The schema associated with this type of object.</returns>
internal override ServiceObjectSchema GetSchema()
{
return ItemSchema.Instance;
}
/// <summary>
/// Gets the minimum required server version.
/// </summary>
/// <returns>Earliest Exchange version in which this service object type is supported.</returns>
internal override ExchangeVersion GetMinimumRequiredServerVersion()
{
return ExchangeVersion.Exchange2007_SP1;
}
/// <summary>
/// Throws exception if this is attachment.
/// </summary>
internal void ThrowIfThisIsAttachment()
{
if (this.IsAttachment)
{
throw new InvalidOperationException(Strings.OperationDoesNotSupportAttachments);
}
}
/// <summary>
/// The property definition for the Id of this object.
/// </summary>
/// <returns>A PropertyDefinition instance.</returns>
internal override PropertyDefinition GetIdPropertyDefinition()
{
return ItemSchema.Id;
}
/// <summary>
/// Loads the specified set of properties on the object.
/// </summary>
/// <param name="propertySet">The properties to load.</param>
internal override void InternalLoad(PropertySet propertySet)
{
this.ThrowIfThisIsNew();
this.ThrowIfThisIsAttachment();
this.Service.InternalLoadPropertiesForItems(
new Item[] { this },
propertySet,
ServiceErrorHandling.ThrowOnError);
}
/// <summary>
/// Deletes the object.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
/// <param name="sendCancellationsMode">Indicates whether meeting cancellation messages should be sent.</param>
/// <param name="affectedTaskOccurrences">Indicate which occurrence of a recurring task should be deleted.</param>
internal override void InternalDelete(
DeleteMode deleteMode,
SendCancellationsMode? sendCancellationsMode,
AffectedTaskOccurrence? affectedTaskOccurrences)
{
this.InternalDelete(deleteMode, sendCancellationsMode, affectedTaskOccurrences, false);
}
/// <summary>
/// Deletes the object.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
/// <param name="sendCancellationsMode">Indicates whether meeting cancellation messages should be sent.</param>
/// <param name="affectedTaskOccurrences">Indicate which occurrence of a recurring task should be deleted.</param>
/// <param name="suppressReadReceipts">Whether to suppress read receipts</param>
internal void InternalDelete(
DeleteMode deleteMode,
SendCancellationsMode? sendCancellationsMode,
AffectedTaskOccurrence? affectedTaskOccurrences,
bool suppressReadReceipts)
{
this.ThrowIfThisIsNew();
this.ThrowIfThisIsAttachment();
// If sendCancellationsMode is null, use the default value that's appropriate for item type.
if (!sendCancellationsMode.HasValue)
{
sendCancellationsMode = this.DefaultSendCancellationsMode;
}
// If affectedTaskOccurrences is null, use the default value that's appropriate for item type.
if (!affectedTaskOccurrences.HasValue)
{
affectedTaskOccurrences = this.DefaultAffectedTaskOccurrences;
}
this.Service.DeleteItem(
this.Id,
deleteMode,
sendCancellationsMode,
affectedTaskOccurrences,
suppressReadReceipts);
}
/// <summary>
/// Create item.
/// </summary>
/// <param name="parentFolderId">The parent folder id.</param>
/// <param name="messageDisposition">The message disposition.</param>
/// <param name="sendInvitationsMode">The send invitations mode.</param>
internal void InternalCreate(
FolderId parentFolderId,
MessageDisposition? messageDisposition,
SendInvitationsMode? sendInvitationsMode)
{
this.ThrowIfThisIsNotNew();
this.ThrowIfThisIsAttachment();
if (this.IsNew || this.IsDirty)
{
this.Service.CreateItem(
this,
parentFolderId,
messageDisposition,
sendInvitationsMode.HasValue ? sendInvitationsMode : this.DefaultSendInvitationsMode);
this.Attachments.Save();
}
}
/// <summary>
/// Update item.
/// </summary>
/// <param name="parentFolderId">The parent folder id.</param>
/// <param name="conflictResolutionMode">The conflict resolution mode.</param>
/// <param name="messageDisposition">The message disposition.</param>
/// <param name="sendInvitationsOrCancellationsMode">The send invitations or cancellations mode.</param>
/// <returns>Updated item.</returns>
internal Item InternalUpdate(
FolderId parentFolderId,
ConflictResolutionMode conflictResolutionMode,
MessageDisposition? messageDisposition,
SendInvitationsOrCancellationsMode? sendInvitationsOrCancellationsMode)
{
return this.InternalUpdate(parentFolderId, conflictResolutionMode, messageDisposition, sendInvitationsOrCancellationsMode, false);
}
/// <summary>
/// Update item.
/// </summary>
/// <param name="parentFolderId">The parent folder id.</param>
/// <param name="conflictResolutionMode">The conflict resolution mode.</param>
/// <param name="messageDisposition">The message disposition.</param>
/// <param name="sendInvitationsOrCancellationsMode">The send invitations or cancellations mode.</param>
/// <param name="suppressReadReceipts">Whether to suppress read receipts</param>
/// <returns>Updated item.</returns>
internal Item InternalUpdate(
FolderId parentFolderId,
ConflictResolutionMode conflictResolutionMode,
MessageDisposition? messageDisposition,
SendInvitationsOrCancellationsMode? sendInvitationsOrCancellationsMode,
bool suppressReadReceipts)
{
this.ThrowIfThisIsNew();
this.ThrowIfThisIsAttachment();
Item returnedItem = null;
if (this.IsDirty && this.PropertyBag.GetIsUpdateCallNecessary())
{
returnedItem = this.Service.UpdateItem(
this,
parentFolderId,
conflictResolutionMode,
messageDisposition,
sendInvitationsOrCancellationsMode.HasValue ? sendInvitationsOrCancellationsMode : this.DefaultSendInvitationsOrCancellationsMode,
suppressReadReceipts);
}
// Regardless of whether item is dirty or not, if it has unprocessed
// attachment changes, validate them and process now.
if (this.HasUnprocessedAttachmentChanges())
{
this.Attachments.Validate();
this.Attachments.Save();
}
return returnedItem;
}
/// <summary>
/// Gets a value indicating whether this instance has unprocessed attachment collection changes.
/// </summary>
internal bool HasUnprocessedAttachmentChanges()
{
return this.Attachments.HasUnprocessedChanges();
}
/// <summary>
/// Gets the parent attachment of this item.
/// </summary>
internal ItemAttachment ParentAttachment
{
get { return this.parentAttachment; }
}
/// <summary>
/// Gets Id of the root item for this item.
/// </summary>
internal ItemId RootItemId
{
get
{
if (this.IsAttachment && this.ParentAttachment.Owner != null)
{
return this.ParentAttachment.Owner.RootItemId;
}
else
{
return this.Id;
}
}
}
/// <summary>
/// Deletes the item. Calling this method results in a call to EWS.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
public void Delete(DeleteMode deleteMode)
{
this.Delete(deleteMode, false);
}
/// <summary>
/// Deletes the item. Calling this method results in a call to EWS.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
/// <param name="suppressReadReceipts">Whether to suppress read receipts</param>
public void Delete(DeleteMode deleteMode, bool suppressReadReceipts)
{
this.InternalDelete(deleteMode, null, null, suppressReadReceipts);
}
/// <summary>
/// Saves this item in a specific folder. Calling this method results in at least one call to EWS.
/// Mutliple calls to EWS might be made if attachments have been added.
/// </summary>
/// <param name="parentFolderId">The Id of the folder in which to save this item.</param>
public void Save(FolderId parentFolderId)
{
EwsUtilities.ValidateParam(parentFolderId, "parentFolderId");
this.InternalCreate(
parentFolderId,
MessageDisposition.SaveOnly,
null);
}
/// <summary>
/// Saves this item in a specific folder. Calling this method results in at least one call to EWS.
/// Mutliple calls to EWS might be made if attachments have been added.
/// </summary>
/// <param name="parentFolderName">The name of the folder in which to save this item.</param>
public void Save(WellKnownFolderName parentFolderName)
{
this.InternalCreate(
new FolderId(parentFolderName),
MessageDisposition.SaveOnly,
null);
}
/// <summary>
/// Saves this item in the default folder based on the item's type (for example, an e-mail message is saved to the Drafts folder).
/// Calling this method results in at least one call to EWS. Mutliple calls to EWS might be made if attachments have been added.
/// </summary>
public void Save()
{
this.InternalCreate(
null,
MessageDisposition.SaveOnly,
null);
}
/// <summary>
/// Applies the local changes that have been made to this item. Calling this method results in at least one call to EWS.
/// Mutliple calls to EWS might be made if attachments have been added or removed.
/// </summary>
/// <param name="conflictResolutionMode">The conflict resolution mode.</param>
public void Update(ConflictResolutionMode conflictResolutionMode)
{
this.Update(conflictResolutionMode, false);
}
/// <summary>
/// Applies the local changes that have been made to this item. Calling this method results in at least one call to EWS.
/// Mutliple calls to EWS might be made if attachments have been added or removed.
/// </summary>
/// <param name="conflictResolutionMode">The conflict resolution mode.</param>
/// <param name="suppressReadReceipts">Whether to suppress read receipts</param>
public void Update(ConflictResolutionMode conflictResolutionMode, bool suppressReadReceipts)
{
this.InternalUpdate(
null /* parentFolder */,
conflictResolutionMode,
MessageDisposition.SaveOnly,
null,
suppressReadReceipts);
}
/// <summary>
/// Creates a copy of this item in the specified folder. Calling this method results in a call to EWS.
/// <para>
/// Copy returns null if the copy operation is across two mailboxes or between a mailbox and a
/// public folder.
/// </para>
/// </summary>
/// <param name="destinationFolderId">The Id of the folder in which to create a copy of this item.</param>
/// <returns>The copy of this item.</returns>
public Item Copy(FolderId destinationFolderId)
{
this.ThrowIfThisIsNew();
this.ThrowIfThisIsAttachment();
EwsUtilities.ValidateParam(destinationFolderId, "destinationFolderId");
return this.Service.CopyItem(this.Id, destinationFolderId);
}
/// <summary>
/// Creates a copy of this item in the specified folder. Calling this method results in a call to EWS.
/// <para>
/// Copy returns null if the copy operation is across two mailboxes or between a mailbox and a
/// public folder.
/// </para>
/// </summary>
/// <param name="destinationFolderName">The name of the folder in which to create a copy of this item.</param>
/// <returns>The copy of this item.</returns>
public Item Copy(WellKnownFolderName destinationFolderName)
{
return this.Copy(new FolderId(destinationFolderName));
}
/// <summary>
/// Moves this item to a the specified folder. Calling this method results in a call to EWS.
/// <para>
/// Move returns null if the move operation is across two mailboxes or between a mailbox and a
/// public folder.
/// </para>
/// </summary>
/// <param name="destinationFolderId">The Id of the folder to which to move this item.</param>
/// <returns>The moved copy of this item.</returns>
public Item Move(FolderId destinationFolderId)
{
this.ThrowIfThisIsNew();
this.ThrowIfThisIsAttachment();
EwsUtilities.ValidateParam(destinationFolderId, "destinationFolderId");
return this.Service.MoveItem(this.Id, destinationFolderId);
}
/// <summary>
/// Moves this item to a the specified folder. Calling this method results in a call to EWS.
/// <para>
/// Move returns null if the move operation is across two mailboxes or between a mailbox and a
/// public folder.
/// </para>
/// </summary>
/// <param name="destinationFolderName">The name of the folder to which to move this item.</param>
/// <returns>The moved copy of this item.</returns>
public Item Move(WellKnownFolderName destinationFolderName)
{
return this.Move(new FolderId(destinationFolderName));
}
/// <summary>
/// Sets the extended property.
/// </summary>
/// <param name="extendedPropertyDefinition">The extended property definition.</param>
/// <param name="value">The value.</param>
public void SetExtendedProperty(ExtendedPropertyDefinition extendedPropertyDefinition, object value)
{
this.ExtendedProperties.SetExtendedProperty(extendedPropertyDefinition, value);
}
/// <summary>
/// Removes an extended property.
/// </summary>
/// <param name="extendedPropertyDefinition">The extended property definition.</param>
/// <returns>True if property was removed.</returns>
public bool RemoveExtendedProperty(ExtendedPropertyDefinition extendedPropertyDefinition)
{
return this.ExtendedProperties.RemoveExtendedProperty(extendedPropertyDefinition);
}
/// <summary>
/// Gets a list of extended properties defined on this object.
/// </summary>
/// <returns>Extended properties collection.</returns>
internal override ExtendedPropertyCollection GetExtendedProperties()
{
return this.ExtendedProperties;
}
/// <summary>
/// Validates this instance.
/// </summary>
internal override void Validate()
{
base.Validate();
this.Attachments.Validate();
// Flag parameter is only valid for Exchange2013 or higher
//
Flag flag;
if (this.TryGetProperty<Flag>(ItemSchema.Flag, out flag) && flag != null)
{
if (this.Service.RequestedServerVersion < ExchangeVersion.Exchange2013)
{
throw new ServiceVersionException(
string.Format(
Strings.ParameterIncompatibleWithRequestVersion,
"Flag",
ExchangeVersion.Exchange2013));
}
flag.Validate();
}
}
/// <summary>
/// Gets a value indicating whether a time zone SOAP header should be emitted in a CreateItem
/// or UpdateItem request so this item can be property saved or updated.
/// </summary>
/// <param name="isUpdateOperation">Indicates whether the operation being petrformed is an update operation.</param>
/// <returns>
/// <c>true</c> if a time zone SOAP header should be emitted; otherwise, <c>false</c>.
/// </returns>
internal override bool GetIsTimeZoneHeaderRequired(bool isUpdateOperation)
{
// Starting E14SP2, attachment will be sent along with CreateItem requests.
// if the attachment used to require the Timezone header, CreateItem request should do so too.
//
if (!isUpdateOperation &&
(this.Service.RequestedServerVersion >= ExchangeVersion.Exchange2010_SP2))
{
foreach (ItemAttachment itemAttachment in this.Attachments.OfType<ItemAttachment>())
{
if ((itemAttachment.Item != null) && itemAttachment.Item.GetIsTimeZoneHeaderRequired(false /* isUpdateOperation */))
{
return true;
}
}
}
return base.GetIsTimeZoneHeaderRequired(isUpdateOperation);
}
#region Properties
/// <summary>
/// Gets a value indicating whether the item is an attachment.
/// </summary>
public bool IsAttachment
{
get { return this.parentAttachment != null; }
}
/// <summary>
/// Gets a value indicating whether this object is a real store item, or if it's a local object
/// that has yet to be saved.
/// </summary>
public override bool IsNew
{
get
{
// Item attachments don't have an Id, need to check whether the
// parentAttachment is new or not.
if (this.IsAttachment)
{
return this.ParentAttachment.IsNew;
}
else
{
return base.IsNew;
}
}
}
/// <summary>
/// Gets the Id of this item.
/// </summary>
public ItemId Id
{
get { return (ItemId)this.PropertyBag[this.GetIdPropertyDefinition()]; }
}
/// <summary>
/// Get or sets the MIME content of this item.
/// </summary>
public MimeContent MimeContent
{
get { return (MimeContent)this.PropertyBag[ItemSchema.MimeContent]; }
set { this.PropertyBag[ItemSchema.MimeContent] = value; }
}
/// <summary>
/// Get or sets the MimeContentUTF8 of this item.
/// </summary>
public MimeContentUTF8 MimeContentUTF8
{
get { return (MimeContentUTF8)this.PropertyBag[ItemSchema.MimeContentUTF8]; }
set { this.PropertyBag[ItemSchema.MimeContentUTF8] = value; }
}
/// <summary>
/// Gets the Id of the parent folder of this item.
/// </summary>
public FolderId ParentFolderId
{
get { return (FolderId)this.PropertyBag[ItemSchema.ParentFolderId]; }
}
/// <summary>
/// Gets or sets the sensitivity of this item.
/// </summary>
public Sensitivity Sensitivity
{
get { return (Sensitivity)this.PropertyBag[ItemSchema.Sensitivity]; }
set { this.PropertyBag[ItemSchema.Sensitivity] = value; }
}
/// <summary>
/// Gets a list of the attachments to this item.
/// </summary>
public AttachmentCollection Attachments
{
get { return (AttachmentCollection)this.PropertyBag[ItemSchema.Attachments]; }
}
/// <summary>
/// Gets the time when this item was received.
/// </summary>
public DateTime DateTimeReceived
{
get { return (DateTime)this.PropertyBag[ItemSchema.DateTimeReceived]; }
}
/// <summary>
/// Gets the size of this item.
/// </summary>
public int Size
{
get { return (int)this.PropertyBag[ItemSchema.Size]; }
}
/// <summary>
/// Gets or sets the list of categories associated with this item.
/// </summary>
public StringList Categories
{
get { return (StringList)this.PropertyBag[ItemSchema.Categories]; }
set { this.PropertyBag[ItemSchema.Categories] = value; }
}
/// <summary>
/// Gets or sets the culture associated with this item.
/// </summary>
public string Culture
{
get { return (string)this.PropertyBag[ItemSchema.Culture]; }
set { this.PropertyBag[ItemSchema.Culture] = value; }
}
/// <summary>
/// Gets or sets the importance of this item.
/// </summary>
public Importance Importance
{
get { return (Importance)this.PropertyBag[ItemSchema.Importance]; }
set { this.PropertyBag[ItemSchema.Importance] = value; }
}
/// <summary>
/// Gets or sets the In-Reply-To reference of this item.
/// </summary>
public string InReplyTo
{
get { return (string)this.PropertyBag[ItemSchema.InReplyTo]; }
set { this.PropertyBag[ItemSchema.InReplyTo] = value; }
}
/// <summary>
/// Gets a value indicating whether the message has been submitted to be sent.
/// </summary>
public bool IsSubmitted
{
get { return (bool)this.PropertyBag[ItemSchema.IsSubmitted]; }
}
/// <summary>
/// Gets a value indicating whether this is an associated item.
/// </summary>
public bool IsAssociated
{
get { return (bool)this.PropertyBag[ItemSchema.IsAssociated]; }
}
/// <summary>
/// Gets a value indicating whether the item is is a draft. An item is a draft when it has not yet been sent.
/// </summary>
public bool IsDraft
{
get { return (bool)this.PropertyBag[ItemSchema.IsDraft]; }
}
/// <summary>
/// Gets a value indicating whether the item has been sent by the current authenticated user.
/// </summary>
public bool IsFromMe
{
get { return (bool)this.PropertyBag[ItemSchema.IsFromMe]; }
}
/// <summary>
/// Gets a value indicating whether the item is a resend of another item.
/// </summary>
public bool IsResend
{
get { return (bool)this.PropertyBag[ItemSchema.IsResend]; }
}
/// <summary>
/// Gets a value indicating whether the item has been modified since it was created.
/// </summary>
public bool IsUnmodified
{
get { return (bool)this.PropertyBag[ItemSchema.IsUnmodified]; }
}
/// <summary>
/// Gets a list of Internet headers for this item.
/// </summary>
public InternetMessageHeaderCollection InternetMessageHeaders
{
get { return (InternetMessageHeaderCollection)this.PropertyBag[ItemSchema.InternetMessageHeaders]; }
}
/// <summary>
/// Gets the date and time this item was sent.
/// </summary>
public DateTime DateTimeSent
{
get { return (DateTime)this.PropertyBag[ItemSchema.DateTimeSent]; }
}
/// <summary>
/// Gets the date and time this item was created.
/// </summary>
public DateTime DateTimeCreated
{
get { return (DateTime)this.PropertyBag[ItemSchema.DateTimeCreated]; }
}
/// <summary>
/// Gets a value indicating which response actions are allowed on this item. Examples of response actions are Reply and Forward.
/// </summary>
public ResponseActions AllowedResponseActions
{
get { return (ResponseActions)this.PropertyBag[ItemSchema.AllowedResponseActions]; }
}
/// <summary>
/// Gets or sets the date and time when the reminder is due for this item.
/// </summary>
public DateTime ReminderDueBy
{
get { return (DateTime)this.PropertyBag[ItemSchema.ReminderDueBy]; }
set { this.PropertyBag[ItemSchema.ReminderDueBy] = value; }
}
/// <summary>
/// Gets or sets a value indicating whether a reminder is set for this item.
/// </summary>
public bool IsReminderSet
{
get { return (bool)this.PropertyBag[ItemSchema.IsReminderSet]; }
set { this.PropertyBag[ItemSchema.IsReminderSet] = value; }
}
/// <summary>
/// Gets or sets the number of minutes before the start of this item when the reminder should be triggered.
/// </summary>
public int ReminderMinutesBeforeStart
{
get { return (int)this.PropertyBag[ItemSchema.ReminderMinutesBeforeStart]; }
set { this.PropertyBag[ItemSchema.ReminderMinutesBeforeStart] = value; }
}
/// <summary>
/// Gets a text summarizing the Cc receipients of this item.
/// </summary>
public string DisplayCc
{
get { return (string)this.PropertyBag[ItemSchema.DisplayCc]; }
}
/// <summary>
/// Gets a text summarizing the To recipients of this item.
/// </summary>
public string DisplayTo
{
get { return (string)this.PropertyBag[ItemSchema.DisplayTo]; }
}
/// <summary>
/// Gets a value indicating whether the item has attachments.
/// </summary>
public bool HasAttachments
{
get { return (bool)this.PropertyBag[ItemSchema.HasAttachments]; }
}
/// <summary>
/// Gets or sets the body of this item.
/// </summary>
public MessageBody Body
{
get { return (MessageBody)this.PropertyBag[ItemSchema.Body]; }
set { this.PropertyBag[ItemSchema.Body] = value; }
}
/// <summary>
/// Gets or sets the custom class name of this item.
/// </summary>
public string ItemClass
{
get { return (string)this.PropertyBag[ItemSchema.ItemClass]; }
set { this.PropertyBag[ItemSchema.ItemClass] = value; }
}
/// <summary>
/// Gets or sets the subject of this item.
/// </summary>
public string Subject
{
get { return (string)this.PropertyBag[ItemSchema.Subject]; }
set { this.SetSubject(value); }
}
/// <summary>
/// Gets the query string that should be appended to the Exchange Web client URL to open this item using the appropriate read form in a web browser.
/// </summary>
public string WebClientReadFormQueryString
{
get { return (string)this.PropertyBag[ItemSchema.WebClientReadFormQueryString]; }
}
/// <summary>
/// Gets the query string that should be appended to the Exchange Web client URL to open this item using the appropriate edit form in a web browser.
/// </summary>
public string WebClientEditFormQueryString
{
get { return (string)this.PropertyBag[ItemSchema.WebClientEditFormQueryString]; }
}
/// <summary>
/// Gets a list of extended properties defined on this item.
/// </summary>
public ExtendedPropertyCollection ExtendedProperties
{
get { return (ExtendedPropertyCollection)this.PropertyBag[ServiceObjectSchema.ExtendedProperties]; }
}
/// <summary>
/// Gets a value indicating the effective rights the current authenticated user has on this item.
/// </summary>
public EffectiveRights EffectiveRights
{
get { return (EffectiveRights)this.PropertyBag[ItemSchema.EffectiveRights]; }
}
/// <summary>
/// Gets the name of the user who last modified this item.
/// </summary>
public string LastModifiedName
{
get { return (string)this.PropertyBag[ItemSchema.LastModifiedName]; }
}
/// <summary>
/// Gets the date and time this item was last modified.
/// </summary>
public DateTime LastModifiedTime
{
get { return (DateTime)this.PropertyBag[ItemSchema.LastModifiedTime]; }
}
/// <summary>
/// Gets the Id of the conversation this item is part of.
/// </summary>
public ConversationId ConversationId
{
get { return (ConversationId)this.PropertyBag[ItemSchema.ConversationId]; }
}
/// <summary>
/// Gets the body part that is unique to the conversation this item is part of.
/// </summary>
public UniqueBody UniqueBody
{
get { return (UniqueBody)this.PropertyBag[ItemSchema.UniqueBody]; }
}
/// <summary>
/// Gets the store entry id.
/// </summary>
public byte[] StoreEntryId
{
get { return (byte[])this.PropertyBag[ItemSchema.StoreEntryId]; }
}
/// <summary>
/// Gets the item instance key.
/// </summary>
public byte[] InstanceKey
{
get { return (byte[])this.PropertyBag[ItemSchema.InstanceKey]; }
}
/// <summary>
/// Get or set the Flag value for this item.
/// </summary>
public Flag Flag
{
get { return (Flag)this.PropertyBag[ItemSchema.Flag]; }
set { this.PropertyBag[ItemSchema.Flag] = value; }
}
/// <summary>
/// Gets the normalized body of the item.
/// </summary>
public NormalizedBody NormalizedBody
{
get { return (NormalizedBody)this.PropertyBag[ItemSchema.NormalizedBody]; }
}
/// <summary>
/// Gets the EntityExtractionResult of the item.
/// </summary>
public EntityExtractionResult EntityExtractionResult
{
get { return (EntityExtractionResult)this.PropertyBag[ItemSchema.EntityExtractionResult]; }
}
/// <summary>
/// Gets or sets the policy tag.
/// </summary>
public PolicyTag PolicyTag
{
get { return (PolicyTag)this.PropertyBag[ItemSchema.PolicyTag]; }
set { this.PropertyBag[ItemSchema.PolicyTag] = value; }
}
/// <summary>
/// Gets or sets the archive tag.
/// </summary>
public ArchiveTag ArchiveTag
{
get { return (ArchiveTag)this.PropertyBag[ItemSchema.ArchiveTag]; }
set { this.PropertyBag[ItemSchema.ArchiveTag] = value; }
}
/// <summary>
/// Gets the retention date.
/// </summary>
public DateTime? RetentionDate
{
get { return (DateTime?)this.PropertyBag[ItemSchema.RetentionDate]; }
}
/// <summary>
/// Gets the item Preview.
/// </summary>
public string Preview
{
get { return (string)this.PropertyBag[ItemSchema.Preview]; }
}
/// <summary>
/// Gets the text body of the item.
/// </summary>
public TextBody TextBody
{
get { return (TextBody)this.PropertyBag[ItemSchema.TextBody]; }
}
/// <summary>
/// Gets the icon index.
/// </summary>
public IconIndex IconIndex
{
get { return (IconIndex)this.PropertyBag[ItemSchema.IconIndex]; }
}
/// <summary>
/// Gets the default setting for how to treat affected task occurrences on Delete.
/// Subclasses will override this for different default behavior.
/// </summary>
internal virtual AffectedTaskOccurrence? DefaultAffectedTaskOccurrences
{
get { return null; }
}
/// <summary>
/// Gets the default setting for sending cancellations on Delete.
/// Subclasses will override this for different default behavior.
/// </summary>
internal virtual SendCancellationsMode? DefaultSendCancellationsMode
{
get { return null; }
}
/// <summary>
/// Gets the default settings for sending invitations on Save.
/// Subclasses will override this for different default behavior.
/// </summary>
internal virtual SendInvitationsMode? DefaultSendInvitationsMode
{
get { return null; }
}
/// <summary>
/// Gets the default settings for sending invitations or cancellations on Update.
/// Subclasses will override this for different default behavior.
/// </summary>
internal virtual SendInvitationsOrCancellationsMode? DefaultSendInvitationsOrCancellationsMode
{
get { return null; }
}
/// <summary>
/// Sets the subject.
/// </summary>
/// <param name="subject">The subject.</param>
internal virtual void SetSubject(string subject)
{
this.PropertyBag[ItemSchema.Subject] = subject;
}
#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.
/*============================================================
**
**
**
**
**
** Purpose: Enumerates files and dirs
**
===========================================================*/
using System.Collections;
using System.Collections.Generic;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Threading;
namespace System.IO
{
// Overview:
// The key methods instantiate FileSystemEnumerableIterators. These compose the iterator with search result
// handlers that instantiate the FileInfo, DirectoryInfo, String, etc. The handlers then perform any
// additional required permission demands.
internal static class FileSystemEnumerableFactory
{
internal static IEnumerable<String> CreateFileNameIterator(String path, String originalUserPath, String searchPattern,
bool includeFiles, bool includeDirs, SearchOption searchOption, bool checkHost)
{
Debug.Assert(path != null);
Debug.Assert(originalUserPath != null);
Debug.Assert(searchPattern != null);
SearchResultHandler<String> handler = new StringResultHandler(includeFiles, includeDirs);
return new FileSystemEnumerableIterator<String>(path, originalUserPath, searchPattern, searchOption, handler, checkHost);
}
}
// Abstract Iterator, borrowed from Linq. Used in anticipation of need for similar enumerables
// in the future
abstract internal class Iterator<TSource> : IEnumerable<TSource>, IEnumerator<TSource>
{
int threadId;
internal int state;
internal TSource current;
public Iterator()
{
threadId = Thread.CurrentThread.ManagedThreadId;
}
public TSource Current
{
get { return current; }
}
protected abstract Iterator<TSource> Clone();
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
current = default(TSource);
state = -1;
}
public IEnumerator<TSource> GetEnumerator()
{
if (threadId == Thread.CurrentThread.ManagedThreadId && state == 0)
{
state = 1;
return this;
}
Iterator<TSource> duplicate = Clone();
duplicate.state = 1;
return duplicate;
}
public abstract bool MoveNext();
object IEnumerator.Current
{
get { return Current; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
}
// Overview:
// Enumerates file system entries matching the search parameters. For recursive searches this
// searches through all the sub dirs and executes the search criteria against every dir.
//
// Generic implementation:
// FileSystemEnumerableIterator is generic. When it gets a WIN32_FIND_DATA, it calls the
// result handler to create an instance of the generic type.
//
// Usage:
// Use FileSystemEnumerableFactory to obtain FSEnumerables that can enumerate file system
// entries as String path names, FileInfos, DirectoryInfos, or FileSystemInfos.
//
// Security:
// For all the dirs/files returned, demands path discovery permission for their parent folders
internal class FileSystemEnumerableIterator<TSource> : Iterator<TSource>
{
private const int STATE_INIT = 1;
private const int STATE_SEARCH_NEXT_DIR = 2;
private const int STATE_FIND_NEXT_FILE = 3;
private const int STATE_FINISH = 4;
private SearchResultHandler<TSource> _resultHandler;
private List<Directory.SearchData> searchStack;
private Directory.SearchData searchData;
private String searchCriteria;
SafeFindHandle _hnd = null;
// empty means we know in advance that we won't find any search results, which can happen if:
// 1. we don't have a search pattern
// 2. we're enumerating only the top directory and found no matches during the first call
// This flag allows us to return early for these cases. We can't know this in advance for
// SearchOption.AllDirectories because we do a "*" search for subdirs and then use the
// searchPattern at each directory level.
bool empty;
private String userPath;
private SearchOption searchOption;
private String fullPath;
private String normalizedSearchPath;
#if !PLATFORM_UNIX
private int _oldMode;
private bool _setBackOldMode;
#endif
internal FileSystemEnumerableIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler<TSource> resultHandler, bool checkHost)
{
Debug.Assert(path != null);
Debug.Assert(originalUserPath != null);
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Debug.Assert(resultHandler != null);
#if !PLATFORM_UNIX
_setBackOldMode = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out _oldMode);
#endif
searchStack = new List<Directory.SearchData>();
String normalizedSearchPattern = NormalizeSearchPattern(searchPattern);
if (normalizedSearchPattern.Length == 0)
{
empty = true;
}
else
{
_resultHandler = resultHandler;
this.searchOption = searchOption;
fullPath = Path.GetFullPath(path);
String fullSearchString = GetFullSearchString(fullPath, normalizedSearchPattern);
normalizedSearchPath = Path.GetDirectoryName(fullSearchString);
// normalize search criteria
searchCriteria = GetNormalizedSearchCriteria(fullSearchString, normalizedSearchPath);
// fix up user path
String searchPatternDirName = Path.GetDirectoryName(normalizedSearchPattern);
String userPathTemp = originalUserPath;
if (searchPatternDirName != null && searchPatternDirName.Length != 0)
{
userPathTemp = Path.Combine(userPathTemp, searchPatternDirName);
}
this.userPath = userPathTemp;
searchData = new Directory.SearchData(normalizedSearchPath, this.userPath, searchOption);
CommonInit();
}
}
private void CommonInit()
{
Debug.Assert(searchCriteria != null && searchData != null, "searchCriteria and searchData should be initialized");
// Execute searchCriteria against the current directory
String searchPath = Path.Combine(searchData.fullPath, searchCriteria);
Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
// Open a Find handle
_hnd = Win32Native.FindFirstFile(searchPath, data);
if (_hnd.IsInvalid)
{
int hr = Marshal.GetLastWin32Error();
if (hr != Win32Native.ERROR_FILE_NOT_FOUND && hr != Win32Native.ERROR_NO_MORE_FILES)
{
HandleError(hr, searchData.fullPath);
}
else
{
// flag this as empty only if we're searching just top directory
// Used in fast path for top directory only
empty = searchData.searchOption == SearchOption.TopDirectoryOnly;
}
}
// fast path for TopDirectoryOnly. If we have a result, go ahead and set it to
// current. If empty, dispose handle.
if (searchData.searchOption == SearchOption.TopDirectoryOnly)
{
if (empty)
{
_hnd.Dispose();
}
else
{
SearchResult searchResult = CreateSearchResult(searchData, data);
if (_resultHandler.IsResultIncluded(searchResult))
{
current = _resultHandler.CreateObject(searchResult);
}
}
}
// for AllDirectories, we first recurse into dirs, so cleanup and add searchData
// to the stack
else
{
_hnd.Dispose();
searchStack.Add(searchData);
}
}
private FileSystemEnumerableIterator(String fullPath, String normalizedSearchPath, String searchCriteria, String userPath, SearchOption searchOption, SearchResultHandler<TSource> resultHandler)
{
this.fullPath = fullPath;
this.normalizedSearchPath = normalizedSearchPath;
this.searchCriteria = searchCriteria;
this._resultHandler = resultHandler;
this.userPath = userPath;
this.searchOption = searchOption;
searchStack = new List<Directory.SearchData>();
if (searchCriteria != null)
{
searchData = new Directory.SearchData(normalizedSearchPath, userPath, searchOption);
CommonInit();
}
else
{
empty = true;
}
}
protected override Iterator<TSource> Clone()
{
return new FileSystemEnumerableIterator<TSource>(fullPath, normalizedSearchPath, searchCriteria, userPath, searchOption, _resultHandler);
}
protected override void Dispose(bool disposing)
{
try
{
if (_hnd != null)
{
_hnd.Dispose();
}
}
finally
{
#if !PLATFORM_UNIX
if (_setBackOldMode)
{
uint _ignore;
Interop.Kernel32.SetThreadErrorMode(_oldMode, out _ignore);
}
#endif
base.Dispose(disposing);
}
}
public override bool MoveNext()
{
Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
switch (state)
{
case STATE_INIT:
{
if (empty)
{
state = STATE_FINISH;
goto case STATE_FINISH;
}
if (searchData.searchOption == SearchOption.TopDirectoryOnly)
{
state = STATE_FIND_NEXT_FILE;
if (current != null)
{
return true;
}
else
{
goto case STATE_FIND_NEXT_FILE;
}
}
else
{
state = STATE_SEARCH_NEXT_DIR;
goto case STATE_SEARCH_NEXT_DIR;
}
}
case STATE_SEARCH_NEXT_DIR:
{
Debug.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly");
// Traverse directory structure. We need to get '*'
while (searchStack.Count > 0)
{
searchData = searchStack[0];
Debug.Assert((searchData.fullPath != null), "fullpath can't be null!");
searchStack.RemoveAt(0);
// Traverse the subdirs
AddSearchableDirsToStack(searchData);
// Execute searchCriteria against the current directory
String searchPath = Path.Combine(searchData.fullPath, searchCriteria);
// Open a Find handle
_hnd = Win32Native.FindFirstFile(searchPath, data);
if (_hnd.IsInvalid)
{
int hr = Marshal.GetLastWin32Error();
if (hr == Win32Native.ERROR_FILE_NOT_FOUND || hr == Win32Native.ERROR_NO_MORE_FILES || hr == Win32Native.ERROR_PATH_NOT_FOUND)
continue;
_hnd.Dispose();
HandleError(hr, searchData.fullPath);
}
state = STATE_FIND_NEXT_FILE;
SearchResult searchResult = CreateSearchResult(searchData, data);
if (_resultHandler.IsResultIncluded(searchResult))
{
current = _resultHandler.CreateObject(searchResult);
return true;
}
else
{
goto case STATE_FIND_NEXT_FILE;
}
}
state = STATE_FINISH;
goto case STATE_FINISH;
}
case STATE_FIND_NEXT_FILE:
{
if (searchData != null && _hnd != null)
{
// Keep asking for more matching files/dirs, add it to the list
while (Win32Native.FindNextFile(_hnd, data))
{
SearchResult searchResult = CreateSearchResult(searchData, data);
if (_resultHandler.IsResultIncluded(searchResult))
{
current = _resultHandler.CreateObject(searchResult);
return true;
}
}
// Make sure we quit with a sensible error.
int hr = Marshal.GetLastWin32Error();
if (_hnd != null)
_hnd.Dispose();
// ERROR_FILE_NOT_FOUND is valid here because if the top level
// dir doen't contain any subdirs and matching files then
// we will get here with this errorcode from the searchStack walk
if ((hr != 0) && (hr != Win32Native.ERROR_NO_MORE_FILES)
&& (hr != Win32Native.ERROR_FILE_NOT_FOUND))
{
HandleError(hr, searchData.fullPath);
}
}
if (searchData.searchOption == SearchOption.TopDirectoryOnly)
{
state = STATE_FINISH;
goto case STATE_FINISH;
}
else
{
state = STATE_SEARCH_NEXT_DIR;
goto case STATE_SEARCH_NEXT_DIR;
}
}
case STATE_FINISH:
{
Dispose();
break;
}
}
return false;
}
private SearchResult CreateSearchResult(Directory.SearchData localSearchData, Win32Native.WIN32_FIND_DATA findData)
{
String userPathFinal = Path.Combine(localSearchData.userPath, findData.cFileName);
String fullPathFinal = Path.Combine(localSearchData.fullPath, findData.cFileName);
return new SearchResult(fullPathFinal, userPathFinal, findData);
}
private void HandleError(int hr, String path)
{
Dispose();
throw Win32Marshal.GetExceptionForWin32Error(hr, path);
}
private void AddSearchableDirsToStack(Directory.SearchData localSearchData)
{
Debug.Assert(localSearchData != null);
String searchPath = Path.Combine(localSearchData.fullPath, "*");
SafeFindHandle hnd = null;
Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
try
{
// Get all files and dirs
hnd = Win32Native.FindFirstFile(searchPath, data);
if (hnd.IsInvalid)
{
int hr = Marshal.GetLastWin32Error();
// This could happen if the dir doesn't contain any files.
// Continue with the recursive search though, eventually
// searchStack will become empty
if (hr == Win32Native.ERROR_FILE_NOT_FOUND || hr == Win32Native.ERROR_NO_MORE_FILES || hr == Win32Native.ERROR_PATH_NOT_FOUND)
return;
HandleError(hr, localSearchData.fullPath);
}
// Add subdirs to searchStack. Exempt ReparsePoints as appropriate
int incr = 0;
do
{
if (FileSystemEnumerableHelpers.IsDir(data))
{
String tempFullPath = Path.Combine(localSearchData.fullPath, data.cFileName);
String tempUserPath = Path.Combine(localSearchData.userPath, data.cFileName);
SearchOption option = localSearchData.searchOption;
#if EXCLUDE_REPARSEPOINTS
// Traverse reparse points depending on the searchoption specified
if ((searchDataSubDir.searchOption == SearchOption.AllDirectories) && (0 != (data.dwFileAttributes & Win32Native.FILE_ATTRIBUTE_REPARSE_POINT)))
option = SearchOption.TopDirectoryOnly;
#endif
// Setup search data for the sub directory and push it into the stack
Directory.SearchData searchDataSubDir = new Directory.SearchData(tempFullPath, tempUserPath, option);
searchStack.Insert(incr++, searchDataSubDir);
}
} while (Win32Native.FindNextFile(hnd, data));
// We don't care about errors here
}
finally
{
if (hnd != null)
hnd.Dispose();
}
}
private static String NormalizeSearchPattern(String searchPattern)
{
Debug.Assert(searchPattern != null);
// Make this corner case more useful, like dir
if (searchPattern.Equals("."))
{
return "*";
}
PathInternal.CheckSearchPattern(searchPattern);
return searchPattern;
}
private static String GetNormalizedSearchCriteria(String fullSearchString, String fullPathMod)
{
Debug.Assert(fullSearchString != null);
Debug.Assert(fullPathMod != null);
Debug.Assert(fullSearchString.Length >= fullPathMod.Length);
String searchCriteria = null;
char lastChar = fullPathMod[fullPathMod.Length - 1];
if (PathInternal.IsDirectorySeparator(lastChar))
{
// Can happen if the path is C:\temp, in which case GetDirectoryName would return C:\
searchCriteria = fullSearchString.Substring(fullPathMod.Length);
}
else
{
Debug.Assert(fullSearchString.Length > fullPathMod.Length);
searchCriteria = fullSearchString.Substring(fullPathMod.Length + 1);
}
return searchCriteria;
}
private static String GetFullSearchString(String fullPath, String searchPattern)
{
Debug.Assert(fullPath != null);
Debug.Assert(searchPattern != null);
String tempStr = Path.Combine(fullPath, searchPattern);
// If path ends in a trailing slash (\), append a * or we'll get a "Cannot find the file specified" exception
char lastChar = tempStr[tempStr.Length - 1];
if (PathInternal.IsDirectorySeparator(lastChar) || lastChar == Path.VolumeSeparatorChar)
{
tempStr = tempStr + '*';
}
return tempStr;
}
}
internal abstract class SearchResultHandler<TSource>
{
internal abstract bool IsResultIncluded(SearchResult result);
internal abstract TSource CreateObject(SearchResult result);
}
internal class StringResultHandler : SearchResultHandler<String>
{
private bool _includeFiles;
private bool _includeDirs;
internal StringResultHandler(bool includeFiles, bool includeDirs)
{
_includeFiles = includeFiles;
_includeDirs = includeDirs;
}
internal override bool IsResultIncluded(SearchResult result)
{
bool includeFile = _includeFiles && FileSystemEnumerableHelpers.IsFile(result.FindData);
bool includeDir = _includeDirs && FileSystemEnumerableHelpers.IsDir(result.FindData);
Debug.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
return (includeFile || includeDir);
}
internal override String CreateObject(SearchResult result)
{
return result.UserPath;
}
}
internal sealed class SearchResult
{
private String fullPath; // fully-qualifed path
private String userPath; // user-specified path
private Win32Native.WIN32_FIND_DATA findData;
internal SearchResult(String fullPath, String userPath, Win32Native.WIN32_FIND_DATA findData)
{
Debug.Assert(fullPath != null);
Debug.Assert(userPath != null);
this.fullPath = fullPath;
this.userPath = userPath;
this.findData = findData;
}
internal String FullPath
{
get { return fullPath; }
}
internal String UserPath
{
get { return userPath; }
}
internal Win32Native.WIN32_FIND_DATA FindData
{
get { return findData; }
}
}
internal static class FileSystemEnumerableHelpers
{
internal static bool IsDir(Win32Native.WIN32_FIND_DATA data)
{
// Don't add "." nor ".."
return (0 != (data.dwFileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY))
&& !data.cFileName.Equals(".") && !data.cFileName.Equals("..");
}
internal static bool IsFile(Win32Native.WIN32_FIND_DATA data)
{
return 0 == (data.dwFileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Invio.Xunit;
using Xunit;
namespace Invio.Immutable {
[UnitTest]
public sealed class DefaultStringFormatterTests {
[Fact]
public void Format_Null() {
// Arrange
var formatter = new DefaultStringFormatter();
// Act
var output = formatter.Format(null);
// Assert
Assert.Equal("null", output);
}
public static IEnumerable<object[]> Format_DateTime_MemberData {
get {
yield return new object[] {
new DateTime(2013, 5, 11, 20, 22, 33, DateTimeKind.Utc),
@"^2013-05-11T20:22:33.0000000Z$"
};
yield return new object[] {
new DateTime(2015, 5, 27, 5, 13, 16, DateTimeKind.Local),
@"^2015-05-27T05:13:16.0000000[-+]\d{2}:\d{2}$"
};
yield return new object[] {
new DateTime(1984, 2, 2, 0, 59, 59, 222, DateTimeKind.Utc),
@"^1984-02-02T00:59:59.2220000Z$"
};
yield return new object[] {
new DateTime(1983, 12, 03, 11, 41, 22, 432, DateTimeKind.Unspecified),
@"^1983-12-03T11:41:22.4320000$"
};
}
}
[Theory]
[MemberData(nameof(Format_DateTime_MemberData))]
public void Format_DateTime(DateTime value, String expected) {
// Arrange
var formatter = new DefaultStringFormatter();
// Act
var actual = formatter.Format(value);
// Assert
Assert.Matches(expected, actual);
}
public static IEnumerable<object[]> Format_NullableDateTime_MemberData {
get {
yield return new object[] {
new DateTime(2013, 5, 11, 20, 22, 33, DateTimeKind.Utc),
@"^2013-05-11T20:22:33.0000000Z$"
};
yield return new object[] {
new DateTime(2015, 5, 27, 5, 13, 16, DateTimeKind.Local),
@"^2015-05-27T05:13:16.0000000[-+]\d{2}:\d{2}$"
};
yield return new object[] {
new DateTime(1984, 2, 2, 0, 59, 59, 222, DateTimeKind.Utc),
@"^1984-02-02T00:59:59.2220000Z$"
};
yield return new object[] {
new DateTime(1983, 12, 03, 11, 41, 22, 432, DateTimeKind.Unspecified),
@"^1983-12-03T11:41:22.4320000$"
};
yield return new object[] { null, "^null$" };
}
}
[Theory]
[MemberData(nameof(Format_NullableDateTime_MemberData))]
public void Format_NullableDateTime(DateTime? value, String expected) {
// Arrange
var formatter = new DefaultStringFormatter();
// Act
var actual = formatter.Format(value);
// Assert
Assert.Matches(expected, actual);
}
[Theory]
[InlineData("foo")]
[InlineData("BAR")]
[InlineData("")]
[InlineData(" ")]
public void Format_String(String value) {
// Arrange
var formatter = new DefaultStringFormatter();
// Act
var output = formatter.Format(value);
// Assert
Assert.Equal(String.Concat("\"", value, "\""), output);
}
public static IEnumerable<object[]> Format_Enums_MemberData {
get {
yield return new object[] { DateTimeKind.Utc, "Utc" };
yield return new object[] { (DateTimeKind)10, "10" };
yield return new object[] {
BindingFlags.Public | BindingFlags.Instance,
"Instance, Public"
};
yield return new object[] { (BindingFlags)Int32.MaxValue, "2147483647" };
}
}
[Theory]
[MemberData(nameof(Format_Enums_MemberData))]
public void Format_Enums<TEnum>(TEnum value, String expected) {
// Arrange
var formatter = new DefaultStringFormatter();
// Act
var actual = formatter.Format(value);
// Assert
Assert.Equal(expected, actual);
}
public static IEnumerable<object[]> Format_IEnumerable_Empty_MemberData {
get {
yield return new object[] { ImmutableHashSet<Guid>.Empty };
yield return new object[] { new object[0] };
yield return new object[] { new List<string>() };
}
}
[Theory]
[MemberData(nameof(Format_IEnumerable_Empty_MemberData))]
public void Format_IEnumerable_Empty(IEnumerable value) {
// Arrange
var formatter = new DefaultStringFormatter();
// Act
var output = formatter.Format(value);
// Assert
Assert.Equal("[]", output);
}
public static IEnumerable<object[]> Format_IEnumerable_Many_MemberData { get; } =
ImmutableList<IEnumerable>
.Empty
.Add(ImmutableList.Create(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()))
.Add(new string[] { null, "FOO", "bar", "biz", "gah", String.Empty })
.Add(ImmutableList.Create<Guid?>(Guid.NewGuid(), null, Guid.NewGuid()))
.Add(new object[] { "foo", Guid.NewGuid(), null, 35m, DateTime.UtcNow })
.Select(enumerable => new object[] { enumerable })
.ToImmutableList();
[Theory]
[MemberData(nameof(Format_IEnumerable_Many_MemberData))]
public void Format_IEnumerable_Many(IEnumerable value) {
// Arrange
var formatter = new DefaultStringFormatter();
// Act
var output = formatter.Format(value);
// Assert
Assert.StartsWith("[ ", output);
Assert.Contains(", ", output);
Assert.EndsWith(" ]", output);
foreach (var item in value) {
Assert.Contains(formatter.Format(item), output);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Tests
{
public static class StackTests
{
[Fact]
public static void Ctor_Empty()
{
var stack = new Stack();
Assert.Equal(0, stack.Count);
Assert.False(stack.IsSynchronized);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void Ctor_Int(int initialCapacity)
{
var stack = new Stack(initialCapacity);
Assert.Equal(0, stack.Count);
Assert.False(stack.IsSynchronized);
}
[Fact]
public static void Ctor_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCapacity", () => new Stack(-1)); // InitialCapacity < 0
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
[InlineData(10000)]
public static void Ctor_ICollection(int count)
{
var array = new object[count];
for (int i = 0; i < count; i++)
{
array[i] = i;
}
var stack = new Stack(array);
Assert.Equal(count, stack.Count);
Assert.False(stack.IsSynchronized);
for (int i = 0; i < count; i++)
{
Assert.Equal(count - i - 1, stack.Pop());
}
}
[Fact]
public static void Ctor_ICollection_NullCollection_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("col", () => new Stack(null)); // Collection is null
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new Stack());
var stack = new Stack();
stack.Push("a");
stack.Push(1);
stack.Push("b");
stack.Push(2);
DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(stack);
PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items");
object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance);
Assert.Equal(stack.ToArray(), items);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute_NullStack_ThrowsArgumentNullException()
{
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Stack), null);
}
catch (TargetInvocationException ex)
{
threwNull = ex.InnerException is ArgumentNullException;
}
Assert.True(threwNull);
}
[Fact]
public static void Clear()
{
Stack stack1 = Helpers.CreateIntStack(100);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
stack2.Clear();
Assert.Equal(0, stack2.Count);
stack2.Clear();
Assert.Equal(0, stack2.Count);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Clone(int count)
{
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
Stack stackClone = (Stack)stack2.Clone();
Assert.Equal(stack2.Count, stackClone.Count);
Assert.Equal(stack2.IsSynchronized, stackClone.IsSynchronized);
for (int i = 0; i < stackClone.Count; i++)
{
Assert.Equal(stack2.Pop(), stackClone.Pop());
}
});
}
[Fact]
public static void Clone_IsShallowCopy()
{
var stack1 = new Stack();
stack1.Push(new Foo(10));
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
Stack stackClone = (Stack)stack2.Clone();
Foo a1 = (Foo)stack2.Pop();
a1.IntValue = 50;
Foo a2 = (Foo)stackClone.Pop();
Assert.Equal(50, a1.IntValue);
});
}
[Fact]
public static void Contains()
{
Stack stack1 = Helpers.CreateIntStack(100);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
for (int i = 0; i < stack2.Count; i++)
{
Assert.True(stack2.Contains(i));
}
Assert.False(stack2.Contains(101));
Assert.False(stack2.Contains("hello"));
Assert.False(stack2.Contains(null));
stack2.Push(null);
Assert.True(stack2.Contains(null));
Assert.False(stack2.Contains(-1)); // We have a null item in the list, so the algorithm may use a different branch
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(1000, 0)]
[InlineData(10, 5)]
[InlineData(100, 50)]
[InlineData(1000, 500)]
public static void CopyTo_ObjectArray(int count, int index)
{
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
object[] oArray = new object[index + count];
stack2.CopyTo(oArray, index);
Assert.Equal(index + count, oArray.Length);
for (int i = index; i < count; i++)
{
Assert.Equal(stack2.Pop(), oArray[i]);
}
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(1000, 0)]
[InlineData(10, 5)]
[InlineData(100, 50)]
[InlineData(1000, 500)]
public static void CopyTo_IntArray(int count, int index)
{
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
int[] iArray = new int[index + count];
stack2.CopyTo(iArray, index);
Assert.Equal(index + count, iArray.Length);
for (int i = index; i < count; i++)
{
Assert.Equal(stack2.Pop(), iArray[i]);
}
});
}
[Fact]
public static void CopyTo_Invalid()
{
Stack stack1 = Helpers.CreateIntStack(100);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
AssertExtensions.Throws<ArgumentNullException>("array", () => stack2.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => stack2.CopyTo(new object[10, 10], 0)); // Array is multidimensional
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => stack2.CopyTo(new object[100], -1)); // Index < 0
AssertExtensions.Throws<ArgumentException>(null, () => stack2.CopyTo(new object[0], 0)); // Index >= array.Count
AssertExtensions.Throws<ArgumentException>(null, () => stack2.CopyTo(new object[100], 1)); // Index + array.Count > stack.Count
AssertExtensions.Throws<ArgumentException>(null, () => stack2.CopyTo(new object[150], 51)); // Index + array.Count > stack.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetEnumerator(int count)
{
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
Assert.NotSame(stack2.GetEnumerator(), stack2.GetEnumerator());
IEnumerator enumerator = stack2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
counter++;
Assert.NotNull(enumerator.Current);
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void GetEnumerator_StartOfEnumeration_Clone()
{
Stack stack = Helpers.CreateIntStack(10);
IEnumerator enumerator = stack.GetEnumerator();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone();
Assert.NotSame(enumerator, clonedEnumerator);
// Cloned and original enumerators should enumerate separately.
Assert.True(enumerator.MoveNext());
Assert.Equal(stack.Count - 1, enumerator.Current);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Current);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(stack.Count - 1, enumerator.Current);
Assert.Equal(stack.Count - 1, clonedEnumerator.Current);
// Cloned and original enumerators should enumerate in the same sequence.
for (int i = 1; i < stack.Count; i++)
{
Assert.True(enumerator.MoveNext());
Assert.NotEqual(enumerator.Current, clonedEnumerator.Current);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
}
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Equal(0, clonedEnumerator.Current);
Assert.False(clonedEnumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Current);
}
[Fact]
public static void GetEnumerator_InMiddleOfEnumeration_Clone()
{
Stack stack = Helpers.CreateIntStack(10);
IEnumerator enumerator = stack.GetEnumerator();
enumerator.MoveNext();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
// Cloned and original enumerators should start at the same spot, even
// if the original is in the middle of enumeration.
IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone();
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
for (int i = 0; i < stack.Count - 1; i++)
{
Assert.True(clonedEnumerator.MoveNext());
}
Assert.False(clonedEnumerator.MoveNext());
}
[Fact]
public static void GetEnumerator_Invalid()
{
Stack stack1 = Helpers.CreateIntStack(100);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
IEnumerator enumerator = stack2.GetEnumerator();
// Index < 0
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Index > dictionary.Count
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throws after resetting
enumerator.Reset();
Assert.True(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// MoveNext and Reset throws after stack is modified, but current doesn't
enumerator = stack2.GetEnumerator();
enumerator.MoveNext();
stack2.Push("hi");
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.NotNull(enumerator.Current);
enumerator = stack2.GetEnumerator();
enumerator.MoveNext();
stack2.Pop();
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.NotNull(enumerator.Current);
});
}
[Fact]
public static void Peek()
{
int count = 100;
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
for (int i = 0; i < count; i++)
{
int peek1 = (int)stack2.Peek();
int peek2 = (int)stack2.Peek();
Assert.Equal(peek1, peek2);
Assert.Equal(stack2.Pop(), peek1);
Assert.Equal(count - i - 1, peek1);
}
});
}
[Fact]
public static void Peek_EmptyStack_ThrowsInvalidOperationException()
{
var stack1 = new Stack();
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
Assert.Throws<InvalidOperationException>(() => stack2.Peek()); // Empty stack
for (int i = 0; i < 1000; i++)
{
stack2.Push(i);
}
for (int i = 0; i < 1000; i++)
{
stack2.Pop();
}
Assert.Throws<InvalidOperationException>(() => stack2.Peek()); // Empty stack
});
}
[Theory]
[InlineData(1, 1)]
[InlineData(10, 10)]
[InlineData(100, 100)]
[InlineData(1000, 1000)]
[InlineData(10, 5)]
[InlineData(100, 50)]
[InlineData(1000, 500)]
public static void Pop(int pushCount, int popCount)
{
Stack stack1 = Helpers.CreateIntStack(pushCount);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
for (int i = 0; i < popCount; i++)
{
Assert.Equal(pushCount - i - 1, stack2.Pop());
Assert.Equal(pushCount - i - 1, stack2.Count);
}
Assert.Equal(pushCount - popCount, stack2.Count);
});
}
[Fact]
public static void Pop_Null()
{
var stack1 = new Stack();
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
stack2.Push(null);
stack2.Push(-1);
stack2.Push(null);
Assert.Equal(null, stack2.Pop());
Assert.Equal(-1, stack2.Pop());
Assert.Equal(null, stack2.Pop());
});
}
[Fact]
public static void Pop_EmptyStack_ThrowsInvalidOperationException()
{
var stack1 = new Stack();
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
Assert.Throws<InvalidOperationException>(() => stack2.Pop()); // Empty stack
});
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void Push(int count)
{
var stack1 = new Stack();
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
for (int i = 0; i < count; i++)
{
stack2.Push(i);
Assert.Equal(i + 1, stack2.Count);
}
Assert.Equal(count, stack2.Count);
});
}
[Fact]
public static void Push_Null()
{
var stack1 = new Stack();
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
stack2.Push(null);
stack2.Push(-1);
stack2.Push(null);
Assert.True(stack2.Contains(null));
Assert.True(stack2.Contains(-1));
});
}
[Fact]
public static void Synchronized_IsSynchronized()
{
Stack stack = Stack.Synchronized(new Stack());
Assert.True(stack.IsSynchronized);
}
[Fact]
public static void Synchronized_NullStack_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("stack", () => Stack.Synchronized(null)); // Stack is null
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void ToArray(int count)
{
Stack stack1 = Helpers.CreateIntStack(count);
Helpers.PerformActionOnAllStackWrappers(stack1, stack2 =>
{
object[] array = stack2.ToArray();
Assert.Equal(stack2.Count, array.Length);
for (int i = 0; i < array.Length; i++)
{
Assert.Equal(stack2.Pop(), array[i]);
}
});
}
private class Foo
{
public Foo(int intValue)
{
IntValue = intValue;
}
public int IntValue { get; set; }
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // Changed behavior
public class Stack_SyncRootTests
{
private Stack _stackDaughter;
private Stack _stackGrandDaughter;
private const int NumberOfElements = 100;
[Fact]
public void GetSyncRootBasic()
{
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenario we have in mind.
// 1) Create your Down to earth mother Stack
// 2) Get a Fixed wrapper from it
// 3) Get a Synchronized wrapper from 2)
// 4) Get a synchronized wrapper of the mother from 1)
// 5) all of these should SyncRoot to the mother earth
var stackMother = new Stack();
for (int i = 0; i < NumberOfElements; i++)
{
stackMother.Push(i);
}
Assert.IsType<Stack>(stackMother.SyncRoot);
Stack stackSon = Stack.Synchronized(stackMother);
_stackGrandDaughter = Stack.Synchronized(stackSon);
_stackDaughter = Stack.Synchronized(stackMother);
Assert.Equal(stackSon.SyncRoot, stackMother.SyncRoot);
Assert.Equal(_stackGrandDaughter.SyncRoot, stackMother.SyncRoot);
Assert.Equal(_stackDaughter.SyncRoot, stackMother.SyncRoot);
Assert.Equal(stackSon.SyncRoot, stackMother.SyncRoot);
// We are going to rumble with the Stacks with 2 threads
Action ts1 = SortElements;
Action ts2 = ReverseElements;
var tasks = new Task[4];
for (int iThreads = 0; iThreads < tasks.Length; iThreads += 2)
{
tasks[iThreads] = Task.Run(ts1);
tasks[iThreads + 1] = Task.Run(ts2);
}
Task.WaitAll(tasks);
}
private void SortElements()
{
_stackGrandDaughter.Clear();
for (int i = 0; i < NumberOfElements; i++)
{
_stackGrandDaughter.Push(i);
}
}
private void ReverseElements()
{
_stackDaughter.Clear();
for (int i = 0; i < NumberOfElements; i++)
{
_stackDaughter.Push(i);
}
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using WindowsHook;
using BorderSkin.BorderSkinning.Explorer.Forms;
using LayeredForms;
using WinApiWrappers;
using Padding = System.Windows.Forms.Padding;
namespace BorderSkin.BorderSkinning.Handlers
{
class WindowEventHandler : IDisposable
{
public const int BorderRemove = 1;
private SkinableWindowBorder _skinWindow;
private Timer _maximizeCheckTimer;
private TopLevelWindow _parent;
private IWindowsHook _windowsHook;
public WindowEventHandler(SkinableWindowBorder skinWindow, TopLevelWindow parent)
{
_skinWindow = skinWindow;
_parent = parent;
CreateMaximizeTimer();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_skinWindow.IsClosing)
{
BorderSkinningManager.RestoreBorder(_skinWindow.Parent);
}
DisposeTimer();
_skinWindow = null;
DeattachFromWindowsHook();
}
public void AdjustSkinWindowPropertiesToParent()
{
_skinWindow.LockUpdate = true;
_skinWindow.Parent.Bounds = _skinWindow.Parent.Bounds;
_skinWindow.UpdateBounds = _skinWindow.Parent.Bounds;
_skinWindow.Text = _skinWindow.Parent.Title;
_skinWindow.Icon = _skinWindow.Parent.Icon;
_skinWindow.Visible = _skinWindow.Parent.Visible;
_skinWindow.Maximized = _skinWindow.Parent.Maximized;
_skinWindow.TopMost = _skinWindow.Parent.TopMost;
_skinWindow.LockUpdate = false;
_skinWindow.Update();
}
private Timer MaximizeCheckTimer
{
get { return _maximizeCheckTimer; }
set
{
if (_maximizeCheckTimer != null)
{
_maximizeCheckTimer.Tick -= MaximizeBoundsChecking;
}
_maximizeCheckTimer = value;
if (_maximizeCheckTimer != null)
{
_maximizeCheckTimer.Tick += MaximizeBoundsChecking;
}
}
}
private Rectangle ParentMaximizedBounds
{
get
{
Rectangle maximizedBounds = _skinWindow.Parent.Screen.WorkingArea;
maximizedBounds.Y += _skinWindow.TopBorder1.Height - TopIncreament;
maximizedBounds.Height += TopIncreament - _skinWindow.TopBorder1.Height;
return maximizedBounds;
}
}
private void DisposeTimer()
{
MaximizeCheckTimer.Enabled = false;
MaximizeCheckTimer.Dispose();
}
public int TopIncreament
{
get
{
if (ExplorerSkinWindow.IsExplorerWindow(_skinWindow.Parent))
{
if (Settings.Settings.HideAddressbar)
{
return Convert.ToInt32(BarsHeight.AddressBarHeight);
}
else if (Settings.Settings.HideMenuBar)
{
return Convert.ToInt32(BarsHeight.MenuBarHeight);
}
}
return 0;
}
}
private enum BarsHeight : int
{
AddressBarHeight = 35,
MenuBarHeight = 22
}
public void CreateMaximizeTimer()
{
MaximizeCheckTimer = new Timer();
MaximizeCheckTimer.Interval = 500;
}
private void MaximizeBoundsChecking(object sender, EventArgs e)
{
if (!_skinWindow.IsClosing && _skinWindow.Parent.Maximized && _skinWindow.Parent.Bounds != ParentMaximizedBounds)
{
_skinWindow.Parent.Bounds = ParentMaximizedBounds;
}
}
public void UpdateMaximizeChangesToParent()
{
if (Maximized)
{
_skinWindow.Parent.ExStyles = (_skinWindow.Parent.ExStyles & ~(int)WindowExtendedStyles.WindowEdge);
_skinWindow.Parent.Styles = (_skinWindow.Parent.Styles & ~(int)WindowStyles.Caption & ~(int)WindowStyles.Sizebox & ~(int)WindowStyles.Border & ~(int)WindowStyles.OverLapped) | unchecked((int)(WindowStyles.Popup));
_skinWindow.VisibleSideBorders = false;
_skinWindow.Parent.Bounds = ParentMaximizedBounds;
_skinWindow.UpdateBounds = _skinWindow.Parent.Bounds;
AdjustSkinWindowToParentBounds();
MaximizeCheckTimer.Start();
}
else
{
MaximizeCheckTimer.Stop();
_skinWindow.Parent.ExStyles = (_skinWindow.Parent.ExStyles) | (int)WindowExtendedStyles.WindowEdge;
_skinWindow.Parent.Styles = (_skinWindow.Parent.Styles & ~unchecked((int)(WindowStyles.Popup))) | (int)(WindowStyles.Caption | WindowStyles.Border | WindowStyles.Sizebox | WindowStyles.OverLapped);
_skinWindow.VisibleSideBorders = _skinWindow.Parent.Visible && !_skinWindow.Parent.Minimized;
_skinWindow.UpdateBounds = _skinWindow.Parent.Bounds;
AdjustSkinWindowToParentBounds();
}
_skinWindow.Parent.FrameChanged();
}
public void AdjustSkinWindowToParentBounds()
{
Padding adjustBounds = new Padding {Top = TopIncreament};
if (_skinWindow.Maximized)
{
adjustBounds.Top += -_skinWindow.TopBorder1.Height;
}
else
{
adjustBounds.Left = ParentBorderSize.Width - _skinWindow.LeftBorder1.Width;
adjustBounds.Top += (SystemInformation.CaptionHeight + ParentBorderSize.Height) - _skinWindow.TopBorder1.Height;
adjustBounds.Right = (ParentBorderSize.Width - _skinWindow.RightBorder1.Width) + adjustBounds.Left;
adjustBounds.Bottom = (ParentBorderSize.Height - _skinWindow.BottomBorder1.Height) + adjustBounds.Top;
}
_skinWindow.Move(_skinWindow.UpdateBounds.X + adjustBounds.Left, _skinWindow.UpdateBounds.Y + adjustBounds.Top, _skinWindow.UpdateBounds.Width - adjustBounds.Right, _skinWindow.UpdateBounds.Height - adjustBounds.Bottom);
}
private Size ParentBorderSize
{
get
{
if (_parent.SizeBox || Environment.OSVersion.Version.Major == 6)
{
return SystemInformation.FrameBorderSize;
}
return SystemInformation.FixedFrameBorderSize;
}
}
private bool Maximized
{
get { return _skinWindow.Maximized; }
}
public void AttachToWindowsHook(IWindowsHook windowsHook)
{
DeattachFromWindowsHook();
_windowsHook = windowsHook;
_windowsHook.ManualUpdate += WindowsHookOnManualUpdate;
_windowsHook.WindowActivating += WindowsHookOnWindowActivating;
_windowsHook.WindowClosed += WindowsHookOnWindowClosed;
_windowsHook.WindowDeactivating += WindowsHookOnWindowDeactivating;
_windowsHook.WindowEnableChanging += WindowsHookOnWindowEnableChanging;
_windowsHook.WindowIconChanging += WindowsHookOnWindowIconChanging;
_windowsHook.WindowLocationChanging += WindowsHookOnWindowLocationChanging;
_windowsHook.WindowMaximized += WindowsHookOnWindowMaximized;
_windowsHook.WindowSizeChanging += WindowsHookOnWindowSizeChanging;
_windowsHook.WindowSizeMoveBegins += WindowsHookOnWindowSizeMoveBegins;
_windowsHook.WindowSizeMoveEnds += WindowsHookOnWindowSizeMoveEnds;
_windowsHook.WindowTitleChanging += WindowsHookOnWindowTitleChanging;
_windowsHook.WindowVisibleChanging += WindowsHookOnWindowVisibleChanging;
}
public void DeattachFromWindowsHook()
{
if (_windowsHook == null)
return;
_windowsHook.ManualUpdate -= WindowsHookOnManualUpdate;
_windowsHook.WindowActivating -= WindowsHookOnWindowActivating;
_windowsHook.WindowClosed -= WindowsHookOnWindowClosed;
_windowsHook.WindowDeactivating -= WindowsHookOnWindowDeactivating;
_windowsHook.WindowEnableChanging -= WindowsHookOnWindowEnableChanging;
_windowsHook.WindowIconChanging -= WindowsHookOnWindowIconChanging;
_windowsHook.WindowLocationChanging -= WindowsHookOnWindowLocationChanging;
_windowsHook.WindowMaximized -= WindowsHookOnWindowMaximized;
_windowsHook.WindowSizeChanging -= WindowsHookOnWindowSizeChanging;
_windowsHook.WindowSizeMoveBegins -= WindowsHookOnWindowSizeMoveBegins;
_windowsHook.WindowSizeMoveEnds -= WindowsHookOnWindowSizeMoveEnds;
_windowsHook.WindowTitleChanging -= WindowsHookOnWindowTitleChanging;
_windowsHook.WindowVisibleChanging -= WindowsHookOnWindowVisibleChanging;
_windowsHook = null;
}
public void WindowsHookOnWindowTitleChanging(IntPtr windowHandle, NewValueEventArgs<string> args)
{
_skinWindow.Text = args.NewValue;
}
public void WindowsHookOnWindowSizeMoveEnds(IntPtr windowHandle, EventArgs args)
{
_skinWindow.IsMoving = false;
if (Settings.Settings.DisableBlurOnMove || Settings.Settings.DisableFullBlurOnMove)
{
_skinWindow.Update();
}
}
public void WindowsHookOnWindowSizeMoveBegins(IntPtr windowHandle, EventArgs args)
{
_skinWindow.IsMoving = true;
}
public void WindowsHookOnWindowSizeChanging(IntPtr windowHandle, WindowSizeChangingEventArgs args)
{
int result = 0;
if (!_skinWindow.Parent.Minimized)
{
_skinWindow.Width = args.NewValue.Width;
_skinWindow.UpdateBounds.Height = args.NewValue.Height;
result = TopIncreament;
if (result == 0)
{
result = BorderRemove;
}
}
args.Result = result;
}
public void WindowsHookOnWindowMaximized(IntPtr windowHandle, EventArgs args)
{
// TODO: REALLY NEEDS REFACTORING, THIS EVENTS REALLY EXCUTED FROM WM_MOVE MESSAGE
if (_skinWindow.Parent.Maximized)
{
_skinWindow.Maximized = true;
UpdateMaximizeChangesToParent();
}
else if (_skinWindow.Maximized && !_skinWindow.Parent.Maximized)
{
_skinWindow.Maximized = false;
UpdateMaximizeChangesToParent();
}
}
public void WindowsHookOnWindowLocationChanging(IntPtr windowHandle, NewValueEventArgs<Point> args)
{
if (!_skinWindow.Parent.Minimized)
{
_skinWindow.UpdateBounds.X = args.NewValue.X;
_skinWindow.UpdateBounds.Y = args.NewValue.Y;
}
}
public void WindowsHookOnWindowIconChanging(IntPtr windowHandle, NewValueEventArgs<Icon> args)
{
_skinWindow.Icon = args.NewValue;
_skinWindow.Update();
}
public void WindowsHookOnWindowEnableChanging(IntPtr windowHandle, NewValueEventArgs<bool> args)
{
_skinWindow.Enabled = _skinWindow.Parent.Enabled;
}
public void WindowsHookOnWindowDeactivating(IntPtr windowHandle, WindowDeactivatingEventArgs args)
{
if (_skinWindow != args.WillBeActivated)
{
_skinWindow.Activated = true;
}
}
public void WindowsHookOnWindowClosed(IntPtr windowHandle, EventArgs args)
{
_skinWindow.Dispose();
}
public void WindowsHookOnWindowActivating(IntPtr windowHandle, EventArgs args)
{
_skinWindow.Activated = true;
}
public void WindowsHookOnManualUpdate(IntPtr windowHandle, EventArgs args)
{
AdjustSkinWindowToParentBounds();
}
public void WindowsHookOnWindowVisibleChanging(IntPtr windowHandle, NewValueEventArgs<bool> args)
{
if (!_skinWindow.Parent.Minimized)
{
_skinWindow.Visible = args.NewValue;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WootzJs.Site.Api.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);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using StructureMap;
using System.Text;
namespace GitTfs.Core
{
public class GitHelpers : IGitHelpers
{
private readonly IContainer _container;
/// <summary>
/// Starting with version 1.7.10, Git uses UTF-8.
/// Use this encoding for Git input and output.
/// </summary>
private static readonly Encoding _encoding = new UTF8Encoding(false, true);
public GitHelpers(IContainer container)
{
_container = container;
}
/// <summary>
/// Runs the given git command, and returns the contents of its STDOUT.
/// </summary>
public string Command(params string[] command)
{
string retVal = null;
CommandOutputPipe(stdout => retVal = stdout.ReadToEnd(), command);
return retVal;
}
/// <summary>
/// Runs the given git command, and returns the first line of its STDOUT.
/// </summary>
public string CommandOneline(params string[] command)
{
string retVal = null;
CommandOutputPipe(stdout => retVal = stdout.ReadLine(), command);
return retVal;
}
/// <summary>
/// Runs the given git command, and passes STDOUT through to the current process's STDOUT.
/// </summary>
public void CommandNoisy(params string[] command)
{
CommandOutputPipe(stdout => Trace.TraceInformation(stdout.ReadToEnd()), command);
}
/// <summary>
/// Runs the given git command, and redirects STDOUT to the provided action.
/// </summary>
public void CommandOutputPipe(Action<TextReader> handleOutput, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, RedirectStdout);
handleOutput(process.StandardOutput);
Close(process);
});
}
/// <summary>
/// Runs the given git command, and returns a reader for STDOUT. NOTE: The returned value MUST be disposed!
/// </summary>
public TextReader CommandOutputPipe(params string[] command)
{
AssertValidCommand(command);
var process = Start(command, RedirectStdout);
return new ProcessStdoutReader(this, process);
}
private class ProcessStdoutReader : TextReader
{
private readonly GitProcess _process;
private readonly GitHelpers _helper;
public ProcessStdoutReader(GitHelpers helper, GitProcess process)
{
_helper = helper;
_process = process;
}
public override void Close()
{
_helper.Close(_process);
}
public override System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
{
return _process.StandardOutput.CreateObjRef(requestedType);
}
protected override void Dispose(bool disposing)
{
if (disposing && _process != null)
{
Close();
}
base.Dispose(disposing);
}
public override bool Equals(object obj)
{
return _process.StandardOutput.Equals(obj);
}
public override int GetHashCode()
{
return _process.StandardOutput.GetHashCode();
}
public override object InitializeLifetimeService()
{
return _process.StandardOutput.InitializeLifetimeService();
}
public override int Peek()
{
return _process.StandardOutput.Peek();
}
public override int Read()
{
return _process.StandardOutput.Read();
}
public override int Read(char[] buffer, int index, int count)
{
return _process.StandardOutput.Read(buffer, index, count);
}
public override int ReadBlock(char[] buffer, int index, int count)
{
return _process.StandardOutput.ReadBlock(buffer, index, count);
}
public override string ReadLine()
{
return _process.StandardOutput.ReadLine();
}
public override string ReadToEnd()
{
return _process.StandardOutput.ReadToEnd();
}
public override string ToString()
{
return _process.StandardOutput.ToString();
}
}
public void CommandInputPipe(Action<TextWriter> action, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, RedirectStdin);
action(process.StandardInput.WithEncoding(_encoding));
Close(process);
});
}
public void CommandInputOutputPipe(Action<TextWriter, TextReader> interact, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, Ext.And<ProcessStartInfo>(RedirectStdin, RedirectStdout));
interact(process.StandardInput.WithEncoding(_encoding), process.StandardOutput);
Close(process);
});
}
private void Time(string[] command, Action action)
{
var start = DateTime.Now;
try
{
action();
}
finally
{
var end = DateTime.Now;
Trace.WriteLine(string.Format("[{0}] {1}", end - start, string.Join(" ", command)), "git command time");
}
}
private void Close(GitProcess process)
{
// if caller doesn't read entire stdout to the EOF - it is possible that
// child process will hang waiting until there will be free space in stdout
// buffer to write the rest of the output.
// See https://github.com/git-tfs/git-tfs/issues/121 for details.
if (process.StartInfo.RedirectStandardOutput)
{
process.StandardOutput.BaseStream.CopyTo(Stream.Null);
process.StandardOutput.Close();
}
if (!process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))
throw new GitCommandException("Command did not terminate.", process);
if (process.ExitCode != 0)
throw new GitCommandException(string.Format("Command exited with error code: {0}\n{1}", process.ExitCode, process.StandardErrorString), process);
}
private void RedirectStdout(ProcessStartInfo startInfo)
{
startInfo.RedirectStandardOutput = true;
startInfo.StandardOutputEncoding = _encoding;
}
private void RedirectStderr(ProcessStartInfo startInfo)
{
startInfo.RedirectStandardError = true;
startInfo.StandardErrorEncoding = _encoding;
}
private void RedirectStdin(ProcessStartInfo startInfo)
{
startInfo.RedirectStandardInput = true;
// there is no StandardInputEncoding property, use extension method StreamWriter.WithEncoding instead
}
private GitProcess Start(string[] command)
{
return Start(command, x => { });
}
protected virtual GitProcess Start(string[] command, Action<ProcessStartInfo> initialize)
{
var startInfo = new ProcessStartInfo();
startInfo.FileName = "git";
startInfo.SetArguments(command);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.EnvironmentVariables["GIT_PAGER"] = "cat";
RedirectStderr(startInfo);
initialize(startInfo);
Trace.WriteLine("Starting process: " + startInfo.FileName + " " + startInfo.Arguments, "git command");
var process = new GitProcess(Process.Start(startInfo));
process.ConsumeStandardError();
return process;
}
/// <summary>
/// WrapGitCommandErrors the actions, and if there are any git exceptions, rethrow a new exception with the given message.
/// </summary>
/// <param name="exceptionMessage">A friendlier message to wrap the GitCommandException with. {0} is replaced with the command line and {1} is replaced with the exit code.</param>
/// <param name="action"></param>
public void WrapGitCommandErrors(string exceptionMessage, Action action)
{
try
{
action();
}
catch (GitCommandException e)
{
throw new Exception(string.Format(exceptionMessage, e.Process.StartInfo.FileName + " " + e.Process.StartInfo.Arguments, e.Process.ExitCode), e);
}
}
public IGitRepository MakeRepository(string dir)
{
return _container
.With("gitDir").EqualTo(dir)
.GetInstance<IGitRepository>();
}
private static readonly Regex ValidCommandName = new Regex("^[a-z0-9A-Z_-]+$");
private static void AssertValidCommand(string[] command)
{
if (command.Length < 1 || !ValidCommandName.IsMatch(command[0]))
throw new Exception("bad git command: " + (command.Length == 0 ? "" : command[0]));
}
protected class GitProcess
{
private readonly Process _process;
public GitProcess(Process process)
{
_process = process;
}
public static implicit operator Process(GitProcess process)
{
return process._process;
}
public string StandardErrorString { get; private set; }
public void ConsumeStandardError()
{
StandardErrorString = "";
_process.ErrorDataReceived += StdErrReceived;
_process.BeginErrorReadLine();
}
private void StdErrReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null && e.Data.Trim() != "")
{
var data = e.Data;
Trace.WriteLine(data.TrimEnd(), "git stderr");
StandardErrorString += data;
}
}
// Delegate a bunch of things to the Process.
public ProcessStartInfo StartInfo { get { return _process.StartInfo; } }
public int ExitCode { get { return _process.ExitCode; } }
public StreamWriter StandardInput { get { return _process.StandardInput; } }
public StreamReader StandardOutput { get { return _process.StandardOutput; } }
public bool WaitForExit(int milliseconds)
{
return _process.WaitForExit(milliseconds);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Drawing;
using OpenQA.Selenium.Interactions;
namespace OpenQA.Selenium
{
[TestFixture]
public class RenderedWebElementTest : DriverTestFixture
{
[Test]
[Category("Javascript")]
public void ShouldPickUpStyleOfAnElement()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("green-parent"));
string backgroundColour = element.GetCssValue("background-color");
Assert.That(backgroundColour, Is.EqualTo("#008000").Or.EqualTo("rgba(0,128,0,1)"));
element = driver.FindElement(By.Id("red-item"));
backgroundColour = element.GetCssValue("background-color");
Assert.That(backgroundColour, Is.EqualTo("#ff0000").Or.EqualTo("rgba(255,0,0,1)"));
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Chrome, "WebKit bug 28804")]
[IgnoreBrowser(Browser.IE, "Position and size are always integer in IE")]
public void ShouldHandleNonIntegerPositionAndSize()
{
driver.Url = rectanglesPage;
IWebElement r2 = driver.FindElement(By.Id("r2"));
string left = r2.GetCssValue("left");
Assert.IsTrue(left.StartsWith("10.9"), "left (\"" + left + "\") should start with \"10.9\".");
string top = r2.GetCssValue("top");
Assert.IsTrue(top.StartsWith("10.1"), "top (\"" + top + "\") should start with \"10.1\".");
Assert.AreEqual(new Point(11, 10), r2.Location);
string width = r2.GetCssValue("width");
Assert.IsTrue(width.StartsWith("48.6"), "width (\"" + left + "\") should start with \"48.6\".");
string height = r2.GetCssValue("height");
Assert.IsTrue(height.StartsWith("49.3"), "height (\"" + left + "\") should start with \"49.3\".");
Assert.AreEqual(r2.Size, new Size(49, 49));
}
[Test]
[Category("Javascript")]
public void ShouldAllowInheritedStylesToBeUsed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("green-item"));
string backgroundColour = element.GetCssValue("background-color");
Assert.That(backgroundColour, Is.EqualTo("transparent").Or.EqualTo("rgba(0, 0, 0, 0)"));
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldAllowUsersToHoverOverElements()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("menu1"));
if (!Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows))
{
Assert.Ignore("Skipping test: Simulating hover needs native events");
}
IHasInputDevices inputDevicesDriver = driver as IHasInputDevices;
if (inputDevicesDriver == null)
{
return;
}
IWebElement item = driver.FindElement(By.Id("item1"));
Assert.AreEqual("", item.Text);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.background = 'green'", element);
//element.Hover();
Actions actionBuilder = new Actions(driver);
actionBuilder.MoveToElement(element).Perform();
item = driver.FindElement(By.Id("item1"));
Assert.AreEqual("Item 1", item.Text);
}
[Test]
[Category("Javascript")]
public void ShouldCorrectlyIdentifyThatAnElementHasWidth()
{
driver.Url = xhtmlTestPage;
IWebElement shrinko = driver.FindElement(By.Id("linkId"));
Size size = shrinko.Size;
Assert.IsTrue(size.Width > 0, "Width expected to be greater than 0");
Assert.IsTrue(size.Height > 0, "Height expected to be greater than 0");
}
[Test]
[Category("Javascript")]
public void CorrectlyDetectMapElementsAreShown()
{
driver.Url = mapVisibilityPage;
IWebElement area = driver.FindElement(By.Id("mtgt_unnamed_0"));
bool isShown = area.Displayed;
Assert.IsTrue(isShown, "The element and the enclosing map should be considered shown.");
}
//[Test]
//[Category("Javascript")]
//[Ignore]
public void CanClickOnSuckerFishMenuItem()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("menu1"));
if (!Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows))
{
Assert.Ignore("Skipping test: Simulating hover needs native events");
}
IWebElement target = driver.FindElement(By.Id("item1"));
Assert.IsTrue(target.Displayed);
target.Click();
String text = driver.FindElement(By.Id("result")).Text;
Assert.IsTrue(text.Contains("item 1"));
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")]
public void MovingMouseByRelativeOffset()
{
driver.Url = mouseTrackerPage;
IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker"));
new Actions(driver).MoveToElement(trackerDiv).Build().Perform();
IWebElement reporter = driver.FindElement(By.Id("status"));
WaitFor(FuzzyMatchingOfCoordinates(reporter, 50, 200));
new Actions(driver).MoveByOffset(10, 20).Build().Perform();
WaitFor(FuzzyMatchingOfCoordinates(reporter, 60, 220));
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")]
public void MovingMouseToRelativeElementOffset()
{
driver.Url = mouseTrackerPage;
IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker"));
new Actions(driver).MoveToElement(trackerDiv, 95, 195).Build().Perform();
IWebElement reporter = driver.FindElement(By.Id("status"));
WaitFor(FuzzyMatchingOfCoordinates(reporter, 95, 195));
}
[Test]
[Category("Javascript")]
[NeedsFreshDriver(BeforeTest = true)]
[IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")]
public void MoveRelativeToBody()
{
driver.Url = mouseTrackerPage;
new Actions(driver).MoveByOffset(50, 100).Build().Perform();
IWebElement reporter = driver.FindElement(By.Id("status"));
WaitFor(FuzzyMatchingOfCoordinates(reporter, 40, 20));
}
private Func<bool> FuzzyMatchingOfCoordinates(IWebElement element, int x, int y)
{
return () =>
{
return FuzzyPositionMatching(x, y, element.Text);
};
}
private bool FuzzyPositionMatching(int expectedX, int expectedY, String locationTuple)
{
string[] splitString = locationTuple.Split(',');
int gotX = int.Parse(splitString[0].Trim());
int gotY = int.Parse(splitString[1].Trim());
// Everything within 5 pixels range is OK
const int ALLOWED_DEVIATION = 5;
return Math.Abs(expectedX - gotX) < ALLOWED_DEVIATION && Math.Abs(expectedY - gotY) < ALLOWED_DEVIATION;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Vector3F.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.Math.Algebra.Vectors
{
using System;
using System.Globalization;
using Slash.Math.Utils;
/// <summary>
/// 3-dimensional float vector.
/// </summary>
[Serializable]
public struct Vector3F
{
#region Constants
/// <summary>
/// Unrotated forward vector.
/// </summary>
public static Vector3F Forward = new Vector3F(0, 0, 1);
/// <summary>
/// All vector components are 1.
/// </summary>
public static Vector3F One = new Vector3F(1, 1, 1);
/// <summary>
/// Unrotated side vector.
/// </summary>
public static Vector3F Right = new Vector3F(1, 0, 0);
/// <summary>
/// Unrotated up vector.
/// </summary>
public static Vector3F Up = new Vector3F(0, 1, 0);
/// <summary>
/// All vector components are 0.
/// </summary>
public static Vector3F Zero = new Vector3F(0, 0, 0);
#endregion
#region Fields
/// <summary>
/// X component.
/// </summary>
public readonly float X;
/// <summary>
/// Y component.
/// </summary>
public readonly float Y;
/// <summary>
/// Z component.
/// </summary>
public readonly float Z;
#endregion
#region Constructors and Destructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="vector"> Initial vector. </param>
public Vector3F(Vector3F vector)
{
this.X = vector.X;
this.Y = vector.Y;
this.Z = vector.Z;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="vector"> Initial vector. </param>
public Vector3F(Vector3I vector)
{
this.X = vector.X;
this.Y = vector.Y;
this.Z = vector.Z;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="x"> Initial x value. </param>
/// <param name="y"> Initial y value. </param>
/// <param name="z"> Initial z value. </param>
public Vector3F(float x, float y, float z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="values">
/// Float array which contains the initial vector value. Value at index 0 is taken as the initial x
/// value, value at index 1 is taken as the initial y value, value at index 2 is taken as the initial z value.
/// </param>
public Vector3F(params float[] values)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
if (values.Length < 3)
{
throw new ArgumentException("Expected a float array which size is at least 3.", "values");
}
this.X = values[0];
this.Y = values[1];
this.Z = values[2];
}
#endregion
#region Properties
/// <summary>
/// Indicates if at least one vector component is not zero.
/// </summary>
public bool IsNonZero
{
get
{
return this.X != 0 || this.Y != 0 || this.Z != 0;
}
}
/// <summary>
/// Indicates if all vector components are zero.
/// </summary>
public bool IsZero
{
get
{
return this.X == 0 && this.Y == 0 && this.Z == 0;
}
}
/// <summary>
/// Magnitude of the vector.
/// </summary>
public float Magnitude
{
get
{
return MathUtils.Sqrt(this.SquareMagnitude);
}
}
/// <summary>
/// Square magnitude of the vector.
/// </summary>
public float SquareMagnitude
{
get
{
return (this.X * this.X) + (this.Y * this.Y) + (this.Z * this.Z);
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Calculates the dot product of this and the passed vector. See http://en.wikipedia.org/wiki/Dot_product for more
/// details.
/// </summary>
/// <param name="vector"> Vector to calculate dot product with. </param>
/// <returns> Dot product of this and the passed vector. </returns>
public float CalculateDotProduct(Vector3F vector)
{
return Dot(this, vector);
}
/// <summary>
/// Calculates the dot product of the two passed vectors. See http://en.wikipedia.org/wiki/Dot_product for more details.
/// </summary>
/// <param name="a"> First vector. </param>
/// <param name="b"> Second vector. </param>
/// <returns> Dot product of the two passed vectors. </returns>
public static float Dot(Vector3F a, Vector3F b)
{
return (a.X * b.X) + (a.Y * b.Y) + (a.Z * b.Z);
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object" /> is equal to the current
/// <see cref="T:System.Object" />.
/// </summary>
/// <returns>
/// true if the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />;
/// otherwise, false.
/// </returns>
/// <param name="obj">
/// The <see cref="T:System.Object" /> to compare with the current <see cref="T:System.Object" />.
/// </param>
/// <filterpriority>2</filterpriority>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return this.Equals((Vector3F)obj);
}
/// <summary>
/// Determines whether the specified <see cref="Vector3F" /> is equal to the current <see cref="Vector3F" />.
/// </summary>
/// <returns>
/// true if the specified <see cref="Vector3F" /> is equal to the current <see cref="Vector3F" />; otherwise, false.
/// </returns>
/// <param name="other">
/// The <see cref="Vector3F" /> to compare with the current <see cref="Vector3F" />.
/// </param>
public bool Equals(Vector3F other)
{
return this.X.Equals(other.X) && this.Y.Equals(other.Y) && this.Z.Equals(other.Z);
}
/// <summary>
/// Calculates the distance between this and the passed vector.
/// </summary>
/// <param name="vector"> Vector to compute distance to. </param>
/// <returns> Distance between this and the passed vector. </returns>
public float GetDistance(Vector3F vector)
{
return MathUtils.Sqrt(this.GetSquareDistance(vector));
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object" />.
/// </returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode()
{
unchecked
{
int hashCode = this.X.GetHashCode();
hashCode = (hashCode * 397) ^ this.Y.GetHashCode();
hashCode = (hashCode * 397) ^ this.Z.GetHashCode();
return hashCode;
}
}
/// <summary>
/// Returns the normalized vector.
/// </summary>
/// <returns> Normalized vector. </returns>
public Vector3F GetNormalized()
{
float magnitude = this.Magnitude;
if (magnitude != 0.0f)
{
return new Vector3F(this.X / magnitude, this.Y / magnitude, this.Z / magnitude);
}
return Zero;
}
/// <summary>
/// Calculates the square distance between this and the passed vector.
/// </summary>
/// <param name="vector"> Vector to compute square distance to. </param>
/// <returns> Square distance between this and the passed vector. </returns>
public float GetSquareDistance(Vector3F vector)
{
return MathUtils.Pow2(vector.X - this.X) + MathUtils.Pow2(vector.Y - this.Y)
+ MathUtils.Pow2(vector.Z - this.Z);
}
/// <summary>
/// Returns a vector that is made from the largest components of two vectors.
/// </summary>
/// <param name="lhs"> First vector. </param>
/// <param name="rhs"> Second vector. </param>
/// <returns>Vector that is made from the largest components of two vectors.</returns>
public static Vector3F Max(Vector3F lhs, Vector3F rhs)
{
return new Vector3F(MathUtils.Max(lhs.X, rhs.X), MathUtils.Max(lhs.Y, rhs.Y), MathUtils.Max(lhs.Z, rhs.Z));
}
/// <summary>
/// Returns a vector that is made from the smallest components of two vectors.
/// </summary>
/// <param name="lhs"> First vector. </param>
/// <param name="rhs"> Second vector. </param>
/// <returns>Vector that is made from the smallest components of two vectors.</returns>
public static Vector3F Min(Vector3F lhs, Vector3F rhs)
{
return new Vector3F(MathUtils.Min(lhs.X, rhs.X), MathUtils.Min(lhs.Y, rhs.Y), MathUtils.Min(lhs.Z, rhs.Z));
}
/// <summary>
/// Normalizes this vector.
/// </summary>
/// <returns>Vector with the same orientation as this one, and unit length.</returns>
public Vector3F Normalize()
{
float magnitude = this.Magnitude;
if (magnitude != 0.0f)
{
return new Vector3F(this.X / magnitude, this.Y / magnitude, this.Z / magnitude);
}
return new Vector3F(this.X, this.Y, this.Z);
}
/// <summary>
/// Sums the components of the passed vectors and returns the resulting vector.
/// </summary>
/// <param name="a"> First vector. </param>
/// <param name="b"> Second vector. </param>
/// <returns> Vector which components are the sum of the respective components of the two passed vectors. </returns>
public static Vector3F operator +(Vector3F a, Vector3F b)
{
return new Vector3F(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
}
/// <summary>
/// Divides each component of the passed vector by the passed value.
/// </summary>
/// <param name="a"> Vector to divide by the float value. </param>
/// <param name="b"> Float value to divide by. </param>
/// <returns>
/// Vector where each component is the result of the particular component of the passed vector divided by the
/// passed float value.
/// </returns>
public static Vector3F operator /(Vector3F a, float b)
{
return new Vector3F(a.X / b, a.Y / b, a.Z / b);
}
/// <summary>
/// Indicates if the two passed vectors are equal.
/// </summary>
/// <param name="a"> First vector. </param>
/// <param name="b"> Second vector. </param>
/// <returns> True if the two passed vectors are equal; otherwise, false. </returns>
public static bool operator ==(Vector3F a, Vector3F b)
{
return Equals(a, b);
}
/// <summary>
/// Indicates if the two passed vectors are not equal.
/// </summary>
/// <param name="a"> First vector. </param>
/// <param name="b"> Second vector. </param>
/// <returns> True if the two passed vectors are not equal; otherwise, false. </returns>
public static bool operator !=(Vector3F a, Vector3F b)
{
return !Equals(a, b);
}
/// <summary>
/// Multiplies each vector component of the two passed vectors.
/// </summary>
/// <param name="a"> First vector. </param>
/// <param name="b"> Second vector. </param>
/// <returns> Vector which components are the product of the respective components of the passed vectors. </returns>
public static Vector3F operator *(Vector3F a, Vector3F b)
{
return new Vector3F(a.X * b.X, a.Y * b.Y, a.Z * b.Z);
}
/// <summary>
/// Multiplies each vector component with the passed float value.
/// </summary>
/// <param name="a"> Vector to multiply. </param>
/// <param name="b"> Float value to multiply by. </param>
/// <returns> Vector which components are the product of the respective component of the passed vector and the float value. </returns>
public static Vector3F operator *(Vector3F a, float b)
{
return new Vector3F(a.X * b, a.Y * b, a.Z * b);
}
/// <summary>
/// Multiplies each vector component with the passed float value.
/// </summary>
/// <param name="a"> Float value to multiply by. </param>
/// <param name="b"> Vector to multiply. </param>
/// <returns> Vector which components are the product of the respective component of the passed vector and the float value. </returns>
public static Vector3F operator *(float a, Vector3F b)
{
return new Vector3F(a * b.X, a * b.Y, a * b.Z);
}
/// <summary>
/// Subtracts the components of the second passed vector from the first passed.
/// </summary>
/// <param name="a"> First vector. </param>
/// <param name="b"> Second vector. </param>
/// <returns> Vector which components are the difference of the respective components of the two passed vectors. </returns>
public static Vector3F operator -(Vector3F a, Vector3F b)
{
return new Vector3F(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
}
/// <summary>
/// Negates each component of the passed vector.
/// </summary>
/// <param name="a"> Vector to negate. </param>
/// <returns> Vector which components have the negated value of the respective components of the passed vector. </returns>
public static Vector3F operator -(Vector3F a)
{
return new Vector3F(-a.X, -a.Y, -a.Z);
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
return string.Format(
"({0},{1},{2})",
this.X.ToString(CultureInfo.InvariantCulture.NumberFormat),
this.Y.ToString(CultureInfo.InvariantCulture.NumberFormat),
this.Z.ToString(CultureInfo.InvariantCulture.NumberFormat));
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis;
namespace Microsoft.NetCore.Analyzers.Data
{
using static MicrosoftNetCoreAnalyzersResources;
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class ReviewSqlQueriesForSecurityVulnerabilities : DiagnosticAnalyzer
{
internal const string RuleId = "CA2100";
internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(
RuleId,
CreateLocalizableResourceString(nameof(ReviewSQLQueriesForSecurityVulnerabilitiesTitle)),
CreateLocalizableResourceString(nameof(ReviewSQLQueriesForSecurityVulnerabilitiesMessageNoNonLiterals)),
DiagnosticCategory.Security,
RuleLevel.Disabled,
description: CreateLocalizableResourceString(nameof(ReviewSQLQueriesForSecurityVulnerabilitiesDescription)),
isPortedFxCopRule: true,
isDataflowRule: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterCompilationStartAction(compilationContext =>
{
INamedTypeSymbol? iDbCommandType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataIDbCommand);
INamedTypeSymbol? iDataAdapterType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataIDataAdapter);
IPropertySymbol? commandTextProperty = iDbCommandType?.GetMembers("CommandText").OfType<IPropertySymbol>().FirstOrDefault();
if (iDbCommandType == null ||
iDataAdapterType == null ||
commandTextProperty == null)
{
return;
}
compilationContext.RegisterOperationBlockStartAction(operationBlockStartContext =>
{
ISymbol symbol = operationBlockStartContext.OwningSymbol;
var isInDbCommandConstructor = false;
var isInDataAdapterConstructor = false;
if (symbol.Kind != SymbolKind.Method)
{
return;
}
var methodSymbol = (IMethodSymbol)symbol;
if (methodSymbol.MethodKind == MethodKind.Constructor)
{
CheckForDbCommandAndDataAdapterImplementation(symbol.ContainingType, iDbCommandType, iDataAdapterType, out isInDbCommandConstructor, out isInDataAdapterConstructor);
}
operationBlockStartContext.RegisterOperationAction(operationContext =>
{
var creation = (IObjectCreationOperation)operationContext.Operation;
AnalyzeMethodCall(operationContext, creation.Constructor, symbol, creation.Arguments, creation.Syntax, isInDbCommandConstructor, isInDataAdapterConstructor, iDbCommandType, iDataAdapterType);
}, OperationKind.ObjectCreation);
// If an object calls a constructor in a base class or the same class, this will get called.
operationBlockStartContext.RegisterOperationAction(operationContext =>
{
var invocation = (IInvocationOperation)operationContext.Operation;
// We only analyze constructor invocations
if (invocation.TargetMethod.MethodKind != MethodKind.Constructor)
{
return;
}
// If we're calling another constructor in the same class from this constructor, assume that all parameters are safe and skip analysis. Parameter usage
// will be analyzed there
if (Equals(invocation.TargetMethod.ContainingType, symbol.ContainingType))
{
return;
}
AnalyzeMethodCall(operationContext, invocation.TargetMethod, symbol, invocation.Arguments, invocation.Syntax, isInDbCommandConstructor, isInDataAdapterConstructor, iDbCommandType, iDataAdapterType);
}, OperationKind.Invocation);
operationBlockStartContext.RegisterOperationAction(operationContext =>
{
var propertyReference = (IPropertyReferenceOperation)operationContext.Operation;
// We're only interested in implementations of IDbCommand.CommandText
if (!propertyReference.Property.IsOverrideOrImplementationOfInterfaceMember(commandTextProperty))
{
return;
}
// Make sure we're in assignment statement
if (propertyReference.Parent is not IAssignmentOperation assignment)
{
return;
}
// Only if the property reference is actually the target of the assignment
if (assignment.Target != propertyReference)
{
return;
}
ReportDiagnosticIfNecessary(operationContext, assignment.Value, assignment.Syntax, propertyReference.Property, symbol);
}, OperationKind.PropertyReference);
});
});
}
private static void AnalyzeMethodCall(OperationAnalysisContext operationContext,
IMethodSymbol constructorSymbol,
ISymbol containingSymbol,
ImmutableArray<IArgumentOperation> arguments,
SyntaxNode invocationSyntax,
bool isInDbCommandConstructor,
bool isInDataAdapterConstructor,
INamedTypeSymbol iDbCommandType,
INamedTypeSymbol iDataAdapterType)
{
CheckForDbCommandAndDataAdapterImplementation(constructorSymbol.ContainingType, iDbCommandType, iDataAdapterType,
out var callingDbCommandConstructor,
out var callingDataAdapterConstructor);
if (!callingDataAdapterConstructor && !callingDbCommandConstructor)
{
return;
}
// All parameters the function takes that are explicit strings are potential vulnerabilities
var potentials = arguments.WhereAsArray(arg => arg.Parameter.Type.SpecialType == SpecialType.System_String && !arg.Parameter.IsImplicitlyDeclared);
if (potentials.IsEmpty)
{
return;
}
var vulnerableArgumentsBuilder = ImmutableArray.CreateBuilder<IArgumentOperation>();
foreach (var argument in potentials)
{
// For the constructor of a IDbCommand-derived class, if there is only one string parameter, then we just
// assume that it's the command text. If it takes more than one string, then we need to figure out which
// one is the command string. However, for the constructor of a IDataAdapter, a lot of times the
// constructor also take in the connection string, so we can't assume it's the command if there is only one
// string.
if (callingDataAdapterConstructor || potentials.Length > 1)
{
if (!IsParameterSymbolVulnerable(argument.Parameter))
{
continue;
}
}
vulnerableArgumentsBuilder.Add(argument);
}
var vulnerableArguments = vulnerableArgumentsBuilder.ToImmutable();
foreach (var argument in vulnerableArguments)
{
if (IsParameterSymbolVulnerable(argument.Parameter) && (isInDbCommandConstructor || isInDataAdapterConstructor))
{
//No warnings, as Constructor parameters in derived classes are assumed to be safe since this rule will check the constructor arguments at their call sites.
return;
}
if (ReportDiagnosticIfNecessary(operationContext, argument.Value, invocationSyntax, constructorSymbol, containingSymbol))
{
// Only report one warning per invocation
return;
}
}
}
private static bool IsParameterSymbolVulnerable(IParameterSymbol parameter)
{
// Parameters might be vulnerable if "cmd" or "command" is in the name
return parameter != null &&
(parameter.Name.IndexOf("cmd", StringComparison.OrdinalIgnoreCase) != -1 ||
parameter.Name.IndexOf("command", StringComparison.OrdinalIgnoreCase) != -1);
}
private static bool ReportDiagnosticIfNecessary(OperationAnalysisContext operationContext,
IOperation argumentValue,
SyntaxNode syntax,
ISymbol invokedSymbol,
ISymbol containingMethod)
{
if (operationContext.Options.IsConfiguredToSkipAnalysis(Rule, containingMethod, operationContext.Compilation))
{
return false;
}
if (argumentValue.Type.SpecialType != SpecialType.System_String || !argumentValue.ConstantValue.HasValue)
{
// We have a candidate for diagnostic. perform more precise dataflow analysis.
if (argumentValue.TryGetEnclosingControlFlowGraph(out var cfg))
{
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(operationContext.Compilation);
var valueContentResult = ValueContentAnalysis.TryGetOrComputeResult(cfg, containingMethod, wellKnownTypeProvider,
operationContext.Options, Rule, PointsToAnalysisKind.Complete);
if (valueContentResult != null)
{
ValueContentAbstractValue value = valueContentResult[argumentValue.Kind, argumentValue.Syntax];
if (value.NonLiteralState == ValueContainsNonLiteralState.No)
{
// The value is a constant literal or default/unitialized, so avoid flagging this usage.
return false;
}
}
}
// Review if the symbol passed to {invocation} in {method/field/constructor/etc} has user input.
operationContext.ReportDiagnostic(syntax.CreateDiagnostic(Rule,
invokedSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
containingMethod.Name));
return true;
}
return false;
}
private static void CheckForDbCommandAndDataAdapterImplementation(INamedTypeSymbol containingType,
INamedTypeSymbol iDbCommandType,
INamedTypeSymbol iDataAdapterType,
out bool implementsDbCommand,
out bool implementsDataCommand)
{
implementsDbCommand = false;
implementsDataCommand = false;
foreach (var @interface in containingType.AllInterfaces)
{
if (Equals(@interface, iDbCommandType))
{
implementsDbCommand = true;
}
else if (Equals(@interface, iDataAdapterType))
{
implementsDataCommand = true;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using Microsoft.AspNetCore.Mvc.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Resources = Microsoft.AspNetCore.Mvc.ViewFeatures.Resources;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// A <see cref="ValidationAttribute"/> which configures Unobtrusive validation to send an Ajax request to the
/// web site. The invoked endpoint should return JSON indicating whether the value is valid.
/// </summary>
/// <remarks>Does no server-side validation of the final form submission.</remarks>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public abstract class RemoteAttributeBase : ValidationAttribute, IClientModelValidator
{
private string _additionalFields = string.Empty;
private string[] _additionalFieldsSplit = Array.Empty<string>();
private bool _checkedForLocalizer;
private IStringLocalizer? _stringLocalizer;
/// <summary>
/// Initialize a new instance of <see cref="RemoteAttributeBase"/>.
/// </summary>
protected RemoteAttributeBase()
: base(errorMessageAccessor: () => Resources.RemoteAttribute_RemoteValidationFailed)
{
RouteData = new RouteValueDictionary();
}
/// <summary>
/// Gets the <see cref="RouteValueDictionary"/> used when generating the URL where client should send a
/// validation request.
/// </summary>
protected RouteValueDictionary RouteData { get; }
/// <summary>
/// Gets or sets the HTTP method (<c>"Get"</c> or <c>"Post"</c>) client should use when sending a validation
/// request.
/// </summary>
public string? HttpMethod { get; set; }
/// <summary>
/// Gets or sets the comma-separated names of fields the client should include in a validation request.
/// </summary>
[AllowNull]
public string AdditionalFields
{
get => _additionalFields;
set
{
_additionalFields = value ?? string.Empty;
_additionalFieldsSplit = SplitAndTrimPropertyNames(value)
.Select(field => FormatPropertyForClientValidation(field))
.ToArray();
}
}
/// <summary>
/// Formats <paramref name="property"/> and <see cref="AdditionalFields"/> for use in generated HTML.
/// </summary>
/// <param name="property">
/// Name of the property associated with this <see cref="RemoteAttribute"/> instance.
/// </param>
/// <returns>Comma-separated names of fields the client should include in a validation request.</returns>
/// <remarks>
/// Excludes any whitespace from <see cref="AdditionalFields"/> in the return value.
/// Prefixes each field name in the return value with <c>"*."</c>.
/// </remarks>
public string FormatAdditionalFieldsForClientValidation(string property)
{
if (string.IsNullOrEmpty(property))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(property));
}
var delimitedAdditionalFields = string.Join(",", _additionalFieldsSplit);
if (!string.IsNullOrEmpty(delimitedAdditionalFields))
{
delimitedAdditionalFields = "," + delimitedAdditionalFields;
}
var formattedString = FormatPropertyForClientValidation(property) + delimitedAdditionalFields;
return formattedString;
}
/// <summary>
/// Formats <paramref name="property"/> for use in generated HTML.
/// </summary>
/// <param name="property">One field name the client should include in a validation request.</param>
/// <returns>Name of a field the client should include in a validation request.</returns>
/// <remarks>Returns <paramref name="property"/> with a <c>"*."</c> prefix.</remarks>
public static string FormatPropertyForClientValidation(string property)
{
if (string.IsNullOrEmpty(property))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(property));
}
return "*." + property;
}
/// <summary>
/// Returns the URL where the client should send a validation request.
/// </summary>
/// <param name="context">The <see cref="ClientModelValidationContext"/> used to generate the URL.</param>
/// <returns>The URL where the client should send a validation request.</returns>
protected abstract string GetUrl(ClientModelValidationContext context);
/// <inheritdoc />
public override string FormatErrorMessage(string name)
{
return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
}
/// <inheritdoc />
/// <remarks>
/// Always returns <c>true</c> since this <see cref="ValidationAttribute"/> does no validation itself.
/// Related validations occur only when the client sends a validation request.
/// </remarks>
public override bool IsValid(object? value)
{
return true;
}
/// <summary>
/// Adds Unobtrusive validation HTML attributes to <see cref="ClientModelValidationContext"/>.
/// </summary>
/// <param name="context">
/// <see cref="ClientModelValidationContext"/> to add Unobtrusive validation HTML attributes to.
/// </param>
/// <remarks>
/// Calls derived <see cref="ValidationAttribute"/> implementation of <see cref="GetUrl(ClientModelValidationContext)"/>.
/// </remarks>
public virtual void AddValidation(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
MergeAttribute(context.Attributes, "data-val", "true");
CheckForLocalizer(context);
var errorMessage = GetErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-remote", errorMessage);
MergeAttribute(context.Attributes, "data-val-remote-url", GetUrl(context));
if (!string.IsNullOrEmpty(HttpMethod))
{
MergeAttribute(context.Attributes, "data-val-remote-type", HttpMethod);
}
var additionalFields = FormatAdditionalFieldsForClientValidation(context.ModelMetadata.PropertyName!);
MergeAttribute(context.Attributes, "data-val-remote-additionalfields", additionalFields);
}
private static void MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (!attributes.ContainsKey(key))
{
attributes.Add(key, value);
}
}
private static IEnumerable<string> SplitAndTrimPropertyNames(string? original)
=> original?.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>();
private void CheckForLocalizer(ClientModelValidationContext context)
{
if (!_checkedForLocalizer)
{
_checkedForLocalizer = true;
var services = context.ActionContext.HttpContext.RequestServices;
var options = services.GetRequiredService<IOptions<MvcDataAnnotationsLocalizationOptions>>();
var factory = services.GetService<IStringLocalizerFactory>();
var provider = options.Value.DataAnnotationLocalizerProvider;
if (factory != null && provider != null)
{
_stringLocalizer = provider(
context.ModelMetadata.ContainerType ?? context.ModelMetadata.ModelType,
factory);
}
}
}
private string GetErrorMessage(string displayName)
{
if (_stringLocalizer != null &&
!string.IsNullOrEmpty(ErrorMessage) &&
string.IsNullOrEmpty(ErrorMessageResourceName) &&
ErrorMessageResourceType == null)
{
return _stringLocalizer[ErrorMessage, displayName];
}
return FormatErrorMessage(displayName);
}
}
}
| |
// Copyright 2012 Jacob Trimble
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using System.Reflection;
namespace ModMaker.Lua {
/// <summary>
/// Attach to an type definition or member to control visibility to Lua code. If this is placed on
/// a member, then the member is not visible to Lua. If placed on a type, then this will alter
/// which members are visible or not.
/// </summary>
/// <remarks>
/// If there is ambiguity, then it favors a member not being visible. Attaching LuaIgnore to a
/// member in an interface only has effect when the backing type has BehavesAs set to the
/// interface type or if the value is a LuaUserData with the interface type. When determining
/// method overloads, only members that are visible are considered.
///
/// If LuaIgnore is marked on a return value or a value passed by reference (i.e. 'ref' or 'out')
/// then it is a special return. A special wrapper value is passed to Lua of type LuaUserData.
/// The type is converted back when passed back to managed code, but behaves a little differently
/// when in Lua code. When determining if a member is visible to this variable, the extra
/// information is added according to the LuaIgnore for how Lua got the variable. The member
/// visibility rules are the same for special returns, except they only apply to a single
/// variable. Lua cannot change a LuaUserData variable; however it is important to note that if
/// your code accepts a variable that it may turn it into a normal variable.
///
/// If you want to ensure that your code does not violate rules for LuaUserData, you can accept a
/// LuaUserData object and manage it directly, then the object is not converted to it's underlying
/// value. If you want static type safety, then you can accept the generic version so only a
/// variable of the given type will be accepted. This also will ensure that it will select the
/// correct overload. Note that the type of the argument must either derive from the generic
/// argument or implement it, overloads for user-defined casts are not supported for generics.
/// For example, LuaUserData<string> is compatible with LuaUserData<object> but not
/// LuaUserData<int>. Also note that if the argument has a BehavesAs, then that type is the
/// only type considered, even if the underlying type is compatible.
///
/// Most variables are converted to LuaUserData and all variables are compatible with LuaUserData
/// types. This is to ensure type-safety for return values when the return type does not match
/// the backing type.
///
/// When determining if a member is visible to Lua, the following is done, in order. If the
/// object is a special return (see above) then that is searched. If AccessMembers is not null,
/// then any member accessible to Lua must be in the array. If IgnoreMembers is not null, then
/// any member accessible to Lua must not be in the array. If BehavesAs is not null, then it is
/// searched. If that type does not define LuaIgnore attribute, then that type must define the
/// member and that version is used. If it does defined LuaIgnore, then this method is applied to
/// that type. If DefinedOnly is true, than this type must explicitly define that member for it
/// to be visible (i.e. inherited members are not visible).
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor |
AttributeTargets.Interface | AttributeTargets.Event |
AttributeTargets.ReturnValue | AttributeTargets.Field | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Struct,
AllowMultiple = false, Inherited = true)]
public sealed class LuaIgnoreAttribute : Attribute {
/// <summary>
/// Gets or sets the members that Lua has access to. If this is not null, then a visible member
/// MUST be in this array.
/// </summary>
public string[] AccessMembers { get; set; }
/// <summary>
/// Gets or sets the members that Lua does not have access to. Can be null.
/// </summary>
public string[] IgnoreMembers { get; set; }
/// <summary>
/// If true, then Lua can only access members defined by the given type, otherwise it has access
/// to inherited members.
/// </summary>
public bool DefinedOnly { get; set; }
/// <summary>
/// Gets or sets the type that this class should behave as if it is. If it is null, then it is
/// ignored. The attached type must derive from or implement this type.
/// </summary>
public Type BehavesAs { get; set; }
/// <summary>
/// Creates a new instance of LuaIgnoreAttribute where all members are not visible to Lua.
/// </summary>
public LuaIgnoreAttribute()
: this(true) { }
/// <summary>
/// Creates a new instance of LuaIgnoreAttribute where the type or return value behaves as-if it
/// is defined as the given type. Visibility is determined by the type.
/// </summary>
/// <param name="behavesAs">The type that the variable should behave as, cannot be null.</param>
/// <exception cref="System.ArgumentNullException">If behavesAs is null.</exception>
public LuaIgnoreAttribute(Type behavesAs) {
if (behavesAs == null) {
throw new ArgumentNullException(nameof(behavesAs));
}
AccessMembers = null;
IgnoreMembers = null;
DefinedOnly = false;
BehavesAs = behavesAs;
}
/// <summary>
/// Creates a new instance of LuaIgnoreAttribute where either all members are visible or
/// invisible.
/// </summary>
/// <param name="allInvisible">
/// True if all members are not visible to Lua; or false if all members are visible.
/// </param>
public LuaIgnoreAttribute(bool allInvisible) {
AccessMembers = allInvisible ? new string[0] : null;
IgnoreMembers = null;
DefinedOnly = false;
BehavesAs = null;
}
/// <summary>
/// Checks whether a given member is visible to Lua code.
/// </summary>
/// <param name="backing">The backing type to check.</param>
/// <param name="member">The name of the member.</param>
/// <returns>True if the member is visible, otherwise false.</returns>
public bool IsMemberVisible(Type backing, string member) {
return IsMemberVisible(backing, member, AccessMembers, IgnoreMembers, DefinedOnly, BehavesAs);
}
/// <summary>
/// Checks whether a given member is visible to Lua code.
/// </summary>
/// <param name="backing">The backing type to check.</param>
/// <param name="member">The name of the member.</param>
/// <param name="access">
/// The members that Lua has access to. If this is not null, then a visible member MUST be in
/// this array.
/// </param>
/// <param name="ignore">The members that Lua does not have access to. Can be null.</param>
/// <param name="definedOnly">
/// If true, then Lua can only access members defined by the given type, otherwise it has access
/// to inherited members.
/// </param>
/// <param name="behavesAs">
/// The type that this class should behave as if it is. If it is null, then it is ignored. The
/// attached type must derive from or implement this type.
/// </param>
/// <returns>True if the member is visible, otherwise false.</returns>
public static bool IsMemberVisible(Type backing, string member, string[] access,
string[] ignore, bool definedOnly, Type behavesAs) {
if (backing == null) {
throw new ArgumentNullException(nameof(backing));
}
if (member == null) {
throw new ArgumentNullException(nameof(member));
}
if (access != null) {
if (!access.Contains(member)) {
return false;
}
}
if (ignore != null) {
if (ignore.Contains(member)) {
return false;
}
}
Func<MemberInfo, bool> visibleMember = (m) =>
m.Name == member &&
m.GetCustomAttributes(typeof(LuaIgnoreAttribute), true).Length == 0;
if (behavesAs != null) {
if (!behavesAs.IsAssignableFrom(backing)) {
throw new InvalidOperationException(Resources.BehavesAsMustDeriveType);
}
var temp = behavesAs.GetCustomAttribute<LuaIgnoreAttribute>(true);
if (temp != null) {
if (!temp.IsMemberVisible(backing, member)) {
return false;
}
} else {
if (!behavesAs.GetMembers().Any(visibleMember)) {
return false;
}
}
} else if (definedOnly) {
// Must only use DeclaredOnly members
var flags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
if (!backing.GetMembers(flags).Any(visibleMember)) {
return false;
}
} else {
if (!backing.GetMembers().Any(visibleMember)) {
return false;
}
}
return true;
}
}
}
| |
//
// X509StoreTest.cs - NUnit tests for X509Store
//
// Author:
// Sebastien Pouliot (spouliot@motus.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
//
#if NET_2_0
using NUnit.Framework;
using System;
using System.Collections;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace MonoTests.System.Security.Cryptography.X509Certificates {
[TestFixture]
public class X509StoreTest : Assertion {
[Test]
public void ConstructorEmpty ()
{
X509Store xs = new X509Store ();
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "MY", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreLocationCurrentUser ()
{
X509Store xs = new X509Store (StoreLocation.CurrentUser);
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "MY", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreLocationLocalMachine ()
{
X509Store xs = new X509Store (StoreLocation.LocalMachine);
// default properties
AssertEquals ("Location", StoreLocation.LocalMachine, xs.Location);
AssertEquals ("Name", "MY", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreStringAddressBook ()
{
X509Store xs = new X509Store ("AddressBook");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "AddressBook", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreStringAuthRoot ()
{
X509Store xs = new X509Store ("AuthRoot");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "AuthRoot", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreStringCertificateAuthority ()
{
X509Store xs = new X509Store ("CA");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "CA", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreStringDisallowed ()
{
X509Store xs = new X509Store ("Disallowed");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "Disallowed", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreStringMy ()
{
X509Store xs = new X509Store ("My");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "My", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreStringRoot ()
{
X509Store xs = new X509Store ("Root");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "Root", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreStringTrustedPeople ()
{
X509Store xs = new X509Store ("TrustedPeople");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "TrustedPeople", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreStringTrustedPublisher ()
{
X509Store xs = new X509Store ("TrustedPublisher");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "TrustedPublisher", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreStringMono ()
{
// mono isn't defined the StoreName
X509Store xs = new X509Store ("Mono");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "Mono", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreNameAddressBook ()
{
X509Store xs = new X509Store (StoreName.AddressBook);
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "AddressBook", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreNameAuthRoot ()
{
X509Store xs = new X509Store (StoreName.AuthRoot);
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "AuthRoot", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreNameCertificateAuthority ()
{
X509Store xs = new X509Store (StoreName.CertificateAuthority);
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "CA", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreNameDisallowed ()
{
X509Store xs = new X509Store (StoreName.Disallowed);
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "Disallowed", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreNameMy () {
X509Store xs = new X509Store (StoreName.My);
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "My", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreNameRoot ()
{
X509Store xs = new X509Store (StoreName.Root);
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "Root", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreNameTrustedPeople ()
{
X509Store xs = new X509Store (StoreName.TrustedPeople);
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "TrustedPeople", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
public void ConstructorStoreNameTrustedPublisher ()
{
X509Store xs = new X509Store (StoreName.TrustedPublisher);
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "TrustedPublisher", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void AddEmptyCertificateToReadOnlyNonExistingStore ()
{
// mono isn't defined the StoreName
X509Store xs = new X509Store ("NonExistingStore");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "NonExistingStore", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
xs.Open (OpenFlags.ReadOnly);
xs.Add (new X509Certificate2 ());
xs.Close ();
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void AddEmptyCertificateToReadWriteNonExistingStore ()
{
// mono isn't defined the StoreName
X509Store xs = new X509Store ("NonExistingStore");
// default properties
AssertEquals ("Location", StoreLocation.CurrentUser, xs.Location);
AssertEquals ("Name", "NonExistingStore", xs.Name);
AssertNotNull ("Certificates", xs.Certificates);
xs.Open (OpenFlags.ReadWrite);
xs.Add (new X509Certificate2 ());
xs.Close ();
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.