context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.ComponentModel;
using Microsoft.PowerShell;
#if CORECLR
using System.Reflection;
#endif
namespace System.Management.Automation
{
/// <summary>
/// Implements Adapter for the COM objects.
/// </summary>
internal class ComAdapter : Adapter
{
private readonly ComTypeInfo _comTypeInfo;
/// <summary>
/// Constructor for the ComAdapter
/// </summary>
/// <param name="typeinfo">typeinfo for the com object we are adapting</param>
internal ComAdapter(ComTypeInfo typeinfo)
{
Diagnostics.Assert(typeinfo != null, "Caller to verify typeinfo is not null.");
_comTypeInfo = typeinfo;
}
internal static string GetComTypeName(string clsid)
{
StringBuilder firstType = new StringBuilder("System.__ComObject");
firstType.Append("#{");
firstType.Append(clsid);
firstType.Append("}");
return firstType.ToString();
}
/// <summary>
/// Returns the TypeNameHierarchy out of an object
/// </summary>
/// <param name="obj">object to get the TypeNameHierarchy from</param>
protected override IEnumerable<string> GetTypeNameHierarchy(object obj)
{
yield return GetComTypeName(_comTypeInfo.Clsid);
foreach (string baseType in GetDotNetTypeNameHierarchy(obj))
{
yield return baseType;
}
}
/// <summary>
/// Returns null if memberName is not a member in the adapter or
/// the corresponding PSMemberInfo
/// </summary>
/// <param name="obj">object to retrieve the PSMemberInfo from</param>
/// <param name="memberName">name of the member to be retrieved</param>
/// <returns>The PSMemberInfo corresponding to memberName from obj</returns>
protected override T GetMember<T>(object obj, string memberName)
{
ComProperty prop;
if (_comTypeInfo.Properties.TryGetValue(memberName, out prop))
{
if (prop.IsParameterized)
{
if (typeof(T).IsAssignableFrom(typeof(PSParameterizedProperty)))
{
return new PSParameterizedProperty(prop.Name, this, obj, prop) as T;
}
}
else if (typeof(T).IsAssignableFrom(typeof(PSProperty)))
{
return new PSProperty(prop.Name, this, obj, prop) as T;
}
}
ComMethod method;
if (typeof(T).IsAssignableFrom(typeof(PSMethod)) &&
(_comTypeInfo != null) && (_comTypeInfo.Methods.TryGetValue(memberName, out method)))
{
PSMethod mshMethod = new PSMethod(method.Name, this, obj, method);
return mshMethod as T;
}
return null;
}
/// <summary>
/// Retrieves all the members available in the object.
/// The adapter implementation is encouraged to cache all properties/methods available
/// in the first call to GetMember and GetMembers so that subsequent
/// calls can use the cache.
/// In the case of the .NET adapter that would be a cache from the .NET type to
/// the public properties and fields available in that type.
/// In the case of the DirectoryEntry adapter, this could be a cache of the objectClass
/// to the properties available in it.
/// </summary>
/// <param name="obj">object to get all the member information from</param>
/// <returns>all members in obj</returns>
protected override PSMemberInfoInternalCollection<T> GetMembers<T>(object obj)
{
PSMemberInfoInternalCollection<T> collection = new PSMemberInfoInternalCollection<T>();
bool lookingForProperties = typeof(T).IsAssignableFrom(typeof(PSProperty));
bool lookingForParameterizedProperties = typeof(T).IsAssignableFrom(typeof(PSParameterizedProperty));
if (lookingForProperties || lookingForParameterizedProperties)
{
foreach (ComProperty prop in _comTypeInfo.Properties.Values)
{
if (prop.IsParameterized)
{
if (lookingForParameterizedProperties)
{
collection.Add(new PSParameterizedProperty(prop.Name, this, obj, prop) as T);
}
}
else if (lookingForProperties)
{
collection.Add(new PSProperty(prop.Name, this, obj, prop) as T);
}
}
}
bool lookingForMethods = typeof(T).IsAssignableFrom(typeof(PSMethod));
if (lookingForMethods)
{
foreach (ComMethod method in _comTypeInfo.Methods.Values)
{
if (collection[method.Name] == null)
{
PSMethod mshmethod = new PSMethod(method.Name, this, obj, method);
collection.Add(mshmethod as T);
}
}
}
return collection;
}
/// <summary>
/// Returns an array with the property attributes
/// </summary>
/// <param name="property">property we want the attributes from</param>
/// <returns>an array with the property attributes</returns>
protected override AttributeCollection PropertyAttributes(PSProperty property)
{
return new AttributeCollection();
}
/// <summary>
/// Returns the value from a property coming from a previous call to DoGetProperty
/// </summary>
/// <param name="property">PSProperty coming from a previous call to DoGetProperty</param>
/// <returns>The value of the property</returns>
protected override object PropertyGet(PSProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.GetValue(property.baseObject);
}
/// <summary>
/// Sets the value of a property coming from a previous call to DoGetProperty
/// </summary>
/// <param name="property">PSProperty coming from a previous call to DoGetProperty</param>
/// <param name="setValue">value to set the property with</param>
/// <param name="convertIfPossible">instructs the adapter to convert before setting, if the adapter suports conversion</param>
protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible)
{
ComProperty prop = (ComProperty)property.adapterData;
prop.SetValue(property.baseObject, setValue);
}
/// <summary>
/// Returns true if the property is settable
/// </summary>
/// <param name="property">property to check</param>
/// <returns>true if the property is settable</returns>
protected override bool PropertyIsSettable(PSProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.IsSettable;
}
/// <summary>
/// Returns true if the property is gettable
/// </summary>
/// <param name="property">property to check</param>
/// <returns>true if the property is gettable</returns>
protected override bool PropertyIsGettable(PSProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.IsGettable;
}
/// <summary>
/// Returns the name of the type corresponding to the property
/// </summary>
/// <param name="property">PSProperty obtained in a previous DoGetProperty</param>
/// <param name="forDisplay">True if the result is for display purposes only</param>
/// <returns>the name of the type corresponding to the property</returns>
protected override string PropertyType(PSProperty property, bool forDisplay)
{
ComProperty prop = (ComProperty)property.adapterData;
return forDisplay ? ToStringCodeMethods.Type(prop.Type) : prop.Type.FullName;
}
/// <summary>
/// get the property signature.
/// </summary>
/// <param name="property">property object whose signature we want</param>
/// <returns>string representing the signature of the property</returns>
protected override string PropertyToString(PSProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.ToString();
}
#region Methods
/// <summary>
/// Called after a non null return from GetMethodData to try to call
/// the method with the arguments
/// </summary>
/// <param name="method">the non empty return from GetMethods</param>
/// <param name="arguments">the arguments to use</param>
/// <returns>the return value for the method</returns>
protected override object MethodInvoke(PSMethod method, object[] arguments)
{
ComMethod commethod = (ComMethod)method.adapterData;
return commethod.InvokeMethod(method, arguments);
}
/// <summary>
/// Called after a non null return from GetMethodData to return the overloads
/// </summary>
/// <param name="method">the return of GetMethodData</param>
/// <returns></returns>
protected override Collection<String> MethodDefinitions(PSMethod method)
{
ComMethod commethod = (ComMethod)method.adapterData;
return commethod.MethodDefinitions();
}
#endregion
#region parameterized property
/// <summary>
/// Returns the name of the type corresponding to the property's value
/// </summary>
/// <param name="property">property obtained in a previous GetMember</param>
/// <returns>the name of the type corresponding to the member</returns>
protected override string ParameterizedPropertyType(PSParameterizedProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.Type.FullName;
}
/// <summary>
/// Returns true if the property is settable
/// </summary>
/// <param name="property">property to check</param>
/// <returns>true if the property is settable</returns>
protected override bool ParameterizedPropertyIsSettable(PSParameterizedProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.IsSettable;
}
/// <summary>
/// Returns true if the property is gettable
/// </summary>
/// <param name="property">property to check</param>
/// <returns>true if the property is gettable</returns>
protected override bool ParameterizedPropertyIsGettable(PSParameterizedProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.IsGettable;
}
/// <summary>
/// Called after a non null return from GetMember to get the property value
/// </summary>
/// <param name="property">the non empty return from GetMember</param>
/// <param name="arguments">the arguments to use</param>
/// <returns>the return value for the property</returns>
protected override object ParameterizedPropertyGet(PSParameterizedProperty property, object[] arguments)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.GetValue(property.baseObject, arguments);
}
/// <summary>
/// Called after a non null return from GetMember to set the property value
/// </summary>
/// <param name="property">the non empty return from GetMember</param>
/// <param name="setValue">the value to set property with</param>
/// <param name="arguments">the arguments to use</param>
protected override void ParameterizedPropertySet(PSParameterizedProperty property, object setValue, object[] arguments)
{
ComProperty prop = (ComProperty)property.adapterData;
prop.SetValue(property.baseObject, setValue, arguments);
}
/// <summary>
/// Returns the string representation of the property in the object
/// </summary>
/// <param name="property">property obtained in a previous GetMember</param>
/// <returns>the string representation of the property in the object</returns>
protected override string ParameterizedPropertyToString(PSParameterizedProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.ToString();
}
/// <summary>
/// Called after a non null return from GetMember to return the overloads
/// </summary>
/// <param name="property">the return of GetMember</param>
protected override Collection<String> ParameterizedPropertyDefinitions(PSParameterizedProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
Collection<string> returnValue = new Collection<string> { prop.GetDefinition() };
return returnValue;
}
#endregion parameterized property
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class MethodInvocationExpression : Expression, INodeWithArguments
{
protected Expression _target;
protected ExpressionCollection _arguments;
protected ExpressionPairCollection _namedArguments;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public MethodInvocationExpression CloneNode()
{
return (MethodInvocationExpression)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public MethodInvocationExpression CleanClone()
{
return (MethodInvocationExpression)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.MethodInvocationExpression; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnMethodInvocationExpression(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( MethodInvocationExpression)node;
if (!Node.Matches(_target, other._target)) return NoMatch("MethodInvocationExpression._target");
if (!Node.AllMatch(_arguments, other._arguments)) return NoMatch("MethodInvocationExpression._arguments");
if (!Node.AllMatch(_namedArguments, other._namedArguments)) return NoMatch("MethodInvocationExpression._namedArguments");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_target == existing)
{
this.Target = (Expression)newNode;
return true;
}
if (_arguments != null)
{
Expression item = existing as Expression;
if (null != item)
{
Expression newItem = (Expression)newNode;
if (_arguments.Replace(item, newItem))
{
return true;
}
}
}
if (_namedArguments != null)
{
ExpressionPair item = existing as ExpressionPair;
if (null != item)
{
ExpressionPair newItem = (ExpressionPair)newNode;
if (_namedArguments.Replace(item, newItem))
{
return true;
}
}
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
MethodInvocationExpression clone = (MethodInvocationExpression)FormatterServices.GetUninitializedObject(typeof(MethodInvocationExpression));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._expressionType = _expressionType;
if (null != _target)
{
clone._target = _target.Clone() as Expression;
clone._target.InitializeParent(clone);
}
if (null != _arguments)
{
clone._arguments = _arguments.Clone() as ExpressionCollection;
clone._arguments.InitializeParent(clone);
}
if (null != _namedArguments)
{
clone._namedArguments = _namedArguments.Clone() as ExpressionPairCollection;
clone._namedArguments.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
_expressionType = null;
if (null != _target)
{
_target.ClearTypeSystemBindings();
}
if (null != _arguments)
{
_arguments.ClearTypeSystemBindings();
}
if (null != _namedArguments)
{
_namedArguments.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression Target
{
get { return _target; }
set
{
if (_target != value)
{
_target = value;
if (null != _target)
{
_target.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(Expression))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ExpressionCollection Arguments
{
get { return _arguments ?? (_arguments = new ExpressionCollection(this)); }
set
{
if (_arguments != value)
{
_arguments = value;
if (null != _arguments)
{
_arguments.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(ExpressionPair))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ExpressionPairCollection NamedArguments
{
get { return _namedArguments ?? (_namedArguments = new ExpressionPairCollection(this)); }
set
{
if (_namedArguments != value)
{
_namedArguments = value;
if (null != _namedArguments)
{
_namedArguments.InitializeParent(this);
}
}
}
}
}
}
| |
using System;
using SharpVectors.Dom;
using SharpVectors.Dom.Css;
using SharpVectors.Dom.Events;
using SharpVectors.Dom.Stylesheets;
using SharpVectors.Dom.Svg;
using SharpVectors.Dom.Views;
using System.Xml;
namespace SharpVectors.Scripting
{
/// <summary>
/// Implementation wrapper for IScriptableCssRuleList
/// </summary>
public class ScriptableCssRuleList : ScriptableObject, IScriptableCssRuleList
{
public ScriptableCssRuleList(object baseObject) : base (baseObject) { }
#region Methods - IScriptableCssRuleList
public IScriptableCssRule item(ulong index)
{
object result = ((ICssRuleList)baseObject)[index];
return (result != null) ? (IScriptableCssRule)ScriptableObject.CreateWrapper(result) : null;
}
#endregion
#region Properties - IScriptableCssRuleList
public ulong length
{
get { return ((ICssRuleList)baseObject).Length; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssRule
/// </summary>
public class ScriptableCssRule : ScriptableObject, IScriptableCssRule
{
const ushort UNKNOWN_RULE = 0;
const ushort STYLE_RULE = 1;
const ushort CHARSET_RULE = 2;
const ushort IMPORT_RULE = 3;
const ushort MEDIA_RULE = 4;
const ushort FONT_FACE_RULE = 5;
const ushort PAGE_RULE = 6;
public ScriptableCssRule(object baseObject) : base (baseObject) { }
#region Properties - IScriptableCssRule
public ushort type
{
get { return (ushort)((ICssRule)baseObject).Type; }
}
public string cssText
{
get { return ((ICssRule)baseObject).CssText; }
set { ((ICssRule)baseObject).CssText = value; }
}
public IScriptableCssStyleSheet parentStyleSheet
{
get { object result = ((ICssRule)baseObject).ParentStyleSheet; return (result != null) ? (IScriptableCssStyleSheet)ScriptableObject.CreateWrapper(result) : null; }
}
public IScriptableCssRule parentRule
{
get { object result = ((ICssRule)baseObject).ParentRule; return (result != null) ? (IScriptableCssRule)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssStyleRule
/// </summary>
public class ScriptableCssStyleRule : ScriptableCssRule, IScriptableCssStyleRule
{
public ScriptableCssStyleRule(object baseObject) : base (baseObject) { }
#region Properties - IScriptableCssStyleRule
public string selectorText
{
get { return ((ICssStyleRule)baseObject).SelectorText; }
set { ((ICssStyleRule)baseObject).SelectorText = value; }
}
public IScriptableCssStyleDeclaration style
{
get { object result = ((ICssStyleRule)baseObject).Style; return (result != null) ? (IScriptableCssStyleDeclaration)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssMediaRule
/// </summary>
public class ScriptableCssMediaRule : ScriptableCssRule, IScriptableCssMediaRule
{
public ScriptableCssMediaRule(object baseObject) : base (baseObject) { }
#region Methods - IScriptableCssMediaRule
public ulong insertRule(string rule, ulong index)
{
return ((ICssMediaRule)baseObject).InsertRule(rule, index);
}
public void deleteRule(ulong index)
{
((ICssMediaRule)baseObject).DeleteRule(index);
}
#endregion
#region Properties - IScriptableCssMediaRule
public IScriptableMediaList media
{
get { object result = ((ICssMediaRule)baseObject).Media; return (result != null) ? (IScriptableMediaList)ScriptableObject.CreateWrapper(result) : null; }
}
public IScriptableCssRuleList cssRules
{
get { object result = ((ICssMediaRule)baseObject).CssRules; return (result != null) ? (IScriptableCssRuleList)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssFontFaceRule
/// </summary>
public class ScriptableCssFontFaceRule : ScriptableCssRule, IScriptableCssFontFaceRule
{
public ScriptableCssFontFaceRule(object baseObject) : base (baseObject) { }
#region Properties - IScriptableCssFontFaceRule
public IScriptableCssStyleDeclaration style
{
get { object result = ((ICssFontFaceRule)baseObject).Style; return (result != null) ? (IScriptableCssStyleDeclaration)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssPageRule
/// </summary>
public class ScriptableCssPageRule : ScriptableCssRule, IScriptableCssPageRule
{
public ScriptableCssPageRule(object baseObject) : base (baseObject) { }
#region Properties - IScriptableCssPageRule
public string selectorText
{
get { return ((ICssPageRule)baseObject).SelectorText; }
set { ((ICssPageRule)baseObject).SelectorText = value; }
}
public IScriptableCssStyleDeclaration style
{
get { object result = ((ICssPageRule)baseObject).Style; return (result != null) ? (IScriptableCssStyleDeclaration)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssImportRule
/// </summary>
public class ScriptableCssImportRule : ScriptableCssRule, IScriptableCssImportRule
{
public ScriptableCssImportRule(object baseObject) : base (baseObject) { }
#region Properties - IScriptableCssImportRule
public string href
{
get { return ((ICssImportRule)baseObject).Href; }
}
public IScriptableMediaList media
{
get { object result = ((ICssImportRule)baseObject).Media; return (result != null) ? (IScriptableMediaList)ScriptableObject.CreateWrapper(result) : null; }
}
public IScriptableCssStyleSheet styleSheet
{
get { object result = ((ICssImportRule)baseObject).StyleSheet; return (result != null) ? (IScriptableCssStyleSheet)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssCharsetRule
/// </summary>
public class ScriptableCssCharsetRule : ScriptableCssRule, IScriptableCssCharsetRule
{
public ScriptableCssCharsetRule(object baseObject) : base (baseObject) { }
#region Properties - IScriptableCssCharsetRule
public string encoding
{
get { return ((ICssCharsetRule)baseObject).Encoding; }
set { ((ICssCharsetRule)baseObject).Encoding = value; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssUnknownRule
/// </summary>
public class ScriptableCssUnknownRule : ScriptableCssRule, IScriptableCssUnknownRule
{
public ScriptableCssUnknownRule(object baseObject) : base (baseObject) { }
}
/// <summary>
/// Implementation wrapper for IScriptableCssStyleDeclaration
/// </summary>
public class ScriptableCssStyleDeclaration : ScriptableObject, IScriptableCssStyleDeclaration
{
public ScriptableCssStyleDeclaration(object baseObject) : base (baseObject) { }
#region Methods - IScriptableCssStyleDeclaration
public string getPropertyValue(string propertyName)
{
return ((ICssStyleDeclaration)baseObject).GetPropertyValue(propertyName);
}
public IScriptableCssValue getPropertyCSSValue(string propertyName)
{
object result = ((ICssStyleDeclaration)baseObject).GetPropertyCssValue(propertyName);
return (result != null) ? (IScriptableCssValue)ScriptableObject.CreateWrapper(result) : null;
}
public string removeProperty(string propertyName)
{
return ((ICssStyleDeclaration)baseObject).RemoveProperty(propertyName);
}
public string getPropertyPriority(string propertyName)
{
return ((ICssStyleDeclaration)baseObject).GetPropertyPriority(propertyName);
}
public void setProperty(string propertyName, string value, string priority)
{
((ICssStyleDeclaration)baseObject).SetProperty(propertyName, value, priority);
}
public string item(ulong index)
{
return ((ICssStyleDeclaration)baseObject)[index];
}
#endregion
#region Properties - IScriptableCssStyleDeclaration
public string cssText
{
get { return ((ICssStyleDeclaration)baseObject).CssText; }
set { ((ICssStyleDeclaration)baseObject).CssText = value; }
}
public ulong length
{
get { return ((ICssStyleDeclaration)baseObject).Length; }
}
public IScriptableCssRule parentRule
{
get { object result = ((ICssStyleDeclaration)baseObject).ParentRule; return (result != null) ? (IScriptableCssRule)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssValue
/// </summary>
public class ScriptableCssValue : ScriptableObject, IScriptableCssValue
{
const ushort CSS_INHERIT = 0;
const ushort CSS_PRIMITIVE_VALUE = 1;
const ushort CSS_VALUE_LIST = 2;
const ushort CSS_CUSTOM = 3;
public ScriptableCssValue(object baseObject) : base (baseObject) { }
#region Properties - IScriptableCssValue
public string cssText
{
get { return ((ICssValue)baseObject).CssText; }
set { ((ICssValue)baseObject).CssText = value; }
}
public ushort cssValueType
{
get { return (ushort)((ICssValue)baseObject).CssValueType; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssPrimitiveValue
/// </summary>
public class ScriptableCssPrimitiveValue : ScriptableCssValue, IScriptableCssPrimitiveValue
{
const ushort CSS_UNKNOWN = 0;
const ushort CSS_NUMBER = 1;
const ushort CSS_PERCENTAGE = 2;
const ushort CSS_EMS = 3;
const ushort CSS_EXS = 4;
const ushort CSS_PX = 5;
const ushort CSS_CM = 6;
const ushort CSS_MM = 7;
const ushort CSS_IN = 8;
const ushort CSS_PT = 9;
const ushort CSS_PC = 10;
const ushort CSS_DEG = 11;
const ushort CSS_RAD = 12;
const ushort CSS_GRAD = 13;
const ushort CSS_MS = 14;
const ushort CSS_S = 15;
const ushort CSS_HZ = 16;
const ushort CSS_KHZ = 17;
const ushort CSS_DIMENSION = 18;
const ushort CSS_STRING = 19;
const ushort CSS_URI = 20;
const ushort CSS_IDENT = 21;
const ushort CSS_ATTR = 22;
const ushort CSS_COUNTER = 23;
const ushort CSS_RECT = 24;
const ushort CSS_RGBCOLOR = 25;
public ScriptableCssPrimitiveValue(object baseObject) : base (baseObject) { }
#region Methods - IScriptableCssPrimitiveValue
public void setFloatValue(ushort unitType, float floatValue)
{
((ICssPrimitiveValue)baseObject).SetFloatValue((CssPrimitiveType)unitType, floatValue);
}
public float getFloatValue(ushort unitType)
{
return (float)((ICssPrimitiveValue)baseObject).GetFloatValue((CssPrimitiveType)unitType);
}
public void setStringValue(ushort stringType, string stringValue)
{
((ICssPrimitiveValue)baseObject).SetStringValue((CssPrimitiveType)stringType, stringValue);
}
public string getStringValue()
{
return ((ICssPrimitiveValue)baseObject).GetStringValue();
}
public IScriptableCounter getCounterValue()
{
object result = ((ICssPrimitiveValue)baseObject).GetCounterValue();
return (result != null) ? (IScriptableCounter)ScriptableObject.CreateWrapper(result) : null;
}
public IScriptableRect getRectValue()
{
object result = ((ICssPrimitiveValue)baseObject).GetRectValue();
return (result != null) ? (IScriptableRect)ScriptableObject.CreateWrapper(result) : null;
}
public IScriptableRgbColor getRGBColorValue()
{
object result = ((ICssPrimitiveValue)baseObject).GetRgbColorValue();
return (result != null) ? (IScriptableRgbColor)ScriptableObject.CreateWrapper(result) : null;
}
#endregion
#region Properties - IScriptableCssPrimitiveValue
public ushort primitiveType
{
get { return (ushort)((ICssPrimitiveValue)baseObject).PrimitiveType; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCssValueList
/// </summary>
public class ScriptableCssValueList : ScriptableCssValue, IScriptableCssValueList
{
public ScriptableCssValueList(object baseObject) : base (baseObject) { }
#region Methods - IScriptableCssValueList
public IScriptableCssValue item(ulong index)
{
object result = ((ICssValueList)baseObject)[index];
return (result != null) ? (IScriptableCssValue)ScriptableObject.CreateWrapper(result) : null;
}
#endregion
#region Properties - IScriptableCssValueList
public ulong length
{
get { return ((ICssValueList)baseObject).Length; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableRgbColor
/// </summary>
public class ScriptableRgbColor : ScriptableObject, IScriptableRgbColor
{
public ScriptableRgbColor(object baseObject) : base (baseObject) { }
#region Properties - IScriptableRgbColor
public IScriptableCssPrimitiveValue red
{
get { object result = ((IRgbColor)baseObject).Red; return (result != null) ? (IScriptableCssPrimitiveValue)ScriptableObject.CreateWrapper(result) : null; }
}
public IScriptableCssPrimitiveValue green
{
get { object result = ((IRgbColor)baseObject).Green; return (result != null) ? (IScriptableCssPrimitiveValue)ScriptableObject.CreateWrapper(result) : null; }
}
public IScriptableCssPrimitiveValue blue
{
get { object result = ((IRgbColor)baseObject).Blue; return (result != null) ? (IScriptableCssPrimitiveValue)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableRect
/// </summary>
public class ScriptableRect : ScriptableObject, IScriptableRect
{
public ScriptableRect(object baseObject) : base (baseObject) { }
#region Properties - IScriptableRect
public IScriptableCssPrimitiveValue top
{
get { object result = ((IRect)baseObject).Top; return (result != null) ? (IScriptableCssPrimitiveValue)ScriptableObject.CreateWrapper(result) : null; }
}
public IScriptableCssPrimitiveValue right
{
get { object result = ((IRect)baseObject).Right; return (result != null) ? (IScriptableCssPrimitiveValue)ScriptableObject.CreateWrapper(result) : null; }
}
public IScriptableCssPrimitiveValue bottom
{
get { object result = ((IRect)baseObject).Bottom; return (result != null) ? (IScriptableCssPrimitiveValue)ScriptableObject.CreateWrapper(result) : null; }
}
public IScriptableCssPrimitiveValue left
{
get { object result = ((IRect)baseObject).Left; return (result != null) ? (IScriptableCssPrimitiveValue)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableCounter
/// </summary>
public class ScriptableCounter : ScriptableObject, IScriptableCounter
{
public ScriptableCounter(object baseObject) : base (baseObject) { }
#region Properties - IScriptableCounter
public string identifier
{
get { return ((ICounter)baseObject).Identifier; }
}
public string listStyle
{
get { return ((ICounter)baseObject).ListStyle; }
}
public string separator
{
get { return ((ICounter)baseObject).Separator; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableElementCssInlineStyle
/// </summary>
public class ScriptableElementCssInlineStyle : ScriptableObject, IScriptableElementCssInlineStyle
{
public ScriptableElementCssInlineStyle(object baseObject) : base (baseObject) { }
#region Properties - IScriptableElementCssInlineStyle
public IScriptableCssStyleDeclaration style
{
get { object result = ((IElementCssInlineStyle)baseObject).Style; return (result != null) ? (IScriptableCssStyleDeclaration)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/*
/// <summary>
/// Implementation wrapper for IScriptableCss2Properties
/// </summary>
public class ScriptableCss2Properties : ScriptableObject, IScriptableCss2Properties
{
public ScriptableCss2Properties(object baseObject) : base (baseObject) { }
#region Properties - IScriptableCss2Properties
public string azimuth
{
get { return ((ICss2Properties)baseObject).Azimuth; }
set { ((ICss2Properties)baseObject).Azimuth = value; }
}
public string background
{
get { return ((ICss2Properties)baseObject).Background; }
set { ((ICss2Properties)baseObject).Background = value; }
}
public string backgroundAttachment
{
get { return ((ICss2Properties)baseObject).BackgroundAttachment; }
set { ((ICss2Properties)baseObject).BackgroundAttachment = value; }
}
public string backgroundColor
{
get { return ((ICss2Properties)baseObject).BackgroundColor; }
set { ((ICss2Properties)baseObject).BackgroundColor = value; }
}
public string backgroundImage
{
get { return ((ICss2Properties)baseObject).BackgroundImage; }
set { ((ICss2Properties)baseObject).BackgroundImage = value; }
}
public string backgroundPosition
{
get { return ((ICss2Properties)baseObject).BackgroundPosition; }
set { ((ICss2Properties)baseObject).BackgroundPosition = value; }
}
public string backgroundRepeat
{
get { return ((ICss2Properties)baseObject).BackgroundRepeat; }
set { ((ICss2Properties)baseObject).BackgroundRepeat = value; }
}
public string border
{
get { return ((ICss2Properties)baseObject).Border; }
set { ((ICss2Properties)baseObject).Border = value; }
}
public string borderCollapse
{
get { return ((ICss2Properties)baseObject).BorderCollapse; }
set { ((ICss2Properties)baseObject).BorderCollapse = value; }
}
public string borderColor
{
get { return ((ICss2Properties)baseObject).BorderColor; }
set { ((ICss2Properties)baseObject).BorderColor = value; }
}
public string borderSpacing
{
get { return ((ICss2Properties)baseObject).BorderSpacing; }
set { ((ICss2Properties)baseObject).BorderSpacing = value; }
}
public string borderStyle
{
get { return ((ICss2Properties)baseObject).BorderStyle; }
set { ((ICss2Properties)baseObject).BorderStyle = value; }
}
public string borderTop
{
get { return ((ICss2Properties)baseObject).BorderTop; }
set { ((ICss2Properties)baseObject).BorderTop = value; }
}
public string borderRight
{
get { return ((ICss2Properties)baseObject).BorderRight; }
set { ((ICss2Properties)baseObject).BorderRight = value; }
}
public string borderBottom
{
get { return ((ICss2Properties)baseObject).BorderBottom; }
set { ((ICss2Properties)baseObject).BorderBottom = value; }
}
public string borderLeft
{
get { return ((ICss2Properties)baseObject).BorderLeft; }
set { ((ICss2Properties)baseObject).BorderLeft = value; }
}
public string borderTopColor
{
get { return ((ICss2Properties)baseObject).BorderTopColor; }
set { ((ICss2Properties)baseObject).BorderTopColor = value; }
}
public string borderRightColor
{
get { return ((ICss2Properties)baseObject).BorderRightColor; }
set { ((ICss2Properties)baseObject).BorderRightColor = value; }
}
public string borderBottomColor
{
get { return ((ICss2Properties)baseObject).BorderBottomColor; }
set { ((ICss2Properties)baseObject).BorderBottomColor = value; }
}
public string borderLeftColor
{
get { return ((ICss2Properties)baseObject).BorderLeftColor; }
set { ((ICss2Properties)baseObject).BorderLeftColor = value; }
}
public string borderTopStyle
{
get { return ((ICss2Properties)baseObject).BorderTopStyle; }
set { ((ICss2Properties)baseObject).BorderTopStyle = value; }
}
public string borderRightStyle
{
get { return ((ICss2Properties)baseObject).BorderRightStyle; }
set { ((ICss2Properties)baseObject).BorderRightStyle = value; }
}
public string borderBottomStyle
{
get { return ((ICss2Properties)baseObject).BorderBottomStyle; }
set { ((ICss2Properties)baseObject).BorderBottomStyle = value; }
}
public string borderLeftStyle
{
get { return ((ICss2Properties)baseObject).BorderLeftStyle; }
set { ((ICss2Properties)baseObject).BorderLeftStyle = value; }
}
public string borderTopWidth
{
get { return ((ICss2Properties)baseObject).BorderTopWidth; }
set { ((ICss2Properties)baseObject).BorderTopWidth = value; }
}
public string borderRightWidth
{
get { return ((ICss2Properties)baseObject).BorderRightWidth; }
set { ((ICss2Properties)baseObject).BorderRightWidth = value; }
}
public string borderBottomWidth
{
get { return ((ICss2Properties)baseObject).BorderBottomWidth; }
set { ((ICss2Properties)baseObject).BorderBottomWidth = value; }
}
public string borderLeftWidth
{
get { return ((ICss2Properties)baseObject).BorderLeftWidth; }
set { ((ICss2Properties)baseObject).BorderLeftWidth = value; }
}
public string borderWidth
{
get { return ((ICss2Properties)baseObject).BorderWidth; }
set { ((ICss2Properties)baseObject).BorderWidth = value; }
}
public string bottom
{
get { return ((ICss2Properties)baseObject).Bottom; }
set { ((ICss2Properties)baseObject).Bottom = value; }
}
public string captionSide
{
get { return ((ICss2Properties)baseObject).CaptionSide; }
set { ((ICss2Properties)baseObject).CaptionSide = value; }
}
public string clear
{
get { return ((ICss2Properties)baseObject).Clear; }
set { ((ICss2Properties)baseObject).Clear = value; }
}
public string clip
{
get { return ((ICss2Properties)baseObject).Clip; }
set { ((ICss2Properties)baseObject).Clip = value; }
}
public string color
{
get { return ((ICss2Properties)baseObject).Color; }
set { ((ICss2Properties)baseObject).Color = value; }
}
public string content
{
get { return ((ICss2Properties)baseObject).Content; }
set { ((ICss2Properties)baseObject).Content = value; }
}
public string counterIncrement
{
get { return ((ICss2Properties)baseObject).CounterIncrement; }
set { ((ICss2Properties)baseObject).CounterIncrement = value; }
}
public string counterReset
{
get { return ((ICss2Properties)baseObject).CounterReset; }
set { ((ICss2Properties)baseObject).CounterReset = value; }
}
public string cue
{
get { return ((ICss2Properties)baseObject).Cue; }
set { ((ICss2Properties)baseObject).Cue = value; }
}
public string cueAfter
{
get { return ((ICss2Properties)baseObject).CueAfter; }
set { ((ICss2Properties)baseObject).CueAfter = value; }
}
public string cueBefore
{
get { return ((ICss2Properties)baseObject).CueBefore; }
set { ((ICss2Properties)baseObject).CueBefore = value; }
}
public string cursor
{
get { return ((ICss2Properties)baseObject).Cursor; }
set { ((ICss2Properties)baseObject).Cursor = value; }
}
public string direction
{
get { return ((ICss2Properties)baseObject).Direction; }
set { ((ICss2Properties)baseObject).Direction = value; }
}
public string display
{
get { return ((ICss2Properties)baseObject).Display; }
set { ((ICss2Properties)baseObject).Display = value; }
}
public string elevation
{
get { return ((ICss2Properties)baseObject).Elevation; }
set { ((ICss2Properties)baseObject).Elevation = value; }
}
public string emptyCells
{
get { return ((ICss2Properties)baseObject).EmptyCells; }
set { ((ICss2Properties)baseObject).EmptyCells = value; }
}
public string cssFloat
{
get { return ((ICss2Properties)baseObject).CssFloat; }
set { ((ICss2Properties)baseObject).CssFloat = value; }
}
public string font
{
get { return ((ICss2Properties)baseObject).Font; }
set { ((ICss2Properties)baseObject).Font = value; }
}
public string fontFamily
{
get { return ((ICss2Properties)baseObject).FontFamily; }
set { ((ICss2Properties)baseObject).FontFamily = value; }
}
public string fontSize
{
get { return ((ICss2Properties)baseObject).FontSize; }
set { ((ICss2Properties)baseObject).FontSize = value; }
}
public string fontSizeAdjust
{
get { return ((ICss2Properties)baseObject).FontSizeAdjust; }
set { ((ICss2Properties)baseObject).FontSizeAdjust = value; }
}
public string fontStretch
{
get { return ((ICss2Properties)baseObject).FontStretch; }
set { ((ICss2Properties)baseObject).FontStretch = value; }
}
public string fontStyle
{
get { return ((ICss2Properties)baseObject).FontStyle; }
set { ((ICss2Properties)baseObject).FontStyle = value; }
}
public string fontVariant
{
get { return ((ICss2Properties)baseObject).FontVariant; }
set { ((ICss2Properties)baseObject).FontVariant = value; }
}
public string fontWeight
{
get { return ((ICss2Properties)baseObject).FontWeight; }
set { ((ICss2Properties)baseObject).FontWeight = value; }
}
public string height
{
get { return ((ICss2Properties)baseObject).Height; }
set { ((ICss2Properties)baseObject).Height = value; }
}
public string left
{
get { return ((ICss2Properties)baseObject).Left; }
set { ((ICss2Properties)baseObject).Left = value; }
}
public string letterSpacing
{
get { return ((ICss2Properties)baseObject).LetterSpacing; }
set { ((ICss2Properties)baseObject).LetterSpacing = value; }
}
public string lineHeight
{
get { return ((ICss2Properties)baseObject).LineHeight; }
set { ((ICss2Properties)baseObject).LineHeight = value; }
}
public string listStyle
{
get { return ((ICss2Properties)baseObject).ListStyle; }
set { ((ICss2Properties)baseObject).ListStyle = value; }
}
public string listStyleImage
{
get { return ((ICss2Properties)baseObject).ListStyleImage; }
set { ((ICss2Properties)baseObject).ListStyleImage = value; }
}
public string listStylePosition
{
get { return ((ICss2Properties)baseObject).ListStylePosition; }
set { ((ICss2Properties)baseObject).ListStylePosition = value; }
}
public string listStyleType
{
get { return ((ICss2Properties)baseObject).ListStyleType; }
set { ((ICss2Properties)baseObject).ListStyleType = value; }
}
public string margin
{
get { return ((ICss2Properties)baseObject).Margin; }
set { ((ICss2Properties)baseObject).Margin = value; }
}
public string marginTop
{
get { return ((ICss2Properties)baseObject).MarginTop; }
set { ((ICss2Properties)baseObject).MarginTop = value; }
}
public string marginRight
{
get { return ((ICss2Properties)baseObject).MarginRight; }
set { ((ICss2Properties)baseObject).MarginRight = value; }
}
public string marginBottom
{
get { return ((ICss2Properties)baseObject).MarginBottom; }
set { ((ICss2Properties)baseObject).MarginBottom = value; }
}
public string marginLeft
{
get { return ((ICss2Properties)baseObject).MarginLeft; }
set { ((ICss2Properties)baseObject).MarginLeft = value; }
}
public string markerOffset
{
get { return ((ICss2Properties)baseObject).MarkerOffset; }
set { ((ICss2Properties)baseObject).MarkerOffset = value; }
}
public string marks
{
get { return ((ICss2Properties)baseObject).Marks; }
set { ((ICss2Properties)baseObject).Marks = value; }
}
public string maxHeight
{
get { return ((ICss2Properties)baseObject).MaxHeight; }
set { ((ICss2Properties)baseObject).MaxHeight = value; }
}
public string maxWidth
{
get { return ((ICss2Properties)baseObject).MaxWidth; }
set { ((ICss2Properties)baseObject).MaxWidth = value; }
}
public string minHeight
{
get { return ((ICss2Properties)baseObject).MinHeight; }
set { ((ICss2Properties)baseObject).MinHeight = value; }
}
public string minWidth
{
get { return ((ICss2Properties)baseObject).MinWidth; }
set { ((ICss2Properties)baseObject).MinWidth = value; }
}
public string orphans
{
get { return ((ICss2Properties)baseObject).Orphans; }
set { ((ICss2Properties)baseObject).Orphans = value; }
}
public string outline
{
get { return ((ICss2Properties)baseObject).Outline; }
set { ((ICss2Properties)baseObject).Outline = value; }
}
public string outlineColor
{
get { return ((ICss2Properties)baseObject).OutlineColor; }
set { ((ICss2Properties)baseObject).OutlineColor = value; }
}
public string outlineStyle
{
get { return ((ICss2Properties)baseObject).OutlineStyle; }
set { ((ICss2Properties)baseObject).OutlineStyle = value; }
}
public string outlineWidth
{
get { return ((ICss2Properties)baseObject).OutlineWidth; }
set { ((ICss2Properties)baseObject).OutlineWidth = value; }
}
public string overflow
{
get { return ((ICss2Properties)baseObject).Overflow; }
set { ((ICss2Properties)baseObject).Overflow = value; }
}
public string padding
{
get { return ((ICss2Properties)baseObject).Padding; }
set { ((ICss2Properties)baseObject).Padding = value; }
}
public string paddingTop
{
get { return ((ICss2Properties)baseObject).PaddingTop; }
set { ((ICss2Properties)baseObject).PaddingTop = value; }
}
public string paddingRight
{
get { return ((ICss2Properties)baseObject).PaddingRight; }
set { ((ICss2Properties)baseObject).PaddingRight = value; }
}
public string paddingBottom
{
get { return ((ICss2Properties)baseObject).PaddingBottom; }
set { ((ICss2Properties)baseObject).PaddingBottom = value; }
}
public string paddingLeft
{
get { return ((ICss2Properties)baseObject).PaddingLeft; }
set { ((ICss2Properties)baseObject).PaddingLeft = value; }
}
public string page
{
get { return ((ICss2Properties)baseObject).Page; }
set { ((ICss2Properties)baseObject).Page = value; }
}
public string pageBreakAfter
{
get { return ((ICss2Properties)baseObject).PageBreakAfter; }
set { ((ICss2Properties)baseObject).PageBreakAfter = value; }
}
public string pageBreakBefore
{
get { return ((ICss2Properties)baseObject).PageBreakBefore; }
set { ((ICss2Properties)baseObject).PageBreakBefore = value; }
}
public string pageBreakInside
{
get { return ((ICss2Properties)baseObject).PageBreakInside; }
set { ((ICss2Properties)baseObject).PageBreakInside = value; }
}
public string pause
{
get { return ((ICss2Properties)baseObject).Pause; }
set { ((ICss2Properties)baseObject).Pause = value; }
}
public string pauseAfter
{
get { return ((ICss2Properties)baseObject).PauseAfter; }
set { ((ICss2Properties)baseObject).PauseAfter = value; }
}
public string pauseBefore
{
get { return ((ICss2Properties)baseObject).PauseBefore; }
set { ((ICss2Properties)baseObject).PauseBefore = value; }
}
public string pitch
{
get { return ((ICss2Properties)baseObject).Pitch; }
set { ((ICss2Properties)baseObject).Pitch = value; }
}
public string pitchRange
{
get { return ((ICss2Properties)baseObject).PitchRange; }
set { ((ICss2Properties)baseObject).PitchRange = value; }
}
public string playDuring
{
get { return ((ICss2Properties)baseObject).PlayDuring; }
set { ((ICss2Properties)baseObject).PlayDuring = value; }
}
public string position
{
get { return ((ICss2Properties)baseObject).Position; }
set { ((ICss2Properties)baseObject).Position = value; }
}
public string quotes
{
get { return ((ICss2Properties)baseObject).Quotes; }
set { ((ICss2Properties)baseObject).Quotes = value; }
}
public string richness
{
get { return ((ICss2Properties)baseObject).Richness; }
set { ((ICss2Properties)baseObject).Richness = value; }
}
public string right
{
get { return ((ICss2Properties)baseObject).Right; }
set { ((ICss2Properties)baseObject).Right = value; }
}
public string size
{
get { return ((ICss2Properties)baseObject).Size; }
set { ((ICss2Properties)baseObject).Size = value; }
}
public string speak
{
get { return ((ICss2Properties)baseObject).Speak; }
set { ((ICss2Properties)baseObject).Speak = value; }
}
public string speakHeader
{
get { return ((ICss2Properties)baseObject).SpeakHeader; }
set { ((ICss2Properties)baseObject).SpeakHeader = value; }
}
public string speakNumeral
{
get { return ((ICss2Properties)baseObject).SpeakNumeral; }
set { ((ICss2Properties)baseObject).SpeakNumeral = value; }
}
public string speakPunctuation
{
get { return ((ICss2Properties)baseObject).SpeakPunctuation; }
set { ((ICss2Properties)baseObject).SpeakPunctuation = value; }
}
public string speechRate
{
get { return ((ICss2Properties)baseObject).SpeechRate; }
set { ((ICss2Properties)baseObject).SpeechRate = value; }
}
public string stress
{
get { return ((ICss2Properties)baseObject).Stress; }
set { ((ICss2Properties)baseObject).Stress = value; }
}
public string tableLayout
{
get { return ((ICss2Properties)baseObject).TableLayout; }
set { ((ICss2Properties)baseObject).TableLayout = value; }
}
public string textAlign
{
get { return ((ICss2Properties)baseObject).TextAlign; }
set { ((ICss2Properties)baseObject).TextAlign = value; }
}
public string textDecoration
{
get { return ((ICss2Properties)baseObject).TextDecoration; }
set { ((ICss2Properties)baseObject).TextDecoration = value; }
}
public string textIndent
{
get { return ((ICss2Properties)baseObject).TextIndent; }
set { ((ICss2Properties)baseObject).TextIndent = value; }
}
public string textShadow
{
get { return ((ICss2Properties)baseObject).TextShadow; }
set { ((ICss2Properties)baseObject).TextShadow = value; }
}
public string textTransform
{
get { return ((ICss2Properties)baseObject).TextTransform; }
set { ((ICss2Properties)baseObject).TextTransform = value; }
}
public string top
{
get { return ((ICss2Properties)baseObject).Top; }
set { ((ICss2Properties)baseObject).Top = value; }
}
public string unicodeBidi
{
get { return ((ICss2Properties)baseObject).UnicodeBidi; }
set { ((ICss2Properties)baseObject).UnicodeBidi = value; }
}
public string verticalAlign
{
get { return ((ICss2Properties)baseObject).VerticalAlign; }
set { ((ICss2Properties)baseObject).VerticalAlign = value; }
}
public string visibility
{
get { return ((ICss2Properties)baseObject).Visibility; }
set { ((ICss2Properties)baseObject).Visibility = value; }
}
public string voiceFamily
{
get { return ((ICss2Properties)baseObject).VoiceFamily; }
set { ((ICss2Properties)baseObject).VoiceFamily = value; }
}
public string volume
{
get { return ((ICss2Properties)baseObject).Volume; }
set { ((ICss2Properties)baseObject).Volume = value; }
}
public string whiteSpace
{
get { return ((ICss2Properties)baseObject).WhiteSpace; }
set { ((ICss2Properties)baseObject).WhiteSpace = value; }
}
public string widows
{
get { return ((ICss2Properties)baseObject).Widows; }
set { ((ICss2Properties)baseObject).Widows = value; }
}
public string width
{
get { return ((ICss2Properties)baseObject).Width; }
set { ((ICss2Properties)baseObject).Width = value; }
}
public string wordSpacing
{
get { return ((ICss2Properties)baseObject).WordSpacing; }
set { ((ICss2Properties)baseObject).WordSpacing = value; }
}
public string zIndex
{
get { return ((ICss2Properties)baseObject).ZIndex; }
set { ((ICss2Properties)baseObject).ZIndex = value; }
}
#endregion
}
*/
/// <summary>
/// Implementation wrapper for IScriptableCssStyleSheet
/// </summary>
public class ScriptableCssStyleSheet : ScriptableStyleSheet, IScriptableCssStyleSheet
{
public ScriptableCssStyleSheet(object baseObject) : base (baseObject) { }
#region Methods - IScriptableCssStyleSheet
public ulong insertRule(string rule, ulong index)
{
return ((ICssStyleSheet)baseObject).InsertRule(rule, index);
}
public void deleteRule(ulong index)
{
((ICssStyleSheet)baseObject).DeleteRule(index);
}
#endregion
#region Properties - IScriptableCssStyleSheet
public IScriptableCssRule ownerRule
{
get { object result = ((ICssStyleSheet)baseObject).OwnerRule; return (result != null) ? (IScriptableCssRule)ScriptableObject.CreateWrapper(result) : null; }
}
public IScriptableCssRuleList cssRules
{
get { object result = ((ICssStyleSheet)baseObject).CssRules; return (result != null) ? (IScriptableCssRuleList)ScriptableObject.CreateWrapper(result) : null; }
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableViewCss
/// </summary>
public class ScriptableViewCss : ScriptableAbstractView, IScriptableViewCss
{
public ScriptableViewCss(object baseObject) : base (baseObject) { }
#region Methods - IScriptableViewCss
public IScriptableCssStyleDeclaration getComputedStyle(IScriptableElement elt, string pseudoElt)
{
object result = ((IViewCss)baseObject).GetComputedStyle(((XmlElement)((ScriptableElement)elt).baseObject), pseudoElt);
return (result != null) ? (IScriptableCssStyleDeclaration)ScriptableObject.CreateWrapper(result) : null;
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableDocumentCss
/// </summary>
public class ScriptableDocumentCss : ScriptableDocumentStyle, IScriptableDocumentCss
{
public ScriptableDocumentCss(object baseObject) : base (baseObject) { }
#region Methods - IScriptableDocumentCss
public IScriptableCssStyleDeclaration getOverrideStyle(IScriptableElement elt, string pseudoElt)
{
object result = ((IDocumentCss)baseObject).GetOverrideStyle(((XmlElement)((ScriptableElement)elt).baseObject), pseudoElt);
return (result != null) ? (IScriptableCssStyleDeclaration)ScriptableObject.CreateWrapper(result) : null;
}
#endregion
}
/// <summary>
/// Implementation wrapper for IScriptableDomImplementationCss
/// </summary>
public class ScriptableDomImplementationCss : ScriptableDomImplementation, IScriptableDomImplementationCss
{
public ScriptableDomImplementationCss(object baseObject) : base (baseObject) { }
#region Methods - IScriptableDomImplementationCss
public IScriptableCssStyleSheet createCSSStyleSheet(string title, string media)
{
object result = ((IDomImplementationCss)baseObject).CreateCssStyleSheet(title, media);
return (result != null) ? (IScriptableCssStyleSheet)ScriptableObject.CreateWrapper(result) : null;
}
#endregion
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
// System references
using System;
using System.Reflection;
// The namespace to test.
using Microsoft.Samples.VisualStudio.IronPythonConsole;
// Unit test framework.
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Samples.VisualStudio.IronPythonConsole.UnitTest
{
[TestClass]
public class HistoryBufferTest
{
private static Type historyBufferType;
private static ConstructorInfo historyBufferCtrInfo;
private static object CreateBuffer()
{
if (null == historyBufferCtrInfo)
{
if (null == historyBufferType)
{
Assembly asm = typeof(PythonConsolePackage).Assembly;
historyBufferType = asm.GetType("Microsoft.Samples.VisualStudio.IronPythonConsole.HistoryBuffer", true);
}
historyBufferCtrInfo = historyBufferType.GetConstructor(new Type[] { });
}
return historyBufferCtrInfo.Invoke(new object[] { });
}
private static ConstructorInfo historyBufferCtrSizeInfo;
private static object CreateBuffer(int size)
{
if (null == historyBufferCtrSizeInfo)
{
if (null == historyBufferType)
{
Assembly asm = typeof(PythonConsolePackage).Assembly;
historyBufferType = asm.GetType("Microsoft.Samples.VisualStudio.IronPythonConsole.HistoryBuffer", true);
}
historyBufferCtrSizeInfo = historyBufferType.GetConstructor(new Type[] { typeof(int) });
}
return historyBufferCtrSizeInfo.Invoke(new object[] { size });
}
private static MethodInfo previousEntryInfo;
private static string PreviousEntry(object buffer)
{
if (null == previousEntryInfo)
{
previousEntryInfo = historyBufferType.GetMethod("PreviousEntry");
}
return (string)previousEntryInfo.Invoke(buffer, new object[] { });
}
private static MethodInfo nextEntryInfo;
private static string NextEntry(object buffer)
{
if (null == nextEntryInfo)
{
nextEntryInfo = historyBufferType.GetMethod("NextEntry");
}
return (string)nextEntryInfo.Invoke(buffer, new object[] { });
}
private static MethodInfo addEntryInfo;
private static string AddEntry(object buffer, string entry)
{
if (null == addEntryInfo)
{
addEntryInfo = historyBufferType.GetMethod("AddEntry");
}
return (string)addEntryInfo.Invoke(buffer, new object[] { entry });
}
private static bool HasConstructorSucceeded(int size)
{
bool exceptionThrown = false;
try
{
object buffer = CreateBuffer(size);
}
catch (ArgumentOutOfRangeException)
{
exceptionThrown = true;
}
catch (System.Reflection.TargetInvocationException e)
{
ArgumentOutOfRangeException inner = e.InnerException as ArgumentOutOfRangeException;
if (null != inner)
exceptionThrown = true;
}
return !exceptionThrown;
}
[TestMethod]
public void VerifySizeOnConstructor()
{
Assert.IsFalse(HasConstructorSucceeded(-3));
Assert.IsFalse(HasConstructorSucceeded(0));
Assert.IsTrue(HasConstructorSucceeded(3));
}
[TestMethod]
public void PreviousOnEmptyBuffer()
{
object buffer = CreateBuffer();
Assert.IsNull(PreviousEntry(buffer));
}
[TestMethod]
public void NextOnEmptyBuffer()
{
object buffer = CreateBuffer();
Assert.IsNull(NextEntry(buffer));
}
[TestMethod]
public void AddOneItem()
{
object buffer = CreateBuffer();
string newEntry = "New Entry";
AddEntry(buffer, newEntry);
Assert.IsNull(NextEntry(buffer));
Assert.IsTrue(newEntry == PreviousEntry(buffer));
Assert.IsNull(PreviousEntry(buffer));
Assert.IsNull(NextEntry(buffer));
}
[TestMethod]
public void AddOverCapacity()
{
object buffer = CreateBuffer(3);
AddEntry(buffer, "String 1");
AddEntry(buffer, "String 2");
AddEntry(buffer, "String 3");
AddEntry(buffer, "String 4");
Assert.IsTrue("String 4" == PreviousEntry(buffer));
Assert.IsTrue("String 3" == PreviousEntry(buffer));
Assert.IsTrue("String 2" == PreviousEntry(buffer));
Assert.IsNull(PreviousEntry(buffer));
Assert.IsTrue("String 3" == NextEntry(buffer));
Assert.IsTrue("String 4" == NextEntry(buffer));
Assert.IsNull(NextEntry(buffer));
}
[TestMethod]
public void AddExistingItem()
{
object buffer = CreateBuffer();
AddEntry(buffer, "String 1");
AddEntry(buffer, "String 2");
AddEntry(buffer, "String 3");
AddEntry(buffer, "String 4");
AddEntry(buffer, "String 2");
Assert.IsTrue("String 2" == PreviousEntry(buffer));
Assert.IsTrue("String 1" == PreviousEntry(buffer));
Assert.IsNull(PreviousEntry(buffer));
Assert.IsTrue("String 2" == NextEntry(buffer));
Assert.IsTrue("String 3" == NextEntry(buffer));
Assert.IsTrue("String 4" == NextEntry(buffer));
Assert.IsNull(NextEntry(buffer));
}
[TestMethod]
public void AddExistingItemNavigateDown()
{
object buffer = CreateBuffer();
AddEntry(buffer, "String 1");
AddEntry(buffer, "String 2");
AddEntry(buffer, "String 3");
AddEntry(buffer, "String 4");
AddEntry(buffer, "String 2");
Assert.IsTrue("String 3" == NextEntry(buffer));
Assert.IsTrue("String 2" == PreviousEntry(buffer));
Assert.IsTrue("String 3" == NextEntry(buffer));
Assert.IsTrue("String 4" == NextEntry(buffer));
Assert.IsNull(NextEntry(buffer));
}
[TestMethod]
public void Nativage()
{
object buffer = CreateBuffer();
AddEntry(buffer, "String 1");
AddEntry(buffer, "String 2");
AddEntry(buffer, "String 3");
Assert.IsNull(NextEntry(buffer));
Assert.IsTrue("String 3" == PreviousEntry(buffer));
Assert.IsTrue("String 2" == PreviousEntry(buffer));
Assert.IsTrue("String 3" == NextEntry(buffer));
Assert.IsTrue("String 2" == PreviousEntry(buffer));
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
namespace AllReady.Migrations
{
public partial class UserTimeZone : 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_Tenant_ManagingTenantId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TenantContact_Contact_ContactId", table: "TenantContact");
migrationBuilder.DropForeignKey(name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact");
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.AddColumn<string>(
name: "TimeZoneId",
table: "AspNetUsers",
nullable: false,
defaultValue: "Central Standard Time");
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_Tenant_ManagingTenantId",
table: "Campaign",
column: "ManagingTenantId",
principalTable: "Tenant",
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_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_TenantContact_Contact_ContactId",
table: "TenantContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TenantContact_Tenant_TenantId",
table: "TenantContact",
column: "TenantId",
principalTable: "Tenant",
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_Tenant_ManagingTenantId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TenantContact_Contact_ContactId", table: "TenantContact");
migrationBuilder.DropForeignKey(name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact");
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: "TimeZoneId", table: "AspNetUsers");
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_Tenant_ManagingTenantId",
table: "Campaign",
column: "ManagingTenantId",
principalTable: "Tenant",
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_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_TenantContact_Contact_ContactId",
table: "TenantContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TenantContact_Tenant_TenantId",
table: "TenantContact",
column: "TenantId",
principalTable: "Tenant",
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);
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using pb.locationIntelligence.Client;
using pb.locationIntelligence.Model;
namespace pb.locationIntelligence.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface ILIAPIGeoPostServiceApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Carrier Route By Address.
/// </summary>
/// <remarks>
/// Get United States Postal Service (USPS) carrier route data for the requested address
/// </remarks>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="address">free form address text</param>
/// <param name="includeGeometry">Y or N (default is Y) - if it is Y, then geometry will be part of response (optional)</param>
/// <returns>CarrierRouteResponse</returns>
CarrierRouteResponse GetCarrierRoutesByAddress (string address, string includeGeometry = null);
/// <summary>
/// Carrier Route By Address.
/// </summary>
/// <remarks>
/// Get United States Postal Service (USPS) carrier route data for the requested address
/// </remarks>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="address">free form address text</param>
/// <param name="includeGeometry">Y or N (default is Y) - if it is Y, then geometry will be part of response (optional)</param>
/// <returns>ApiResponse of CarrierRouteResponse</returns>
ApiResponse<CarrierRouteResponse> GetCarrierRoutesByAddressWithHttpInfo (string address, string includeGeometry = null);
/// <summary>
/// Gets GeoPost Carrier Routes for Multiple Addresses
/// </summary>
/// <remarks>
/// Gets GeoPost Carrier Routes for Multiple Addresses
/// </remarks>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body"> (optional)</param>
/// <returns>CarrierRouteResponseList</returns>
CarrierRouteResponseList GetCarrierRoutesByAddressBatch (CarrierRouteAddressRequest body = null);
/// <summary>
/// Gets GeoPost Carrier Routes for Multiple Addresses
/// </summary>
/// <remarks>
/// Gets GeoPost Carrier Routes for Multiple Addresses
/// </remarks>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body"> (optional)</param>
/// <returns>ApiResponse of CarrierRouteResponseList</returns>
ApiResponse<CarrierRouteResponseList> GetCarrierRoutesByAddressBatchWithHttpInfo (CarrierRouteAddressRequest body = null);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Carrier Route By Address.
/// </summary>
/// <remarks>
/// Get United States Postal Service (USPS) carrier route data for the requested address
/// </remarks>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="address">free form address text</param>
/// <param name="includeGeometry">Y or N (default is Y) - if it is Y, then geometry will be part of response (optional)</param>
/// <returns>Task of CarrierRouteResponse</returns>
System.Threading.Tasks.Task<CarrierRouteResponse> GetCarrierRoutesByAddressAsync (string address, string includeGeometry = null);
/// <summary>
/// Carrier Route By Address.
/// </summary>
/// <remarks>
/// Get United States Postal Service (USPS) carrier route data for the requested address
/// </remarks>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="address">free form address text</param>
/// <param name="includeGeometry">Y or N (default is Y) - if it is Y, then geometry will be part of response (optional)</param>
/// <returns>Task of ApiResponse (CarrierRouteResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<CarrierRouteResponse>> GetCarrierRoutesByAddressAsyncWithHttpInfo (string address, string includeGeometry = null);
/// <summary>
/// Gets GeoPost Carrier Routes for Multiple Addresses
/// </summary>
/// <remarks>
/// Gets GeoPost Carrier Routes for Multiple Addresses
/// </remarks>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body"> (optional)</param>
/// <returns>Task of CarrierRouteResponseList</returns>
System.Threading.Tasks.Task<CarrierRouteResponseList> GetCarrierRoutesByAddressBatchAsync (CarrierRouteAddressRequest body = null);
/// <summary>
/// Gets GeoPost Carrier Routes for Multiple Addresses
/// </summary>
/// <remarks>
/// Gets GeoPost Carrier Routes for Multiple Addresses
/// </remarks>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body"> (optional)</param>
/// <returns>Task of ApiResponse (CarrierRouteResponseList)</returns>
System.Threading.Tasks.Task<ApiResponse<CarrierRouteResponseList>> GetCarrierRoutesByAddressBatchAsyncWithHttpInfo (CarrierRouteAddressRequest body = null);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class LIAPIGeoPostServiceApi : ILIAPIGeoPostServiceApi
{
private pb.locationIntelligence.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="LIAPIGeoPostServiceApi"/> class.
/// </summary>
/// <returns></returns>
public LIAPIGeoPostServiceApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = pb.locationIntelligence.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="LIAPIGeoPostServiceApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public LIAPIGeoPostServiceApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = pb.locationIntelligence.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public pb.locationIntelligence.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Carrier Route By Address. Get United States Postal Service (USPS) carrier route data for the requested address
/// </summary>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="address">free form address text</param>
/// <param name="includeGeometry">Y or N (default is Y) - if it is Y, then geometry will be part of response (optional)</param>
/// <returns>CarrierRouteResponse</returns>
public CarrierRouteResponse GetCarrierRoutesByAddress (string address, string includeGeometry = null)
{
ApiResponse<CarrierRouteResponse> localVarResponse = GetCarrierRoutesByAddressWithHttpInfo(address, includeGeometry);
return localVarResponse.Data;
}
/// <summary>
/// Carrier Route By Address. Get United States Postal Service (USPS) carrier route data for the requested address
/// </summary>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="address">free form address text</param>
/// <param name="includeGeometry">Y or N (default is Y) - if it is Y, then geometry will be part of response (optional)</param>
/// <returns>ApiResponse of CarrierRouteResponse</returns>
public ApiResponse< CarrierRouteResponse > GetCarrierRoutesByAddressWithHttpInfo (string address, string includeGeometry = null)
{
// verify the required parameter 'address' is set
if (address == null)
throw new ApiException(400, "Missing required parameter 'address' when calling LIAPIGeoPostServiceApi->GetCarrierRoutesByAddress");
var localVarPath = "/geopost/v1/carrierroute/byaddress";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/xml",
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (address != null) localVarQueryParams.Add("address", Configuration.ApiClient.ParameterToString(address)); // query parameter
if (includeGeometry != null) localVarQueryParams.Add("includeGeometry", Configuration.ApiClient.ParameterToString(includeGeometry)); // query parameter
// authentication (oAuth2Password) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
else if (!String.IsNullOrEmpty(Configuration.OAuthApiKey) && !String.IsNullOrEmpty(Configuration.OAuthSecret))
{
Configuration.ApiClient.GenerateAndSetAccessToken(Configuration.OAuthApiKey,Configuration.OAuthSecret);
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetCarrierRoutesByAddress", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<CarrierRouteResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x1 => x1.Name, x1 => x1.Value.ToString()),
(CarrierRouteResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(CarrierRouteResponse)));
}
/// <summary>
/// Carrier Route By Address. Get United States Postal Service (USPS) carrier route data for the requested address
/// </summary>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="address">free form address text</param>
/// <param name="includeGeometry">Y or N (default is Y) - if it is Y, then geometry will be part of response (optional)</param>
/// <returns>Task of CarrierRouteResponse</returns>
public async System.Threading.Tasks.Task<CarrierRouteResponse> GetCarrierRoutesByAddressAsync (string address, string includeGeometry = null)
{
ApiResponse<CarrierRouteResponse> localVarResponse = await GetCarrierRoutesByAddressAsyncWithHttpInfo(address, includeGeometry);
return localVarResponse.Data;
}
/// <summary>
/// Carrier Route By Address. Get United States Postal Service (USPS) carrier route data for the requested address
/// </summary>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="address">free form address text</param>
/// <param name="includeGeometry">Y or N (default is Y) - if it is Y, then geometry will be part of response (optional)</param>
/// <returns>Task of ApiResponse (CarrierRouteResponse)</returns>
public async System.Threading.Tasks.Task<ApiResponse<CarrierRouteResponse>> GetCarrierRoutesByAddressAsyncWithHttpInfo (string address, string includeGeometry = null)
{
// verify the required parameter 'address' is set
if (address == null)
throw new ApiException(400, "Missing required parameter 'address' when calling LIAPIGeoPostServiceApi->GetCarrierRoutesByAddress");
var localVarPath = "/geopost/v1/carrierroute/byaddress";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/xml",
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (address != null) localVarQueryParams.Add("address", Configuration.ApiClient.ParameterToString(address)); // query parameter
if (includeGeometry != null) localVarQueryParams.Add("includeGeometry", Configuration.ApiClient.ParameterToString(includeGeometry)); // query parameter
// authentication (oAuth2Password) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
else if (!String.IsNullOrEmpty(Configuration.OAuthApiKey) && !String.IsNullOrEmpty(Configuration.OAuthSecret))
{
Configuration.ApiClient.GenerateAndSetAccessToken(Configuration.OAuthApiKey,Configuration.OAuthSecret);
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetCarrierRoutesByAddress", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<CarrierRouteResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x1 => x1.Name, x1 => x1.Value.ToString()),
(CarrierRouteResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(CarrierRouteResponse)));
}
/// <summary>
/// Gets GeoPost Carrier Routes for Multiple Addresses Gets GeoPost Carrier Routes for Multiple Addresses
/// </summary>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body"> (optional)</param>
/// <returns>CarrierRouteResponseList</returns>
public CarrierRouteResponseList GetCarrierRoutesByAddressBatch (CarrierRouteAddressRequest body = null)
{
ApiResponse<CarrierRouteResponseList> localVarResponse = GetCarrierRoutesByAddressBatchWithHttpInfo(body);
return localVarResponse.Data;
}
/// <summary>
/// Gets GeoPost Carrier Routes for Multiple Addresses Gets GeoPost Carrier Routes for Multiple Addresses
/// </summary>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body"> (optional)</param>
/// <returns>ApiResponse of CarrierRouteResponseList</returns>
public ApiResponse< CarrierRouteResponseList > GetCarrierRoutesByAddressBatchWithHttpInfo (CarrierRouteAddressRequest body = null)
{
var localVarPath = "/geopost/v1/carrierroute/byaddress";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/xml",
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (oAuth2Password) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
else if (!String.IsNullOrEmpty(Configuration.OAuthApiKey) && !String.IsNullOrEmpty(Configuration.OAuthSecret))
{
Configuration.ApiClient.GenerateAndSetAccessToken(Configuration.OAuthApiKey,Configuration.OAuthSecret);
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetCarrierRoutesByAddressBatch", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<CarrierRouteResponseList>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x1 => x1.Name, x1 => x1.Value.ToString()),
(CarrierRouteResponseList) Configuration.ApiClient.Deserialize(localVarResponse, typeof(CarrierRouteResponseList)));
}
/// <summary>
/// Gets GeoPost Carrier Routes for Multiple Addresses Gets GeoPost Carrier Routes for Multiple Addresses
/// </summary>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body"> (optional)</param>
/// <returns>Task of CarrierRouteResponseList</returns>
public async System.Threading.Tasks.Task<CarrierRouteResponseList> GetCarrierRoutesByAddressBatchAsync (CarrierRouteAddressRequest body = null)
{
ApiResponse<CarrierRouteResponseList> localVarResponse = await GetCarrierRoutesByAddressBatchAsyncWithHttpInfo(body);
return localVarResponse.Data;
}
/// <summary>
/// Gets GeoPost Carrier Routes for Multiple Addresses Gets GeoPost Carrier Routes for Multiple Addresses
/// </summary>
/// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body"> (optional)</param>
/// <returns>Task of ApiResponse (CarrierRouteResponseList)</returns>
public async System.Threading.Tasks.Task<ApiResponse<CarrierRouteResponseList>> GetCarrierRoutesByAddressBatchAsyncWithHttpInfo (CarrierRouteAddressRequest body = null)
{
var localVarPath = "/geopost/v1/carrierroute/byaddress";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/xml",
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (oAuth2Password) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
else if (!String.IsNullOrEmpty(Configuration.OAuthApiKey) && !String.IsNullOrEmpty(Configuration.OAuthSecret))
{
Configuration.ApiClient.GenerateAndSetAccessToken(Configuration.OAuthApiKey,Configuration.OAuthSecret);
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetCarrierRoutesByAddressBatch", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<CarrierRouteResponseList>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x1 => x1.Name, x1 => x1.Value.ToString()),
(CarrierRouteResponseList) Configuration.ApiClient.Deserialize(localVarResponse, typeof(CarrierRouteResponseList)));
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Collections.ObjectModel
{
public abstract partial class KeyedCollection<TKey, TItem> : System.Collections.ObjectModel.Collection<TItem> where TKey : notnull
{
protected KeyedCollection() { }
protected KeyedCollection(System.Collections.Generic.IEqualityComparer<TKey>? comparer) { }
protected KeyedCollection(System.Collections.Generic.IEqualityComparer<TKey>? comparer, int dictionaryCreationThreshold) { }
public System.Collections.Generic.IEqualityComparer<TKey> Comparer { get { throw null; } }
protected System.Collections.Generic.IDictionary<TKey, TItem>? Dictionary { get { throw null; } }
public TItem this[TKey key] { get { throw null; } }
protected void ChangeItemKey(TItem item, TKey newKey) { }
protected override void ClearItems() { }
public bool Contains(TKey key) { throw null; }
protected abstract TKey GetKeyForItem(TItem item);
protected override void InsertItem(int index, TItem item) { }
public bool Remove(TKey key) { throw null; }
protected override void RemoveItem(int index) { }
protected override void SetItem(int index, TItem item) { }
public bool TryGetValue(TKey key, [System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out TItem item) { throw null; }
}
public partial class ObservableCollection<T> : System.Collections.ObjectModel.Collection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged
{
public ObservableCollection() { }
public ObservableCollection(System.Collections.Generic.IEnumerable<T> collection) { }
public ObservableCollection(System.Collections.Generic.List<T> list) { }
public virtual event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged { add { } remove { } }
protected virtual event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged { add { } remove { } }
event System.ComponentModel.PropertyChangedEventHandler? System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } }
protected System.IDisposable BlockReentrancy() { throw null; }
protected void CheckReentrancy() { }
protected override void ClearItems() { }
protected override void InsertItem(int index, T item) { }
public void Move(int oldIndex, int newIndex) { }
protected virtual void MoveItem(int oldIndex, int newIndex) { }
protected virtual void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { }
protected virtual void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e) { }
protected override void RemoveItem(int index) { }
protected override void SetItem(int index, T item) { }
}
public partial class ReadOnlyDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable where TKey : notnull
{
public ReadOnlyDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { }
public int Count { get { throw null; } }
protected System.Collections.Generic.IDictionary<TKey, TValue> Dictionary { get { throw null; } }
public TValue this[TKey key] { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.KeyCollection Keys { get { throw null; } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.IsReadOnly { get { throw null; } }
TValue System.Collections.Generic.IDictionary<TKey,TValue>.this[TKey key] { get { throw null; } set { } }
System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey,TValue>.Keys { get { throw null; } }
System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey,TValue>.Values { get { throw null; } }
System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Keys { get { throw null; } }
System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Values { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
bool System.Collections.IDictionary.IsFixedSize { get { throw null; } }
bool System.Collections.IDictionary.IsReadOnly { get { throw null; } }
object? System.Collections.IDictionary.this[object key] { get { throw null; } set { } }
System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } }
System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.ValueCollection Values { get { throw null; } }
public bool ContainsKey(TKey key) { throw null; }
public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Clear() { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int arrayIndex) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { throw null; }
void System.Collections.Generic.IDictionary<TKey,TValue>.Add(TKey key, TValue value) { }
bool System.Collections.Generic.IDictionary<TKey,TValue>.Remove(TKey key) { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
void System.Collections.IDictionary.Add(object key, object? value) { }
void System.Collections.IDictionary.Clear() { }
bool System.Collections.IDictionary.Contains(object key) { throw null; }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; }
void System.Collections.IDictionary.Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public bool TryGetValue(TKey key, [System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out TValue value) { throw null; }
public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable
{
internal KeyCollection() { }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void CopyTo(TKey[] array, int arrayIndex) { }
public System.Collections.Generic.IEnumerator<TKey> GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { }
void System.Collections.Generic.ICollection<TKey>.Clear() { }
bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { throw null; }
bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable
{
internal ValueCollection() { }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void CopyTo(TValue[] array, int arrayIndex) { }
public System.Collections.Generic.IEnumerator<TValue> GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { }
void System.Collections.Generic.ICollection<TValue>.Clear() { }
bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { throw null; }
bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
}
public partial class ReadOnlyObservableCollection<T> : System.Collections.ObjectModel.ReadOnlyCollection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged
{
public ReadOnlyObservableCollection(System.Collections.ObjectModel.ObservableCollection<T> list) : base (default(System.Collections.Generic.IList<T>)) { }
protected virtual event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged { add { } remove { } }
protected virtual event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged { add { } remove { } }
event System.Collections.Specialized.NotifyCollectionChangedEventHandler? System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged { add { } remove { } }
event System.ComponentModel.PropertyChangedEventHandler? System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } }
protected virtual void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs args) { }
protected virtual void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args) { }
}
}
namespace System.Collections.Specialized
{
public partial interface INotifyCollectionChanged
{
event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged;
}
public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}
public partial class NotifyCollectionChangedEventArgs : System.EventArgs
{
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList? changedItems) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems, int startingIndex) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList? changedItems, int startingIndex) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList? changedItems, int index, int oldIndex) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object? changedItem) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object? changedItem, int index) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object? changedItem, int index, int oldIndex) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object? newItem, object? oldItem) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object? newItem, object? oldItem, int index) { }
public System.Collections.Specialized.NotifyCollectionChangedAction Action { get { throw null; } }
public System.Collections.IList? NewItems { get { throw null; } }
public int NewStartingIndex { get { throw null; } }
public System.Collections.IList? OldItems { get { throw null; } }
public int OldStartingIndex { get { throw null; } }
}
public delegate void NotifyCollectionChangedEventHandler(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e);
}
namespace System.ComponentModel
{
public partial class DataErrorsChangedEventArgs : System.EventArgs
{
public DataErrorsChangedEventArgs(string? propertyName) { }
public virtual string? PropertyName { get { throw null; } }
}
public partial interface INotifyDataErrorInfo
{
bool HasErrors { get; }
event System.EventHandler<System.ComponentModel.DataErrorsChangedEventArgs>? ErrorsChanged;
System.Collections.IEnumerable GetErrors(string? propertyName);
}
public partial interface INotifyPropertyChanged
{
event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged;
}
public partial interface INotifyPropertyChanging
{
event System.ComponentModel.PropertyChangingEventHandler? PropertyChanging;
}
public partial class PropertyChangedEventArgs : System.EventArgs
{
public PropertyChangedEventArgs(string? propertyName) { }
public virtual string? PropertyName { get { throw null; } }
}
public delegate void PropertyChangedEventHandler(object? sender, System.ComponentModel.PropertyChangedEventArgs e);
public partial class PropertyChangingEventArgs : System.EventArgs
{
public PropertyChangingEventArgs(string? propertyName) { }
public virtual string? PropertyName { get { throw null; } }
}
public delegate void PropertyChangingEventHandler(object? sender, System.ComponentModel.PropertyChangingEventArgs e);
[System.AttributeUsageAttribute(System.AttributeTargets.All)]
public sealed partial class TypeConverterAttribute : System.Attribute
{
public static readonly System.ComponentModel.TypeConverterAttribute Default;
public TypeConverterAttribute() { }
public TypeConverterAttribute(string typeName) { }
public TypeConverterAttribute(System.Type type) { }
public string ConverterTypeName { get { throw null; } }
public override bool Equals(object? obj) { throw null; }
public override int GetHashCode() { throw null; }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)]
public sealed partial class TypeDescriptionProviderAttribute : System.Attribute
{
public TypeDescriptionProviderAttribute(string typeName) { }
public TypeDescriptionProviderAttribute(System.Type type) { }
public string TypeName { get { throw null; } }
}
}
namespace System.Reflection
{
public partial interface ICustomTypeProvider
{
System.Type GetCustomType();
}
}
namespace System.Windows.Input
{
[System.ComponentModel.TypeConverterAttribute("System.Windows.Input.CommandConverter, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")]
[System.Windows.Markup.ValueSerializerAttribute("System.Windows.Input.CommandValueSerializer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")]
public partial interface ICommand
{
event System.EventHandler CanExecuteChanged;
bool CanExecute(object? parameter);
void Execute(object? parameter);
}
}
namespace System.Windows.Markup
{
[System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=true)]
public sealed partial class ValueSerializerAttribute : System.Attribute
{
public ValueSerializerAttribute(string valueSerializerTypeName) { }
public ValueSerializerAttribute(System.Type valueSerializerType) { }
public System.Type ValueSerializerType { get { throw null; } }
public string ValueSerializerTypeName { get { throw null; } }
}
}
| |
/*
** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
** Copyright (C) 2011 Silicon Graphics, Inc.
** All Rights Reserved.
**
** 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 including the dates of first publication and either this
** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ 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 SILICON GRAPHICS, INC.
** 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.
**
** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not
** be used in advertising or otherwise to promote the sale, use or other dealings in
** this Software without prior written authorization from Silicon Graphics, Inc.
*/
/*
** Original Author: Eric Veach, July 1994.
** libtess2: Mikko Mononen, http://code.google.com/p/libtess2/.
** LibTessDotNet: Remi Gillig, https://github.com/speps/LibTessDotNet
*/
using System;
using System.Diagnostics;
namespace UnityEngine.Experimental.Rendering.LWRP
{
#if DOUBLE
using Real = System.Double;
namespace LibTessDotNet.Double
#else
using Real = System.Single;
namespace LibTessDotNet
#endif
{
internal enum WindingRule
{
EvenOdd,
NonZero,
Positive,
Negative,
AbsGeqTwo
}
internal enum ElementType
{
Polygons,
ConnectedPolygons,
BoundaryContours
}
internal enum ContourOrientation
{
Original,
Clockwise,
CounterClockwise
}
internal struct ContourVertex
{
public Vec3 Position;
public object Data;
public override string ToString()
{
return string.Format("{0}, {1}", Position, Data);
}
}
internal delegate object CombineCallback(Vec3 position, object[] data, Real[] weights);
internal partial class Tess
{
private Mesh _mesh;
private Vec3 _normal;
private Vec3 _sUnit;
private Vec3 _tUnit;
private Real _bminX, _bminY, _bmaxX, _bmaxY;
private WindingRule _windingRule;
private Dict<ActiveRegion> _dict;
private PriorityQueue<MeshUtils.Vertex> _pq;
private MeshUtils.Vertex _event;
private CombineCallback _combineCallback;
private ContourVertex[] _vertices;
private int _vertexCount;
private int[] _elements;
private int _elementCount;
public Vec3 Normal { get { return _normal; } set { _normal = value; } }
public Real SUnitX = 1;
public Real SUnitY = 0;
#if DOUBLE
public Real SentinelCoord = 4e150;
#else
public Real SentinelCoord = 4e30f;
#endif
/// <summary>
/// If true, will remove empty (zero area) polygons.
/// </summary>
public bool NoEmptyPolygons = false;
/// <summary>
/// If true, will use pooling to reduce GC (compare performance with/without, can vary wildly).
/// </summary>
public bool UsePooling = false;
public ContourVertex[] Vertices { get { return _vertices; } }
public int VertexCount { get { return _vertexCount; } }
public int[] Elements { get { return _elements; } }
public int ElementCount { get { return _elementCount; } }
public Tess()
{
_normal = Vec3.Zero;
_bminX = _bminY = _bmaxX = _bmaxY = 0;
_windingRule = WindingRule.EvenOdd;
_mesh = null;
_vertices = null;
_vertexCount = 0;
_elements = null;
_elementCount = 0;
}
private void ComputeNormal(ref Vec3 norm)
{
var v = _mesh._vHead._next;
var minVal = new Real[3] { v._coords.X, v._coords.Y, v._coords.Z };
var minVert = new MeshUtils.Vertex[3] { v, v, v };
var maxVal = new Real[3] { v._coords.X, v._coords.Y, v._coords.Z };
var maxVert = new MeshUtils.Vertex[3] { v, v, v };
for (; v != _mesh._vHead; v = v._next)
{
if (v._coords.X < minVal[0]) { minVal[0] = v._coords.X; minVert[0] = v; }
if (v._coords.Y < minVal[1]) { minVal[1] = v._coords.Y; minVert[1] = v; }
if (v._coords.Z < minVal[2]) { minVal[2] = v._coords.Z; minVert[2] = v; }
if (v._coords.X > maxVal[0]) { maxVal[0] = v._coords.X; maxVert[0] = v; }
if (v._coords.Y > maxVal[1]) { maxVal[1] = v._coords.Y; maxVert[1] = v; }
if (v._coords.Z > maxVal[2]) { maxVal[2] = v._coords.Z; maxVert[2] = v; }
}
// Find two vertices separated by at least 1/sqrt(3) of the maximum
// distance between any two vertices
int i = 0;
if (maxVal[1] - minVal[1] > maxVal[0] - minVal[0]) { i = 1; }
if (maxVal[2] - minVal[2] > maxVal[i] - minVal[i]) { i = 2; }
if (minVal[i] >= maxVal[i])
{
// All vertices are the same -- normal doesn't matter
norm = new Vec3 { X = 0, Y = 0, Z = 1 };
return;
}
// Look for a third vertex which forms the triangle with maximum area
// (Length of normal == twice the triangle area)
Real maxLen2 = 0, tLen2;
var v1 = minVert[i];
var v2 = maxVert[i];
Vec3 d1, d2, tNorm;
Vec3.Sub(ref v1._coords, ref v2._coords, out d1);
for (v = _mesh._vHead._next; v != _mesh._vHead; v = v._next)
{
Vec3.Sub(ref v._coords, ref v2._coords, out d2);
tNorm.X = d1.Y * d2.Z - d1.Z * d2.Y;
tNorm.Y = d1.Z * d2.X - d1.X * d2.Z;
tNorm.Z = d1.X * d2.Y - d1.Y * d2.X;
tLen2 = tNorm.X*tNorm.X + tNorm.Y*tNorm.Y + tNorm.Z*tNorm.Z;
if (tLen2 > maxLen2)
{
maxLen2 = tLen2;
norm = tNorm;
}
}
if (maxLen2 <= 0.0f)
{
// All points lie on a single line -- any decent normal will do
norm = Vec3.Zero;
i = Vec3.LongAxis(ref d1);
norm[i] = 1;
}
}
private void CheckOrientation()
{
// When we compute the normal automatically, we choose the orientation
// so that the the sum of the signed areas of all contours is non-negative.
Real area = 0.0f;
for (var f = _mesh._fHead._next; f != _mesh._fHead; f = f._next)
{
if (f._anEdge._winding <= 0)
{
continue;
}
area += MeshUtils.FaceArea(f);
}
if (area < 0.0f)
{
// Reverse the orientation by flipping all the t-coordinates
for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next)
{
v._t = -v._t;
}
Vec3.Neg(ref _tUnit);
}
}
private void ProjectPolygon()
{
var norm = _normal;
bool computedNormal = false;
if (norm.X == 0.0f && norm.Y == 0.0f && norm.Z == 0.0f)
{
ComputeNormal(ref norm);
_normal = norm;
computedNormal = true;
}
int i = Vec3.LongAxis(ref norm);
_sUnit[i] = 0;
_sUnit[(i + 1) % 3] = SUnitX;
_sUnit[(i + 2) % 3] = SUnitY;
_tUnit[i] = 0;
_tUnit[(i + 1) % 3] = norm[i] > 0.0f ? -SUnitY : SUnitY;
_tUnit[(i + 2) % 3] = norm[i] > 0.0f ? SUnitX : -SUnitX;
// Project the vertices onto the sweep plane
for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next)
{
Vec3.Dot(ref v._coords, ref _sUnit, out v._s);
Vec3.Dot(ref v._coords, ref _tUnit, out v._t);
}
if (computedNormal)
{
CheckOrientation();
}
// Compute ST bounds.
bool first = true;
for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next)
{
if (first)
{
_bminX = _bmaxX = v._s;
_bminY = _bmaxY = v._t;
first = false;
}
else
{
if (v._s < _bminX) _bminX = v._s;
if (v._s > _bmaxX) _bmaxX = v._s;
if (v._t < _bminY) _bminY = v._t;
if (v._t > _bmaxY) _bmaxY = v._t;
}
}
}
/// <summary>
/// TessellateMonoRegion( face ) tessellates a monotone region
/// (what else would it do??) The region must consist of a single
/// loop of half-edges (see mesh.h) oriented CCW. "Monotone" in this
/// case means that any vertical line intersects the interior of the
/// region in a single interval.
///
/// Tessellation consists of adding interior edges (actually pairs of
/// half-edges), to split the region into non-overlapping triangles.
///
/// The basic idea is explained in Preparata and Shamos (which I don't
/// have handy right now), although their implementation is more
/// complicated than this one. The are two edge chains, an upper chain
/// and a lower chain. We process all vertices from both chains in order,
/// from right to left.
///
/// The algorithm ensures that the following invariant holds after each
/// vertex is processed: the untessellated region consists of two
/// chains, where one chain (say the upper) is a single edge, and
/// the other chain is concave. The left vertex of the single edge
/// is always to the left of all vertices in the concave chain.
///
/// Each step consists of adding the rightmost unprocessed vertex to one
/// of the two chains, and forming a fan of triangles from the rightmost
/// of two chain endpoints. Determining whether we can add each triangle
/// to the fan is a simple orientation test. By making the fan as large
/// as possible, we restore the invariant (check it yourself).
/// </summary>
private void TessellateMonoRegion(MeshUtils.Face face)
{
// All edges are oriented CCW around the boundary of the region.
// First, find the half-edge whose origin vertex is rightmost.
// Since the sweep goes from left to right, face->anEdge should
// be close to the edge we want.
var up = face._anEdge;
Debug.Assert(up._Lnext != up && up._Lnext._Lnext != up);
while (Geom.VertLeq(up._Dst, up._Org)) up = up._Lprev;
while (Geom.VertLeq(up._Org, up._Dst)) up = up._Lnext;
var lo = up._Lprev;
while (up._Lnext != lo)
{
if (Geom.VertLeq(up._Dst, lo._Org))
{
// up.Dst is on the left. It is safe to form triangles from lo.Org.
// The EdgeGoesLeft test guarantees progress even when some triangles
// are CW, given that the upper and lower chains are truly monotone.
while (lo._Lnext != up && (Geom.EdgeGoesLeft(lo._Lnext)
|| Geom.EdgeSign(lo._Org, lo._Dst, lo._Lnext._Dst) <= 0.0f))
{
lo = _mesh.Connect(lo._Lnext, lo)._Sym;
}
lo = lo._Lprev;
}
else
{
// lo.Org is on the left. We can make CCW triangles from up.Dst.
while (lo._Lnext != up && (Geom.EdgeGoesRight(up._Lprev)
|| Geom.EdgeSign(up._Dst, up._Org, up._Lprev._Org) >= 0.0f))
{
up = _mesh.Connect(up, up._Lprev)._Sym;
}
up = up._Lnext;
}
}
// Now lo.Org == up.Dst == the leftmost vertex. The remaining region
// can be tessellated in a fan from this leftmost vertex.
Debug.Assert(lo._Lnext != up);
while (lo._Lnext._Lnext != up)
{
lo = _mesh.Connect(lo._Lnext, lo)._Sym;
}
}
/// <summary>
/// TessellateInterior( mesh ) tessellates each region of
/// the mesh which is marked "inside" the polygon. Each such region
/// must be monotone.
/// </summary>
private void TessellateInterior()
{
MeshUtils.Face f, next;
for (f = _mesh._fHead._next; f != _mesh._fHead; f = next)
{
// Make sure we don't try to tessellate the new triangles.
next = f._next;
if (f._inside)
{
TessellateMonoRegion(f);
}
}
}
/// <summary>
/// DiscardExterior zaps (ie. sets to null) all faces
/// which are not marked "inside" the polygon. Since further mesh operations
/// on NULL faces are not allowed, the main purpose is to clean up the
/// mesh so that exterior loops are not represented in the data structure.
/// </summary>
private void DiscardExterior()
{
MeshUtils.Face f, next;
for (f = _mesh._fHead._next; f != _mesh._fHead; f = next)
{
// Since f will be destroyed, save its next pointer.
next = f._next;
if( ! f._inside ) {
_mesh.ZapFace(f);
}
}
}
/// <summary>
/// SetWindingNumber( value, keepOnlyBoundary ) resets the
/// winding numbers on all edges so that regions marked "inside" the
/// polygon have a winding number of "value", and regions outside
/// have a winding number of 0.
///
/// If keepOnlyBoundary is TRUE, it also deletes all edges which do not
/// separate an interior region from an exterior one.
/// </summary>
private void SetWindingNumber(int value, bool keepOnlyBoundary)
{
MeshUtils.Edge e, eNext;
for (e = _mesh._eHead._next; e != _mesh._eHead; e = eNext)
{
eNext = e._next;
if (e._Rface._inside != e._Lface._inside)
{
/* This is a boundary edge (one side is interior, one is exterior). */
e._winding = (e._Lface._inside) ? value : -value;
}
else
{
/* Both regions are interior, or both are exterior. */
if (!keepOnlyBoundary)
{
e._winding = 0;
}
else
{
_mesh.Delete(e);
}
}
}
}
private int GetNeighbourFace(MeshUtils.Edge edge)
{
if (edge._Rface == null)
return MeshUtils.Undef;
if (!edge._Rface._inside)
return MeshUtils.Undef;
return edge._Rface._n;
}
private void OutputPolymesh(ElementType elementType, int polySize)
{
MeshUtils.Vertex v;
MeshUtils.Face f;
MeshUtils.Edge edge;
int maxFaceCount = 0;
int maxVertexCount = 0;
int faceVerts, i;
if (polySize < 3)
{
polySize = 3;
}
// Assume that the input data is triangles now.
// Try to merge as many polygons as possible
if (polySize > 3)
{
_mesh.MergeConvexFaces(polySize);
}
// Mark unused
for (v = _mesh._vHead._next; v != _mesh._vHead; v = v._next)
v._n = MeshUtils.Undef;
// Create unique IDs for all vertices and faces.
for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next)
{
f._n = MeshUtils.Undef;
if (!f._inside) continue;
if (NoEmptyPolygons)
{
var area = MeshUtils.FaceArea(f);
if (Math.Abs(area) < Real.Epsilon)
{
continue;
}
}
edge = f._anEdge;
faceVerts = 0;
do {
v = edge._Org;
if (v._n == MeshUtils.Undef)
{
v._n = maxVertexCount;
maxVertexCount++;
}
faceVerts++;
edge = edge._Lnext;
}
while (edge != f._anEdge);
Debug.Assert(faceVerts <= polySize);
f._n = maxFaceCount;
++maxFaceCount;
}
_elementCount = maxFaceCount;
if (elementType == ElementType.ConnectedPolygons)
maxFaceCount *= 2;
_elements = new int[maxFaceCount * polySize];
_vertexCount = maxVertexCount;
_vertices = new ContourVertex[_vertexCount];
// Output vertices.
for (v = _mesh._vHead._next; v != _mesh._vHead; v = v._next)
{
if (v._n != MeshUtils.Undef)
{
// Store coordinate
_vertices[v._n].Position = v._coords;
_vertices[v._n].Data = v._data;
}
}
// Output indices.
int elementIndex = 0;
for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next)
{
if (!f._inside) continue;
if (NoEmptyPolygons)
{
var area = MeshUtils.FaceArea(f);
if (Math.Abs(area) < Real.Epsilon)
{
continue;
}
}
// Store polygon
edge = f._anEdge;
faceVerts = 0;
do {
v = edge._Org;
_elements[elementIndex++] = v._n;
faceVerts++;
edge = edge._Lnext;
} while (edge != f._anEdge);
// Fill unused.
for (i = faceVerts; i < polySize; ++i)
{
_elements[elementIndex++] = MeshUtils.Undef;
}
// Store polygon connectivity
if (elementType == ElementType.ConnectedPolygons)
{
edge = f._anEdge;
do
{
_elements[elementIndex++] = GetNeighbourFace(edge);
edge = edge._Lnext;
} while (edge != f._anEdge);
// Fill unused.
for (i = faceVerts; i < polySize; ++i)
{
_elements[elementIndex++] = MeshUtils.Undef;
}
}
}
}
private void OutputContours()
{
MeshUtils.Face f;
MeshUtils.Edge edge, start;
int startVert = 0;
int vertCount = 0;
_vertexCount = 0;
_elementCount = 0;
for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next)
{
if (!f._inside) continue;
start = edge = f._anEdge;
do
{
++_vertexCount;
edge = edge._Lnext;
}
while (edge != start);
++_elementCount;
}
_elements = new int[_elementCount * 2];
_vertices = new ContourVertex[_vertexCount];
int vertIndex = 0;
int elementIndex = 0;
startVert = 0;
for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next)
{
if (!f._inside) continue;
vertCount = 0;
start = edge = f._anEdge;
do {
_vertices[vertIndex].Position = edge._Org._coords;
_vertices[vertIndex].Data = edge._Org._data;
++vertIndex;
++vertCount;
edge = edge._Lnext;
} while (edge != start);
_elements[elementIndex++] = startVert;
_elements[elementIndex++] = vertCount;
startVert += vertCount;
}
}
private Real SignedArea(ContourVertex[] vertices)
{
Real area = 0.0f;
for (int i = 0; i < vertices.Length; i++)
{
var v0 = vertices[i];
var v1 = vertices[(i + 1) % vertices.Length];
area += v0.Position.X * v1.Position.Y;
area -= v0.Position.Y * v1.Position.X;
}
return 0.5f * area;
}
public void AddContour(ContourVertex[] vertices)
{
AddContour(vertices, ContourOrientation.Original);
}
public void AddContour(ContourVertex[] vertices, ContourOrientation forceOrientation)
{
if (_mesh == null)
{
_mesh = new Mesh();
}
bool reverse = false;
if (forceOrientation != ContourOrientation.Original)
{
var area = SignedArea(vertices);
reverse = (forceOrientation == ContourOrientation.Clockwise && area < 0.0f) || (forceOrientation == ContourOrientation.CounterClockwise && area > 0.0f);
}
MeshUtils.Edge e = null;
for (int i = 0; i < vertices.Length; ++i)
{
if (e == null)
{
e = _mesh.MakeEdge();
_mesh.Splice(e, e._Sym);
}
else
{
// Create a new vertex and edge which immediately follow e
// in the ordering around the left face.
_mesh.SplitEdge(e);
e = e._Lnext;
}
int index = reverse ? vertices.Length - 1 - i : i;
// The new vertex is now e._Org.
e._Org._coords = vertices[index].Position;
e._Org._data = vertices[index].Data;
// The winding of an edge says how the winding number changes as we
// cross from the edge's right face to its left face. We add the
// vertices in such an order that a CCW contour will add +1 to
// the winding number of the region inside the contour.
e._winding = 1;
e._Sym._winding = -1;
}
}
public void Tessellate(WindingRule windingRule, ElementType elementType, int polySize)
{
Tessellate(windingRule, elementType, polySize, null);
}
public void Tessellate(WindingRule windingRule, ElementType elementType, int polySize, CombineCallback combineCallback)
{
_normal = Vec3.Zero;
_vertices = null;
_elements = null;
_windingRule = windingRule;
_combineCallback = combineCallback;
if (_mesh == null)
{
return;
}
// Determine the polygon normal and project vertices onto the plane
// of the polygon.
ProjectPolygon();
// ComputeInterior computes the planar arrangement specified
// by the given contours, and further subdivides this arrangement
// into regions. Each region is marked "inside" if it belongs
// to the polygon, according to the rule given by windingRule.
// Each interior region is guaranteed be monotone.
ComputeInterior();
// If the user wants only the boundary contours, we throw away all edges
// except those which separate the interior from the exterior.
// Otherwise we tessellate all the regions marked "inside".
if (elementType == ElementType.BoundaryContours)
{
SetWindingNumber(1, true);
}
else
{
TessellateInterior();
}
_mesh.Check();
if (elementType == ElementType.BoundaryContours)
{
OutputContours();
}
else
{
OutputPolymesh(elementType, polySize);
}
if (UsePooling)
{
_mesh.Free();
}
_mesh = null;
}
}
}
}
| |
using System;
using System.Security;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Collections.Generic;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using MS.Internal.Automation;
using MS.Internal;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Automation.Peers
{
///
public class UIElementAutomationPeer: AutomationPeer
{
///
public UIElementAutomationPeer(UIElement owner)
{
if(owner == null)
{
throw new ArgumentNullException("owner");
}
_owner = owner;
}
///
public UIElement Owner
{
get
{
return _owner;
}
}
///<summary>
/// This static helper creates an AutomationPeer for the specified element and
/// caches it - that means the created peer is going to live long and shadow the
/// element for its lifetime. The peer will be used by Automation to proxy the element, and
/// to fire events to the Automation when something happens with the element.
/// The created peer is returned from this method and also from subsequent calls to this method
/// and <seealso cref="FromElement"/>. The type of the peer is determined by the
/// <seealso cref="UIElement.OnCreateAutomationPeer"/> virtual callback. If UIElement does not
/// implement the callback, there will be no peer and this method will return 'null' (in other
/// words, there is no such thing as a 'default peer').
///</summary>
public static AutomationPeer CreatePeerForElement(UIElement element)
{
if(element == null)
{
throw new ArgumentNullException("element");
}
return element.CreateAutomationPeer();
}
///
public static AutomationPeer FromElement(UIElement element)
{
if(element == null)
{
throw new ArgumentNullException("element");
}
return element.GetAutomationPeer();
}
///
override protected List<AutomationPeer> GetChildrenCore()
{
List<AutomationPeer> children = null;
iterate(_owner,
(IteratorCallback)delegate(AutomationPeer peer)
{
if (children == null)
children = new List<AutomationPeer>();
children.Add(peer);
return (false);
});
return children;
}
///
/// <SecurityNote>
/// Critical - Calls critical AutomationPeer.Hwnd setter.
/// </SecurityNote>
[SecurityCritical]
internal static AutomationPeer GetRootAutomationPeer(Visual rootVisual, IntPtr hwnd)
{
AutomationPeer root = null;
iterate(rootVisual,
(IteratorCallback)delegate(AutomationPeer peer)
{
root = peer;
return (true);
});
if (root != null)
{
root.Hwnd = hwnd;
}
return root;
}
private delegate bool IteratorCallback(AutomationPeer peer);
//
private static bool iterate(DependencyObject parent, IteratorCallback callback)
{
bool done = false;
if(parent != null)
{
AutomationPeer peer = null;
int count = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < count && !done; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if( child != null
&& child is UIElement
&& (peer = CreatePeerForElement((UIElement)child)) != null )
{
done = callback(peer);
}
else if ( child != null
&& child is UIElement3D
&& (peer = UIElement3DAutomationPeer.CreatePeerForElement(((UIElement3D)child))) != null )
{
done = callback(peer);
}
else
{
done = iterate(child, callback);
}
}
}
return done;
}
///
override public object GetPattern(PatternInterface patternInterface)
{
//Support synchronized input
if (patternInterface == PatternInterface.SynchronizedInput)
{
// Adaptor object is used here to avoid loading UIA assemblies in non-UIA scenarios.
if (_synchronizedInputPattern == null)
_synchronizedInputPattern = new SynchronizedInputAdaptor(_owner);
return _synchronizedInputPattern;
}
return null;
}
//
// P R O P E R T I E S
//
///
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.Custom;
}
///
protected override string GetAutomationIdCore()
{
return (AutomationProperties.GetAutomationId(_owner));
}
///
protected override string GetNameCore()
{
return (AutomationProperties.GetName(_owner));
}
///
protected override string GetHelpTextCore()
{
return (AutomationProperties.GetHelpText(_owner));
}
///
/// <SecurityNote>
/// Critical - Calls PresentationSource.CriticalFromVisual to get the source for this visual
/// TreatAsSafe - The returned PresenationSource object is not exposed and is only used for converting
/// co-ordinates to screen space.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
override protected Rect GetBoundingRectangleCore()
{
PresentationSource presentationSource = PresentationSource.CriticalFromVisual(_owner);
// If there's no source, the element is not visible, return empty rect
if(presentationSource == null)
return Rect.Empty;
HwndSource hwndSource = presentationSource as HwndSource;
// If the source isn't an HwnSource, there's not much we can do, return empty rect
if(hwndSource == null)
return Rect.Empty;
Rect rectElement = new Rect(new Point(0, 0), _owner.RenderSize);
Rect rectRoot = PointUtil.ElementToRoot(rectElement, _owner, presentationSource);
Rect rectClient = PointUtil.RootToClient(rectRoot, presentationSource);
Rect rectScreen = PointUtil.ClientToScreen(rectClient, hwndSource);
return rectScreen;
}
///
/// <SecurityNote>
/// Critical - Calls PresentationSource.CriticalFromVisual to get the source for this visual
/// TreatAsSafe - The returned PresenationSource object is not exposed and is only used for converting
/// co-ordinates to screen space.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal override Rect GetVisibleBoundingRectCore()
{
PresentationSource presentationSource = PresentationSource.CriticalFromVisual(_owner);
// If there's no source, the element is not visible, return empty rect
if (presentationSource == null)
return Rect.Empty;
HwndSource hwndSource = presentationSource as HwndSource;
// If the source isn't an HwnSource, there's not much we can do, return empty rect
if (hwndSource == null)
return Rect.Empty;
Rect rectElement = CalculateVisibleBoundingRect(_owner);
Rect rectRoot = PointUtil.ElementToRoot(rectElement, _owner, presentationSource);
Rect rectClient = PointUtil.RootToClient(rectRoot, presentationSource);
Rect rectScreen = PointUtil.ClientToScreen(rectClient, hwndSource);
return rectScreen;
}
///
override protected bool IsOffscreenCore()
{
IsOffscreenBehavior behavior = AutomationProperties.GetIsOffscreenBehavior(_owner);
switch (behavior)
{
case IsOffscreenBehavior.Onscreen :
return false;
case IsOffscreenBehavior.Offscreen :
return true;
case IsOffscreenBehavior.FromClip:
{
bool isOffscreen = !_owner.IsVisible;
if (!isOffscreen)
{
Rect boundingRect = CalculateVisibleBoundingRect(_owner);
isOffscreen = (DoubleUtil.AreClose(boundingRect, Rect.Empty) ||
DoubleUtil.AreClose(boundingRect.Height, 0) ||
DoubleUtil.AreClose(boundingRect.Width, 0));
}
return isOffscreen;
}
default :
return !_owner.IsVisible;
}
}
///<summary>
/// This eliminates the part of bounding rectangle if it is at all being overlapped/clipped by any of the visual ancestor up in the parent chain
///</summary>
internal static Rect CalculateVisibleBoundingRect(UIElement owner)
{
Rect boundingRect = new Rect(owner.RenderSize);
// Compute visible portion of the rectangle.
DependencyObject parent = VisualTreeHelper.GetParent(owner);
while (parent != null &&
!DoubleUtil.AreClose(boundingRect, Rect.Empty) &&
!DoubleUtil.AreClose(boundingRect.Height, 0) &&
!DoubleUtil.AreClose(boundingRect.Width, 0))
{
Visual visualParent = parent as Visual;
if (visualParent != null)
{
Geometry clipGeometry = VisualTreeHelper.GetClip(visualParent);
if (clipGeometry != null)
{
GeneralTransform transform = owner.TransformToAncestor(visualParent).Inverse;
// Safer version of transform to descendent (doing the inverse ourself and saves us changing the co-ordinate space of the owner's bounding rectangle),
// we want the rect inside of our space. (Which is always rectangular and much nicer to work with)
if (transform != null)
{
Rect clipBounds = clipGeometry.Bounds;
clipBounds = transform.TransformBounds(clipBounds);
boundingRect.Intersect(clipBounds);
}
else
{
// No visibility if non-invertable transform exists.
boundingRect = Rect.Empty;
}
}
}
parent = VisualTreeHelper.GetParent(parent);
}
return boundingRect;
}
///
override protected AutomationOrientation GetOrientationCore()
{
return (AutomationOrientation.None);
}
///
override protected string GetItemTypeCore()
{
return AutomationProperties.GetItemType(_owner);
}
///
override protected string GetClassNameCore()
{
return string.Empty;
}
///
override protected string GetItemStatusCore()
{
return AutomationProperties.GetItemStatus(_owner);
}
///
override protected bool IsRequiredForFormCore()
{
return AutomationProperties.GetIsRequiredForForm(_owner);
}
///
override protected bool IsKeyboardFocusableCore()
{
return Keyboard.IsFocusable(_owner);
}
///
override protected bool HasKeyboardFocusCore()
{
return _owner.IsKeyboardFocused;
}
///
override protected bool IsEnabledCore()
{
return _owner.IsEnabled;
}
///
override protected bool IsPasswordCore()
{
return false;
}
///
override protected bool IsContentElementCore()
{
return true;
}
///
override protected bool IsControlElementCore()
{
return true;
}
///
override protected AutomationPeer GetLabeledByCore()
{
UIElement element = AutomationProperties.GetLabeledBy(_owner);
if (element != null)
return element.GetAutomationPeer();
return null;
}
///
override protected string GetAcceleratorKeyCore()
{
return AutomationProperties.GetAcceleratorKey(_owner);
}
///
override protected string GetAccessKeyCore()
{
string result = AutomationProperties.GetAccessKey(_owner);
if (string.IsNullOrEmpty(result))
return AccessKeyManager.InternalGetAccessKeyCharacter(_owner);
return string.Empty;
}
//
// M E T H O D S
//
///
/// <SecurityNote>
/// Critical - Calls PresentationSource.CriticalFromVisual to get the source for this visual
/// TreatAsSafe - The returned PresenationSource object is not exposed and is only used for converting
/// co-ordinates to screen space.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
override protected Point GetClickablePointCore()
{
Point pt = new Point(double.NaN, double.NaN);
PresentationSource presentationSource = PresentationSource.CriticalFromVisual(_owner);
// If there's no source, the element is not visible, return (double.NaN, double.NaN) point
if(presentationSource == null)
return pt;
HwndSource hwndSource = presentationSource as HwndSource;
// If the source isn't an HwnSource, there's not much we can do, return (double.NaN, double.NaN) point
if(hwndSource == null)
return pt;
Rect rectElement = new Rect(new Point(0, 0), _owner.RenderSize);
Rect rectRoot = PointUtil.ElementToRoot(rectElement, _owner, presentationSource);
Rect rectClient = PointUtil.RootToClient(rectRoot, presentationSource);
Rect rectScreen = PointUtil.ClientToScreen(rectClient, hwndSource);
pt = new Point(rectScreen.Left + rectScreen.Width * 0.5, rectScreen.Top + rectScreen.Height * 0.5);
return pt;
}
///
override protected void SetFocusCore()
{
if (!_owner.Focus())
throw new InvalidOperationException(SR.Get(SRID.SetFocusFailed));
}
private UIElement _owner;
private SynchronizedInputAdaptor _synchronizedInputPattern;
}
}
| |
using UnityEngine;
using Stratus;
using System;
using Stratus.AI;
namespace Stratus.Gameplay
{
/// <summary>
/// An action taken in combat.
/// </summary>
public abstract class StratusCombatAction
{
//----------------------------------------------------------------------/
// Declarations
//----------------------------------------------------------------------/
/// <summary>
/// Specific timings for the action's transitions
/// </summary>
[Serializable]
public class Timings
{
/// <summary>
/// How long to wait before the action starts casting
/// </summary>
[Tooltip("How long to wait before the action starts casting")]
[Range(0f, 1.5f)]
public float start = 0.1f;
/// <summary>
/// How long this action will take to cast
/// </summary>
[Range(0f, 10f)]
[Tooltip("How long it will take this action to cast")]
public float cast = 0.5f;
/// <summary>
/// How long to wait before the action is executed
/// </summary>
[Range(0f, 1.5f)]
[Tooltip("How long to wait before the action starts executing.")]
public float trigger = 0.0f;
/// <summary>
/// How long it takes to execute the action
/// </summary>
[Range(0f, 1.5f)]
[Tooltip("How long it takes to execute the action")]
public float execute = 0.25f;
/// <summary>
/// How long to wait before the action is ended
/// </summary>
[Range(0f, 1.5f)]
[Tooltip("How long to wait before the action is ended")]
public float end = 0.25f;
}
/// <summary>
/// The phases, from beginning to end, of a combat action
/// </summary>
public enum Phase
{
/// <summary>
/// The action has been selected and will start casting once it gets in range of the target
/// </summary>
Queue,
/// <summary>
/// The action has started
/// </summary>
Started,
/// <summary>
/// The action is now casting
/// </summary>
Casting,
/// <summary>
/// The action is ready to be executed
/// </summary>
Trigger,
/// <summary>
/// The action is being executed
/// </summary>
Execute,
/// <summary>
/// The action has ended
/// </summary>
Ended
}
//----------------------------------------------------------------------/
// Events
//----------------------------------------------------------------------/
public abstract class CombatActionEvent : Stratus.StratusEvent { public StratusCombatAction Action; }
/// <summary>
/// Signals that an action has been queued up
/// </summary>
public class QueueEvent : CombatActionEvent { }
/// <summary>
/// When an action should be selected by the combat controller
/// </summary>
public class SelectEvent : CombatActionEvent { }
/// <summary>
/// When the action has started casting
/// </summary>
public class StartedEvent : CombatActionEvent { }
/// <summary>
/// When the action needs the agent to approach the target to within a specified range.
/// </summary>
public class ApproachEvent : CombatActionEvent
{
public StratusCombatController Target;
public float Range;
}
/// <summary>
/// Signals that an action is ready to be executed
/// </summary>
public class TriggerEvent : CombatActionEvent { }
/// <summary>
/// Signals that an action is executing
/// </summary>
public class ExecuteEvent : CombatActionEvent { public StratusCombatTrigger.Result Result; }
/// <summary>
/// Signals that an action has finished executing
/// </summary>
public class EndedEvent : CombatActionEvent { }
/// <summary>
/// Cancels the action
/// </summary>
public class CancelEvent : CombatActionEvent { }
/// <summary>
/// Delays an action for a specified amount of time
/// </summary>
public class DelayEvent : CombatActionEvent { public float Delay; }
/// <summary>
/// When an action failed to be created.
/// </summary>
public class FailedEvent : CombatActionEvent { }
/// <summary>
/// Reassess what action to take
/// </summary>
public class ReassessEvent : CombatActionEvent { }
//----------------------------------------------------------------------/
// Properties
//----------------------------------------------------------------------/
/// <summary>
/// Specific timers for this action's transitions
/// </summary>
public Timings Timers;
/// <summary>
/// At what range from the target should this action take place
/// </summary>
public float Range = 3.0f;
/// <summary>
/// The caster of this action
/// </summary>
public StratusCombatController User;
/// <summary>
/// The target of this action
/// </summary>
public StratusCombatController Target;
//------------------------------------------------------------------------/
/// <summary>
/// How much of the cast has progressed, as a percentage
/// </summary>
public float castProgress
{
get
{
if (Timers.cast == 0.0f) return 1.0f;
return castTimer / Timers.cast;
}
}
/// <summary>
/// The name of this action
/// </summary>
public abstract string name { get; }
/// <summary>
/// Description of the action
/// </summary>
public abstract string description { get; }
//----------------------------------------------------------------------/
// Fields
//----------------------------------------------------------------------/
/// <summary>
/// The current phase this action is on
/// </summary>
public Phase currentPhase { get; private set; }
/// <summary>
/// Whether the action has finished executing.
/// </summary>
public bool isFinished { get; private set; }
/// <summary>
/// Whether the user of this action is within range
/// </summary>
private bool isWithinRange = false;
/// <summary>
/// How much time has spent casting the action
/// </summary>
protected float castTimer = 0.0f;
/// <summary>
/// The sequence currently being played for the active phase
/// </summary>
private StratusActionSet currentPhaseSequence;
//----------------------------------------------------------------------/
// Interface
//----------------------------------------------------------------------/
protected abstract void OnStart(StratusCombatController user, StratusCombatController target);
protected abstract void OnCasting(StratusCombatController user, StratusCombatController target, float step);
protected abstract void OnTrigger(StratusCombatController user, StratusCombatController target);
protected abstract void OnExecute(StratusCombatController user, StratusCombatController target);
protected abstract void OnEnd();
protected abstract void OnCancel();
//protected abstract void OnCast(CombatController user, CombatController target, float step);
//----------------------------------------------------------------------/
// Methods
//----------------------------------------------------------------------/
/// <summary>
/// CombatAction constructor.
/// </summary>
/// <param name="user">The controller who will be running this action.</param>
/// <param name="target">The target this action will be acted upon.</param>
/// <param name="castTime">The cast time of this action.</param>
/// <param name="range">The range of this action.</param>
/// <param name="duration"></param>
public StratusCombatAction(StratusCombatController user, StratusCombatController target, float range, Timings timings)
{
this.Initialize(user, target, range, timings);
}
/// <summary>
/// Initializes the action, configuring it for use.
/// </summary>
/// <param name="user"></param>
/// <param name="target"></param>
/// <param name="castTime"></param>
/// <param name="range"></param>
/// <param name="duration"></param>
public void Initialize(StratusCombatController user, StratusCombatController target, float range, Timings timings)
{
this.User = user;
this.Target = target;
this.Range = range;
this.Timers = timings;
// Inform the user that we have picked this target
var targetEvent = new StratusCombatController.TargetEvent();
targetEvent.target = target;
user.gameObject.Dispatch<StratusCombatController.TargetEvent>(targetEvent);
// Inform the user to approach the target
var approachEvent = new ApproachEvent();
approachEvent.Action = this;
approachEvent.Target = this.Target;
approachEvent.Range = this.Range;
user.gameObject.Dispatch<ApproachEvent>(approachEvent);
currentPhase = Phase.Queue;
}
/// <summary>
/// Updates this CombatAction.
/// </summary>
/// <param name="timeStep">How much to update the action</param>
public void Update(float timeStep)
{
if (isFinished)
return;
// Check whether we are in range of the target
if (!isWithinRange)
{
if (StratusDetection.CheckRange(User.transform, Target.transform, this.Range))
{
isWithinRange = true;
this.Start(User, Target);
//this.User.gameObject.Dispatch<Movement.EndedEvent>(new Movement.EndedEvent());
}
}
// Once within range of the target, start casting the action
else
{
//Cast(this.User, this.Target, timeStep);
switch (this.currentPhase)
{
case Phase.Casting:
Cast(this.User, this.Target, timeStep);
break;
case Phase.Trigger:
break;
}
}
}
/// <summary>
/// After getting in range of the target, starts the action. It will begin casting it.
/// </summary>
/// <param name="user">The controller who will be running this action.</param>
/// <param name="target"></param>
protected void Start(StratusCombatController user, StratusCombatController target)
{
currentPhase = Phase.Started;
//Trace.Script("Starting", user);
// Called the first time the action is about to start casting
//this.OnStart(user, target);
// Inform the controller the the action has started casting
this.currentPhaseSequence = StratusActions.Sequence(this.User.behaviour);
StratusActions.Call(this.currentPhaseSequence, () => Inform<StartedEvent>());
StratusActions.Delay(this.currentPhaseSequence, Timers.start);
StratusActions.Call(this.currentPhaseSequence, () => this.OnStart(user, target));
StratusActions.Call(this.currentPhaseSequence, () =>
{
currentPhase = Phase.Casting;
});
//Actions.Property(seq, () => this.CurrentPhase, Phase.Casting, 0f, Ease.Linear);
}
/// <summary>
/// Continuously casts the current action. Once it has finished casting, it will be triggered.
/// </summary>
/// <param name="user">The controller who will be running this action.</param>
/// <param name="target">The target this action will be acted upon.</param>
/// <param name="timeStep">How much will the cast be progressed</param>
protected virtual void Cast(StratusCombatController user, StratusCombatController target, float timeStep)
{
// Update the timer
castTimer += timeStep;
//Trace.Script("Casting action , cast timer = " + this.CastTimer, user);
// Once we are done casting the current action, execute it! It will first
// animate it and check for a trigger.
// Once the trigger has run, it will be calling this action's 'Execute' method
if (castTimer >= Timers.cast)
{
this.Trigger(user, target);
}
// If the skill is still casting,...
else
{
OnCasting(user, target, timeStep);
}
}
/// <summary>
/// Triggers this action, signaling that it is ready to be executed.
/// </summary>
/// <param name="user"></param>
public void Trigger(StratusCombatController user, StratusCombatController target)
{
currentPhase = Phase.Trigger;
// Inform the skill is ready to be triggered
this.currentPhaseSequence = StratusActions.Sequence(this.User.behaviour);
StratusActions.Call(this.currentPhaseSequence, () => Inform<TriggerEvent>(), Timers.trigger);
// The action is now finished updating
isFinished = true;
// Invoke the trigger
this.OnTrigger(user, target);
}
/// <summary>
/// Begins executing of this action. After it is executed, it will be considered ended.
/// </summary>
public void Execute()
{
currentPhase = Phase.Execute;
StratusDebug.Log("Now executing", User.behaviour);
this.currentPhaseSequence = StratusActions.Sequence(this.User.behaviour);
StratusActions.Delay(this.currentPhaseSequence, this.Timers.execute);
StratusActions.Call(this.currentPhaseSequence, () => this.OnExecute(this.User, this.Target));
StratusActions.Call(this.currentPhaseSequence, () => Inform<ExecuteEvent>());
StratusActions.Call(this.currentPhaseSequence, () => this.End(this.User));
}
/// <summary>
/// Announces the end of this action.
/// </summary>
/// <param name="user"></param>
protected void End(StratusCombatController user)
{
currentPhase = Phase.Ended;
this.OnEnd();
this.currentPhaseSequence = StratusActions.Sequence(this.User.behaviour);
StratusActions.Call(this.currentPhaseSequence, () => Inform<EndedEvent>(), Timers.end);
}
/// <summary>
/// Delays the cast time of this action.
/// </summary>
/// <param name="delay">How much to delay this action.</param>
public void Delay(float delay)
{
//Trace.Script("Delayed by " + delay, this.User);
this.castTimer -= delay;
if (this.castTimer < 0.0f) this.castTimer = 0.0f;
}
/// <summary>
/// Cancels the current action.
/// </summary>
public void Cancel()
{
StratusDebug.Log("Action cancelled!", User.behaviour);
if (this.currentPhaseSequence != null)
this.currentPhaseSequence.Cancel();
this.OnCancel();
this.End(this.User);
}
/// <summary>
/// Inform the combat controller of the current phase in the action
/// </summary>
/// <typeparam name="T"></typeparam>
void Inform<T>() where T : StratusCombatAction.CombatActionEvent, new()
{
var actionEvent = new T();
actionEvent.Action = this;
this.User.gameObject.Dispatch<T>(actionEvent);
}
}
}
| |
namespace android.view.animation
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.view.animation.Animation_))]
public abstract partial class Animation : java.lang.Object, java.lang.Cloneable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Animation()
{
InitJNI();
}
protected Animation(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.animation.Animation.AnimationListener_))]
public interface AnimationListener : global::MonoJavaBridge.IJavaObject
{
void onAnimationStart(android.view.animation.Animation arg0);
void onAnimationEnd(android.view.animation.Animation arg0);
void onAnimationRepeat(android.view.animation.Animation arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.animation.Animation.AnimationListener))]
public sealed partial class AnimationListener_ : java.lang.Object, AnimationListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static AnimationListener_()
{
InitJNI();
}
internal AnimationListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onAnimationStart9900;
void android.view.animation.Animation.AnimationListener.onAnimationStart(android.view.animation.Animation arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation.AnimationListener_._onAnimationStart9900, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.AnimationListener_.staticClass, global::android.view.animation.Animation.AnimationListener_._onAnimationStart9900, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onAnimationEnd9901;
void android.view.animation.Animation.AnimationListener.onAnimationEnd(android.view.animation.Animation arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation.AnimationListener_._onAnimationEnd9901, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.AnimationListener_.staticClass, global::android.view.animation.Animation.AnimationListener_._onAnimationEnd9901, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onAnimationRepeat9902;
void android.view.animation.Animation.AnimationListener.onAnimationRepeat(android.view.animation.Animation arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation.AnimationListener_._onAnimationRepeat9902, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.AnimationListener_.staticClass, global::android.view.animation.Animation.AnimationListener_._onAnimationRepeat9902, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.Animation.AnimationListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/Animation$AnimationListener"));
global::android.view.animation.Animation.AnimationListener_._onAnimationStart9900 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.AnimationListener_.staticClass, "onAnimationStart", "(Landroid/view/animation/Animation;)V");
global::android.view.animation.Animation.AnimationListener_._onAnimationEnd9901 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.AnimationListener_.staticClass, "onAnimationEnd", "(Landroid/view/animation/Animation;)V");
global::android.view.animation.Animation.AnimationListener_._onAnimationRepeat9902 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.AnimationListener_.staticClass, "onAnimationRepeat", "(Landroid/view/animation/Animation;)V");
}
}
[global::MonoJavaBridge.JavaClass()]
protected partial class Description : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Description()
{
InitJNI();
}
protected Description(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _Description9903;
protected Description() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.Animation.Description.staticClass, global::android.view.animation.Animation.Description._Description9903);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _type9904;
public int type
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _value9905;
public float value
{
get
{
return default(float);
}
set
{
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.Animation.Description.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/Animation$Description"));
global::android.view.animation.Animation.Description._Description9903 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.Description.staticClass, "<init>", "()V");
}
}
internal static global::MonoJavaBridge.MethodId _clone9906;
protected virtual new global::android.view.animation.Animation clone()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.view.animation.Animation._clone9906)) as android.view.animation.Animation;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._clone9906)) as android.view.animation.Animation;
}
internal static global::MonoJavaBridge.MethodId _start9907;
public virtual void start()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._start9907);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._start9907);
}
internal static global::MonoJavaBridge.MethodId _reset9908;
public virtual void reset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._reset9908);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._reset9908);
}
internal static global::MonoJavaBridge.MethodId _initialize9909;
public virtual void initialize(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._initialize9909, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._initialize9909, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _cancel9910;
public virtual void cancel()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._cancel9910);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._cancel9910);
}
internal static global::MonoJavaBridge.MethodId _resolveSize9911;
protected virtual float resolveSize(int arg0, float arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.view.animation.Animation._resolveSize9911, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._resolveSize9911, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _getRepeatCount9912;
public virtual int getRepeatCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.animation.Animation._getRepeatCount9912);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getRepeatCount9912);
}
internal static global::MonoJavaBridge.MethodId _setInterpolator9913;
public virtual void setInterpolator(android.view.animation.Interpolator arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setInterpolator9913, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setInterpolator9913, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setInterpolator9914;
public virtual void setInterpolator(android.content.Context arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setInterpolator9914, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setInterpolator9914, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getInterpolator9915;
public virtual global::android.view.animation.Interpolator getInterpolator()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.animation.Interpolator>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.animation.Animation._getInterpolator9915)) as android.view.animation.Interpolator;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.animation.Interpolator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getInterpolator9915)) as android.view.animation.Interpolator;
}
internal static global::MonoJavaBridge.MethodId _isInitialized9916;
public virtual bool isInitialized()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.Animation._isInitialized9916);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._isInitialized9916);
}
internal static global::MonoJavaBridge.MethodId _setStartOffset9917;
public virtual void setStartOffset(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setStartOffset9917, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setStartOffset9917, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setDuration9918;
public virtual void setDuration(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setDuration9918, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setDuration9918, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _restrictDuration9919;
public virtual void restrictDuration(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._restrictDuration9919, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._restrictDuration9919, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _scaleCurrentDuration9920;
public virtual void scaleCurrentDuration(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._scaleCurrentDuration9920, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._scaleCurrentDuration9920, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setStartTime9921;
public virtual void setStartTime(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setStartTime9921, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setStartTime9921, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _startNow9922;
public virtual void startNow()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._startNow9922);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._startNow9922);
}
internal static global::MonoJavaBridge.MethodId _setRepeatMode9923;
public virtual void setRepeatMode(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setRepeatMode9923, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setRepeatMode9923, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setRepeatCount9924;
public virtual void setRepeatCount(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setRepeatCount9924, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setRepeatCount9924, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isFillEnabled9925;
public virtual bool isFillEnabled()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.Animation._isFillEnabled9925);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._isFillEnabled9925);
}
internal static global::MonoJavaBridge.MethodId _setFillEnabled9926;
public virtual void setFillEnabled(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setFillEnabled9926, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setFillEnabled9926, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setFillBefore9927;
public virtual void setFillBefore(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setFillBefore9927, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setFillBefore9927, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setFillAfter9928;
public virtual void setFillAfter(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setFillAfter9928, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setFillAfter9928, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setZAdjustment9929;
public virtual void setZAdjustment(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setZAdjustment9929, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setZAdjustment9929, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setDetachWallpaper9930;
public virtual void setDetachWallpaper(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setDetachWallpaper9930, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setDetachWallpaper9930, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getStartTime9931;
public virtual long getStartTime()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.view.animation.Animation._getStartTime9931);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getStartTime9931);
}
internal static global::MonoJavaBridge.MethodId _getDuration9932;
public virtual long getDuration()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.view.animation.Animation._getDuration9932);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getDuration9932);
}
internal static global::MonoJavaBridge.MethodId _getStartOffset9933;
public virtual long getStartOffset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.view.animation.Animation._getStartOffset9933);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getStartOffset9933);
}
internal static global::MonoJavaBridge.MethodId _getRepeatMode9934;
public virtual int getRepeatMode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.animation.Animation._getRepeatMode9934);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getRepeatMode9934);
}
internal static global::MonoJavaBridge.MethodId _getFillBefore9935;
public virtual bool getFillBefore()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.Animation._getFillBefore9935);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getFillBefore9935);
}
internal static global::MonoJavaBridge.MethodId _getFillAfter9936;
public virtual bool getFillAfter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.Animation._getFillAfter9936);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getFillAfter9936);
}
internal static global::MonoJavaBridge.MethodId _getZAdjustment9937;
public virtual int getZAdjustment()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.animation.Animation._getZAdjustment9937);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getZAdjustment9937);
}
internal static global::MonoJavaBridge.MethodId _getDetachWallpaper9938;
public virtual bool getDetachWallpaper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.Animation._getDetachWallpaper9938);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getDetachWallpaper9938);
}
internal static global::MonoJavaBridge.MethodId _willChangeTransformationMatrix9939;
public virtual bool willChangeTransformationMatrix()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.Animation._willChangeTransformationMatrix9939);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._willChangeTransformationMatrix9939);
}
internal static global::MonoJavaBridge.MethodId _willChangeBounds9940;
public virtual bool willChangeBounds()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.Animation._willChangeBounds9940);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._willChangeBounds9940);
}
internal static global::MonoJavaBridge.MethodId _setAnimationListener9941;
public virtual void setAnimationListener(android.view.animation.Animation.AnimationListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._setAnimationListener9941, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._setAnimationListener9941, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _ensureInterpolator9942;
protected virtual void ensureInterpolator()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._ensureInterpolator9942);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._ensureInterpolator9942);
}
internal static global::MonoJavaBridge.MethodId _computeDurationHint9943;
public virtual long computeDurationHint()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.view.animation.Animation._computeDurationHint9943);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._computeDurationHint9943);
}
internal static global::MonoJavaBridge.MethodId _getTransformation9944;
public virtual bool getTransformation(long arg0, android.view.animation.Transformation arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.Animation._getTransformation9944, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._getTransformation9944, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _hasStarted9945;
public virtual bool hasStarted()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.Animation._hasStarted9945);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._hasStarted9945);
}
internal static global::MonoJavaBridge.MethodId _hasEnded9946;
public virtual bool hasEnded()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.Animation._hasEnded9946);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._hasEnded9946);
}
internal static global::MonoJavaBridge.MethodId _applyTransformation9947;
protected virtual void applyTransformation(float arg0, android.view.animation.Transformation arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.Animation._applyTransformation9947, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.Animation.staticClass, global::android.view.animation.Animation._applyTransformation9947, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _Animation9948;
public Animation(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.Animation.staticClass, global::android.view.animation.Animation._Animation9948, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Animation9949;
public Animation() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.Animation.staticClass, global::android.view.animation.Animation._Animation9949);
Init(@__env, handle);
}
public static int INFINITE
{
get
{
return -1;
}
}
public static int RESTART
{
get
{
return 1;
}
}
public static int REVERSE
{
get
{
return 2;
}
}
public static int START_ON_FIRST_FRAME
{
get
{
return -1;
}
}
public static int ABSOLUTE
{
get
{
return 0;
}
}
public static int RELATIVE_TO_SELF
{
get
{
return 1;
}
}
public static int RELATIVE_TO_PARENT
{
get
{
return 2;
}
}
public static int ZORDER_NORMAL
{
get
{
return 0;
}
}
public static int ZORDER_TOP
{
get
{
return 1;
}
}
public static int ZORDER_BOTTOM
{
get
{
return -1;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.Animation.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/Animation"));
global::android.view.animation.Animation._clone9906 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "clone", "()Landroid/view/animation/Animation;");
global::android.view.animation.Animation._start9907 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "start", "()V");
global::android.view.animation.Animation._reset9908 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "reset", "()V");
global::android.view.animation.Animation._initialize9909 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "initialize", "(IIII)V");
global::android.view.animation.Animation._cancel9910 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "cancel", "()V");
global::android.view.animation.Animation._resolveSize9911 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "resolveSize", "(IFII)F");
global::android.view.animation.Animation._getRepeatCount9912 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getRepeatCount", "()I");
global::android.view.animation.Animation._setInterpolator9913 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setInterpolator", "(Landroid/view/animation/Interpolator;)V");
global::android.view.animation.Animation._setInterpolator9914 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setInterpolator", "(Landroid/content/Context;I)V");
global::android.view.animation.Animation._getInterpolator9915 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getInterpolator", "()Landroid/view/animation/Interpolator;");
global::android.view.animation.Animation._isInitialized9916 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "isInitialized", "()Z");
global::android.view.animation.Animation._setStartOffset9917 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setStartOffset", "(J)V");
global::android.view.animation.Animation._setDuration9918 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setDuration", "(J)V");
global::android.view.animation.Animation._restrictDuration9919 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "restrictDuration", "(J)V");
global::android.view.animation.Animation._scaleCurrentDuration9920 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "scaleCurrentDuration", "(F)V");
global::android.view.animation.Animation._setStartTime9921 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setStartTime", "(J)V");
global::android.view.animation.Animation._startNow9922 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "startNow", "()V");
global::android.view.animation.Animation._setRepeatMode9923 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setRepeatMode", "(I)V");
global::android.view.animation.Animation._setRepeatCount9924 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setRepeatCount", "(I)V");
global::android.view.animation.Animation._isFillEnabled9925 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "isFillEnabled", "()Z");
global::android.view.animation.Animation._setFillEnabled9926 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setFillEnabled", "(Z)V");
global::android.view.animation.Animation._setFillBefore9927 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setFillBefore", "(Z)V");
global::android.view.animation.Animation._setFillAfter9928 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setFillAfter", "(Z)V");
global::android.view.animation.Animation._setZAdjustment9929 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setZAdjustment", "(I)V");
global::android.view.animation.Animation._setDetachWallpaper9930 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setDetachWallpaper", "(Z)V");
global::android.view.animation.Animation._getStartTime9931 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getStartTime", "()J");
global::android.view.animation.Animation._getDuration9932 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getDuration", "()J");
global::android.view.animation.Animation._getStartOffset9933 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getStartOffset", "()J");
global::android.view.animation.Animation._getRepeatMode9934 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getRepeatMode", "()I");
global::android.view.animation.Animation._getFillBefore9935 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getFillBefore", "()Z");
global::android.view.animation.Animation._getFillAfter9936 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getFillAfter", "()Z");
global::android.view.animation.Animation._getZAdjustment9937 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getZAdjustment", "()I");
global::android.view.animation.Animation._getDetachWallpaper9938 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getDetachWallpaper", "()Z");
global::android.view.animation.Animation._willChangeTransformationMatrix9939 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "willChangeTransformationMatrix", "()Z");
global::android.view.animation.Animation._willChangeBounds9940 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "willChangeBounds", "()Z");
global::android.view.animation.Animation._setAnimationListener9941 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "setAnimationListener", "(Landroid/view/animation/Animation$AnimationListener;)V");
global::android.view.animation.Animation._ensureInterpolator9942 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "ensureInterpolator", "()V");
global::android.view.animation.Animation._computeDurationHint9943 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "computeDurationHint", "()J");
global::android.view.animation.Animation._getTransformation9944 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "getTransformation", "(JLandroid/view/animation/Transformation;)Z");
global::android.view.animation.Animation._hasStarted9945 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "hasStarted", "()Z");
global::android.view.animation.Animation._hasEnded9946 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "hasEnded", "()Z");
global::android.view.animation.Animation._applyTransformation9947 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "applyTransformation", "(FLandroid/view/animation/Transformation;)V");
global::android.view.animation.Animation._Animation9948 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::android.view.animation.Animation._Animation9949 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "<init>", "()V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.animation.Animation))]
public sealed partial class Animation_ : android.view.animation.Animation
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Animation_()
{
InitJNI();
}
internal Animation_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.Animation_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/Animation"));
}
}
}
| |
using Signum.Utilities.Reflection;
using Signum.Engine.Maps;
namespace Signum.Engine.Linq;
internal static class SmartEqualizer
{
public static ConstantExpression True = Expression.Constant(true);
public static ConstantExpression False = Expression.Constant(false);
static ConstantExpression NewId = Expression.Constant("NewID");
public static Expression EqualNullableGroupBy(Expression e1, Expression e2)
{
return Expression.Or(Expression.Equal(e1.Nullify(), e2.Nullify()),
Expression.And(new IsNullExpression(e1), new IsNullExpression(e2)));
}
public static Expression EqualNullable(Expression e1, Expression e2)
{
if (e1 == NewId || e2 == NewId)
return False;
if (e1.Type.IsNullable() == e2.Type.IsNullable())
return Expression.Equal(e1, e2);
return Expression.Equal(e1.Nullify(), e2.Nullify());
}
public static Expression NotEqualNullable(Expression e1, Expression e2)
{
if (e1.Type.IsNullable() == e2.Type.IsNullable())
return Expression.NotEqual(e1, e2);
return Expression.NotEqual(e1.Nullify(), e2.Nullify());
}
public static Expression PolymorphicEqual(Expression exp1, Expression exp2)
{
if (exp1.NodeType == ExpressionType.New || exp2.NodeType == ExpressionType.New)
{
if (exp1.IsNull() || exp2.IsNull())
return Expression.Constant(false);
exp1 = ConstanToNewExpression(exp1) ?? exp1;
exp2 = ConstanToNewExpression(exp2) ?? exp2;
return ((NewExpression)exp1).Arguments.ZipStrict(
((NewExpression)exp2).Arguments, (o, i) => SmartEqualizer.PolymorphicEqual(o, i)).AggregateAnd();
}
Expression? result;
result = PrimaryKeyEquals(exp1, exp2);
if (result != null)
return result;
result = ObjectEquals(exp1, exp2);
if (result != null)
return result;
result = ConditionalEquals(exp1, exp2);
if (result != null)
return result;
result = CoalesceEquals(exp1, exp2);
if (result != null)
return result;
result = LiteEquals(exp1, exp2);
if (result != null)
return result;
result = EntityEquals(exp1, exp2);
if (result != null)
return result;
result = TypeEquals(exp1, exp2);
if (result != null)
return result;
result = MListElementEquals(exp1, exp2);
if (result != null)
return result;
result = EnumEquals(exp1, exp2);
if (result != null)
return result;
return EqualNullable(exp1, exp2);
}
private static Expression? EnumEquals(Expression exp1, Expression exp2)
{
bool anyEnum = false;
var exp1Clean = RemoveConvertChain(exp1, ref anyEnum);
var exp2Clean = RemoveConvertChain(exp2, ref anyEnum);
if (exp1Clean.Type.UnNullify() == typeof(DayOfWeek) ||
exp2Clean.Type.UnNullify() == typeof(DayOfWeek))
{
return SmartEqualizer.EqualNullable(
ConstantToDayOfWeek(exp1Clean) ?? exp1Clean,
ConstantToDayOfWeek(exp2Clean) ?? exp2Clean);
}
if (anyEnum)
{
var type = exp2.Type.IsNullable() ? exp1.Type.Nullify(): exp1.Type;
return SmartEqualizer.EqualNullable(exp1Clean.TryConvert(type), exp2Clean.TryConvert(type));
}
return null;
}
private static Expression? ConstantToDayOfWeek(Expression exp)
{
if (exp is ConstantExpression c)
{
if (c.Value == null)
return Expression.Constant(null, typeof(DayOfWeek?));
return Expression.Constant((DayOfWeek)(int)c.Value, exp.Type.IsNullable() ? typeof(DayOfWeek?) : typeof(DayOfWeek));
}
return null;
}
private static Expression RemoveConvertChain(Expression exp, ref bool anyEnum)
{
while (true)
{
var newExp = exp.TryRemoveConvert(t => t.UnNullify().IsEnum);
if (newExp != null)
anyEnum = true;
else
newExp = exp.TryRemoveConvert(t => ReflectionTools.IsIntegerNumber(t.UnNullify()));
if (newExp == null)
return exp;
exp = newExp;
}
}
private static Expression? ConstanToNewExpression(Expression exp)
{
if (exp is not ConstantExpression ce)
return null;
var type = ce.Value!.GetType();
if (!type.IsAnonymous())
return null;
var values = type.GetProperties().ToDictionary(a => a.Name, a => a.GetValue(ce.Value));
var ci = type.GetConstructors().SingleEx();
return Expression.New(ci, ci.GetParameters().Select(p => Expression.Constant(values.GetOrThrow(p.Name!), p.ParameterType)));
}
public static Expression? PrimaryKeyEquals(Expression exp1, Expression exp2)
{
if (exp1.Type.UnNullify() == typeof(PrimaryKey) || exp2.Type.UnNullify() == typeof(PrimaryKey))
{
var left = UnwrapPrimaryKey(exp1);
var right = UnwrapPrimaryKey(exp2);
return EqualNullable(left.Nullify(), right.Nullify());
}
return null;
}
public static Expression? ObjectEquals(Expression expr1, Expression expr2)
{
if (expr1.Type == typeof(object) && expr2.Type == typeof(object))
{
var left = UncastObject(expr1);
var right = UncastObject(expr2);
if (left == null && right == null)
return null;
left ??= ChangeConstant(expr1, right!.Type);
right ??= ChangeConstant(expr2, left!.Type);
if (left == null || right == null)
return null;
return PolymorphicEqual(left, right);
}
return null;
}
private static Expression? ChangeConstant(Expression exp, Type type)
{
if (exp is ConstantExpression ce)
{
var val = ce.Value;
if (val == null)
{
if (type.IsNullable() || !type.IsValueType)
return Expression.Constant(val, type);
else
return null;
}
if (type.IsAssignableFrom(val.GetType()))
return Expression.Constant(val, type);
return null;
}
return null;
}
private static Expression? UncastObject(Expression expr)
{
if (expr.NodeType == ExpressionType.Convert)
return ((UnaryExpression)expr).Operand;
return null;
}
public static BinaryExpression UnwrapPrimaryKeyBinary(BinaryExpression b)
{
if (b.Left.Type.UnNullify() == typeof(PrimaryKey) || b.Right.Type.UnNullify() == typeof(PrimaryKey))
{
var left = UnwrapPrimaryKey(b.Left);
var right = UnwrapPrimaryKey(b.Right);
if (left.Type.UnNullify() == typeof(Guid))
{
return Expression.MakeBinary(b.NodeType, left.Nullify(), right.Nullify(), true, GuidComparer.GetMethod(b.NodeType));
}
else
{
return Expression.MakeBinary(b.NodeType, left.Nullify(), right.Nullify());
}
}
return b;
}
static class GuidComparer
{
static bool GreaterThan(Guid a, Guid b)
{
return a.CompareTo(b) > 0;
}
static bool GreaterThanOrEqual(Guid a, Guid b)
{
return a.CompareTo(b) >= 0;
}
static bool LessThan(Guid a, Guid b)
{
return a.CompareTo(b) < 0;
}
static bool LessThanOrEqual(Guid a, Guid b)
{
return a.CompareTo(b) <= 0;
}
public static MethodInfo? GetMethod(ExpressionType type)
{
return type switch
{
ExpressionType.GreaterThan => ReflectionTools.GetMethodInfo(() => GreaterThan(Guid.Empty, Guid.Empty)),
ExpressionType.GreaterThanOrEqual => ReflectionTools.GetMethodInfo(() => GreaterThanOrEqual(Guid.Empty, Guid.Empty)),
ExpressionType.LessThan => ReflectionTools.GetMethodInfo(() => LessThan(Guid.Empty, Guid.Empty)),
ExpressionType.LessThanOrEqual => ReflectionTools.GetMethodInfo(() => LessThanOrEqual(Guid.Empty, Guid.Empty)),
ExpressionType.Equal => null,
ExpressionType.NotEqual => null,
_ => throw new InvalidOperationException("GuidComparer.GetMethod unexpected ExpressionType " + type),
};
}
}
public static Expression UnwrapPrimaryKey(Expression unary)
{
if (unary.NodeType == ExpressionType.Convert && unary.Type.UnNullify() == typeof(PrimaryKey))
return UnwrapPrimaryKey(((UnaryExpression)unary).Operand);
if (unary is PrimaryKeyExpression pk)
return pk.Value;
if (unary is ConstantExpression ce)
{
var obj = ce.Value;
if (obj == null)
return Expression.Constant(null, unary.Type);
return Expression.Constant(((PrimaryKey)obj).Object);
}
return unary;
}
private static Expression? ConditionalEquals(Expression exp1, Expression exp2)
{
if (Schema.Current.Settings.IsDbType(exp1.Type.UnNullify())||
Schema.Current.Settings.IsDbType(exp2.Type.UnNullify()))
return null;
if (exp1 is ConditionalExpression ce1)
return DispachConditional(ce1, exp2);
if (exp2 is ConditionalExpression ce2)
return DispachConditional(ce2, exp1);
return null;
}
private static Expression DispachConditional(ConditionalExpression ce, Expression exp)
{
var ifTrue = PolymorphicEqual(ce.IfTrue, exp);
var ifFalse = PolymorphicEqual(ce.IfFalse, exp);
return SmartOr(SmartAnd(ce.Test, ifTrue), SmartAnd(SmartNot(ce.Test), ifFalse));
}
private static Expression? CoalesceEquals(Expression exp1, Expression exp2)
{
if (Schema.Current.Settings.IsDbType(exp1.Type.UnNullify()) ||
Schema.Current.Settings.IsDbType(exp2.Type.UnNullify()))
return null;
if (exp1.NodeType == ExpressionType.Coalesce)
return DispachCoalesce((BinaryExpression)exp1, exp2);
if (exp2.NodeType == ExpressionType.Coalesce)
return DispachCoalesce((BinaryExpression)exp2, exp1);
return null;
}
private static Expression DispachCoalesce(BinaryExpression be, Expression exp)
{
var leftNull = PolymorphicEqual(be.Left, Expression.Constant(null, be.Type));
var left = PolymorphicEqual(be.Left, exp);
var right = PolymorphicEqual(be.Right, exp);
return SmartOr(SmartAnd(SmartNot(leftNull), left), SmartAnd(leftNull, right));
}
private static Expression SmartAnd(Expression e1, Expression e2)
{
if (e1 == True)
return e2;
if (e2 == True)
return e1;
if (e1 == False || e2 == False)
return False;
return Expression.And(e1, e2);
}
private static Expression SmartNot(Expression e)
{
if (e == True)
return False;
if (e == False)
return True;
return Expression.Not(e);
}
private static Expression SmartOr(Expression e1, Expression e2)
{
if (e1 == False)
return e2;
if (e2 == False)
return e1;
if (e1 == True || e2 == True)
return True;
return Expression.Or(e1, e2);
}
private static Expression? TypeEquals(Expression exp1, Expression exp2)
{
if (exp1.Type != typeof(Type) || exp2.Type != typeof(Type))
return null;
if (exp1 is ConstantExpression c1)
{
if (exp2 is ConstantExpression c2) return TypeConstantConstantEquals(c1, c2);
else if (exp2 is TypeEntityExpression te2) return TypeConstantEntityEquals(c1, te2);
else if (exp2 is TypeImplementedByExpression tib2) return TypeConstantIbEquals(c1, tib2);
else if (exp2 is TypeImplementedByAllExpression tiba2) return TypeConstantIbaEquals(c1, tiba2);
}
else if (exp1 is TypeEntityExpression te1)
{
if (exp2 is ConstantExpression c2) return TypeConstantEntityEquals(c2, te1);
else if (exp2 is TypeEntityExpression te2) return TypeEntityEntityEquals(te1, te2);
else if (exp2 is TypeImplementedByExpression tib2) return TypeEntityIbEquals(te1, tib2);
else if (exp2 is TypeImplementedByAllExpression tiba2) return TypeEntityIbaEquals(te1, tiba2);
}
else if (exp1 is TypeImplementedByExpression tib1)
{
if (exp2 is ConstantExpression c2) return TypeConstantIbEquals(c2, tib1);
else if (exp2 is TypeEntityExpression te2) return TypeEntityIbEquals(te2, tib1);
else if (exp2 is TypeImplementedByExpression tib2) return TypeIbIbEquals(tib1, tib2);
else if (exp2 is TypeImplementedByAllExpression tiba2) return TypeIbIbaEquals(tib1, tiba2);
}
else if (exp1 is TypeImplementedByAllExpression tiba1)
{
if (exp2 is ConstantExpression c2) return TypeConstantIbaEquals(c2, tiba1);
else if (exp2 is TypeEntityExpression te2) return TypeEntityIbaEquals(te2, tiba1);
else if (exp2 is TypeImplementedByExpression tib2) return TypeIbIbaEquals(tib2, tiba1);
else if (exp2 is TypeImplementedByAllExpression tiba2) return TypeIbaIbaEquals(tiba1, tiba2);
}
throw new InvalidOperationException("Impossible to resolve '{0}' equals '{1}'".FormatWith(exp1.ToString(), exp2.ToString()));
}
private static Expression TypeConstantEntityEquals(ConstantExpression ce, TypeEntityExpression typeEntity)
{
if (ce.IsNull())
return EqualsToNull(typeEntity.ExternalId);
if (((Type)ce.Value! == typeEntity.TypeValue))
return NotEqualToNull(typeEntity.ExternalId);
return False;
}
private static Expression? TypeConstantIbEquals(ConstantExpression ce, TypeImplementedByExpression typeIb)
{
if (ce.IsNull())
{
return typeIb.TypeImplementations.Select(imp => EqualsToNull(imp.Value)).AggregateAnd();
}
Type type = (Type)ce.Value!;
var externalId = typeIb.TypeImplementations.TryGetC(type);
return externalId == null ? False : NotEqualToNull(externalId);
}
private static Expression TypeConstantIbaEquals(ConstantExpression ce, TypeImplementedByAllExpression typeIba)
{
if (ce.IsNull())
return EqualsToNull(typeIba.TypeColumn);
return EqualNullable(QueryBinder.TypeConstant((Type)ce.Value!), typeIba.TypeColumn.Value);
}
private static Expression TypeConstantConstantEquals(ConstantExpression c1, ConstantExpression c2)
{
if (c1.IsNull())
{
if (c2.IsNull()) return True;
else return False;
}
else
{
if (c2.IsNull()) return False;
if (c1.Value!.Equals(c2.Value)) return True;
else return False;
}
}
private static Expression TypeEntityEntityEquals(TypeEntityExpression typeEntity1, TypeEntityExpression typeEntity2)
{
if (typeEntity1.TypeValue != typeEntity2.TypeValue)
return False;
return Expression.And(NotEqualToNull(typeEntity1.ExternalId), NotEqualToNull(typeEntity2.ExternalId));
}
private static Expression TypeEntityIbEquals(TypeEntityExpression typeEntity, TypeImplementedByExpression typeIb)
{
var externalId = typeIb.TypeImplementations.TryGetC(typeEntity.TypeValue);
if (externalId == null)
return False;
return Expression.And(NotEqualToNull(typeEntity.ExternalId), NotEqualToNull(externalId));
}
private static Expression TypeEntityIbaEquals(TypeEntityExpression typeEntity, TypeImplementedByAllExpression typeIba)
{
return Expression.And(NotEqualToNull(typeEntity.ExternalId), EqualNullable(typeIba.TypeColumn, QueryBinder.TypeConstant(typeEntity.TypeValue)));
}
private static Expression TypeIbaIbaEquals(TypeImplementedByAllExpression t1, TypeImplementedByAllExpression t2)
{
return Expression.Equal(t1.TypeColumn, t2.TypeColumn);
}
private static Expression TypeIbIbEquals(TypeImplementedByExpression typeIb1, TypeImplementedByExpression typeIb2)
{
var joins = (from imp1 in typeIb1.TypeImplementations
join imp2 in typeIb2.TypeImplementations on imp1.Key equals imp2.Key
select Expression.And(NotEqualToNull(imp1.Value), NotEqualToNull(imp2.Value))).ToList();
return joins.AggregateOr();
}
private static Expression TypeIbIbaEquals(TypeImplementedByExpression typeIb, TypeImplementedByAllExpression typeIba)
{
return typeIb.TypeImplementations
.Select(imp => Expression.And(NotEqualToNull(imp.Value), EqualNullable(typeIba.TypeColumn, QueryBinder.TypeConstant(imp.Key))))
.AggregateOr();
}
internal static Expression TypeIn(Expression typeExpr, IEnumerable<Type> collection)
{
if (collection.IsNullOrEmpty())
return False;
if (typeExpr.NodeType == ExpressionType.Conditional)
return DispachConditionalTypesIn((ConditionalExpression)typeExpr, collection);
if (typeExpr.NodeType == ExpressionType.Constant)
{
Type type = (Type)((ConstantExpression)typeExpr).Value!;
return collection.Contains(type) ? True : False;
}
if (typeExpr is TypeEntityExpression typeEntity)
{
return collection.Contains(typeEntity.TypeValue) ? NotEqualToNull(typeEntity.ExternalId) : (Expression)False;
}
if (typeExpr is TypeImplementedByExpression typeIb)
{
return typeIb.TypeImplementations.Where(imp => collection.Contains(imp.Key))
.Select(imp => NotEqualToNull(imp.Value)).AggregateOr();
}
if (typeExpr is TypeImplementedByAllExpression typeIba)
{
PrimaryKey[] ids = collection.Select(t => QueryBinder.TypeId(t)).ToArray();
return InPrimaryKey(typeIba.TypeColumn, ids);
}
throw new InvalidOperationException("Impossible to resolve '{0}' in '{1}'".FormatWith(typeExpr.ToString(), collection.ToString(t=>t.TypeName(), ", ")));
}
public static Expression In(Expression element, object[] values, bool isPostgres)
{
var nominate = DbExpressionNominator.FullNominate(element)!;
if (nominate.RemoveUnNullify() is ToDayOfWeekExpression dowe)
{
if (isPostgres)
{
var sqlWeekDays = values.Cast<DayOfWeek>()
.Select(a => (object)(int)a)
.ToArray();
return InExpression.FromValues(dowe.Expression, sqlWeekDays);
}
else
{
byte dateFirs = ((SqlServerConnector)Connector.Current).DateFirst;
var sqlWeekDays = values.Cast<DayOfWeek>()
.Select(a => (object)ToDayOfWeekExpression.ToSqlWeekDay(a, dateFirs))
.ToArray();
return InExpression.FromValues(dowe.Expression, sqlWeekDays);
}
}
else
return InExpression.FromValues(nominate, values);
}
public static Expression InPrimaryKey(Expression element, PrimaryKey[] values)
{
var cleanValues = values.Select(a => a.Object).ToArray();
var cleanElement = SmartEqualizer.UnwrapPrimaryKey(element);
if (cleanElement == NewId)
return False;
cleanElement = DbExpressionNominator.FullNominate(cleanElement)!;
if (cleanElement.Type == typeof(string))
return InExpression.FromValues(cleanElement, cleanValues.Select(a => (object)a.ToString()!).ToArray());
else
return InExpression.FromValues(cleanElement, cleanValues);
}
private static Expression DispachConditionalTypesIn(ConditionalExpression ce, IEnumerable<Type> collection)
{
var ifTrue = TypeIn(ce.IfTrue, collection);
var ifFalse = TypeIn(ce.IfFalse, collection);
return SmartOr(SmartAnd(ce.Test, ifTrue), SmartAnd(SmartNot(ce.Test), ifFalse));
}
internal static Expression EntityIn(Expression newItem, IEnumerable<Entity> collection)
{
if (collection.IsEmpty())
return False;
Dictionary<Type, PrimaryKey[]> entityIDs = collection.Where(a => a.IdOrNull.HasValue).AgGroupToDictionary(a => a.GetType(), gr => gr.Select(a => a.Id).ToArray());
return EntityIn(newItem, entityIDs);
}
internal static Expression EntityIn(LiteReferenceExpression liteReference, IEnumerable<Lite<IEntity>> collection)
{
if (collection.IsEmpty())
return False;
Dictionary<Type, PrimaryKey[]> entityIDs = collection.Where(a => a.IdOrNull.HasValue).AgGroupToDictionary(a => a.EntityType, gr => gr.Select(a => a.Id).ToArray());
return EntityIn(liteReference.Reference, entityIDs);
}
static Expression EntityIn(Expression newItem, Dictionary<Type, PrimaryKey[]> entityIDs)
{
if (newItem is EntityExpression ee)
return InPrimaryKey(ee.ExternalId, entityIDs.TryGetC(ee.Type) ?? Array.Empty<PrimaryKey>());
if (newItem is ImplementedByExpression ib)
return ib.Implementations.JoinDictionary(entityIDs,
(t, f, values) => Expression.And(DbExpressionNominator.FullNominate(NotEqualToNull(f.ExternalId)), InPrimaryKey(f.ExternalId, values)))
.Values.AggregateOr();
if (newItem is ImplementedByAllExpression iba)
return entityIDs.Select(kvp => Expression.And(
EqualNullable(new PrimaryKeyExpression(QueryBinder.TypeConstant(kvp.Key).Nullify()), iba.TypeId.TypeColumn),
InPrimaryKey(iba.Id, kvp.Value))).AggregateOr();
throw new InvalidOperationException("EntityIn not defined for newItem of type {0}".FormatWith(newItem.Type.Name));
}
public static Expression? LiteEquals(Expression e1, Expression e2)
{
if ( e1.Type.IsLite() || e2.Type.IsLite())
{
if (!e1.Type.IsLite() && !e1.IsNull() || !e2.Type.IsLite() && !e2.IsNull())
throw new InvalidOperationException("Imposible to compare expressions of type {0} == {1}".FormatWith(e1.Type.TypeName(), e2.Type.TypeName()));
return PolymorphicEqual(GetEntity(e1), GetEntity(e2)); //Conditional and Coalesce could be inside
}
return null;
}
public static Expression? MListElementEquals(Expression e1, Expression e2)
{
if (e1 is MListElementExpression || e2 is MListElementExpression)
{
if (e1.IsNull())
return EqualsToNull(((MListElementExpression)e2).RowId);
if (e2.IsNull())
return EqualsToNull(((MListElementExpression)e1).RowId);
return EqualNullable(((MListElementExpression)e1).RowId, ((MListElementExpression)e2).RowId);
}
return null;
}
private static Expression GetEntity(Expression liteExp)
{
liteExp = ConstantToLite(liteExp) ?? liteExp;
if (liteExp.IsNull())
return Expression.Constant(null, liteExp.Type.CleanType());
if (liteExp is UnaryExpression ue && (ue.NodeType == ExpressionType.Convert || ue.NodeType == ExpressionType.ConvertChecked))
liteExp = ue.Operand;
if (liteExp is not LiteReferenceExpression liteReference)
throw new InvalidCastException("Impossible to convert expression to Lite: {0}".FormatWith(liteExp.ToString()));
return liteReference.Reference;
}
public static Expression? EntityEquals(Expression e1, Expression e2)
{
e1 = ConstantToEntity(e1) ?? e1;
e2 = ConstantToEntity(e2) ?? e2;
if (e1 is EmbeddedEntityExpression eee1 && e2.IsNull())
return EmbeddedNullEquals(eee1);
if (e2 is EmbeddedEntityExpression eee2 && e1.IsNull())
return EmbeddedNullEquals(eee2);
if (e1 is EntityExpression ee1)
{
if (e2 is EntityExpression ee2) return EntityEntityEquals(ee1, ee2);
else if (e2 is ImplementedByExpression ib2) return EntityIbEquals(ee1, ib2);
else if (e2 is ImplementedByAllExpression iba2) return EntityIbaEquals(ee1, iba2);
else if (e2.IsNull()) return EqualsToNull((ee1).ExternalId);
else return null;
}
else if (e1 is ImplementedByExpression ib1)
{
if (e2 is EntityExpression ee2) return EntityIbEquals(ee2, ib1);
else if (e2 is ImplementedByExpression ib2) return IbIbEquals(ib1, ib2);
else if (e2 is ImplementedByAllExpression iba2) return IbIbaEquals(ib1, iba2);
else if (e2.IsNull()) return (ib1).Implementations.Select(a => EqualsToNull(a.Value.ExternalId)).AggregateAnd();
else return null;
}
else if (e1 is ImplementedByAllExpression iba1)
{
if (e2 is EntityExpression ee2) return EntityIbaEquals(ee2, iba1);
else if (e2 is ImplementedByExpression ib2) return IbIbaEquals(ib2, iba1);
else if (e2 is ImplementedByAllExpression iba2) return IbaIbaEquals(iba1, iba2);
else if (e2.IsNull()) return EqualsToNull((iba1).TypeId.TypeColumn);
else return null;
}
else if (e1.IsNull())
{
if (e2 is EntityExpression ee2) return EqualsToNull((ee2).ExternalId);
else if (e2 is ImplementedByExpression ib2) return ib2.Implementations.Select(a => EqualsToNull(a.Value.ExternalId)).AggregateAnd();
else if (e2 is ImplementedByAllExpression iba2) return EqualsToNull(iba2.TypeId.TypeColumn);
else if (e2.IsNull()) return True;
else return null;
}
else return null;
}
static Expression EmbeddedNullEquals(EmbeddedEntityExpression eee)
{
return Expression.Not(eee.HasValue);
}
static Expression EntityEntityEquals(EntityExpression e1, EntityExpression e2)
{
if (e1.Type == e2.Type)
return PolymorphicEqual(e1.ExternalId, e2.ExternalId).And(e1.ExternalPeriod.Overlaps(e2.ExternalPeriod));
else
return False;
}
static Expression EntityIbEquals(EntityExpression ee, ImplementedByExpression ib)
{
var imp = ib.Implementations.TryGetC(ee.Type);
if (imp == null)
return False;
return EntityEntityEquals(imp, ee);
}
static Expression EntityIbaEquals(EntityExpression ee, ImplementedByAllExpression iba)
{
return Expression.And(
ee.ExternalId.Value == NewId ? False : EqualNullable(new SqlCastExpression(typeof(string), ee.ExternalId.Value), iba.Id),
EqualNullable(QueryBinder.TypeConstant(ee.Type), iba.TypeId.TypeColumn.Value))
.And(ee.ExternalPeriod.Overlaps(iba.ExternalPeriod));
}
static Expression IbIbEquals(ImplementedByExpression ib, ImplementedByExpression ib2)
{
var list = ib.Implementations.JoinDictionary(ib2.Implementations, (t, i, j) => EntityEntityEquals(i, j)).Values.ToList();
return list.AggregateOr();
}
static Expression IbIbaEquals(ImplementedByExpression ib, ImplementedByAllExpression iba)
{
var list = ib.Implementations.Values.Select(i =>
Expression.And(
i.ExternalId.Value == NewId ? (Expression)False : EqualNullable(iba.Id, new SqlCastExpression(typeof(string), i.ExternalId.Value)),
EqualNullable(iba.TypeId.TypeColumn.Value, QueryBinder.TypeConstant(i.Type)))).ToList();
return list.AggregateOr();
}
static Expression IbaIbaEquals(ImplementedByAllExpression iba, ImplementedByAllExpression iba2)
{
return Expression.And(EqualNullable(iba.Id, iba2.Id), EqualNullable(iba.TypeId.TypeColumn.Value, iba2.TypeId.TypeColumn.Value));
}
static Expression EqualsToNull(PrimaryKeyExpression exp)
{
return EqualNullable(exp.Value, new SqlConstantExpression(null, exp.ValueType));
}
static Expression NotEqualToNull(PrimaryKeyExpression exp)
{
return NotEqualNullable(exp.Value, new SqlConstantExpression(null, exp.ValueType));
}
public static Expression? ConstantToEntity(Expression expression)
{
if (expression is not ConstantExpression c)
return null;
if (c.Value == null)
return c;
if (c.Type.IsIEntity())
{
var ei = (Entity)c.Value;
var id = GetPrimaryKeyValue(ei.IdOrNull, ei.GetType());
return new EntityExpression(ei.GetType(),
new PrimaryKeyExpression(id), null, null, null, null, null, avoidExpandOnRetrieving: true);
}
return null;
}
public static Expression? ConstantToLite(Expression expression)
{
if (expression is not ConstantExpression c)
return null;
if (c.Value == null)
return c;
if (c.Type.IsLite())
{
Lite<IEntity> lite = (Lite<IEntity>)c.Value;
var id = GetPrimaryKeyValue(lite.IdOrNull, lite.EntityType);
EntityExpression ere = new EntityExpression(lite.EntityType, new PrimaryKeyExpression(id), null, null, null, null, null, false);
return new LiteReferenceExpression(Lite.Generate(lite.EntityType), ere, null, false, false);
}
return null;
}
private static Expression GetPrimaryKeyValue(PrimaryKey? idOrNull, Type type)
{
if (idOrNull == null)
return SmartEqualizer.NewId;
var pkType = PrimaryKey.Type(type).Nullify();
if (idOrNull.Value.VariableName != null && PrimaryKeyExpression.PreferVariableNameVariable.Value)
return new SqlVariableExpression(idOrNull.Value.VariableName, pkType);
return Expression.Constant(idOrNull.Value.Object, pkType);
}
}
| |
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen
//Copyright 2006-2011 Jeroen van Menen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion Copyright
using System;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using WatiN.Core.UnitTests.TestUtils;
namespace WatiN.Core.UnitTests
{
[TestFixture]
public class ControlTests : BaseWithBrowserTests
{
[Test]
public void ExistsShouldReturnTrue()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var control = browser.Control<TextFieldControl>("name");
// WHEN
var exists = control.Exists;
// THEN
Assert.That(exists, Is.True);
});
}
[Test]
public void ExistsShouldReturnFalse()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var control = browser.Control<TextFieldControl>("noneExistingTextFieldId");
// WHEN
var exists = control.Exists;
// THEN
Assert.That(exists, Is.False);
});
}
[Test]
public void ExistsShouldReturnImmediatelyIfNoMatchingElementCanBeFound()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
Assert.That(Settings.WaitUntilExistsTimeOut, Is.GreaterThan(1), "pre-condition failed");
var control = browser.Control<TextFieldControl>("noneExistingTextFieldId");
// WHEN
var start = DateTime.Now;
var exists = control.Exists;
var end = DateTime.Now;
// THEN
Assert.That(end.Subtract(start).TotalSeconds, Is.LessThanOrEqualTo(1d),
"Should not wait for element to show up");
Assert.That(exists, Is.False, "control shouldn't exist");
});
}
[Test]
public void ShouldFindControlWhenUsingAPredicate()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var control = browser.Control<TextFieldControl>(tfc => Equals(tfc.Id, "name"));
// WHEN
var exists = control.Exists;
// THEN
Assert.That(exists, Is.True);
});
}
[Test]
public void ShouldInitializeElementField()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var control = browser.Control<FormControl>("Form");
// WHEN
var member = control.NameTextField;
// THEN
Assert.That(member, Is.Not.Null);
Assert.That(member.Description, Is.Null);
Assert.That(member.Name, Is.EqualTo("textinput1"));
});
}
[Test]
public void ShouldInitializeElementPropertyWithDescription()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var control = browser.Control<FormControl>("Form");
// WHEN
var member = control.PopUpButton;
// THEN
Assert.That(member, Is.Not.Null);
Assert.That(member.Description, Is.EqualTo("Popup button."));
Assert.That(member.Id, Is.EqualTo("popupid"));
});
}
[Test]
public void ShouldInitializeControlFieldWithDescription()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var control = browser.Control<FormControl>("Form");
// WHEN
var member = control.NameTextFieldControl;
// THEN
Assert.That(member, Is.Not.Null);
Assert.That(member.Description, Is.EqualTo("Text field control."));
Assert.That(member.Id, Is.EqualTo("name"));
});
}
[Test]
public void ToStringWhenDescriptionIsNotSetShouldDescribeControl()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var control = browser.Control<FormControl>("Form");
// WHEN
var description = control.Description;
var toString = control.ToString();
// THEN
Assert.That(description, Is.Null);
Assert.That(toString, Is.EqualTo("FormControl (Form)"));
});
}
[Test]
public void ToStringWhenDescriptionIsSetShouldReturnDescription()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
#if !NET20
var control = browser.Control<FormControl>("Form").WithDescription("foo");
#else
var control = browser.Control<FormControl>("Form");
control.Description = "foo";
#endif
// WHEN
var description = control.Description;
var toString = control.ToString();
// THEN
Assert.That(description, Is.EqualTo("foo"));
Assert.That(toString, Is.EqualTo("foo"));
});
}
public override Uri TestPageUri
{
get { return MainURI; }
}
public class TextFieldControl : Control<TextField>
{
public string Text
{
get { return Element.Value; }
}
public string Id
{
get { return Element.Id; }
}
}
public class FormControl : Control<Form>
{
[FindBy(Name = "textinput1")]
public TextField NameTextField;
[FindBy(Id = "popupid")]
[Description("Popup button.")]
public Button PopUpButton { get; set; }
[FindBy(Name = "textinput1")]
[Description("Text field control.")]
internal TextFieldControl NameTextFieldControl = null; // intentionally non-public
}
[Test]
public void Should_refind_nested_element_after_page_and_control_refresh()
{
ExecuteTest(browser =>
{
// GIVEN
var containerControl = browser.Control<ContainerControl>("Form");
var childElement = containerControl.Button;
Assert.That(childElement.Exists, "Pre-Condition");
childElement.DoSomethingPostbackish();
// WHEN
childElement.Refresh();
// THEN it should re-find it again
Assert.That(childElement.WrappedElement.Id, Is.EqualTo("popupid"));
});
}
public class ContainerControl : Control<Form>
{
public ChildControl Button
{
get { return Element.Control<ChildControl>("popupid"); }
}
}
public class ChildControl: Control<Button>
{
public Button WrappedElement
{
get { return Element; }
}
public void DoSomethingPostbackish()
{
((Browser)Element.DomContainer).Refresh();
}
}
}
}
| |
// 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 CultureInfo = System.Globalization.CultureInfo;
using System.Security;
using System.IO;
using StringBuilder = System.Text.StringBuilder;
using System.Configuration.Assemblies;
using StackCrawlMark = System.Threading.StackCrawlMark;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading;
namespace System.Reflection
{
internal class RuntimeAssembly : Assembly
{
internal RuntimeAssembly() { throw new NotSupportedException(); }
#region private data members
private event ModuleResolveEventHandler _ModuleResolve;
private string m_fullname;
private object m_syncRoot; // Used to keep collectible types alive and as the syncroot for reflection.emit
private IntPtr m_assembly; // slack for ptr datum on unmanaged side
#endregion
internal object SyncRoot
{
get
{
if (m_syncRoot == null)
{
Interlocked.CompareExchange<object>(ref m_syncRoot, new object(), null);
}
return m_syncRoot;
}
}
public override event ModuleResolveEventHandler ModuleResolve
{
add
{
_ModuleResolve += value;
}
remove
{
_ModuleResolve -= value;
}
}
private const String s_localFilePrefix = "file:";
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetCodeBase(RuntimeAssembly assembly,
bool copiedName,
StringHandleOnStack retString);
internal String GetCodeBase(bool copiedName)
{
String codeBase = null;
GetCodeBase(GetNativeHandle(), copiedName, JitHelpers.GetStringHandleOnStack(ref codeBase));
return codeBase;
}
public override String CodeBase
{
get
{
String codeBase = GetCodeBase(false);
return codeBase;
}
}
internal RuntimeAssembly GetNativeHandle()
{
return this;
}
// If the assembly is copied before it is loaded, the codebase will be set to the
// actual file loaded if copiedName is true. If it is false, then the original code base
// is returned.
public override AssemblyName GetName(bool copiedName)
{
AssemblyName an = new AssemblyName();
String codeBase = GetCodeBase(copiedName);
an.Init(GetSimpleName(),
GetPublicKey(),
null, // public key token
GetVersion(),
GetLocale(),
GetHashAlgorithm(),
AssemblyVersionCompatibility.SameMachine,
codeBase,
GetFlags() | AssemblyNameFlags.PublicKey,
null); // strong name key pair
PortableExecutableKinds pek;
ImageFileMachine ifm;
Module manifestModule = ManifestModule;
if (manifestModule != null)
{
if (manifestModule.MDStreamVersion > 0x10000)
{
ManifestModule.GetPEKind(out pek, out ifm);
an.SetProcArchIndex(pek, ifm);
}
}
return an;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetFullName(RuntimeAssembly assembly, StringHandleOnStack retString);
public override String FullName
{
get
{
// If called by Object.ToString(), return val may be NULL.
if (m_fullname == null)
{
string s = null;
GetFullName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s));
Interlocked.CompareExchange<string>(ref m_fullname, s, null);
}
return m_fullname;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetEntryPoint(RuntimeAssembly assembly, ObjectHandleOnStack retMethod);
public override MethodInfo EntryPoint
{
get
{
IRuntimeMethodInfo methodHandle = null;
GetEntryPoint(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref methodHandle));
if (methodHandle == null)
return null;
return (MethodInfo)RuntimeType.GetMethodBase(methodHandle);
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetType(RuntimeAssembly assembly,
String name,
bool throwOnError,
bool ignoreCase,
ObjectHandleOnStack type,
ObjectHandleOnStack keepAlive);
public override Type GetType(String name, bool throwOnError, bool ignoreCase)
{
// throw on null strings regardless of the value of "throwOnError"
if (name == null)
throw new ArgumentNullException(nameof(name));
RuntimeType type = null;
Object keepAlive = null;
GetType(GetNativeHandle(), name, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
GC.KeepAlive(keepAlive);
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes);
public override Type[] GetExportedTypes()
{
Type[] types = null;
GetExportedTypes(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types));
return types;
}
public override IEnumerable<TypeInfo> DefinedTypes
{
get
{
List<RuntimeType> rtTypes = new List<RuntimeType>();
RuntimeModule[] modules = GetModulesInternal(true, false);
for (int i = 0; i < modules.Length; i++)
{
rtTypes.AddRange(modules[i].GetDefinedTypes());
}
return rtTypes.ToArray();
}
}
// Load a resource based on the NameSpace of the type.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Stream GetManifestResourceStream(Type type, String name)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return GetManifestResourceStream(type, name, false, ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Stream GetManifestResourceStream(String name)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return GetManifestResourceStream(name, ref stackMark, false);
}
// ISerializable implementation
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public override Module ManifestModule
{
get
{
// We don't need to return the "external" ModuleBuilder because
// it is meant to be read-only
return RuntimeAssembly.GetManifestModule(GetNativeHandle());
}
}
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
// Wrapper function to wrap the typical use of InternalLoad.
internal static RuntimeAssembly InternalLoad(String assemblyString,
ref StackCrawlMark stackMark)
{
return InternalLoad(assemblyString, ref stackMark, IntPtr.Zero);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
internal static RuntimeAssembly InternalLoad(String assemblyString,
ref StackCrawlMark stackMark,
IntPtr pPrivHostBinder)
{
RuntimeAssembly assembly;
AssemblyName an = CreateAssemblyName(assemblyString, out assembly);
if (assembly != null)
{
// The assembly was returned from ResolveAssemblyEvent
return assembly;
}
return InternalLoadAssemblyName(an, null, ref stackMark,
pPrivHostBinder,
true /*thrownOnFileNotFound*/);
}
// Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised.
internal static AssemblyName CreateAssemblyName(
String assemblyString,
out RuntimeAssembly assemblyFromResolveEvent)
{
if (assemblyString == null)
throw new ArgumentNullException(nameof(assemblyString));
if ((assemblyString.Length == 0) ||
(assemblyString[0] == '\0'))
throw new ArgumentException(SR.Format_StringZeroLength);
AssemblyName an = new AssemblyName();
an.Name = assemblyString;
an.nInit(out assemblyFromResolveEvent, true);
return an;
}
// Wrapper function to wrap the typical use of InternalLoadAssemblyName.
internal static RuntimeAssembly InternalLoadAssemblyName(
AssemblyName assemblyRef,
RuntimeAssembly reqAssembly,
ref StackCrawlMark stackMark,
bool throwOnFileNotFound,
IntPtr ptrLoadContextBinder = default(IntPtr))
{
return InternalLoadAssemblyName(assemblyRef, reqAssembly, ref stackMark, IntPtr.Zero, true /*throwOnError*/, ptrLoadContextBinder);
}
internal static RuntimeAssembly InternalLoadAssemblyName(
AssemblyName assemblyRef,
RuntimeAssembly reqAssembly,
ref StackCrawlMark stackMark,
IntPtr pPrivHostBinder,
bool throwOnFileNotFound,
IntPtr ptrLoadContextBinder = default(IntPtr))
{
if (assemblyRef == null)
throw new ArgumentNullException(nameof(assemblyRef));
if (assemblyRef.CodeBase != null)
{
AppDomain.CheckLoadFromSupported();
}
assemblyRef = (AssemblyName)assemblyRef.Clone();
if (assemblyRef.ProcessorArchitecture != ProcessorArchitecture.None)
{
// PA does not have a semantics for by-name binds for execution
assemblyRef.ProcessorArchitecture = ProcessorArchitecture.None;
}
String codeBase = VerifyCodeBase(assemblyRef.CodeBase);
return nLoad(assemblyRef, codeBase, reqAssembly, ref stackMark,
pPrivHostBinder,
throwOnFileNotFound, ptrLoadContextBinder);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern RuntimeAssembly nLoad(AssemblyName fileName,
String codeBase,
RuntimeAssembly locationHint,
ref StackCrawlMark stackMark,
IntPtr pPrivHostBinder,
bool throwOnFileNotFound,
IntPtr ptrLoadContextBinder = default(IntPtr));
public override bool ReflectionOnly
{
get
{
return false;
}
}
// Returns the module in this assembly with name 'name'
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetModule(RuntimeAssembly assembly, String name, ObjectHandleOnStack retModule);
public override Module GetModule(String name)
{
Module retModule = null;
GetModule(GetNativeHandle(), name, JitHelpers.GetObjectHandleOnStack(ref retModule));
return retModule;
}
// Returns the file in the File table of the manifest that matches the
// given name. (Name should not include path.)
public override FileStream GetFile(String name)
{
RuntimeModule m = (RuntimeModule)GetModule(name);
if (m == null)
return null;
return new FileStream(m.GetFullyQualifiedName(),
FileMode.Open,
FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false);
}
public override FileStream[] GetFiles(bool getResourceModules)
{
Module[] m = GetModules(getResourceModules);
FileStream[] fs = new FileStream[m.Length];
for (int i = 0; i < fs.Length; i++)
{
fs[i] = new FileStream(((RuntimeModule)m[i]).GetFullyQualifiedName(),
FileMode.Open,
FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false);
}
return fs;
}
// Returns the names of all the resources
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern String[] GetManifestResourceNames(RuntimeAssembly assembly);
// Returns the names of all the resources
public override String[] GetManifestResourceNames()
{
return GetManifestResourceNames(GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetExecutingAssembly(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retAssembly);
internal static RuntimeAssembly GetExecutingAssembly(ref StackCrawlMark stackMark)
{
RuntimeAssembly retAssembly = null;
GetExecutingAssembly(JitHelpers.GetStackCrawlMarkHandle(ref stackMark), JitHelpers.GetObjectHandleOnStack(ref retAssembly));
return retAssembly;
}
// Returns the names of all the resources
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern AssemblyName[] GetReferencedAssemblies(RuntimeAssembly assembly);
public override AssemblyName[] GetReferencedAssemblies()
{
return GetReferencedAssemblies(GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern int GetManifestResourceInfo(RuntimeAssembly assembly,
String resourceName,
ObjectHandleOnStack assemblyRef,
StringHandleOnStack retFileName,
StackCrawlMarkHandle stackMark);
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
{
RuntimeAssembly retAssembly = null;
String fileName = null;
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
int location = GetManifestResourceInfo(GetNativeHandle(), resourceName,
JitHelpers.GetObjectHandleOnStack(ref retAssembly),
JitHelpers.GetStringHandleOnStack(ref fileName),
JitHelpers.GetStackCrawlMarkHandle(ref stackMark));
if (location == -1)
return null;
return new ManifestResourceInfo(retAssembly, fileName,
(ResourceLocation)location);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetLocation(RuntimeAssembly assembly, StringHandleOnStack retString);
public override String Location
{
get
{
String location = null;
GetLocation(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref location));
return location;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetImageRuntimeVersion(RuntimeAssembly assembly, StringHandleOnStack retString);
public override String ImageRuntimeVersion
{
get
{
String s = null;
GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s));
return s;
}
}
public override bool GlobalAssemblyCache
{
get
{
return false;
}
}
public override Int64 HostContext
{
get
{
return 0;
}
}
private static String VerifyCodeBase(String codebase)
{
if (codebase == null)
return null;
int len = codebase.Length;
if (len == 0)
return null;
int j = codebase.IndexOf(':');
// Check to see if the url has a prefix
if ((j != -1) &&
(j + 2 < len) &&
((codebase[j + 1] == '/') || (codebase[j + 1] == '\\')) &&
((codebase[j + 2] == '/') || (codebase[j + 2] == '\\')))
return codebase;
#if PLATFORM_WINDOWS
else if ((len > 2) && (codebase[0] == '\\') && (codebase[1] == '\\'))
return "file://" + codebase;
else
return "file:///" + Path.GetFullPath(codebase);
#else
else
return "file://" + Path.GetFullPath(codebase);
#endif // PLATFORM_WINDOWS
}
internal Stream GetManifestResourceStream(
Type type,
String name,
bool skipSecurityCheck,
ref StackCrawlMark stackMark)
{
StringBuilder sb = new StringBuilder();
if (type == null)
{
if (name == null)
throw new ArgumentNullException(nameof(type));
}
else
{
String nameSpace = type.Namespace;
if (nameSpace != null)
{
sb.Append(nameSpace);
if (name != null)
sb.Append(Type.Delimiter);
}
}
if (name != null)
sb.Append(name);
return GetManifestResourceStream(sb.ToString(), ref stackMark, skipSecurityCheck);
}
// GetResource will return a pointer to the resources in memory.
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static unsafe extern byte* GetResource(RuntimeAssembly assembly,
String resourceName,
out ulong length,
StackCrawlMarkHandle stackMark,
bool skipSecurityCheck);
internal unsafe Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck)
{
ulong length = 0;
byte* pbInMemoryResource = GetResource(GetNativeHandle(), name, out length, JitHelpers.GetStackCrawlMarkHandle(ref stackMark), skipSecurityCheck);
if (pbInMemoryResource != null)
{
//Console.WriteLine("Creating an unmanaged memory stream of length "+length);
if (length > Int64.MaxValue)
throw new NotImplementedException(SR.NotImplemented_ResourcesLongerThanInt64Max);
return new UnmanagedMemoryStream(pbInMemoryResource, (long)length, (long)length, FileAccess.Read);
}
//Console.WriteLine("GetManifestResourceStream: Blob "+name+" not found...");
return null;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetVersion(RuntimeAssembly assembly,
out int majVer,
out int minVer,
out int buildNum,
out int revNum);
internal Version GetVersion()
{
int majorVer, minorVer, build, revision;
GetVersion(GetNativeHandle(), out majorVer, out minorVer, out build, out revision);
return new Version(majorVer, minorVer, build, revision);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetLocale(RuntimeAssembly assembly, StringHandleOnStack retString);
internal CultureInfo GetLocale()
{
String locale = null;
GetLocale(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref locale));
if (locale == null)
return CultureInfo.InvariantCulture;
return new CultureInfo(locale);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool FCallIsDynamic(RuntimeAssembly assembly);
public override bool IsDynamic
{
get
{
return FCallIsDynamic(GetNativeHandle());
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetSimpleName(RuntimeAssembly assembly, StringHandleOnStack retSimpleName);
internal String GetSimpleName()
{
string name = null;
GetSimpleName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref name));
return name;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static AssemblyHashAlgorithm GetHashAlgorithm(RuntimeAssembly assembly);
private AssemblyHashAlgorithm GetHashAlgorithm()
{
return GetHashAlgorithm(GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static AssemblyNameFlags GetFlags(RuntimeAssembly assembly);
private AssemblyNameFlags GetFlags()
{
return GetFlags(GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetPublicKey(RuntimeAssembly assembly, ObjectHandleOnStack retPublicKey);
internal byte[] GetPublicKey()
{
byte[] publicKey = null;
GetPublicKey(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref publicKey));
return publicKey;
}
// This method is called by the VM.
private RuntimeModule OnModuleResolveEvent(String moduleName)
{
ModuleResolveEventHandler moduleResolve = _ModuleResolve;
if (moduleResolve == null)
return null;
Delegate[] ds = moduleResolve.GetInvocationList();
int len = ds.Length;
for (int i = 0; i < len; i++)
{
RuntimeModule ret = (RuntimeModule)((ModuleResolveEventHandler)ds[i])(this, new ResolveEventArgs(moduleName, this));
if (ret != null)
return ret;
}
return null;
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Assembly GetSatelliteAssembly(CultureInfo culture)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetSatelliteAssembly(culture, null, ref stackMark);
}
// Useful for binding to a very specific version of a satellite assembly
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetSatelliteAssembly(culture, version, ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
internal Assembly InternalGetSatelliteAssembly(CultureInfo culture,
Version version,
ref StackCrawlMark stackMark)
{
if (culture == null)
throw new ArgumentNullException(nameof(culture));
String name = GetSimpleName() + ".resources";
return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
internal RuntimeAssembly InternalGetSatelliteAssembly(String name,
CultureInfo culture,
Version version,
bool throwOnFileNotFound,
ref StackCrawlMark stackMark)
{
AssemblyName an = new AssemblyName();
an.SetPublicKey(GetPublicKey());
an.Flags = GetFlags() | AssemblyNameFlags.PublicKey;
if (version == null)
an.Version = GetVersion();
else
an.Version = version;
an.CultureInfo = culture;
an.Name = name;
RuntimeAssembly retAssembly = nLoad(an, null, this, ref stackMark,
IntPtr.Zero,
throwOnFileNotFound);
if (retAssembly == this || (retAssembly == null && throwOnFileNotFound))
{
throw new FileNotFoundException(String.Format(culture, SR.IO_FileNotFound_FileName, an.Name));
}
return retAssembly;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetModules(RuntimeAssembly assembly,
bool loadIfNotFound,
bool getResourceModules,
ObjectHandleOnStack retModuleHandles);
private RuntimeModule[] GetModulesInternal(bool loadIfNotFound,
bool getResourceModules)
{
RuntimeModule[] modules = null;
GetModules(GetNativeHandle(), loadIfNotFound, getResourceModules, JitHelpers.GetObjectHandleOnStack(ref modules));
return modules;
}
public override Module[] GetModules(bool getResourceModules)
{
return GetModulesInternal(true, getResourceModules);
}
public override Module[] GetLoadedModules(bool getResourceModules)
{
return GetModulesInternal(false, getResourceModules);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeModule GetManifestModule(RuntimeAssembly assembly);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeAssembly assembly);
public sealed override Type[] GetForwardedTypes()
{
List<Type> types = new List<Type>();
List<Exception> exceptions = new List<Exception>();
MetadataImport scope = GetManifestModule(GetNativeHandle()).MetadataImport;
scope.Enum(MetadataTokenType.ExportedType, 0, out MetadataEnumResult enumResult);
for (int i = 0; i < enumResult.Length; i++)
{
MetadataToken mdtExternalType = enumResult[i];
Type type = null;
Exception exception = null;
ObjectHandleOnStack pType = JitHelpers.GetObjectHandleOnStack(ref type);
try
{
GetForwardedType(this, mdtExternalType, pType);
if (type == null)
continue; // mdtExternalType was not a forwarder entry.
}
catch (Exception e)
{
type = null;
exception = e;
}
Debug.Assert((type != null) != (exception != null)); // Exactly one of these must be non-null.
if (type != null)
{
types.Add(type);
AddPublicNestedTypes(type, types, exceptions);
}
else
{
exceptions.Add(exception);
}
}
if (exceptions.Count != 0)
{
int numTypes = types.Count;
int numExceptions = exceptions.Count;
types.AddRange(new Type[numExceptions]); // add one null Type for each exception.
exceptions.InsertRange(0, new Exception[numTypes]); // align the Exceptions with the null Types.
throw new ReflectionTypeLoadException(types.ToArray(), exceptions.ToArray());
}
return types.ToArray();
}
private static void AddPublicNestedTypes(Type type, List<Type> types, List<Exception> exceptions)
{
Type[] nestedTypes;
try
{
nestedTypes = type.GetNestedTypes(BindingFlags.Public);
}
catch (Exception e)
{
exceptions.Add(e);
return;
}
foreach (Type nestedType in nestedTypes)
{
types.Add(nestedType);
AddPublicNestedTypes(nestedType, types, exceptions);
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetForwardedType(RuntimeAssembly assembly, MetadataToken mdtExternalType, ObjectHandleOnStack type);
}
}
| |
/*
* Muhimbi PDF
*
* Convert, Merge, Watermark, Secure and OCR files.
*
* OpenAPI spec version: 9.15
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Muhimbi.PDF.Online.Client.Client;
using Muhimbi.PDF.Online.Client.Model;
namespace Muhimbi.PDF.Online.Client.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface ICopyMetadataforSharePointOnlyApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Copy metadata (SharePoint only)
/// </summary>
/// <remarks>
/// Copy metadata and set content type.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>OperationResponseCommon</returns>
OperationResponseCommon CopyMetadata (CopyMetadataData inputData);
/// <summary>
/// Copy metadata (SharePoint only)
/// </summary>
/// <remarks>
/// Copy metadata and set content type.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>ApiResponse of OperationResponseCommon</returns>
ApiResponse<OperationResponseCommon> CopyMetadataWithHttpInfo (CopyMetadataData inputData);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Copy metadata (SharePoint only)
/// </summary>
/// <remarks>
/// Copy metadata and set content type.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of OperationResponseCommon</returns>
System.Threading.Tasks.Task<OperationResponseCommon> CopyMetadataAsync (CopyMetadataData inputData);
/// <summary>
/// Copy metadata (SharePoint only)
/// </summary>
/// <remarks>
/// Copy metadata and set content type.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of ApiResponse (OperationResponseCommon)</returns>
System.Threading.Tasks.Task<ApiResponse<OperationResponseCommon>> CopyMetadataAsyncWithHttpInfo (CopyMetadataData inputData);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class CopyMetadataforSharePointOnlyApi : ICopyMetadataforSharePointOnlyApi
{
private Muhimbi.PDF.Online.Client.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="CopyMetadataforSharePointOnlyApi"/> class.
/// </summary>
/// <returns></returns>
public CopyMetadataforSharePointOnlyApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = Muhimbi.PDF.Online.Client.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="CopyMetadataforSharePointOnlyApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public CopyMetadataforSharePointOnlyApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = Muhimbi.PDF.Online.Client.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Muhimbi.PDF.Online.Client.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Copy metadata (SharePoint only) Copy metadata and set content type.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>OperationResponseCommon</returns>
public OperationResponseCommon CopyMetadata (CopyMetadataData inputData)
{
ApiResponse<OperationResponseCommon> localVarResponse = CopyMetadataWithHttpInfo(inputData);
return localVarResponse.Data;
}
/// <summary>
/// Copy metadata (SharePoint only) Copy metadata and set content type.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>ApiResponse of OperationResponseCommon</returns>
public ApiResponse< OperationResponseCommon > CopyMetadataWithHttpInfo (CopyMetadataData inputData)
{
// verify the required parameter 'inputData' is set
if (inputData == null)
throw new ApiException(400, "Missing required parameter 'inputData' when calling CopyMetadataforSharePointOnlyApi->CopyMetadata");
var localVarPath = "/v1/operations/copy_metadata";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (inputData != null && inputData.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter
}
else
{
localVarPostBody = inputData; // byte array
}
// authentication (oauth2_auth) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key")))
{
localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("CopyMetadata", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OperationResponseCommon>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(OperationResponseCommon) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperationResponseCommon)));
}
/// <summary>
/// Copy metadata (SharePoint only) Copy metadata and set content type.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of OperationResponseCommon</returns>
public async System.Threading.Tasks.Task<OperationResponseCommon> CopyMetadataAsync (CopyMetadataData inputData)
{
ApiResponse<OperationResponseCommon> localVarResponse = await CopyMetadataAsyncWithHttpInfo(inputData);
return localVarResponse.Data;
}
/// <summary>
/// Copy metadata (SharePoint only) Copy metadata and set content type.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of ApiResponse (OperationResponseCommon)</returns>
public async System.Threading.Tasks.Task<ApiResponse<OperationResponseCommon>> CopyMetadataAsyncWithHttpInfo (CopyMetadataData inputData)
{
// verify the required parameter 'inputData' is set
if (inputData == null)
throw new ApiException(400, "Missing required parameter 'inputData' when calling CopyMetadataforSharePointOnlyApi->CopyMetadata");
var localVarPath = "/v1/operations/copy_metadata";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (inputData != null && inputData.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter
}
else
{
localVarPostBody = inputData; // byte array
}
// authentication (oauth2_auth) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key")))
{
localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("CopyMetadata", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OperationResponseCommon>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(OperationResponseCommon) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperationResponseCommon)));
}
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// The following code is a port of XNA StockEffects http://xbox.create.msdn.com/en-US/education/catalog/sample/stock_effects
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
//-----------------------------------------------------------------------------
// EnvironmentMapEffect.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Built-in effect that supports environment mapping.
/// </summary>
public partial class EnvironmentMapEffect : Effect, IEffectMatrices, IEffectLights, IEffectFog
{
#region Effect Parameters
EffectParameter textureParam;
EffectParameter environmentMapParam;
EffectParameter environmentMapAmountParam;
EffectParameter environmentMapSpecularParam;
EffectParameter fresnelFactorParam;
EffectParameter diffuseColorParam;
EffectParameter emissiveColorParam;
EffectParameter eyePositionParam;
EffectParameter fogColorParam;
EffectParameter fogVectorParam;
EffectParameter worldParam;
EffectParameter worldInverseTransposeParam;
EffectParameter worldViewProjParam;
EffectPass shaderPass;
#endregion
#region Fields
bool oneLight;
bool fogEnabled;
bool fresnelEnabled;
bool specularEnabled;
Matrix world = Matrix.Identity;
Matrix view = Matrix.Identity;
Matrix projection = Matrix.Identity;
Matrix worldView;
Vector4 diffuseColor = Vector4.One;
Vector3 emissiveColor = Vector3.Zero;
Vector3 ambientLightColor = Vector3.Zero;
float alpha = 1;
DirectionalLight light0;
DirectionalLight light1;
DirectionalLight light2;
float fogStart = 0;
float fogEnd = 1;
EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the world matrix.
/// </summary>
public Matrix World
{
get { return world; }
set
{
world = value;
dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the view matrix.
/// </summary>
public Matrix View
{
get { return view; }
set
{
view = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the projection matrix.
/// </summary>
public Matrix Projection
{
get { return projection; }
set
{
projection = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj;
}
}
/// <summary>
/// Gets or sets the material diffuse color (range 0 to 1).
/// </summary>
public Vector4 DiffuseColor
{
get { return diffuseColor; }
set
{
diffuseColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material emissive color (range 0 to 1).
/// </summary>
public Vector3 EmissiveColor
{
get { return emissiveColor; }
set
{
emissiveColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material alpha.
/// </summary>
public float Alpha
{
get { return alpha; }
set
{
alpha = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the ambient light color (range 0 to 1).
/// </summary>
public Vector3 AmbientLightColor
{
get { return ambientLightColor; }
set
{
ambientLightColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets the first directional light.
/// </summary>
public DirectionalLight DirectionalLight0 { get { return light0; } }
/// <summary>
/// Gets the second directional light.
/// </summary>
public DirectionalLight DirectionalLight1 { get { return light1; } }
/// <summary>
/// Gets the third directional light.
/// </summary>
public DirectionalLight DirectionalLight2 { get { return light2; } }
/// <summary>
/// Gets or sets the fog enable flag.
/// </summary>
public bool FogEnabled
{
get { return fogEnabled; }
set
{
if (fogEnabled != value)
{
fogEnabled = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable;
}
}
}
/// <summary>
/// Gets or sets the fog start distance.
/// </summary>
public float FogStart
{
get { return fogStart; }
set
{
fogStart = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog end distance.
/// </summary>
public float FogEnd
{
get { return fogEnd; }
set
{
fogEnd = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog color.
/// </summary>
public Vector3 FogColor
{
get { return fogColorParam.GetValue<Vector3>(); }
set { fogColorParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the current texture.
/// </summary>
public Texture2D Texture
{
get { return textureParam.GetResource<Texture2D>(); }
set { textureParam.SetResource(value); }
}
/// <summary>
/// Gets or sets the current environment map texture.
/// </summary>
public TextureCube EnvironmentMap
{
get { return environmentMapParam.GetResource<TextureCube>(); }
set { environmentMapParam.SetResource(value); }
}
/// <summary>
/// Gets or sets the amount of the environment map RGB that will be blended over
/// the base texture. Range 0 to 1, default 1. If set to zero, the RGB channels
/// of the environment map will completely ignored (but the environment map alpha
/// may still be visible if EnvironmentMapSpecular is greater than zero).
/// </summary>
public float EnvironmentMapAmount
{
get { return environmentMapAmountParam.GetValue<float>(); }
set { environmentMapAmountParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the amount of the environment map alpha channel that will
/// be added to the base texture. Range 0 to 1, default 0. This can be used
/// to implement cheap specular lighting, by encoding one or more specular
/// highlight patterns into the environment map alpha channel, then setting
/// EnvironmentMapSpecular to the desired specular light color.
/// </summary>
public Vector3 EnvironmentMapSpecular
{
get { return environmentMapSpecularParam.GetValue<Vector3>(); }
set
{
environmentMapSpecularParam.SetValue(value);
bool enabled = (value != Vector3.Zero);
if (specularEnabled != enabled)
{
specularEnabled = enabled;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
}
/// <summary>
/// Gets or sets the Fresnel factor used for the environment map blending.
/// Higher values make the environment map only visible around the silhouette
/// edges of the object, while lower values make it visible everywhere.
/// Setting this property to 0 disables Fresnel entirely, making the
/// environment map equally visible regardless of view angle. The default is
/// 1. Fresnel only affects the environment map RGB (the intensity of which is
/// controlled by EnvironmentMapAmount). The alpha contribution (controlled by
/// EnvironmentMapSpecular) is not affected by the Fresnel setting.
/// </summary>
public float FresnelFactor
{
get { return fresnelFactorParam.GetValue<float>(); }
set
{
fresnelFactorParam.SetValue(value);
bool enabled = (value != 0);
if (fresnelEnabled != enabled)
{
fresnelEnabled = enabled;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
}
/// <summary>
/// This effect requires lighting, so we explicitly implement
/// IEffectLights.LightingEnabled, and do not allow turning it off.
/// </summary>
bool IEffectLights.LightingEnabled
{
get { return true; }
set { if (!value) throw new NotSupportedException("EnvironmentMapEffect does not support setting LightingEnabled to false."); }
}
#endregion
#region Methods
/// <summary>
/// Creates a new EnvironmentMapEffect with default parameter settings.
/// </summary>
public EnvironmentMapEffect(GraphicsDevice device) : this(device, device.DefaultEffectPool)
{
}
/// <summary>
/// Creates a new EnvironmentMapEffect with default parameter settings from a specified <see cref="EffectPool"/>.
/// </summary>
public EnvironmentMapEffect(GraphicsDevice device, EffectPool pool)
: base(device, effectBytecode, pool)
{
CacheEffectParameters(null);
DirectionalLight0.Enabled = true;
EnvironmentMapAmount = 1;
EnvironmentMapSpecular = Vector3.Zero;
FresnelFactor = 1;
}
protected override void Initialize()
{
Pool.RegisterBytecode(effectBytecode);
base.Initialize();
}
///// <summary>
///// Creates a new EnvironmentMapEffect by cloning parameter settings from an existing instance.
///// </summary>
//protected EnvironmentMapEffect(EnvironmentMapEffect cloneSource)
// : base(cloneSource)
//{
// CacheEffectParameters(cloneSource);
// fogEnabled = cloneSource.fogEnabled;
// fresnelEnabled = cloneSource.fresnelEnabled;
// specularEnabled = cloneSource.specularEnabled;
// world = cloneSource.world;
// view = cloneSource.view;
// projection = cloneSource.projection;
// diffuseColor = cloneSource.diffuseColor;
// emissiveColor = cloneSource.emissiveColor;
// ambientLightColor = cloneSource.ambientLightColor;
// alpha = cloneSource.alpha;
// fogStart = cloneSource.fogStart;
// fogEnd = cloneSource.fogEnd;
//}
///// <summary>
///// Creates a clone of the current EnvironmentMapEffect instance.
///// </summary>
//public override Effect Clone()
//{
// return new EnvironmentMapEffect(this);
//}
/// <summary>
/// Sets up the standard key/fill/back lighting rig.
/// </summary>
public void EnableDefaultLighting()
{
AmbientLightColor = EffectHelpers.EnableDefaultLighting(light0, light1, light2);
}
/// <summary>
/// Looks up shortcut references to our effect parameters.
/// </summary>
void CacheEffectParameters(EnvironmentMapEffect cloneSource)
{
textureParam = Parameters["Texture"];
environmentMapParam = Parameters["EnvironmentMap"];
environmentMapAmountParam = Parameters["EnvironmentMapAmount"];
environmentMapSpecularParam = Parameters["EnvironmentMapSpecular"];
fresnelFactorParam = Parameters["FresnelFactor"];
diffuseColorParam = Parameters["DiffuseColor"];
emissiveColorParam = Parameters["EmissiveColor"];
eyePositionParam = Parameters["EyePosition"];
fogColorParam = Parameters["FogColor"];
fogVectorParam = Parameters["FogVector"];
worldParam = Parameters["World"];
worldInverseTransposeParam = Parameters["WorldInverseTranspose"];
worldViewProjParam = Parameters["WorldViewProj"];
light0 = new DirectionalLight(Parameters["DirLight0Direction"],
Parameters["DirLight0DiffuseColor"],
null,
(cloneSource != null) ? cloneSource.light0 : null);
light1 = new DirectionalLight(Parameters["DirLight1Direction"],
Parameters["DirLight1DiffuseColor"],
null,
(cloneSource != null) ? cloneSource.light1 : null);
light2 = new DirectionalLight(Parameters["DirLight2Direction"],
Parameters["DirLight2DiffuseColor"],
null,
(cloneSource != null) ? cloneSource.light2 : null);
}
/// <summary>
/// Lazily computes derived parameter values immediately before applying the effect.
/// </summary>
protected internal override EffectPass OnApply(EffectPass pass)
{
// Recompute the world+view+projection matrix or fog vector?
dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam);
// Recompute the world inverse transpose and eye position?
dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam);
// Recompute the diffuse/emissive/alpha material color parameters?
if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0)
{
EffectHelpers.SetMaterialColor(true, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam);
dirtyFlags &= ~EffectDirtyFlags.MaterialColor;
}
// Check if we can use the only-bother-with-the-first-light shader optimization.
bool newOneLight = !light1.Enabled && !light2.Enabled;
if (oneLight != newOneLight)
{
oneLight = newOneLight;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
// Recompute the shader index?
if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0)
{
int shaderIndex = 0;
if (!fogEnabled)
shaderIndex += 1;
if (fresnelEnabled)
shaderIndex += 2;
if (specularEnabled)
shaderIndex += 4;
if (oneLight)
shaderIndex += 8;
shaderPass = pass.SubPasses[shaderIndex];
dirtyFlags &= ~EffectDirtyFlags.ShaderIndex;
}
return base.OnApply(shaderPass);
}
#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.Text;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.Assemblies;
using System.Reflection.Runtime.MethodInfos;
using Internal.LowLevelLinq;
using Internal.Runtime.Augments;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Core.NonPortable;
using Internal.Reflection.Extensions.NonPortable;
namespace System.Reflection.Runtime.General
{
internal static partial class Helpers
{
// This helper helps reduce the temptation to write "h == default(RuntimeTypeHandle)" which causes boxing.
public static bool IsNull(this RuntimeTypeHandle h)
{
return h.Equals(default(RuntimeTypeHandle));
}
// Clones a Type[] array for the purpose of returning it from an api.
public static Type[] CloneTypeArray(this Type[] types)
{
int count = types.Length;
if (count == 0)
return Array.Empty<Type>(); // Ok not to clone empty arrays - those are immutable.
Type[] clonedTypes = new Type[count];
for (int i = 0; i < count; i++)
{
clonedTypes[i] = types[i];
}
return clonedTypes;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Type[] GetGenericTypeParameters(this Type type)
{
Debug.Assert(type.IsGenericTypeDefinition);
return type.GetGenericArguments();
}
public static RuntimeTypeInfo[] ToRuntimeTypeInfoArray(this Type[] types)
{
int count = types.Length;
RuntimeTypeInfo[] typeInfos = new RuntimeTypeInfo[count];
for (int i = 0; i < count; i++)
{
typeInfos[i] = types[i].CastToRuntimeTypeInfo();
}
return typeInfos;
}
public static string LastResortString(this RuntimeTypeHandle typeHandle)
{
return ReflectionCoreExecution.ExecutionEnvironment.GetLastResortString(typeHandle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeNamedTypeInfo CastToRuntimeNamedTypeInfo(this Type type)
{
Debug.Assert(type is RuntimeNamedTypeInfo);
return (RuntimeNamedTypeInfo)type;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo CastToRuntimeTypeInfo(this Type type)
{
Debug.Assert(type == null || type is RuntimeTypeInfo);
return (RuntimeTypeInfo)type;
}
public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> enumeration)
{
return new ReadOnlyCollection<T>(enumeration.ToArray());
}
public static MethodInfo FilterAccessor(this MethodInfo accessor, bool nonPublic)
{
if (nonPublic)
return accessor;
if (accessor.IsPublic)
return accessor;
return null;
}
public static Type GetTypeCore(this Assembly assembly, string name, bool ignoreCase)
{
RuntimeAssembly runtimeAssembly = assembly as RuntimeAssembly;
if (runtimeAssembly != null)
{
// Not a recursion - this one goes to the actual instance method on RuntimeAssembly.
return runtimeAssembly.GetTypeCore(name, ignoreCase: ignoreCase);
}
else
{
// This is a third-party Assembly object. We can emulate GetTypeCore() by calling the public GetType()
// method. This is wasteful because it'll probably reparse a type string that we've already parsed
// but it can't be helped.
string escapedName = name.EscapeTypeNameIdentifier();
return assembly.GetType(escapedName, throwOnError: false, ignoreCase: ignoreCase);
}
}
public static TypeLoadException CreateTypeLoadException(string typeName, Assembly assemblyIfAny)
{
if (assemblyIfAny == null)
throw new TypeLoadException(SR.Format(SR.TypeLoad_TypeNotFound, typeName));
else
throw Helpers.CreateTypeLoadException(typeName, assemblyIfAny.FullName);
}
public static TypeLoadException CreateTypeLoadException(string typeName, string assemblyName)
{
string message = SR.Format(SR.TypeLoad_TypeNotFoundInAssembly, typeName, assemblyName);
return ReflectionCoreNonPortable.CreateTypeLoadException(message, typeName);
}
// Escape identifiers as described in "Specifying Fully Qualified Type Names" on msdn.
// Current link is http://msdn.microsoft.com/en-us/library/yfsftwz6(v=vs.110).aspx
public static string EscapeTypeNameIdentifier(this string identifier)
{
// Some characters in a type name need to be escaped
if (identifier != null && identifier.IndexOfAny(s_charsToEscape) != -1)
{
StringBuilder sbEscapedName = new StringBuilder(identifier.Length);
foreach (char c in identifier)
{
if (c.NeedsEscapingInTypeName())
sbEscapedName.Append('\\');
sbEscapedName.Append(c);
}
identifier = sbEscapedName.ToString();
}
return identifier;
}
public static bool NeedsEscapingInTypeName(this char c)
{
return Array.IndexOf(s_charsToEscape, c) >= 0;
}
private static readonly char[] s_charsToEscape = new char[] { '\\', '[', ']', '+', '*', '&', ',' };
public static RuntimeMethodInfo GetInvokeMethod(this RuntimeTypeInfo delegateType)
{
Debug.Assert(delegateType.IsDelegate);
MethodInfo invokeMethod = delegateType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
if (invokeMethod == null)
{
// No Invoke method found. Since delegate types are compiler constructed, the most likely cause is missing metadata rather than
// a missing Invoke method.
// We're deliberating calling FullName rather than ToString() because if it's the type that's missing metadata,
// the FullName property constructs a more informative MissingMetadataException than we can.
string fullName = delegateType.FullName;
throw new MissingMetadataException(SR.Format(SR.Arg_InvokeMethodMissingMetadata, fullName)); // No invoke method found.
}
return (RuntimeMethodInfo)invokeMethod;
}
public static BinderBundle ToBinderBundle(this Binder binder, BindingFlags invokeAttr, CultureInfo cultureInfo)
{
if (binder == null || binder is DefaultBinder || ((invokeAttr & BindingFlags.ExactBinding) != 0))
return null;
return new BinderBundle(binder, cultureInfo);
}
// Helper for ICustomAttributeProvider.GetCustomAttributes(). The result of this helper is returned directly to apps
// so it must always return a newly allocated array. Unlike most of the newer custom attribute apis, the attribute type
// need not derive from System.Attribute. (In particular, it can be an interface or System.Object.)
public static object[] InstantiateAsArray(this IEnumerable<CustomAttributeData> cads, Type actualElementType)
{
LowLevelList<object> attributes = new LowLevelList<object>();
foreach (CustomAttributeData cad in cads)
{
object instantiatedAttribute = cad.Instantiate();
attributes.Add(instantiatedAttribute);
}
int count = attributes.Count;
object[] result = (object[])Array.CreateInstance(actualElementType, count);
attributes.CopyTo(result, 0);
return result;
}
public static bool GetCustomAttributeDefaultValueIfAny(IEnumerable<CustomAttributeData> customAttributes, bool raw, out object defaultValue)
{
// Legacy: If there are multiple default value attribute, the desktop picks one at random (and so do we...)
foreach (CustomAttributeData cad in customAttributes)
{
Type attributeType = cad.AttributeType;
if (attributeType.IsSubclassOf(typeof(CustomConstantAttribute)))
{
if (raw)
{
foreach (CustomAttributeNamedArgument namedArgument in cad.NamedArguments)
{
if (namedArgument.MemberInfo.Name.Equals("Value"))
{
defaultValue = namedArgument.TypedValue.Value;
return true;
}
}
defaultValue = null;
return false;
}
else
{
CustomConstantAttribute customConstantAttribute = (CustomConstantAttribute)(cad.Instantiate());
defaultValue = customConstantAttribute.Value;
return true;
}
}
if (attributeType.Equals(typeof(DecimalConstantAttribute)))
{
// We should really do a non-instanting check if "raw == false" but given that we don't support
// reflection-only loads, there isn't an observable difference.
DecimalConstantAttribute decimalConstantAttribute = (DecimalConstantAttribute)(cad.Instantiate());
defaultValue = decimalConstantAttribute.Value;
return true;
}
}
defaultValue = null;
return false;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="XmlElementCollection.cs" company="Microsoft">
// Copyright (C) 2003 by Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Subclass of ObservableCollection<T> which also registers for
// change notifications from the XmlElements it contains. It fires
// CollectionChanged event with action==Reset for any item that
// changed. This is sufficient to let owner objects know an item
// has changed.
//
// History:
// 03/10/2005 : rruiz - created
//
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Data;
using System.Xml;
using MS.Internal;
namespace MS.Internal.Annotations
{
/// <summary>
/// </summary>
internal sealed class XmlElementCollection : ObservableCollection<XmlElement>
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Initializes a new instance of XmlElementCollection that is empty and has default initial capacity.
/// </summary>
public XmlElementCollection() : base()
{
_xmlDocsRefCounts = new Dictionary<XmlDocument, int>();
}
#endregion Constructors
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// called by base class Collection<T> when the list is being cleared;
/// unregisters from all items
/// </summary>
protected override void ClearItems()
{
foreach (XmlElement item in this)
{
UnregisterForElement(item);
}
base.ClearItems();
}
/// <summary>
/// called by base class Collection<T> when an item is removed from list;
/// unregisters on item being removed
/// </summary>
protected override void RemoveItem(int index)
{
XmlElement removedItem = this[index];
UnregisterForElement(removedItem);
base.RemoveItem(index);
}
/// <summary>
/// called by base class Collection<T> when an item is added to list;
/// registers on new item
/// </summary>
protected override void InsertItem(int index, XmlElement item)
{
if (item != null && this.Contains(item))
{
throw new ArgumentException(SR.Get(SRID.XmlNodeAlreadyOwned, "change", "change"), "item");
}
base.InsertItem(index, item);
RegisterForElement(item);
}
/// <summary>
/// called by base class Collection<T> when an item is added to list;
/// unregisters on previous item and registers for new item
/// </summary>
protected override void SetItem(int index, XmlElement item)
{
if (item != null && this.Contains(item))
{
throw new ArgumentException(SR.Get(SRID.XmlNodeAlreadyOwned, "change", "change"), "item");
}
XmlElement originalItem = this[index];
UnregisterForElement(originalItem);
Items[index] = item; // directly set Collection<T> inner Items collection
OnCollectionReset();
RegisterForElement(item);
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Unregister for change notifications for this element.
/// We decrease the reference count and unregister if the count
/// has reached zero.
/// </summary>
/// <param name="element">the element to unregister for</param>
private void UnregisterForElement(XmlElement element)
{
// Nulls may exist in the collection in which case we don't need to unregister
if (element == null)
return;
Invariant.Assert(_xmlDocsRefCounts.ContainsKey(element.OwnerDocument), "Not registered on XmlElement");
// Decrease the reference count
_xmlDocsRefCounts[element.OwnerDocument]--;
// If the reference count is at zero, we can unregister for notifications
// from the document and clear out its entry in the hashtable.
if (_xmlDocsRefCounts[element.OwnerDocument] == 0)
{
element.OwnerDocument.NodeChanged -= OnNodeChanged;
element.OwnerDocument.NodeInserted -= OnNodeChanged;
element.OwnerDocument.NodeRemoved -= OnNodeChanged;
_xmlDocsRefCounts.Remove(element.OwnerDocument);
}
}
/// <summary>
/// Register for change notifications for this element. In
/// reality we regiser on the OwnerDocument, so we keep a count
/// of all the elements from a particular docuemnt we are listening
/// for. If that ref count gets to zero we unregister from the
/// document.
/// </summary>
/// <param name="element">the element to register for</param>
private void RegisterForElement(XmlElement element)
{
// Nulls may exist in the collection in which case we don't need to register
if (element == null)
return;
if (!_xmlDocsRefCounts.ContainsKey(element.OwnerDocument))
{
// If we aren't register on this document yet, register
// and initialize the reference count to 1.
_xmlDocsRefCounts[element.OwnerDocument] = 1;
XmlNodeChangedEventHandler handler = new XmlNodeChangedEventHandler(OnNodeChanged);
element.OwnerDocument.NodeChanged += handler;
element.OwnerDocument.NodeInserted += handler;
element.OwnerDocument.NodeRemoved += handler;
}
else
{
// Increase the reference count
_xmlDocsRefCounts[element.OwnerDocument]++;
}
}
/// <summary>
/// We register for node changes on the documents that own the contents
/// of this Resource. Its the only way to know if the contents have
/// changed.
/// </summary>
/// <param name="sender">document whose node has changed</param>
/// <param name="args">args describing the kind of change and specifying the node that changed</param>
private void OnNodeChanged(object sender, XmlNodeChangedEventArgs args)
{
XmlAttribute attr = null;
XmlElement element = null;
// We should only be getting notifications from documents we have registered on
Invariant.Assert(_xmlDocsRefCounts.ContainsKey(sender as XmlDocument), "Not expecting a notification from this sender");
// The node that changed may not be a content but could be a part of a content
// (such as an attribute node). Therefore we must walk up from the node until
// we either a) get to the root or b) find a content we contain. In the case of
// (a) we do nothing. In the case of (b) we must fire a change notification
// for this Resource.
XmlNode current = args.Node;
while (current != null)
{
element = current as XmlElement;
if (element != null && this.Contains(element))
{
OnCollectionReset();
break;
}
// Get the parent of the current node
attr = current as XmlAttribute;
if (attr != null)
{
// ParentNode isn't implemented for XmlAttributes, we must
// use its OwnerElement to continue our walk up the node tree.
current = attr.OwnerElement;
}
else
{
current = current.ParentNode;
}
}
}
private void OnCollectionReset()
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
Dictionary<XmlDocument, int> _xmlDocsRefCounts;
#endregion Private Fields
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ISSE.SafetyChecking.Modeling
{
using System;
using System.Runtime.CompilerServices;
using ExecutableModel;
public struct Option<T> //Probabilistic Option. Use it until we have real Tuples in C#
{
public Probability Probability;
public T Result;
public Option(Probability probability, T result)
{
Probability = probability;
Result = result;
}
}
/// <summary>
/// Represents a nondeterministic choice.
/// </summary>
public sealed class Choice
{
private static readonly Probability _probability1Div2 = new Probability(1.0 / 2.0);
private static readonly Probability _probability1Div3 = new Probability(1.0 / 3.0);
private static readonly Probability _probability1Div4 = new Probability(1.0 / 4.0);
private static readonly Probability _probability1Div5 = new Probability(1.0 / 5.0);
private static readonly Probability _probability1Div6 = new Probability(1.0 / 6.0);
/// <summary>
/// Gets or sets the resolver that is used to resolve nondeterministic choices.
/// </summary>
public ChoiceResolver Resolver { get; set; }
/// <summary>
/// Returns an index in the range of <paramref name="elementCount" />. Returns <c>-1</c> if <paramref name="elementCount" />
/// is 0.
/// </summary>
/// <param name="elementCount">The element count to choose the index from.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ChooseIndex(int elementCount)
{
switch (elementCount)
{
case 0:
return -1;
case 1:
return 0;
default:
return Resolver.HandleChoice(elementCount);
}
}
/// <summary>
/// Returns a value within the range of the given bounds.
/// </summary>
/// <param name="lowerBound">The inclusive lower bound of the range to choose from.</param>
/// <param name="upperBound">The inclusive upper bound of the range to choose from.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ChooseFromRange(int lowerBound, int upperBound)
{
var range = upperBound - lowerBound + 1;
if (range <= 0)
throw new InvalidOperationException($"Invalid range [{lowerBound}, {upperBound}].");
return lowerBound + ChooseIndex(range);
}
/// <summary>
/// Deterministically returns the default value for <typeparamref name="T" />.
/// </summary>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>()
{
return default(T);
}
/// <summary>
/// Deterministically returns the <paramref name="value" />.
/// </summary>
/// <param name="value">The value to return.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(T value)
{
return value;
}
/// <summary>
/// Returns either <paramref name="value1" /> or <paramref name="value2" /> nondeterministically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(T value1, T value2)
{
switch (Resolver.HandleChoice(2))
{
case 0:
return value1;
default:
return value2;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, or <paramref name="value3" /> nondeterministically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(T value1, T value2, T value3)
{
switch (Resolver.HandleChoice(3))
{
case 0:
return value1;
case 1:
return value2;
default:
return value3;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, <paramref name="value3" />, or
/// <paramref name="value4" /> nondeterministically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <param name="value4">The fourth value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(T value1, T value2, T value3, T value4)
{
switch (Resolver.HandleChoice(4))
{
case 0:
return value1;
case 1:
return value2;
case 2:
return value3;
default:
return value4;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, <paramref name="value3" />,
/// <paramref name="value4" />, or <paramref name="value5" /> nondeterministically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <param name="value4">The fourth value to choose.</param>
/// <param name="value5">The fifth value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(T value1, T value2, T value3, T value4, T value5)
{
switch (Resolver.HandleChoice(5))
{
case 0:
return value1;
case 1:
return value2;
case 2:
return value3;
case 3:
return value4;
default:
return value5;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, <paramref name="value3" />,
/// <paramref name="value4" />, <paramref name="value5" />, or <paramref name="value6" /> nondeterministically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <param name="value4">The fourth value to choose.</param>
/// <param name="value5">The fifth value to choose.</param>
/// <param name="value6">The sixth value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(T value1, T value2, T value3, T value4, T value5, T value6)
{
switch (Resolver.HandleChoice(6))
{
case 0:
return value1;
case 1:
return value2;
case 2:
return value3;
case 3:
return value4;
case 4:
return value5;
default:
return value6;
}
}
/// <summary>
/// Returns one of the <paramref name="values" /> nondeterministically.
/// </summary>
/// <param name="values">The values to choose from.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(params T[] values)
{
if (values.Length == 1)
return values[0];
return values[Resolver.HandleChoice(values.Length)];
}
/// <summary>
/// Returns an index in the range of <paramref name="elementCount" />. Returns <c>-1</c> if <paramref name="elementCount" />
/// is 0.
/// </summary>
/// <param name="elementCount">The element count to choose the index from.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ChooseIndexWithUniformDistribution(int elementCount)
{
switch (elementCount)
{
case 0:
return -1;
case 1:
return 0;
case 2:
var result = Resolver.HandleProbabilisticChoice(_probability1Div2, _probability1Div2);
return result;
case 3:
result = Resolver.HandleProbabilisticChoice(_probability1Div3, _probability1Div3, _probability1Div3);
return result;
default:
var probability = new Probability(1.0 / elementCount);
var array = new Probability[elementCount];
for (var i = 0; i < elementCount; i++)
{
array[i] = probability;
}
result = Resolver.HandleProbabilisticChoice(array);
return result;
}
}
/// <summary>
/// Returns a value within the range of the given bounds.
/// </summary>
/// <param name="lowerBound">The inclusive lower bound of the range to choose from.</param>
/// <param name="upperBound">The inclusive upper bound of the range to choose from.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ChooseFromRangeWithUniformDistribution(int lowerBound, int upperBound)
{
var range = upperBound - lowerBound + 1;
if (range <= 0)
throw new InvalidOperationException($"Invalid range [{lowerBound}, {upperBound}].");
return lowerBound+ChooseIndexWithUniformDistribution(range);
}
/// <summary>
/// Deterministically returns the <paramref name="value" />.
/// </summary>
/// <param name="value">The value to return.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(Option<T> value)
{
Utilities.Assert.That(value.Probability.Is(1.0,0.000000000001),"probability in this case must be 1");
return value.Result;
}
/// <summary>
/// Returns either <paramref name="value1" /> or <paramref name="value2" /> probabilistically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(Option<T> value1, Option<T> value2)
{
var result = Resolver.HandleProbabilisticChoice(value1.Probability, value2.Probability);
switch (result)
{
case 0:
return value1.Result;
default:
return value2.Result;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, or <paramref name="value3" /> probabilistically.
/// </summary>
/// <param name="value1">The firsOption< T> value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(Option<T> value1, Option<T> value2, Option<T> value3)
{
var result = Resolver.HandleProbabilisticChoice(value1.Probability, value2.Probability, value3.Probability);
switch (result)
{
case 0:
return value1.Result;
case 1:
return value2.Result;
default:
return value3.Result;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, <paramref name="value3" />, or
/// <paramref name="value4" /> probabilistically.
/// </summary>
/// <param name="value1">The firsOption< T> value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <param name="value4">The fourth value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(Option<T> value1, Option<T> value2, Option<T> value3, Option<T> value4)
{
var result = Resolver.HandleProbabilisticChoice(value1.Probability, value2.Probability, value3.Probability, value4.Probability);
switch (result)
{
case 0:
return value1.Result;
case 1:
return value2.Result;
case 2:
return value3.Result;
default:
return value4.Result;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, <paramref name="value3" />,
/// <paramref name="value4" />, or <paramref name="value5" /> probabilistically.
/// </summary>
/// <param name="value1">The firsOption< T> value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <param name="value4">The fourth value to choose.</param>
/// <param name="value5">The fifth value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(Option<T> value1, Option<T> value2, Option<T> value3, Option<T> value4, Option<T> value5)
{
var result = Resolver.HandleProbabilisticChoice(value1.Probability, value2.Probability, value3.Probability, value4.Probability, value5.Probability);
switch (result)
{
case 0:
return value1.Result;
case 1:
return value2.Result;
case 2:
return value3.Result;
case 3:
return value4.Result;
default:
return value5.Result;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, <paramref name="value3" />,
/// <paramref name="value4" />, <paramref name="value5" />, or <paramref name="value6" /> probabilistically.
/// </summary>
/// <param name="value1">The firsOption< T> value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <param name="value4">The fourth value to choose.</param>
/// <param name="value5">The fifth value to choose.</param>
/// <param name="value6">The sixth value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(Option<T> value1, Option<T> value2, Option<T> value3, Option<T> value4, Option<T> value5, Option<T> value6)
{
var result = Resolver.HandleProbabilisticChoice(value1.Probability, value2.Probability, value3.Probability, value4.Probability, value5.Probability, value6.Probability);
switch (result)
{
case 0:
return value1.Result;
case 1:
return value2.Result;
case 2:
return value3.Result;
case 3:
return value4.Result;
case 4:
return value5.Result;
default:
return value6.Result;
}
}
/// <summary>
/// Returns one of the <paramref name="values" /> probabilistically.
/// </summary>
/// <param name="values">The values to choose from.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Choose<T>(params Option<T>[] values)
{
var array = new Probability[values.Length];
for (var i = 0; i < values.Length; i++)
{
array[i] = values[i].Probability;
}
var optionIndex = Resolver.HandleProbabilisticChoice(array);
return values[optionIndex].Result;
}
/// <summary>
/// Returns either <paramref name="value1" /> or <paramref name="value2" /> nondeterministically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T ChooseWithUniformDistribution<T>(T value1, T value2)
{
var probability = _probability1Div2;
switch (Resolver.HandleProbabilisticChoice(probability, probability))
{
case 0:
return value1;
default:
return value2;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, or <paramref name="value3" /> nondeterministically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T ChooseWithUniformDistribution<T>(T value1, T value2, T value3)
{
var probability = _probability1Div3;
switch (Resolver.HandleProbabilisticChoice(probability, probability, probability))
{
case 0:
return value1;
case 1:
return value2;
default:
return value3;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, <paramref name="value3" />, or
/// <paramref name="value4" /> nondeterministically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <param name="value4">The fourth value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T ChooseWithUniformDistribution<T>(T value1, T value2, T value3, T value4)
{
var probability = _probability1Div4;
switch (Resolver.HandleProbabilisticChoice(probability, probability, probability, probability))
{
case 0:
return value1;
case 1:
return value2;
case 2:
return value3;
default:
return value4;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, <paramref name="value3" />,
/// <paramref name="value4" />, or <paramref name="value5" /> nondeterministically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <param name="value4">The fourth value to choose.</param>
/// <param name="value5">The fifth value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T ChooseWithUniformDistribution<T>(T value1, T value2, T value3, T value4, T value5)
{
var probability = _probability1Div5;
switch (Resolver.HandleProbabilisticChoice(probability, probability, probability, probability, probability))
{
case 0:
return value1;
case 1:
return value2;
case 2:
return value3;
case 3:
return value4;
default:
return value5;
}
}
/// <summary>
/// Returns either <paramref name="value1" />, <paramref name="value2" />, <paramref name="value3" />,
/// <paramref name="value4" />, <paramref name="value5" />, or <paramref name="value6" /> nondeterministically.
/// </summary>
/// <param name="value1">The first value to choose.</param>
/// <param name="value2">The second value to choose.</param>
/// <param name="value3">The third value to choose.</param>
/// <param name="value4">The fourth value to choose.</param>
/// <param name="value5">The fifth value to choose.</param>
/// <param name="value6">The sixth value to choose.</param>
/// <remarks>This method is a performance optimization.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T ChooseWithUniformDistribution<T>(T value1, T value2, T value3, T value4, T value5, T value6)
{
var probability = _probability1Div6;
switch (Resolver.HandleProbabilisticChoice(probability, probability, probability, probability, probability, probability))
{
case 0:
return value1;
case 1:
return value2;
case 2:
return value3;
case 3:
return value4;
case 4:
return value5;
default:
return value6;
}
}
/// <summary>
/// Returns one of the <paramref name="values" /> probabilistically.
/// </summary>
/// <param name="values">The values to choose from.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T ChooseWithUniformDistribution<T>(params T[] values)
{
var probability = new Probability(1.0 / values.Length);
var array = new Probability[values.Length];
for (var i = 0; i < values.Length; i++)
{
array[i] = probability;
}
var optionIndex = Resolver.HandleProbabilisticChoice(array);
return values[optionIndex];
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using Glass.Mapper.Pipelines.DataMapperResolver;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.DataMappers;
using NSubstitute;
using NUnit.Framework;
using Sitecore.Data.Items;
using Sitecore.FakeDb;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreParentMapperFixture
{
#region Property - ReadOnly
[Test]
public void ReadOnly_ReturnsTrue()
{
//Assign
var mapper = new SitecoreParentMapper();
//Act
var result = mapper.ReadOnly;
//Assert
Assert.IsTrue(result);
}
#endregion
#region Method - MapToProperty
[Test]
public void MapToProperty_ConfigurationSetupCorrectly_CallsCreateClassOnService()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
})
{
var item = database.GetItem("/sitecore/content/TestItem");
var service = Substitute.For<ISitecoreService>();
var scContext = new SitecoreDataMappingContext(null, item, service);
var config = new SitecoreParentConfiguration();
config.PropertyInfo = typeof(Stub).GetProperty("Property");
var mapper = new SitecoreParentMapper();
mapper.Setup(new DataMapperResolverArgs(null, config));
//Act
var result = mapper.MapToProperty(scContext);
//Assert
//ME - I am not sure why I have to use the Arg.Is but just using item.Parent as the argument fails.
service.Received()
.CreateType(config.PropertyInfo.PropertyType, Arg.Is<Item>(x => x.ID == item.Parent.ID), true, false,
null);
}
}
[Test]
public void MapToProperty_ConfigurationIsLazy_CallsCreateClassOnServiceWithIsLazy()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
})
{
var item = database.GetItem("/sitecore/content/TestItem");
var service = Substitute.For<ISitecoreService>();
var scContext = new SitecoreDataMappingContext(null, item, service);
var config = new SitecoreParentConfiguration();
config.PropertyInfo = typeof(Stub).GetProperty("Property");
config.IsLazy = true;
var mapper = new SitecoreParentMapper();
mapper.Setup(new DataMapperResolverArgs(null, config));
//Act
var result = mapper.MapToProperty(scContext);
//Assert
//ME - I am not sure why I have to use the Arg.Is but just using item.Parent as the argument fails.
service.Received()
.CreateType(config.PropertyInfo.PropertyType, Arg.Is<Item>(x => x.ID == item.Parent.ID), true, false,
null);
}
}
[Test]
public void MapToProperty_ConfigurationInferType_CallsCreateClassOnServiceWithInferType()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
})
{
var item = database.GetItem("/sitecore/content/TestItem");
var service = Substitute.For<ISitecoreService>();
var scContext = new SitecoreDataMappingContext(null, item, service);
var config = new SitecoreParentConfiguration();
config.PropertyInfo = typeof(Stub).GetProperty("Property");
config.InferType = true;
var mapper = new SitecoreParentMapper();
mapper.Setup(new DataMapperResolverArgs(null, config));
//Act
var result = mapper.MapToProperty(scContext);
//Assert
//ME - I am not sure why I have to use the Arg.Is but just using item.Parent as the argument fails.
service.Received()
.CreateType(config.PropertyInfo.PropertyType, Arg.Is<Item>(x => x.ID == item.Parent.ID), true, true,
null);
}
}
#endregion
#region Method - CanHandle
[Test]
public void CanHandle_ConfigurationIsSitecoreParent_ReturnsTrue()
{
//Assign
var config = new SitecoreParentConfiguration();
var mapper = new SitecoreParentMapper();
//Act
var result = mapper.CanHandle(config, null);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_ConfigurationIsSitecoreInfo_ReturnsFalse()
{
//Assign
var config = new SitecoreInfoConfiguration();
var mapper = new SitecoreParentMapper();
//Act
var result = mapper.CanHandle(config, null);
//Assert
Assert.IsFalse(result);
}
#endregion
#region Method - MapToCms
[Test]
public void MapToCms_ThrowsException()
{
//Assign
var mapper = new SitecoreParentMapper();
//Act
Assert.Throws<NotSupportedException>(()=> mapper.MapToCms(null));
}
#endregion
#region Stubs
public class Stub
{
public string Property { get; set; }
}
#endregion
}
}
| |
namespace BB.Caching.Redis
{
using System;
using System.Collections.Generic;
using StackExchange.Redis;
/// <summary>
/// A group of connections for Redis.
/// <remarks>
/// Used to group a master-slave setup so that we can treat the master as the single write connection
/// (/ read connection) and the slave(s) as the read connection(s).
/// </remarks>
/// </summary>
public class ConnectionGroup
{
/// <summary>
/// When creating the read pool, read connections are added with this weight.
/// </summary>
private const int READ_WEIGHT = 2;
/// <summary>
/// When creating the read pool, write connections are added with this weight.
/// </summary>
private const int WRITE_WEIGHT = 1;
/// <summary>
/// The pool of read connections to select from.
/// <remarks>
/// Will include both read and write connections, and will round-robin on the available connections.
/// </remarks>
/// </summary>
private List<ConnectionMultiplexer> _readPool;
/// <summary>
/// The last-used read pool connection. This is used for round-robining the connections.
/// </summary>
private int _readPoolIndex = -1;
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionGroup"/> class.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <param name="analytics">
/// True if this connection group is used for bitwise analytics.
/// </param>
public ConnectionGroup(string name, bool analytics = false)
{
this.Name = name;
this.ReadConnections = new List<string>();
this.WriteConnection = null;
this.ReadMultiplexers = new List<ConnectionMultiplexer>();
this.WriteMultiplexer = null;
this.IsAnalytics = analytics;
}
/// <summary>
/// This connection group is used for bitwise analytics.
/// </summary>
public bool IsAnalytics { get; private set; }
/// <summary>
/// The name of this redis connection wrapper.
/// </summary>
public string Name
{
get;
private set;
}
/// <summary>
/// The multiplexers that we can write to. (Master(s))
/// </summary>
public ConnectionMultiplexer WriteMultiplexer { get; private set; }
/// <summary>
/// The connections that we can write to. (Master(s))
/// </summary>
public string WriteConnection { get; private set; }
/// <summary>
/// The slave multiplexers we can read from. (Slave(s))
/// </summary>
public List<ConnectionMultiplexer> ReadMultiplexers { get; private set; }
/// <summary>
/// The slave connections we can read from. (Slave(s))
/// </summary>
public List<string> ReadConnections { get; private set; }
/// <summary>
/// Adds a write connection.
/// </summary>
/// <param name="connection">
/// The connection.
/// </param>
/// <param name="establishConnection">
/// Talks with the redis instance defined in the connection string to establish a connection.
/// </param>
public void AddWriteConnection(string connection, bool establishConnection = true)
{
if (this.WriteConnection != null)
{
throw new Exception(
string.Format("can only have one write connection per connection group\n\t'{0}'", connection));
}
this.WriteConnection = connection;
if (establishConnection)
{
var multiplexer = ConnectionMultiplexer.Connect(connection);
this.WriteMultiplexer = multiplexer;
}
this.UpdateReadPool();
}
/// <summary>
/// Adds a read connection.
/// </summary>
/// <param name="connection">
/// The connection.
/// </param>
/// <param name="establishConnection">
/// Talks with the redis instance defined in the connection string to establish a connection.
/// </param>
public void AddReadConnection(string connection, bool establishConnection = true)
{
this.ReadConnections.Add(connection);
if (establishConnection)
{
var multiplexer = ConnectionMultiplexer.Connect(connection);
this.ReadMultiplexers.Add(multiplexer);
}
this.UpdateReadPool();
}
/// <summary>
/// Retrieves a connection from the read pool on a round-robin basis.
/// </summary>
/// <returns>
/// The read <see cref="ConnectionMultiplexer"/>.
/// </returns>
public ConnectionMultiplexer GetReadMultiplexer()
{
this._readPoolIndex = (this._readPoolIndex + 1) % this._readPool.Count;
return this._readPool[this._readPoolIndex];
}
/// <summary>
/// Retrieves the available write connections.
/// </summary>
/// <returns>
/// The array of write <see><cref>ConnectionMultiplexer[]</cref></see>.
/// </returns>
public ConnectionMultiplexer GetWriteMultiplexer()
{
return this.WriteMultiplexer;
}
/// <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 this.Name;
}
/// <summary>
/// Updates the read pool with connections.
/// </summary>
private void UpdateReadPool()
{
int writeCount = this.WriteMultiplexer == null ? 0 : 1;
int readCount = this.ReadMultiplexers.Count;
this._readPool = new List<ConnectionMultiplexer>((writeCount * WRITE_WEIGHT) + (readCount * READ_WEIGHT));
int readIndex = 0;
int writeIndex = 0;
while (readIndex < readCount || writeIndex < writeCount)
{
if (readCount > 0)
{
for (int i = 0; i < READ_WEIGHT; i++)
{
this._readPool.Add(this.ReadMultiplexers[readIndex]);
}
}
if (writeCount > 0)
{
for (int i = 0; i < WRITE_WEIGHT; i++)
{
this._readPool.Add(this.WriteMultiplexer);
}
}
++readIndex;
++writeIndex;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using Codentia.Common.WebControls.HtmlElements;
namespace Codentia.Common.WebControls
{
/// <summary>
/// SelectionList control
/// </summary>
public class SelectionList : CECompositeControl
{
private string _candidateTitle;
private string _selectionTitle;
private string _saveLinkText = "Save";
private SelectionListItemCollection _items;
/// <summary>
/// Initializes a new instance of the <see cref="SelectionList"/> class.
/// </summary>
public SelectionList()
{
_items = new SelectionListItemCollection();
}
/// <summary>
/// Handler for SelectionList event
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="indexes">The indexes.</param>
public delegate void SelectionListEventHandler(SelectionList sender, int[] indexes);
/// <summary>
/// Occurs when [selected index changed].
/// </summary>
public event SelectionListEventHandler SelectedIndexChanged;
/// <summary>
/// Occurs when [selection cancelled].
/// </summary>
public event SelectionListEventHandler SelectionCancelled;
/// <summary>
/// Gets or sets the items.
/// </summary>
/// <value>The items.</value>
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public SelectionListItemCollection Items
{
get
{
return _items;
}
set
{
_items = value;
}
}
/// <summary>
/// Sets the selection title.
/// </summary>
/// <value>The selection title.</value>
public string SelectionTitle
{
set
{
_selectionTitle = value;
}
}
/// <summary>
/// Sets the candidate title.
/// </summary>
/// <value>The candidate title.</value>
public string CandidateTitle
{
set
{
_candidateTitle = value;
}
}
/// <summary>
/// Sets the save link text.
/// </summary>
/// <value>The save link text.</value>
public string SaveLinkText
{
set
{
_saveLinkText = value;
}
}
/// <summary>
/// Handle the PreRender event
/// </summary>
/// <param name="e">The Arguments</param>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.Page != null)
{
CECompositeControl.RegisterClientScriptResource(this, typeof(SelectionList), "Codentia.Common.WebControls.SelectionList.js");
Control addList = this.FindChildControl("add");
Control optionsList = this.FindChildControl("optionsList");
Control selection = this.FindChildControl("selection");
string definitions = "var selectedIndexes = ''; var selectedValues = ''; var addList = document.getElementById('" + addList.ClientID + "'); var optionsList = document.getElementById('" + optionsList.ClientID + "'); var selection = document.getElementById('" + selection.ClientID + "');";
CECompositeControl.RegisterStartupScript(this, typeof(SelectionList), "Globals", definitions, true);
string registerClickHandlers = "for(i=0;i<optionsList.childNodes.length;i++) { optionsList.childNodes[i].childNodes[0].onclick=moveFromCandidatesToChanges; }";
CECompositeControl.RegisterStartupScript(this, typeof(SelectionList), "RegisterClickHandlers", registerClickHandlers, true);
}
}
/// <summary>
/// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
/// </summary>
protected override void CreateChildControls()
{
this.Controls.Clear();
HiddenField selection = new HiddenField();
selection.ID = "selection";
selection.Value = string.Empty;
this.Controls.Add(selection);
// available items (not chosen)
Div candidates = new Div();
if (!string.IsNullOrEmpty(_candidateTitle))
{
Label candidateLabel = new Label();
candidateLabel.Text = _candidateTitle;
candidates.Controls.Add(candidateLabel);
candidates.Controls.Add(new Br());
}
TextBox filterBox = new TextBox();
filterBox.ID = "filter";
filterBox.Attributes.Add("onkeyup", "filterCandidates(this.value);");
Label filterLabel = new Label();
filterLabel.Text = "Filter:";
filterLabel.AssociatedControlID = "filter";
candidates.Controls.Add(filterLabel);
candidates.Controls.Add(filterBox);
Ul optionsList = new Ul();
optionsList.ID = "optionsList";
for (int i = 0; i < _items.Count; i++)
{
Li item = new Li();
HyperLink itemLink = new HyperLink();
itemLink.ID = string.Format("_{0}", i.ToString());
itemLink.NavigateUrl = "#";
itemLink.Text = _items[i].Description;
item.Controls.Add(itemLink);
optionsList.Controls.Add(item);
}
candidates.Controls.Add(optionsList);
this.Controls.Add(candidates);
// changes
Div selections = new Div();
if (!string.IsNullOrEmpty(_candidateTitle))
{
Label selectionLabel = new Label();
selectionLabel.Text = _selectionTitle;
selections.Controls.Add(selectionLabel);
}
Ul addList = new Ul();
addList.ID = "add";
selections.Controls.Add(addList);
this.Controls.Add(selections);
P linkContainer = new P();
LinkButton cancelLink = new LinkButton();
cancelLink.ID = "cancel";
cancelLink.Text = "Cancel";
cancelLink.Click += new EventHandler(cancelLink_Click);
linkContainer.Controls.Add(cancelLink);
LinkButton saveLink = new LinkButton();
saveLink.ID = "save";
saveLink.Text = _saveLinkText;
saveLink.Click += new EventHandler(saveLink_Click);
linkContainer.Controls.Add(saveLink);
this.Controls.Add(linkContainer);
}
/// <summary>
/// Handles the Click event of the cancelLink control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void cancelLink_Click(object sender, EventArgs e)
{
HiddenField hidden = (HiddenField)this.FindChildControl("selection");
hidden.Value = string.Empty;
if (SelectionCancelled != null)
{
SelectionCancelled(this, null);
}
}
/// <summary>
/// Handles the Click event of the saveLink control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void saveLink_Click(object sender, EventArgs e)
{
HiddenField hidden = (HiddenField)this.FindChildControl("selection");
string value = hidden.Value;
hidden.Value = string.Empty;
if (!string.IsNullOrEmpty(value))
{
if (SelectedIndexChanged != null)
{
string[] parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int[] indexes = new int[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
indexes[i] = Convert.ToInt32(parts[i]);
}
Array.Sort(indexes);
SelectedIndexChanged(this, indexes);
}
}
else
{
cancelLink_Click(sender, e);
}
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
#if ENCODER
using System.Diagnostics;
namespace Iced.Intel.EncoderInternal {
abstract class Op {
public abstract void Encode(Encoder encoder, in Instruction instruction, int operand);
/// <summary>
/// If this is an immediate operand, it returns the <see cref="OpKind"/> value, else it returns -1
/// </summary>
/// <returns></returns>
public virtual OpKind GetImmediateOpKind() => (OpKind)(-1);
/// <summary>
/// If this is a near branch operand, it returns the <see cref="OpKind"/> value, else it returns -1
/// </summary>
/// <returns></returns>
public virtual OpKind GetNearBranchOpKind() => (OpKind)(-1);
/// <summary>
/// If this is a far branch operand, it returns the <see cref="OpKind"/> value, else it returns -1
/// </summary>
/// <returns></returns>
public virtual OpKind GetFarBranchOpKind() => (OpKind)(-1);
}
sealed class OpModRM_rm_mem_only : Op {
readonly bool mustUseSib;
public OpModRM_rm_mem_only(bool mustUseSib) => this.mustUseSib = mustUseSib;
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
if (mustUseSib)
encoder.EncoderFlags |= EncoderFlags.MustUseSib;
encoder.AddRegOrMem(instruction, operand, Register.None, Register.None, allowMemOp: true, allowRegOp: false);
}
}
sealed class OpModRM_rm : Op {
readonly Register regLo;
readonly Register regHi;
public OpModRM_rm(Register regLo, Register regHi) {
this.regLo = regLo;
this.regHi = regHi;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) =>
encoder.AddRegOrMem(instruction, operand, regLo, regHi, allowMemOp: true, allowRegOp: true);
}
sealed class OpRegEmbed8: Op {
readonly Register regLo;
readonly Register regHi;
public OpRegEmbed8(Register regLo, Register regHi) {
this.regLo = regLo;
this.regHi = regHi;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) =>
encoder.AddReg(instruction, operand, regLo, regHi);
}
sealed class OpModRM_rm_reg_only : Op {
readonly Register regLo;
readonly Register regHi;
public OpModRM_rm_reg_only(Register regLo, Register regHi) {
this.regLo = regLo;
this.regHi = regHi;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) =>
encoder.AddRegOrMem(instruction, operand, regLo, regHi, allowMemOp: false, allowRegOp: true);
}
sealed class OpModRM_reg : Op {
readonly Register regLo;
readonly Register regHi;
public OpModRM_reg(Register regLo, Register regHi) {
this.regLo = regLo;
this.regHi = regHi;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) =>
encoder.AddModRMRegister(instruction, operand, regLo, regHi);
}
sealed class OpModRM_reg_mem : Op {
readonly Register regLo;
readonly Register regHi;
public OpModRM_reg_mem(Register regLo, Register regHi) {
this.regLo = regLo;
this.regHi = regHi;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
encoder.AddModRMRegister(instruction, operand, regLo, regHi);
encoder.EncoderFlags |= EncoderFlags.RegIsMemory;
}
}
sealed class OpModRM_regF0 : Op {
readonly Register regLo;
readonly Register regHi;
public OpModRM_regF0(Register regLo, Register regHi) {
this.regLo = regLo;
this.regHi = regHi;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
if (encoder.Bitness != 64 && instruction.GetOpKind(operand) == OpKind.Register && instruction.GetOpRegister(operand) >= regLo + 8 && instruction.GetOpRegister(operand) <= regLo + 15) {
encoder.EncoderFlags |= EncoderFlags.PF0;
encoder.AddModRMRegister(instruction, operand, regLo + 8, regLo + 15);
}
else
encoder.AddModRMRegister(instruction, operand, regLo, regHi);
}
}
sealed class OpReg : Op {
readonly Register register;
public OpReg(Register register) => this.register = register;
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
encoder.Verify(operand, OpKind.Register, instruction.GetOpKind(operand));
encoder.Verify(operand, register, instruction.GetOpRegister(operand));
}
}
sealed class OpRegSTi : Op {
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
if (!encoder.Verify(operand, OpKind.Register, instruction.GetOpKind(operand)))
return;
var reg = instruction.GetOpRegister(operand);
if (!encoder.Verify(operand, reg, Register.ST0, Register.ST7))
return;
Debug.Assert((encoder.OpCode & 7) == 0);
encoder.OpCode |= (uint)(reg - Register.ST0);
}
}
sealed class OprDI : Op {
static int GetRegSize(OpKind opKind) {
if (opKind == OpKind.MemorySegRDI)
return 8;
if (opKind == OpKind.MemorySegEDI)
return 4;
if (opKind == OpKind.MemorySegDI)
return 2;
return 0;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
var regSize = GetRegSize(instruction.GetOpKind(operand));
if (regSize == 0) {
encoder.ErrorMessage = $"Operand {operand}: expected OpKind = {nameof(OpKind.MemorySegDI)}, {nameof(OpKind.MemorySegEDI)} or {nameof(OpKind.MemorySegRDI)}";
return;
}
encoder.SetAddrSize(regSize);
}
}
sealed class OpIb : Op {
readonly OpKind opKind;
public OpIb(OpKind opKind) => this.opKind = opKind;
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
switch (encoder.ImmSize) {
case ImmSize.Size1:
if (!encoder.Verify(operand, OpKind.Immediate8_2nd, instruction.GetOpKind(operand)))
return;
encoder.ImmSize = ImmSize.Size1_1;
encoder.ImmediateHi = instruction.Immediate8_2nd;
break;
case ImmSize.Size2:
if (!encoder.Verify(operand, OpKind.Immediate8_2nd, instruction.GetOpKind(operand)))
return;
encoder.ImmSize = ImmSize.Size2_1;
encoder.ImmediateHi = instruction.Immediate8_2nd;
break;
default:
var opImmKind = instruction.GetOpKind(operand);
if (!encoder.Verify(operand, opKind, opImmKind))
return;
encoder.ImmSize = ImmSize.Size1;
encoder.Immediate = instruction.Immediate8;
break;
}
}
public override OpKind GetImmediateOpKind() => opKind;
}
sealed class OpIw : Op {
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
if (!encoder.Verify(operand, OpKind.Immediate16, instruction.GetOpKind(operand)))
return;
encoder.ImmSize = ImmSize.Size2;
encoder.Immediate = instruction.Immediate16;
}
public override OpKind GetImmediateOpKind() => OpKind.Immediate16;
}
sealed class OpId : Op {
readonly OpKind opKind;
public OpId(OpKind opKind) => this.opKind = opKind;
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
var opImmKind = instruction.GetOpKind(operand);
if (!encoder.Verify(operand, opKind, opImmKind))
return;
encoder.ImmSize = ImmSize.Size4;
encoder.Immediate = instruction.Immediate32;
}
public override OpKind GetImmediateOpKind() => opKind;
}
sealed class OpIq : Op {
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
if (!encoder.Verify(operand, OpKind.Immediate64, instruction.GetOpKind(operand)))
return;
encoder.ImmSize = ImmSize.Size8;
ulong imm = instruction.Immediate64;
encoder.Immediate = (uint)imm;
encoder.ImmediateHi = (uint)(imm >> 32);
}
public override OpKind GetImmediateOpKind() => OpKind.Immediate64;
}
sealed class OpI4 : Op {
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
var opImmKind = instruction.GetOpKind(operand);
if (!encoder.Verify(operand, OpKind.Immediate8, opImmKind))
return;
Debug.Assert(encoder.ImmSize == ImmSize.SizeIbReg);
Debug.Assert((encoder.Immediate & 0xF) == 0);
if (instruction.Immediate8 > 0xF) {
encoder.ErrorMessage = $"Operand {operand}: Immediate value must be 0-15, but value is 0x{instruction.Immediate8:X2}";
return;
}
encoder.ImmSize = ImmSize.Size1;
encoder.Immediate |= instruction.Immediate8;
}
public override OpKind GetImmediateOpKind() => OpKind.Immediate8;
}
sealed class OpX : Op {
internal static int GetXRegSize(OpKind opKind) {
if (opKind == OpKind.MemorySegRSI)
return 8;
if (opKind == OpKind.MemorySegESI)
return 4;
if (opKind == OpKind.MemorySegSI)
return 2;
return 0;
}
internal static int GetYRegSize(OpKind opKind) {
if (opKind == OpKind.MemoryESRDI)
return 8;
if (opKind == OpKind.MemoryESEDI)
return 4;
if (opKind == OpKind.MemoryESDI)
return 2;
return 0;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
var regXSize = GetXRegSize(instruction.GetOpKind(operand));
if (regXSize == 0) {
encoder.ErrorMessage = $"Operand {operand}: expected OpKind = {nameof(OpKind.MemorySegSI)}, {nameof(OpKind.MemorySegESI)} or {nameof(OpKind.MemorySegRSI)}";
return;
}
switch (instruction.Code) {
case Code.Movsb_m8_m8:
case Code.Movsw_m16_m16:
case Code.Movsd_m32_m32:
case Code.Movsq_m64_m64:
var regYSize = GetYRegSize(instruction.Op0Kind);
if (regXSize != regYSize) {
encoder.ErrorMessage = $"Same sized register must be used: reg #1 size = {regYSize * 8}, reg #2 size = {regXSize * 8}";
return;
}
break;
}
encoder.SetAddrSize(regXSize);
}
}
sealed class OpY : Op {
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
var regYSize = OpX.GetYRegSize(instruction.GetOpKind(operand));
if (regYSize == 0) {
encoder.ErrorMessage = $"Operand {operand}: expected OpKind = {nameof(OpKind.MemoryESDI)}, {nameof(OpKind.MemoryESEDI)} or {nameof(OpKind.MemoryESRDI)}";
return;
}
switch (instruction.Code) {
case Code.Cmpsb_m8_m8:
case Code.Cmpsw_m16_m16:
case Code.Cmpsd_m32_m32:
case Code.Cmpsq_m64_m64:
var regXSize = OpX.GetXRegSize(instruction.Op0Kind);
if (regXSize != regYSize) {
encoder.ErrorMessage = $"Same sized register must be used: reg #1 size = {regXSize * 8}, reg #2 size = {regYSize * 8}";
return;
}
break;
}
encoder.SetAddrSize(regYSize);
}
}
sealed class OpMRBX : Op {
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
if (!encoder.Verify(operand, OpKind.Memory, instruction.GetOpKind(operand)))
return;
var baseReg = instruction.MemoryBase;
if (instruction.MemoryDisplSize != 0 || instruction.MemoryIndex != Register.AL || (baseReg != Register.BX && baseReg != Register.EBX && baseReg != Register.RBX)) {
encoder.ErrorMessage = $"Operand {operand}: Operand must be [bx+al], [ebx+al], or [rbx+al]";
return;
}
int regSize;
if (baseReg == Register.RBX)
regSize = 8;
else if (baseReg == Register.EBX)
regSize = 4;
else {
Debug.Assert(baseReg == Register.BX);
regSize = 2;
}
encoder.SetAddrSize(regSize);
}
}
sealed class OpJ : Op {
readonly OpKind opKind;
readonly int immSize;
public OpJ(OpKind opKind, int immSize) {
this.opKind = opKind;
this.immSize = immSize;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) =>
encoder.AddBranch(opKind, immSize, instruction, operand);
public override OpKind GetNearBranchOpKind() => opKind;
}
sealed class OpJx : Op {
readonly int immSize;
public OpJx(int immSize) => this.immSize = immSize;
public override void Encode(Encoder encoder, in Instruction instruction, int operand) =>
encoder.AddBranchX(immSize, instruction, operand);
public override OpKind GetNearBranchOpKind() {
// xbegin is special and doesn't mask the target IP. We need to know the code size to return the correct value.
// Instruction.CreateXbegin() should be used to create the instruction and this method should never be called.
Debug.Fail("Call Instruction.CreateXbegin()");
return base.GetNearBranchOpKind();
}
}
sealed class OpJdisp : Op {
readonly int displSize;
public OpJdisp(int displSize) => this.displSize = displSize;
public override void Encode(Encoder encoder, in Instruction instruction, int operand) =>
encoder.AddBranchDisp(displSize, instruction, operand);
public override OpKind GetNearBranchOpKind() => displSize == 2 ? OpKind.NearBranch16 : OpKind.NearBranch32;
}
sealed class OpA : Op {
readonly int size;
public OpA(int size) {
Debug.Assert(size == 2 || size == 4);
this.size = size;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) =>
encoder.AddFarBranch(instruction, operand, size);
public override OpKind GetFarBranchOpKind() {
Debug.Assert(size == 2 || size == 4);
return size == 2 ? OpKind.FarBranch16 : OpKind.FarBranch32;
}
}
sealed class OpO : Op {
public override void Encode(Encoder encoder, in Instruction instruction, int operand) =>
encoder.AddAbsMem(instruction, operand);
}
sealed class OpImm : Op {
readonly byte value;
public OpImm(byte value) => this.value = value;
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
if (!encoder.Verify(operand, OpKind.Immediate8, instruction.GetOpKind(operand)))
return;
if (instruction.Immediate8 != value) {
encoder.ErrorMessage = $"Operand {operand}: Expected 0x{value:X2}, actual: 0x{instruction.Immediate8:X2}";
return;
}
}
public override OpKind GetImmediateOpKind() => OpKind.Immediate8;
}
sealed class OpHx : Op {
readonly Register regLo;
readonly Register regHi;
public OpHx(Register regLo, Register regHi) {
this.regLo = regLo;
this.regHi = regHi;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
if (!encoder.Verify(operand, OpKind.Register, instruction.GetOpKind(operand)))
return;
var reg = instruction.GetOpRegister(operand);
if (!encoder.Verify(operand, reg, regLo, regHi))
return;
encoder.EncoderFlags |= (EncoderFlags)((uint)(reg - regLo) << (int)EncoderFlags.VvvvvShift);
}
}
#if !NO_VEX || !NO_EVEX
sealed class OpVsib : Op {
readonly Register vsibIndexRegLo;
readonly Register vsibIndexRegHi;
public OpVsib(Register regLo, Register regHi) {
vsibIndexRegLo = regLo;
vsibIndexRegHi = regHi;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
encoder.EncoderFlags |= EncoderFlags.MustUseSib;
encoder.AddRegOrMem(instruction, operand, Register.None, Register.None, vsibIndexRegLo, vsibIndexRegHi, allowMemOp: true, allowRegOp: false);
}
}
#endif
#if !NO_VEX || !NO_XOP
sealed class OpIsX : Op {
readonly Register regLo;
readonly Register regHi;
public OpIsX(Register regLo, Register regHi) {
this.regLo = regLo;
this.regHi = regHi;
}
public override void Encode(Encoder encoder, in Instruction instruction, int operand) {
if (!encoder.Verify(operand, OpKind.Register, instruction.GetOpKind(operand)))
return;
var reg = instruction.GetOpRegister(operand);
if (!encoder.Verify(operand, reg, regLo, regHi))
return;
encoder.ImmSize = ImmSize.SizeIbReg;
encoder.Immediate = (uint)(reg - regLo) << 4;
}
}
#endif
}
#endif
| |
/*
* SubSonic - http://subsonicproject.com
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using SubSonic.Utilities;
namespace SubSonic.Sugar
{
/// <summary>
/// Summary for the Strings class
/// </summary>
public static class Strings
{
private static readonly Dictionary<int, string> _entityTable = new Dictionary<int, string>();
private static readonly Dictionary<string, string> _USStateTable = new Dictionary<string, string>();
/// <summary>
/// Initializes the <see cref="Strings"/> class.
/// </summary>
static Strings()
{
FillEntities();
FillUSStates();
}
/// <summary>
/// Strips the last specified chars from a string.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <param name="removeFromEnd">The remove from end.</param>
/// <returns></returns>
public static string Chop(string sourceString, int removeFromEnd)
{
string result = sourceString;
if((removeFromEnd > 0) && (sourceString.Length > removeFromEnd - 1))
result = result.Remove(sourceString.Length - removeFromEnd, removeFromEnd);
return result;
}
/// <summary>
/// Strips the last specified chars from a string.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <param name="backDownTo">The back down to.</param>
/// <returns></returns>
public static string Chop(string sourceString, string backDownTo)
{
int removeDownTo = sourceString.LastIndexOf(backDownTo);
int removeFromEnd = 0;
if(removeDownTo > 0)
removeFromEnd = sourceString.Length - removeDownTo;
string result = sourceString;
if(sourceString.Length > removeFromEnd - 1)
result = result.Remove(removeDownTo, removeFromEnd);
return result;
}
/// <summary>
/// Removes the specified chars from the beginning of a string.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <param name="removeFromBeginning">The remove from beginning.</param>
/// <returns></returns>
public static string Clip(string sourceString, int removeFromBeginning)
{
string result = sourceString;
if(sourceString.Length > removeFromBeginning)
result = result.Remove(0, removeFromBeginning);
return result;
}
/// <summary>
/// Removes chars from the beginning of a string, up to the specified string
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <param name="removeUpTo">The remove up to.</param>
/// <returns></returns>
public static string Clip(string sourceString, string removeUpTo)
{
int removeFromBeginning = sourceString.IndexOf(removeUpTo);
string result = sourceString;
if(sourceString.Length > removeFromBeginning && removeFromBeginning > 0)
result = result.Remove(0, removeFromBeginning);
return result;
}
/// <summary>
/// Strips the last char from a a string.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <returns></returns>
public static string Chop(string sourceString)
{
return Chop(sourceString, 1);
}
/// <summary>
/// Strips the last char from a a string.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <returns></returns>
public static string Clip(string sourceString)
{
return Clip(sourceString, 1);
}
/// <summary>
/// Returns text that is located between the startText and endText tags.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <param name="startText">The text from which to start the crop</param>
/// <param name="endText">The endpoint of the crop</param>
/// <returns></returns>
public static string Crop(string sourceString, string startText, string endText)
{
int startIndex = sourceString.IndexOf(startText, StringComparison.CurrentCultureIgnoreCase);
if(startIndex == -1)
return String.Empty;
startIndex += startText.Length;
int endIndex = sourceString.IndexOf(endText, startIndex, StringComparison.CurrentCultureIgnoreCase);
if(endIndex == -1)
return String.Empty;
return sourceString.Substring(startIndex, endIndex - startIndex);
}
/// <summary>
/// Removes excess white space in a string.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <returns></returns>
public static string Squeeze(string sourceString)
{
char[] delim = {' '};
string[] lines = sourceString.Split(delim, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach(string s in lines)
{
if(!String.IsNullOrEmpty(s.Trim()))
sb.Append(s + " ");
}
//remove the last pipe
string result = Chop(sb.ToString());
return result.Trim();
}
/// <summary>
/// Creates a string array based on the words in a sentence
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <returns></returns>
public static string[] ToWords(string sourceString)
{
string result = sourceString.Trim();
return result.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>
/// Strips all HTML tags from a string
/// </summary>
/// <param name="htmlString">The HTML string.</param>
/// <returns></returns>
public static string StripHTML(string htmlString)
{
return StripHTML(htmlString, String.Empty);
}
/// <summary>
/// Strips all HTML tags from a string and replaces the tags with the specified replacement
/// </summary>
/// <param name="htmlString">The HTML string.</param>
/// <param name="htmlPlaceHolder">The HTML place holder.</param>
/// <returns></returns>
public static string StripHTML(string htmlString, string htmlPlaceHolder)
{
const string pattern = @"<(.|\n)*?>";
string sOut = Regex.Replace(htmlString, pattern, htmlPlaceHolder);
sOut = sOut.Replace(" ", String.Empty);
sOut = sOut.Replace("&", "&");
sOut = sOut.Replace(">", ">");
sOut = sOut.Replace("<", "<");
return sOut;
}
[Obsolete("Will be removed in future versions. Use Validation.IsEmail instead")]
public static bool IsValidEmail(string emailAddressString)
{
return Validation.IsEmail(emailAddressString);
}
/// <summary>
/// Convert string to proper case
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <returns></returns>
public static string ToProper(string sourceString)
{
string propertyName = Inflector.ToPascalCase(sourceString);
//if(propertyName.EndsWith("TypeCode"))
// propertyName = propertyName.Substring(0, propertyName.Length - 4);
return propertyName;
}
/// <summary>
/// Converts a generic List collection to a single comma-delimitted string.
/// </summary>
/// <param name="list">The list.</param>
/// <returns></returns>
public static string ToDelimitedList(List<string> list)
{
return ToDelimitedList(list, ",");
}
/// <summary>
/// Converts a generic List collection to a single string using the specified delimitter.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="delimiter">The delimiter.</param>
/// <returns></returns>
public static string ToDelimitedList(List<string> list, string delimiter)
{
StringBuilder sb = new StringBuilder();
foreach(string s in list)
sb.Append(String.Concat(s, delimiter));
string result = sb.ToString();
result = Chop(result);
return result;
}
/// <summary>
/// Converts an array of strings to a single string using the specified delimitter.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="delimiter">The delimiter.</param>
/// <returns></returns>
public static string ToDelimitedList(string[] list, string delimiter)
{
StringBuilder sb = new StringBuilder();
foreach(string s in list)
sb.Append(String.Concat(s, delimiter));
string result = sb.ToString();
result = Chop(result);
return result;
}
/// <summary>
/// Camels to proper.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <returns></returns>
public static string CamelToProper(string sourceString)
{
return Utility.ParseCamelToProper(sourceString);
}
/// <summary>
/// Plurals to singular.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <returns></returns>
public static string PluralToSingular(string sourceString)
{
return Inflector.MakeSingular(sourceString);
}
/// <summary>
/// Singulars to plural.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <returns></returns>
public static string SingularToPlural(string sourceString)
{
return Inflector.MakePlural(sourceString);
}
/// <summary>
/// Make plural when count is not one
/// </summary>
/// <param name="number">The number of things</param>
/// <param name="sourceString">The source string.</param>
/// <returns></returns>
public static string Pluralize(int number, string sourceString)
{
if(number == 1)
return String.Concat(number, " ", Inflector.MakeSingular(sourceString));
return String.Concat(number, " ", Inflector.MakePlural(sourceString));
}
/// <summary>
/// Strips the specified input.
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <param name="stripValue">The strip value.</param>
/// <returns></returns>
public static string Strip(string sourceString, string stripValue)
{
if(!String.IsNullOrEmpty(stripValue))
{
string[] replace = stripValue.Split(new char[] {','});
for(int i = 0; i < replace.Length; i++)
{
if(!String.IsNullOrEmpty(sourceString))
sourceString = Regex.Replace(sourceString, replace[i], String.Empty);
}
}
return sourceString;
}
/// <summary>
/// Replaces most non-alpha-numeric chars
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <returns></returns>
public static string StripNonAlphaNumeric(string sourceString)
{
return Utility.StripNonAlphaNumeric(sourceString);
}
/// <summary>
/// Replaces most non-alpha-numeric chars
/// </summary>
/// <param name="sourceString">The source string.</param>
/// <param name="cReplace">The placeholder character to use for replacement</param>
/// <returns></returns>
public static string StripNonAlphaNumeric(string sourceString, char cReplace)
{
return Utility.StripNonAlphaNumeric(sourceString, cReplace);
}
/// <summary>
/// Converts ASCII encoding to Unicode
/// </summary>
/// <param name="asciiCode">The ASCII code.</param>
/// <returns></returns>
public static string AsciiToUnicode(int asciiCode)
{
Encoding ascii = Encoding.UTF32;
char c = (char)asciiCode;
Byte[] b = ascii.GetBytes(c.ToString());
return ascii.GetString((b));
}
/// <summary>
/// Converts Text to HTML-encoded string
/// </summary>
/// <param name="textString">The text string.</param>
/// <returns></returns>
public static string TextToEntity(string textString)
{
foreach(KeyValuePair<int, string> key in _entityTable)
textString = textString.Replace(AsciiToUnicode(key.Key), key.Value);
return textString.Replace(AsciiToUnicode(38), "&");
}
/// <summary>
/// Converts HTML-encoded bits to Text
/// </summary>
/// <param name="entityText">The entity text.</param>
/// <returns></returns>
public static string EntityToText(string entityText)
{
entityText = entityText.Replace("&", "&");
foreach(KeyValuePair<int, string> key in _entityTable)
entityText = entityText.Replace(key.Value, AsciiToUnicode(key.Key));
return entityText;
}
/// <summary>
/// Fills the entities.
/// </summary>
private static void FillEntities()
{
_entityTable.Add(160, " ");
_entityTable.Add(161, "¡");
_entityTable.Add(162, "¢");
_entityTable.Add(163, "£");
_entityTable.Add(164, "¤");
_entityTable.Add(165, "¥");
_entityTable.Add(166, "¦");
_entityTable.Add(167, "§");
_entityTable.Add(168, "¨");
_entityTable.Add(169, "©");
_entityTable.Add(170, "ª");
_entityTable.Add(171, "«");
_entityTable.Add(172, "¬");
_entityTable.Add(173, "­");
_entityTable.Add(174, "®");
_entityTable.Add(175, "¯");
_entityTable.Add(176, "°");
_entityTable.Add(177, "±");
_entityTable.Add(178, "²");
_entityTable.Add(179, "³");
_entityTable.Add(180, "´");
_entityTable.Add(181, "µ");
_entityTable.Add(182, "¶");
_entityTable.Add(183, "·");
_entityTable.Add(184, "¸");
_entityTable.Add(185, "¹");
_entityTable.Add(186, "º");
_entityTable.Add(187, "»");
_entityTable.Add(188, "¼");
_entityTable.Add(189, "½");
_entityTable.Add(190, "¾");
_entityTable.Add(191, "¿");
_entityTable.Add(192, "À");
_entityTable.Add(193, "Á");
_entityTable.Add(194, "Â");
_entityTable.Add(195, "Ã");
_entityTable.Add(196, "Ä");
_entityTable.Add(197, "Å");
_entityTable.Add(198, "Æ");
_entityTable.Add(199, "Ç");
_entityTable.Add(200, "È");
_entityTable.Add(201, "É");
_entityTable.Add(202, "Ê");
_entityTable.Add(203, "Ë");
_entityTable.Add(204, "Ì");
_entityTable.Add(205, "Í");
_entityTable.Add(206, "Î");
_entityTable.Add(207, "Ï");
_entityTable.Add(208, "Ð");
_entityTable.Add(209, "Ñ");
_entityTable.Add(210, "Ò");
_entityTable.Add(211, "Ó");
_entityTable.Add(212, "Ô");
_entityTable.Add(213, "Õ");
_entityTable.Add(214, "Ö");
_entityTable.Add(215, "×");
_entityTable.Add(216, "Ø");
_entityTable.Add(217, "Ù");
_entityTable.Add(218, "Ú");
_entityTable.Add(219, "Û");
_entityTable.Add(220, "Ü");
_entityTable.Add(221, "Ý");
_entityTable.Add(222, "Þ");
_entityTable.Add(223, "ß");
_entityTable.Add(224, "à");
_entityTable.Add(225, "á");
_entityTable.Add(226, "â");
_entityTable.Add(227, "ã");
_entityTable.Add(228, "ä");
_entityTable.Add(229, "å");
_entityTable.Add(230, "æ");
_entityTable.Add(231, "ç");
_entityTable.Add(232, "è");
_entityTable.Add(233, "é");
_entityTable.Add(234, "ê");
_entityTable.Add(235, "ë");
_entityTable.Add(236, "ì");
_entityTable.Add(237, "í");
_entityTable.Add(238, "î");
_entityTable.Add(239, "ï");
_entityTable.Add(240, "ð");
_entityTable.Add(241, "ñ");
_entityTable.Add(242, "ò");
_entityTable.Add(243, "ó");
_entityTable.Add(244, "ô");
_entityTable.Add(245, "õ");
_entityTable.Add(246, "ö");
_entityTable.Add(247, "÷");
_entityTable.Add(248, "ø");
_entityTable.Add(249, "ù");
_entityTable.Add(250, "ú");
_entityTable.Add(251, "û");
_entityTable.Add(252, "ü");
_entityTable.Add(253, "ý");
_entityTable.Add(254, "þ");
_entityTable.Add(255, "ÿ");
_entityTable.Add(402, "ƒ");
_entityTable.Add(913, "Α");
_entityTable.Add(914, "Β");
_entityTable.Add(915, "Γ");
_entityTable.Add(916, "Δ");
_entityTable.Add(917, "Ε");
_entityTable.Add(918, "Ζ");
_entityTable.Add(919, "Η");
_entityTable.Add(920, "Θ");
_entityTable.Add(921, "Ι");
_entityTable.Add(922, "Κ");
_entityTable.Add(923, "Λ");
_entityTable.Add(924, "Μ");
_entityTable.Add(925, "Ν");
_entityTable.Add(926, "Ξ");
_entityTable.Add(927, "Ο");
_entityTable.Add(928, "Π");
_entityTable.Add(929, "Ρ");
_entityTable.Add(931, "Σ");
_entityTable.Add(932, "Τ");
_entityTable.Add(933, "Υ");
_entityTable.Add(934, "Φ");
_entityTable.Add(935, "Χ");
_entityTable.Add(936, "Ψ");
_entityTable.Add(937, "Ω");
_entityTable.Add(945, "α");
_entityTable.Add(946, "β");
_entityTable.Add(947, "γ");
_entityTable.Add(948, "δ");
_entityTable.Add(949, "ε");
_entityTable.Add(950, "ζ");
_entityTable.Add(951, "η");
_entityTable.Add(952, "θ");
_entityTable.Add(953, "ι");
_entityTable.Add(954, "κ");
_entityTable.Add(955, "λ");
_entityTable.Add(956, "μ");
_entityTable.Add(957, "ν");
_entityTable.Add(958, "ξ");
_entityTable.Add(959, "ο");
_entityTable.Add(960, "π");
_entityTable.Add(961, "ρ");
_entityTable.Add(962, "ς");
_entityTable.Add(963, "σ");
_entityTable.Add(964, "τ");
_entityTable.Add(965, "υ");
_entityTable.Add(966, "φ");
_entityTable.Add(967, "χ");
_entityTable.Add(968, "ψ");
_entityTable.Add(969, "ω");
_entityTable.Add(977, "ϑ");
_entityTable.Add(978, "ϒ");
_entityTable.Add(982, "ϖ");
_entityTable.Add(8226, "•");
_entityTable.Add(8230, "…");
_entityTable.Add(8242, "′");
_entityTable.Add(8243, "″");
_entityTable.Add(8254, "‾");
_entityTable.Add(8260, "⁄");
_entityTable.Add(8472, "℘");
_entityTable.Add(8465, "ℑ");
_entityTable.Add(8476, "ℜ");
_entityTable.Add(8482, "™");
_entityTable.Add(8501, "ℵ");
_entityTable.Add(8592, "←");
_entityTable.Add(8593, "↑");
_entityTable.Add(8594, "→");
_entityTable.Add(8595, "↓");
_entityTable.Add(8596, "↔");
_entityTable.Add(8629, "↵");
_entityTable.Add(8656, "⇐");
_entityTable.Add(8657, "⇑");
_entityTable.Add(8658, "⇒");
_entityTable.Add(8659, "⇓");
_entityTable.Add(8660, "⇔");
_entityTable.Add(8704, "∀");
_entityTable.Add(8706, "∂");
_entityTable.Add(8707, "∃");
_entityTable.Add(8709, "∅");
_entityTable.Add(8711, "∇");
_entityTable.Add(8712, "∈");
_entityTable.Add(8713, "∉");
_entityTable.Add(8715, "∋");
_entityTable.Add(8719, "∏");
_entityTable.Add(8721, "∑");
_entityTable.Add(8722, "−");
_entityTable.Add(8727, "∗");
_entityTable.Add(8730, "√");
_entityTable.Add(8733, "∝");
_entityTable.Add(8734, "∞");
_entityTable.Add(8736, "∠");
_entityTable.Add(8743, "∧");
_entityTable.Add(8744, "∨");
_entityTable.Add(8745, "∩");
_entityTable.Add(8746, "∪");
_entityTable.Add(8747, "∫");
_entityTable.Add(8756, "∴");
_entityTable.Add(8764, "∼");
_entityTable.Add(8773, "≅");
_entityTable.Add(8776, "≈");
_entityTable.Add(8800, "≠");
_entityTable.Add(8801, "≡");
_entityTable.Add(8804, "≤");
_entityTable.Add(8805, "≥");
_entityTable.Add(8834, "⊂");
_entityTable.Add(8835, "⊃");
_entityTable.Add(8836, "⊄");
_entityTable.Add(8838, "⊆");
_entityTable.Add(8839, "⊇");
_entityTable.Add(8853, "⊕");
_entityTable.Add(8855, "⊗");
_entityTable.Add(8869, "⊥");
_entityTable.Add(8901, "⋅");
_entityTable.Add(8968, "⌈");
_entityTable.Add(8969, "⌉");
_entityTable.Add(8970, "⌊");
_entityTable.Add(8971, "⌋");
_entityTable.Add(9001, "⟨");
_entityTable.Add(9002, "⟩");
_entityTable.Add(9674, "◊");
_entityTable.Add(9824, "♠");
_entityTable.Add(9827, "♣");
_entityTable.Add(9829, "♥");
_entityTable.Add(9830, "♦");
_entityTable.Add(34, """);
//_entityTable.Add(38, "&");
_entityTable.Add(60, "<");
_entityTable.Add(62, ">");
_entityTable.Add(338, "Œ");
_entityTable.Add(339, "œ");
_entityTable.Add(352, "Š");
_entityTable.Add(353, "š");
_entityTable.Add(376, "Ÿ");
_entityTable.Add(710, "ˆ");
_entityTable.Add(732, "˜");
_entityTable.Add(8194, " ");
_entityTable.Add(8195, " ");
_entityTable.Add(8201, " ");
_entityTable.Add(8204, "‌");
_entityTable.Add(8205, "‍");
_entityTable.Add(8206, "‎");
_entityTable.Add(8207, "‏");
_entityTable.Add(8211, "–");
_entityTable.Add(8212, "—");
_entityTable.Add(8216, "‘");
_entityTable.Add(8217, "’");
_entityTable.Add(8218, "‚");
_entityTable.Add(8220, "“");
_entityTable.Add(8221, "”");
_entityTable.Add(8222, "„");
_entityTable.Add(8224, "†");
_entityTable.Add(8225, "‡");
_entityTable.Add(8240, "‰");
_entityTable.Add(8249, "‹");
_entityTable.Add(8250, "›");
_entityTable.Add(8364, "€");
}
/// <summary>
/// Converts US State Name to it's two-character abbreviation. Returns null if the state name was not found.
/// </summary>
/// <param name="stateName">US State Name (ie Texas)</param>
/// <returns></returns>
public static string USStateNameToAbbrev(string stateName)
{
stateName = stateName.ToUpper();
foreach(KeyValuePair<string, string> key in _USStateTable)
{
if(stateName == key.Key)
return key.Value;
}
return null;
}
/// <summary>
/// Converts a two-character US State Abbreviation to it's official Name Returns null if the abbreviation was not found.
/// </summary>
/// <param name="stateAbbrev">US State Name (ie Texas)</param>
/// <returns></returns>
public static string USStateAbbrevToName(string stateAbbrev)
{
stateAbbrev = stateAbbrev.ToUpper();
foreach(KeyValuePair<string, string> key in _USStateTable)
{
if(stateAbbrev == key.Value)
return key.Key;
}
return null;
}
/// <summary>
/// Fills the US States.
/// </summary>
private static void FillUSStates()
{
_USStateTable.Add("ALABAMA", "AL");
_USStateTable.Add("ALASKA", "AK");
_USStateTable.Add("AMERICAN SAMOA", "AS");
_USStateTable.Add("ARIZONA ", "AZ");
_USStateTable.Add("ARKANSAS", "AR");
_USStateTable.Add("CALIFORNIA ", "CA");
_USStateTable.Add("COLORADO ", "CO");
_USStateTable.Add("CONNECTICUT", "CT");
_USStateTable.Add("DELAWARE", "DE");
_USStateTable.Add("DISTRICT OF COLUMBIA", "DC");
_USStateTable.Add("FEDERATED STATES OF MICRONESIA", "FM");
_USStateTable.Add("FLORIDA", "FL");
_USStateTable.Add("GEORGIA", "GA");
_USStateTable.Add("GUAM ", "GU");
_USStateTable.Add("HAWAII", "HI");
_USStateTable.Add("IDAHO", "ID");
_USStateTable.Add("ILLINOIS", "IL");
_USStateTable.Add("INDIANA", "IN");
_USStateTable.Add("IOWA", "IA");
_USStateTable.Add("KANSAS", "KS");
_USStateTable.Add("KENTUCKY", "KY");
_USStateTable.Add("LOUISIANA", "LA");
_USStateTable.Add("MAINE", "ME");
_USStateTable.Add("MARSHALL ISLANDS", "MH");
_USStateTable.Add("MARYLAND", "MD");
_USStateTable.Add("MASSACHUSETTS", "MA");
_USStateTable.Add("MICHIGAN", "MI");
_USStateTable.Add("MINNESOTA", "MN");
_USStateTable.Add("MISSISSIPPI", "MS");
_USStateTable.Add("MISSOURI", "MO");
_USStateTable.Add("MONTANA", "MT");
_USStateTable.Add("NEBRASKA", "NE");
_USStateTable.Add("NEVADA", "NV");
_USStateTable.Add("NEW HAMPSHIRE", "NH");
_USStateTable.Add("NEW JERSEY", "NJ");
_USStateTable.Add("NEW MEXICO", "NM");
_USStateTable.Add("NEW YORK", "NY");
_USStateTable.Add("NORTH CAROLINA", "NC");
_USStateTable.Add("NORTH DAKOTA", "ND");
_USStateTable.Add("NORTHERN MARIANA ISLANDS", "MP");
_USStateTable.Add("OHIO", "OH");
_USStateTable.Add("OKLAHOMA", "OK");
_USStateTable.Add("OREGON", "OR");
_USStateTable.Add("PALAU", "PW");
_USStateTable.Add("PENNSYLVANIA", "PA");
_USStateTable.Add("PUERTO RICO", "PR");
_USStateTable.Add("RHODE ISLAND", "RI");
_USStateTable.Add("SOUTH CAROLINA", "SC");
_USStateTable.Add("SOUTH DAKOTA", "SD");
_USStateTable.Add("TENNESSEE", "TN");
_USStateTable.Add("TEXAS", "TX");
_USStateTable.Add("UTAH", "UT");
_USStateTable.Add("VERMONT", "VT");
_USStateTable.Add("VIRGIN ISLANDS", "VI");
_USStateTable.Add("VIRGINIA ", "VA");
_USStateTable.Add("WASHINGTON", "WA");
_USStateTable.Add("WEST VIRGINIA", "WV");
_USStateTable.Add("WISCONSIN", "WI");
_USStateTable.Add("WYOMING", "WY");
}
[Obsolete("Will be removed in future versions. Use Validation.IsAlpha instead")]
public static bool IsAlpha(string s)
{
return Validation.IsAlpha(s);
}
[Obsolete("Will be removed in future versions. Use Validation.IsAlphaNumeric instead")]
public static bool IsAlphaNumeric(string s)
{
return Validation.IsAlphaNumeric(s);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ActorGraphInterpreter.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.Event;
using Akka.Pattern;
using Akka.Streams.Stage;
using Akka.Util.Internal;
using Reactive.Streams;
// ReSharper disable MemberHidesStaticFromOuterClass
namespace Akka.Streams.Implementation.Fusing
{
internal class GraphModule : AtomicModule
{
public readonly IModule[] MaterializedValueIds;
public readonly GraphAssembly Assembly;
public GraphModule(GraphAssembly assembly, Shape shape, Attributes attributes, IModule[] materializedValueIds)
{
Assembly = assembly;
Shape = shape;
Attributes = attributes;
MaterializedValueIds = materializedValueIds;
}
public override Shape Shape { get; }
public override Attributes Attributes { get; }
public override IModule WithAttributes(Attributes attributes)
{
return new GraphModule(Assembly, Shape, attributes, MaterializedValueIds);
}
public override IModule CarbonCopy()
{
return new CopiedModule(Shape.DeepCopy(), Attributes.None, this);
}
public override IModule ReplaceShape(Shape newShape)
{
if (!newShape.Equals(Shape))
return CompositeModule.Create(this, newShape);
return this;
}
public override string ToString() => $"GraphModule\n {Assembly.ToString().Replace("\n", "\n ")}\n shape={Shape}, attributes={Attributes}";
}
internal sealed class GraphInterpreterShell
{
private readonly GraphAssembly _assembly;
private readonly IInHandler[] _inHandlers;
private readonly IOutHandler[] _outHandlers;
private readonly GraphStageLogic[] _logics;
private readonly Shape _shape;
private readonly ActorMaterializerSettings _settings;
internal readonly ActorMaterializerImpl Materializer;
/// <summary>
/// Limits the number of events processed by the interpreter before scheduling
/// a self-message for fairness with other actors. The basic assumption here is
/// to give each input buffer slot a chance to run through the whole pipeline
/// and back (for the elements).
/// </summary>
private readonly int _shellEventLimit;
// Limits the number of events processed by the interpreter on an abort event.
private readonly int _abortLimit;
private readonly ActorGraphInterpreter.BatchingActorInputBoundary[] _inputs;
private readonly ActorGraphInterpreter.IActorOutputBoundary[] _outputs;
private ILoggingAdapter _log;
private GraphInterpreter _interpreter;
private int _subscribersPending;
private int _publishersPending;
private bool _resumeScheduled;
private bool _waitingForShutdown;
private Action<object> _enqueueToShourtCircuit;
private readonly ActorGraphInterpreter.Resume _resume;
public GraphInterpreterShell(GraphAssembly assembly, IInHandler[] inHandlers, IOutHandler[] outHandlers, GraphStageLogic[] logics, Shape shape, ActorMaterializerSettings settings, ActorMaterializerImpl materializer)
{
_assembly = assembly;
_inHandlers = inHandlers;
_outHandlers = outHandlers;
_logics = logics;
_shape = shape;
_settings = settings;
Materializer = materializer;
_inputs = new ActorGraphInterpreter.BatchingActorInputBoundary[shape.Inlets.Count()];
_outputs = new ActorGraphInterpreter.IActorOutputBoundary[shape.Outlets.Count()];
_subscribersPending = _inputs.Length;
_publishersPending = _outputs.Length;
_shellEventLimit = settings.MaxInputBufferSize * (assembly.Inlets.Length + assembly.Outlets.Length);
_abortLimit = _shellEventLimit * 2;
_resume = new ActorGraphInterpreter.Resume(this);
IsTerminated = false;
}
public bool IsInitialized => Self != null;
public bool IsTerminated { get; private set; }
public bool CanShutdown => _subscribersPending + _publishersPending == 0;
public IActorRef Self { get; private set; }
public ILoggingAdapter Log => _log ?? (_log = GetLogger());
public GraphInterpreter Interpreter => _interpreter ?? (_interpreter = GetInterpreter());
public int Init(IActorRef self, SubFusingActorMaterializerImpl subMat, Action<object> enqueueToShourtCircuit, int eventLimit)
{
Self = self;
_enqueueToShourtCircuit = enqueueToShourtCircuit;
for (int i = 0; i < _inputs.Length; i++)
{
var input = new ActorGraphInterpreter.BatchingActorInputBoundary(_settings.MaxInputBufferSize, i);
_inputs[i] = input;
Interpreter.AttachUpstreamBoundary(i, input);
}
var offset = _assembly.ConnectionCount - _outputs.Length;
for (int i = 0; i < _outputs.Length; i++)
{
var outputType = _shape.Outlets[i].GetType().GetGenericArguments().First();
var output = (ActorGraphInterpreter.IActorOutputBoundary) typeof(ActorGraphInterpreter.ActorOutputBoundary<>).Instantiate(outputType, Self, this, i);
_outputs[i] = output;
Interpreter.AttachDownstreamBoundary(i + offset, (GraphInterpreter.DownstreamBoundaryStageLogic) output);
}
Interpreter.Init(subMat);
return RunBatch(eventLimit);
}
public int Receive(ActorGraphInterpreter.IBoundaryEvent e, int eventLimit)
{
_resumeScheduled = false;
if (_waitingForShutdown)
{
if (e is ActorGraphInterpreter.ExposedPublisher)
{
var exposedPublisher = (ActorGraphInterpreter.ExposedPublisher) e;
_outputs[exposedPublisher.Id].ExposedPublisher(exposedPublisher.Publisher);
_publishersPending--;
if (CanShutdown) IsTerminated = true;
}
else if (e is ActorGraphInterpreter.OnSubscribe)
{
var onSubscribe = (ActorGraphInterpreter.OnSubscribe) e;
ReactiveStreamsCompliance.TryCancel(onSubscribe.Subscription);
_subscribersPending--;
if (CanShutdown) IsTerminated = true;
}
else if (e is ActorGraphInterpreter.Abort)
{
TryAbort(new TimeoutException(
$"Streaming actor has been already stopped processing (normally), but not all of its inputs or outputs have been subscribed in [{_settings.SubscriptionTimeoutSettings.Timeout}]. Aborting actor now."));
}
return eventLimit;
}
// Cases that are most likely on the hot path, in decreasing order of frequency
if (e is ActorGraphInterpreter.OnNext)
{
var onNext = (ActorGraphInterpreter.OnNext) e;
if (GraphInterpreter.IsDebug)
Console.WriteLine($"{Interpreter.Name} OnNext {onNext.Event} id={onNext.Id}");
_inputs[onNext.Id].OnNext(onNext.Event);
return RunBatch(eventLimit);
}
if (e is ActorGraphInterpreter.RequestMore)
{
var requestMore = (ActorGraphInterpreter.RequestMore) e;
if (GraphInterpreter.IsDebug)
Console.WriteLine($"{Interpreter.Name} Request {requestMore.Demand} id={requestMore.Id}");
_outputs[requestMore.Id].RequestMore(requestMore.Demand);
return RunBatch(eventLimit);
}
if (e is ActorGraphInterpreter.Resume)
{
if (GraphInterpreter.IsDebug) Console.WriteLine($"{Interpreter.Name} Resume");
if (Interpreter.IsSuspended)
return RunBatch(eventLimit);
return eventLimit;
}
if (e is ActorGraphInterpreter.AsyncInput)
{
var asyncInput = (ActorGraphInterpreter.AsyncInput) e;
Interpreter.RunAsyncInput(asyncInput.Logic, asyncInput.Event, asyncInput.Handler);
if (eventLimit == 1 && _interpreter.IsSuspended)
{
SendResume(true);
return 0;
}
return RunBatch(eventLimit - 1);
}
// Initialization and completion messages
if (e is ActorGraphInterpreter.OnError)
{
var onError = (ActorGraphInterpreter.OnError) e;
if (GraphInterpreter.IsDebug) Console.WriteLine($"{Interpreter.Name} OnError id={onError.Id}");
_inputs[onError.Id].OnError(onError.Cause);
return RunBatch(eventLimit);
}
if (e is ActorGraphInterpreter.OnComplete)
{
var onComplete = (ActorGraphInterpreter.OnComplete) e;
if (GraphInterpreter.IsDebug) Console.WriteLine($"{Interpreter.Name} OnComplete id={onComplete.Id}");
_inputs[onComplete.Id].OnComplete();
return RunBatch(eventLimit);
}
if (e is ActorGraphInterpreter.OnSubscribe)
{
var onSubscribe = (ActorGraphInterpreter.OnSubscribe) e;
if (GraphInterpreter.IsDebug) Console.WriteLine($"{Interpreter.Name} OnSubscribe id={onSubscribe.Id}");
_subscribersPending--;
_inputs[onSubscribe.Id].OnSubscribe(onSubscribe.Subscription);
return RunBatch(eventLimit);
}
if (e is ActorGraphInterpreter.Cancel)
{
var cancel = (ActorGraphInterpreter.Cancel) e;
if (GraphInterpreter.IsDebug) Console.WriteLine($"{Interpreter.Name} Cancel id={cancel.Id}");
_outputs[cancel.Id].Cancel();
return RunBatch(eventLimit);
}
if (e is ActorGraphInterpreter.SubscribePending)
{
var subscribePending = (ActorGraphInterpreter.SubscribePending) e;
_outputs[subscribePending.Id].SubscribePending();
return eventLimit;
}
if (e is ActorGraphInterpreter.ExposedPublisher)
{
var exposedPublisher = (ActorGraphInterpreter.ExposedPublisher) e;
_publishersPending--;
_outputs[exposedPublisher.Id].ExposedPublisher(exposedPublisher.Publisher);
return eventLimit;
}
return eventLimit;
}
/**
* Attempts to abort execution, by first propagating the reason given until either
* - the interpreter successfully finishes
* - the event limit is reached
* - a new error is encountered
*/
public void TryAbort(Exception reason)
{
// This should handle termination while interpreter is running. If the upstream have been closed already this
// call has no effect and therefore do the right thing: nothing.
try
{
foreach (var input in _inputs)
input.OnInternalError(reason);
Interpreter.Execute(_abortLimit);
Interpreter.Finish();
}
catch (Exception) { /* swallow? */ }
finally
{
IsTerminated = true;
// Will only have an effect if the above call to the interpreter failed to emit a proper failure to the downstream
// otherwise this will have no effect
foreach (var output in _outputs) output.Fail(reason);
foreach (var input in _inputs) input.Cancel();
}
}
private int RunBatch(int actorEventLimit)
{
try
{
var usingShellLimit = _shellEventLimit < actorEventLimit;
var remainingQuota = _interpreter.Execute(Math.Min(actorEventLimit, _shellEventLimit));
if (Interpreter.IsCompleted)
{
// Cannot stop right away if not completely subscribed
if (CanShutdown) IsTerminated = true;
else
{
_waitingForShutdown = true;
Materializer.ScheduleOnce(_settings.SubscriptionTimeoutSettings.Timeout,
() => Self.Tell(new ActorGraphInterpreter.Abort(this)));
}
}
else if (Interpreter.IsSuspended && !_resumeScheduled)
SendResume(!usingShellLimit);
return usingShellLimit ? actorEventLimit - _shellEventLimit + remainingQuota : remainingQuota;
}
catch (Exception reason)
{
TryAbort(reason);
return actorEventLimit - 1;
}
}
private void SendResume(bool sendResume)
{
_resumeScheduled = true;
if (sendResume)
Self.Tell(_resume);
else
_enqueueToShourtCircuit(_resume);
}
private GraphInterpreter GetInterpreter()
{
return new GraphInterpreter(_assembly, Materializer, Log, _inHandlers, _outHandlers, _logics,
(logic, @event, handler) =>
{
var asyncInput = new ActorGraphInterpreter.AsyncInput(this, logic, @event, handler);
var currentInterpreter = GraphInterpreter.CurrentInterpreterOrNull;
if (currentInterpreter == null || currentInterpreter.Context != Self)
Self.Tell(new ActorGraphInterpreter.AsyncInput(this, logic, @event, handler));
else
_enqueueToShourtCircuit(asyncInput);
}, _settings.IsFuzzingMode, Self);
}
private BusLogging GetLogger()
{
return new BusLogging(Materializer.System.EventStream, Self.ToString(), typeof(GraphInterpreterShell), new DefaultLogMessageFormatter());
}
public override string ToString() => $"GraphInterpreterShell\n {_assembly.ToString().Replace("\n", "\n ")}";
}
internal class ActorGraphInterpreter : ActorBase
{
#region messages
public interface IBoundaryEvent : INoSerializationVerificationNeeded, IDeadLetterSuppression
{
GraphInterpreterShell Shell { get; }
}
public struct OnError : IBoundaryEvent
{
public readonly int Id;
public readonly Exception Cause;
public OnError(GraphInterpreterShell shell, int id, Exception cause)
{
Shell = shell;
Id = id;
Cause = cause;
}
public GraphInterpreterShell Shell { get; }
}
public struct OnComplete : IBoundaryEvent
{
public readonly int Id;
public OnComplete(GraphInterpreterShell shell, int id)
{
Shell = shell;
Id = id;
}
public GraphInterpreterShell Shell { get; }
}
public struct OnNext : IBoundaryEvent
{
public readonly int Id;
public readonly object Event;
public OnNext(GraphInterpreterShell shell, int id, object @event)
{
Shell = shell;
Id = id;
Event = @event;
}
public GraphInterpreterShell Shell { get; }
}
public struct OnSubscribe : IBoundaryEvent
{
public readonly int Id;
public readonly ISubscription Subscription;
public OnSubscribe(GraphInterpreterShell shell, int id, ISubscription subscription)
{
Shell = shell;
Id = id;
Subscription = subscription;
}
public GraphInterpreterShell Shell { get; }
}
public struct RequestMore : IBoundaryEvent
{
public readonly int Id;
public readonly long Demand;
public RequestMore(GraphInterpreterShell shell, int id, long demand)
{
Shell = shell;
Id = id;
Demand = demand;
}
public GraphInterpreterShell Shell { get; }
}
public struct Cancel : IBoundaryEvent
{
public readonly int Id;
public Cancel(GraphInterpreterShell shell, int id)
{
Shell = shell;
Id = id;
}
public GraphInterpreterShell Shell { get; }
}
public struct SubscribePending : IBoundaryEvent
{
public readonly int Id;
public SubscribePending(GraphInterpreterShell shell, int id)
{
Shell = shell;
Id = id;
}
public GraphInterpreterShell Shell { get; }
}
public struct ExposedPublisher : IBoundaryEvent
{
public readonly int Id;
public readonly IActorPublisher Publisher;
public ExposedPublisher(GraphInterpreterShell shell, int id, IActorPublisher publisher)
{
Shell = shell;
Id = id;
Publisher = publisher;
}
public GraphInterpreterShell Shell { get; }
}
public struct AsyncInput : IBoundaryEvent
{
public readonly GraphStageLogic Logic;
public readonly object Event;
public readonly Action<object> Handler;
public AsyncInput(GraphInterpreterShell shell, GraphStageLogic logic, object @event, Action<object> handler)
{
Shell = shell;
Logic = logic;
Event = @event;
Handler = handler;
}
public GraphInterpreterShell Shell { get; }
}
public struct Resume : IBoundaryEvent
{
public Resume(GraphInterpreterShell shell)
{
Shell = shell;
}
public GraphInterpreterShell Shell { get; }
}
public struct Abort : IBoundaryEvent
{
public Abort(GraphInterpreterShell shell)
{
Shell = shell;
}
public GraphInterpreterShell Shell { get; }
}
private class ShellRegistered
{
public static readonly ShellRegistered Instance = new ShellRegistered();
private ShellRegistered()
{
}
}
#endregion
#region internal classes
public sealed class BoundaryPublisher<T> : ActorPublisher<T>
{
public BoundaryPublisher(IActorRef parent, GraphInterpreterShell shell, int id) : base(parent)
{
_wakeUpMessage = new SubscribePending(shell, id);
}
private readonly SubscribePending _wakeUpMessage;
protected override object WakeUpMessage => _wakeUpMessage;
}
public sealed class BoundarySubscription : ISubscription
{
private readonly IActorRef _parent;
private readonly GraphInterpreterShell _shell;
private readonly int _id;
public BoundarySubscription(IActorRef parent, GraphInterpreterShell shell, int id)
{
_parent = parent;
_shell = shell;
_id = id;
}
public void Request(long elements) => _parent.Tell(new RequestMore(_shell, _id, elements));
public void Cancel() => _parent.Tell(new Cancel(_shell, _id));
public override string ToString() => $"BoundarySubscription[{_parent}, {_id}]";
}
public sealed class BoundarySubscriber<T> : ISubscriber<T>
{
private readonly IActorRef _parent;
private readonly GraphInterpreterShell _shell;
private readonly int _id;
public BoundarySubscriber(IActorRef parent, GraphInterpreterShell shell, int id)
{
_parent = parent;
_shell = shell;
_id = id;
}
public void OnSubscribe(ISubscription subscription)
{
ReactiveStreamsCompliance.RequireNonNullSubscription(subscription);
_parent.Tell(new OnSubscribe(_shell, _id, subscription));
}
public void OnError(Exception cause)
{
ReactiveStreamsCompliance.RequireNonNullException(cause);
_parent.Tell(new OnError(_shell, _id, cause));
}
public void OnComplete() => _parent.Tell(new OnComplete(_shell, _id));
public void OnNext(T element)
{
ReactiveStreamsCompliance.RequireNonNullElement(element);
_parent.Tell(new OnNext(_shell, _id, element));
}
}
public class BatchingActorInputBoundary : GraphInterpreter.UpstreamBoundaryStageLogic
{
#region OutHandler
private sealed class OutHandler : Stage.OutHandler
{
private readonly BatchingActorInputBoundary _that;
public OutHandler(BatchingActorInputBoundary that)
{
_that = that;
}
public override void OnPull()
{
var elementsCount = _that._inputBufferElements;
var upstreamCompleted = _that._upstreamCompleted;
if (elementsCount > 1) _that.Push(_that.Out, _that.Dequeue());
else if (elementsCount == 1)
{
if (upstreamCompleted)
{
_that.Push(_that.Out, _that.Dequeue());
_that.Complete(_that.Out);
}
else _that.Push(_that.Out, _that.Dequeue());
}
else if (upstreamCompleted) _that.Complete(_that.Out);
}
public override void OnDownstreamFinish() => _that.Cancel();
public override string ToString() => _that.ToString();
}
#endregion
private readonly int _size;
private readonly int _id;
private readonly object[] _inputBuffer;
private readonly int _indexMask;
private ISubscription _upstream;
private int _inputBufferElements;
private int _nextInputElementCursor;
private bool _upstreamCompleted;
private bool _downstreamCanceled;
private readonly int _requestBatchSize;
private int _batchRemaining;
private readonly Outlet _outlet;
public BatchingActorInputBoundary(int size, int id)
{
if (size <= 0) throw new ArgumentException("Buffer size cannot be zero", nameof(size));
if ((size & (size - 1)) != 0) throw new ArgumentException("Buffer size must be power of two", nameof(size));
_size = size;
_id = id;
_inputBuffer = new object[size];
_indexMask = size - 1;
_requestBatchSize = Math.Max(1, _inputBuffer.Length/2);
_batchRemaining = _requestBatchSize;
_outlet = new Outlet<object>("UpstreamBoundary" + id) { Id = 0 };
SetHandler(_outlet, new OutHandler(this));
}
public override Outlet Out => _outlet;
// Call this when an error happens that does not come from the usual onError channel
// (exceptions while calling RS interfaces, abrupt termination etc)
public void OnInternalError(Exception reason)
{
if (!(_upstreamCompleted || _downstreamCanceled) && !ReferenceEquals(_upstream, null))
_upstream.Cancel();
if (!IsClosed(Out))
OnError(reason);
}
public void OnError(Exception reason)
{
if (!_upstreamCompleted || !_downstreamCanceled)
{
_upstreamCompleted = true;
Clear();
Fail(Out, reason);
}
}
public void OnComplete()
{
if (!_upstreamCompleted)
{
_upstreamCompleted = true;
if (_inputBufferElements == 0)
Complete(Out);
}
}
public void OnSubscribe(ISubscription subscription)
{
if (subscription == null) throw new ArgumentException("Subscription cannot be null");
if (_upstreamCompleted) ReactiveStreamsCompliance.TryCancel(subscription);
else if (_downstreamCanceled)
{
_upstreamCompleted = true;
ReactiveStreamsCompliance.TryCancel(subscription);
}
else
{
_upstream = subscription;
// prefetch
ReactiveStreamsCompliance.TryRequest(_upstream, _inputBuffer.Length);
}
}
public void OnNext(object element)
{
if (!_upstreamCompleted)
{
if (_inputBufferElements == _size)
throw new IllegalStateException("Input buffer overrun");
_inputBuffer[(_nextInputElementCursor + _inputBufferElements) & _indexMask] = element;
_inputBufferElements++;
if (IsAvailable(Out))
Push(Out, Dequeue());
}
}
public void Cancel()
{
_downstreamCanceled = true;
if (!_upstreamCompleted)
{
_upstreamCompleted = true;
if (!ReferenceEquals(_upstream, null))
ReactiveStreamsCompliance.TryCancel(_upstream);
Clear();
}
}
private object Dequeue()
{
var element = _inputBuffer[_nextInputElementCursor];
if (element == null)
throw new IllegalStateException("Internal queue must never contain a null");
_inputBuffer[_nextInputElementCursor] = null;
_batchRemaining--;
if (_batchRemaining == 0 && !_upstreamCompleted)
{
ReactiveStreamsCompliance.TryRequest(_upstream, _requestBatchSize);
_batchRemaining = _requestBatchSize;
}
_inputBufferElements--;
_nextInputElementCursor = (_nextInputElementCursor + 1) & _indexMask;
return element;
}
private void Clear()
{
_inputBuffer.Initialize();
_inputBufferElements = 0;
}
public override string ToString() => $"BatchingActorInputBoundary(id={_id}, fill={_inputBufferElements}/{_size}, completed={_upstreamCompleted}, canceled={_downstreamCanceled})";
}
public interface IActorOutputBoundary
{
void SubscribePending();
void ExposedPublisher(IActorPublisher publisher);
void RequestMore(long elements);
void Cancel();
void Fail(Exception reason);
}
public class ActorOutputBoundary<T> : GraphInterpreter.DownstreamBoundaryStageLogic, IActorOutputBoundary
{
#region InHandler
private sealed class InHandler : Stage.InHandler
{
private readonly ActorOutputBoundary<T> _that;
public InHandler(ActorOutputBoundary<T> that)
{
_that = that;
}
public override void OnPush()
{
_that.OnNext(_that.Grab<T>(_that.In));
if (_that._downstreamCompleted)
_that.Cancel(_that.In);
else if (_that._downstreamDemand > 0)
_that.Pull<T>(_that.In);
}
public override void OnUpstreamFinish() => _that.Complete();
public override void OnUpstreamFailure(Exception e) => _that.Fail(e);
public override string ToString() => _that.ToString();
}
#endregion
private readonly IActorRef _actor;
private readonly GraphInterpreterShell _shell;
private readonly int _id;
private ActorPublisher<T> _exposedPublisher;
private ISubscriber<T> _subscriber;
private long _downstreamDemand;
// This flag is only used if complete/fail is called externally since this op turns into a Finished one inside the
// interpreter (i.e. inside this op this flag has no effects since if it is completed the op will not be invoked)
private bool _downstreamCompleted;
// when upstream failed before we got the exposed publisher
private Exception _upstreamFailed;
private bool _upstreamCompleted;
private readonly Inlet<T> _inlet;
public ActorOutputBoundary(IActorRef actor, GraphInterpreterShell shell, int id)
{
_actor = actor;
_shell = shell;
_id = id;
_inlet = new Inlet<T>("UpstreamBoundary" + id) { Id = 0 };
SetHandler(_inlet, new InHandler(this));
}
public override Inlet In => _inlet;
public void RequestMore(long elements)
{
if (elements < 1)
{
Cancel((Inlet<T>) In);
Fail(ReactiveStreamsCompliance.NumberOfElementsInRequestMustBePositiveException);
}
else
{
_downstreamDemand += elements;
if (_downstreamDemand < 0)
_downstreamDemand = long.MaxValue; // Long overflow, Reactive Streams Spec 3:17: effectively unbounded
if (!HasBeenPulled(In) && !IsClosed(In))
Pull<T>(In);
}
}
public void SubscribePending()
{
foreach (var subscriber in _exposedPublisher.TakePendingSubscribers())
{
if (ReferenceEquals(_subscriber, null))
{
_subscriber = subscriber;
ReactiveStreamsCompliance.TryOnSubscribe(_subscriber, new BoundarySubscription(_actor, _shell, _id));
if (GraphInterpreter.IsDebug)
Console.WriteLine($"{Interpreter.Name} Subscribe subscriber={subscriber}");
}
else ReactiveStreamsCompliance.RejectAdditionalSubscriber(subscriber, GetType().FullName);
}
}
void IActorOutputBoundary.ExposedPublisher(IActorPublisher publisher) => ExposedPublisher((ActorPublisher<T>) publisher);
public void ExposedPublisher(ActorPublisher<T> publisher)
{
_exposedPublisher = publisher;
if (_upstreamFailed != null)
publisher.Shutdown(_upstreamFailed);
else
{
if (_upstreamCompleted)
publisher.Shutdown(null);
}
}
public void Cancel()
{
_downstreamCompleted = true;
_subscriber = null;
_exposedPublisher.Shutdown(new NormalShutdownException("UpstreamBoundary"));
Cancel(In);
}
public void Fail(Exception reason)
{
// No need to fail if had already been cancelled, or we closed earlier
if (!(_downstreamCompleted || _upstreamCompleted))
{
_upstreamCompleted = true;
_upstreamFailed = reason;
if (!ReferenceEquals(_exposedPublisher, null))
_exposedPublisher.Shutdown(reason);
if (!ReferenceEquals(_subscriber, null) && !(reason is ISpecViolation))
ReactiveStreamsCompliance.TryOnError(_subscriber, reason);
}
}
private void OnNext(T element)
{
_downstreamDemand--;
ReactiveStreamsCompliance.TryOnNext(_subscriber, element);
}
private void Complete()
{
// No need to complete if had already been cancelled, or we closed earlier
if (!(_upstreamCompleted || _downstreamCompleted))
{
_upstreamCompleted = true;
if (!ReferenceEquals(_exposedPublisher, null))
_exposedPublisher.Shutdown(null);
if (!ReferenceEquals(_subscriber, null))
ReactiveStreamsCompliance.TryOnComplete(_subscriber);
}
}
}
#endregion
public static Props Props(GraphInterpreterShell shell)
{
return Actor.Props.Create(() => new ActorGraphInterpreter(shell)).WithDeploy(Deploy.Local);
}
private ISet<GraphInterpreterShell> _activeInterpreters = new HashSet<GraphInterpreterShell>();
private readonly Queue<GraphInterpreterShell> _newShells = new Queue<GraphInterpreterShell>();
private readonly SubFusingActorMaterializerImpl _subFusingMaterializerImpl;
private readonly GraphInterpreterShell _initial;
private ILoggingAdapter _log;
//this limits number of messages that can be processed synchronously during one actor receive.
private readonly int _eventLimit;
private int _currentLimit;
//this is a var in order to save the allocation when no short-circuiting actually happens
private Queue<object> _shortCircuitBuffer;
public ActorGraphInterpreter(GraphInterpreterShell shell)
{
_initial = shell;
_subFusingMaterializerImpl = new SubFusingActorMaterializerImpl(shell.Materializer, RegisterShell);
_eventLimit = _initial.Materializer.Settings.SyncProcessingLimit;
_currentLimit = _eventLimit;
}
public ILoggingAdapter Log => _log ?? (_log = Context.GetLogger());
private void EnqueueToShortCircuit(object input)
{
if(_shortCircuitBuffer == null)
_shortCircuitBuffer = new Queue<object>();
_shortCircuitBuffer.Enqueue(input);
}
private bool TryInit(GraphInterpreterShell shell)
{
try
{
_currentLimit = shell.Init(Self, _subFusingMaterializerImpl, EnqueueToShortCircuit, _currentLimit);
if (GraphInterpreter.IsDebug)
Console.WriteLine($"registering new shell in {_initial}\n {shell.ToString().Replace("\n", "\n ")}");
if (shell.IsTerminated)
return false;
_activeInterpreters.Add(shell);
return true;
}
catch (Exception e)
{
if (Log.IsErrorEnabled)
Log.Error(e, "Initialization of GraphInterpreterShell failed for {0}", shell);
return false;
}
}
public IActorRef RegisterShell(GraphInterpreterShell shell)
{
_newShells.Enqueue(shell);
EnqueueToShortCircuit(ShellRegistered.Instance);
return Self;
}
// Avoid performing the initialization (which starts the first RunBatch())
// within RegisterShell in order to avoid unbounded recursion.
private void FinishShellRegistration()
{
if (_newShells.Count == 0)
{
if (_activeInterpreters.Count == 0)
Context.Stop(Self);
}
else
{
var shell = _newShells.Dequeue();
if (shell.IsInitialized)
{
// yes, this steals another shell's Resume, but that's okay because extra ones will just not do anything
FinishShellRegistration();
}
else if (!TryInit(shell))
{
if (_activeInterpreters.Count == 0)
FinishShellRegistration();
}
}
}
protected override void PreStart()
{
TryInit(_initial);
if (_activeInterpreters.Count == 0)
Context.Stop(Self);
else if (_shortCircuitBuffer != null)
ShortCircuitBatch();
}
private void ShortCircuitBatch()
{
while (_shortCircuitBuffer.Count != 0 && _currentLimit > 0 && _activeInterpreters.Count != 0)
{
var element = _shortCircuitBuffer.Dequeue();
var boundary = element as IBoundaryEvent;
if (boundary != null)
ProcessEvent(boundary);
else if (element is ShellRegistered)
FinishShellRegistration();
}
if(_shortCircuitBuffer.Count != 0 && _currentLimit == 0)
Self.Tell(ShellRegistered.Instance);
}
private void ProcessEvent(IBoundaryEvent b)
{
var shell = b.Shell;
if (!shell.IsTerminated && (shell.IsInitialized || TryInit(shell)))
{
_currentLimit = shell.Receive(b, _currentLimit);
if (shell.IsTerminated)
{
_activeInterpreters.Remove(shell);
if(_activeInterpreters.Count == 0 && _newShells.Count == 0)
Context.Stop(Self);
}
}
}
protected override bool Receive(object message)
{
if (message is IBoundaryEvent)
{
_currentLimit = _eventLimit;
ProcessEvent((IBoundaryEvent)message);
if(_shortCircuitBuffer != null)
ShortCircuitBatch();
}
else if (message is ShellRegistered)
{
_currentLimit = _eventLimit;
if (_shortCircuitBuffer != null)
ShortCircuitBatch();
}
else if (message is StreamSupervisor.PrintDebugDump)
{
Console.WriteLine("ActiveShells:");
_activeInterpreters.ForEach(shell =>
{
Console.WriteLine(" " + shell.ToString().Replace(@"\n", @"\n "));
shell.Interpreter.DumpWaits();
});
Console.WriteLine("NewShells:");
_newShells.ForEach(shell =>
{
Console.WriteLine(" " + shell.ToString().Replace(@"\n", @"\n "));
shell.Interpreter.DumpWaits();
});
}
else
return false;
return true;
}
protected override void PostStop()
{
foreach (var shell in _activeInterpreters)
shell.TryAbort(new AbruptTerminationException(Self));
_activeInterpreters = new HashSet<GraphInterpreterShell>();
foreach (var shell in _newShells)
{
if (TryInit(shell))
shell.TryAbort(new AbruptTerminationException(Self));
}
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils
{
using System.Collections.Generic;
using System.IO;
/// <summary>
/// Converts a Buffer into a Stream.
/// </summary>
public class BufferStream : SparseStream
{
private IBuffer _buffer;
private FileAccess _access;
private long _position;
/// <summary>
/// Initializes a new instance of the BufferStream class.
/// </summary>
/// <param name="buffer">The buffer to use.</param>
/// <param name="access">The access permitted to clients.</param>
public BufferStream(IBuffer buffer, FileAccess access)
{
_buffer = buffer;
_access = access;
}
/// <summary>
/// Gets an indication of whether read access is permitted.
/// </summary>
public override bool CanRead
{
get { return _access != FileAccess.Write; }
}
/// <summary>
/// Gets an indication of whether seeking is permitted.
/// </summary>
public override bool CanSeek
{
get { return true; }
}
/// <summary>
/// Gets an indication of whether write access is permitted.
/// </summary>
public override bool CanWrite
{
get { return _access != FileAccess.Read; }
}
/// <summary>
/// Gets the length of the stream (the capacity of the underlying buffer).
/// </summary>
public override long Length
{
get { return _buffer.Capacity; }
}
/// <summary>
/// Gets and sets the current position within the stream.
/// </summary>
public override long Position
{
get { return _position; }
set { _position = value; }
}
/// <summary>
/// Gets the stored extents within the sparse stream.
/// </summary>
public override IEnumerable<StreamExtent> Extents
{
get { return _buffer.Extents; }
}
/// <summary>
/// Flushes all data to the underlying storage.
/// </summary>
public override void Flush()
{
}
/// <summary>
/// Reads a number of bytes from the stream.
/// </summary>
/// <param name="buffer">The destination buffer.</param>
/// <param name="offset">The start offset within the destination buffer.</param>
/// <param name="count">The number of bytes to read.</param>
/// <returns>The number of bytes read.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (!CanRead)
{
throw new IOException("Attempt to read from write-only stream");
}
Utilities.AssertBufferParameters(buffer, offset, count);
int numRead = _buffer.Read(_position, buffer, offset, count);
_position += numRead;
return numRead;
}
/// <summary>
/// Changes the current stream position.
/// </summary>
/// <param name="offset">The origin-relative stream position.</param>
/// <param name="origin">The origin for the stream position.</param>
/// <returns>The new stream position.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
long effectiveOffset = offset;
if (origin == SeekOrigin.Current)
{
effectiveOffset += _position;
}
else if (origin == SeekOrigin.End)
{
effectiveOffset += _buffer.Capacity;
}
if (effectiveOffset < 0)
{
throw new IOException("Attempt to move before beginning of disk");
}
else
{
_position = effectiveOffset;
return _position;
}
}
/// <summary>
/// Sets the length of the stream (the underlying buffer's capacity).
/// </summary>
/// <param name="value">The new length of the stream.</param>
public override void SetLength(long value)
{
_buffer.SetCapacity(value);
}
/// <summary>
/// Writes a buffer to the stream.
/// </summary>
/// <param name="buffer">The buffer to write.</param>
/// <param name="offset">The starting offset within buffer.</param>
/// <param name="count">The number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (!CanWrite)
{
throw new IOException("Attempt to write to read-only stream");
}
Utilities.AssertBufferParameters(buffer, offset, count);
_buffer.Write(_position, buffer, offset, count);
_position += count;
}
/// <summary>
/// Clears bytes from the stream.
/// </summary>
/// <param name="count">The number of bytes (from the current position) to clear.</param>
/// <remarks>
/// <para>Logically equivalent to writing <c>count</c> null/zero bytes to the stream, some
/// implementations determine that some (or all) of the range indicated is not actually
/// stored. There is no direct, automatic, correspondence to clearing bytes and them
/// not being represented as an 'extent' - for example, the implementation of the underlying
/// stream may not permit fine-grained extent storage.</para>
/// <para>It is always safe to call this method to 'zero-out' a section of a stream, regardless of
/// the underlying stream implementation.</para>
/// </remarks>
public override void Clear(int count)
{
if (!CanWrite)
{
throw new IOException("Attempt to erase bytes in a read-only stream");
}
_buffer.Clear(_position, count);
_position += count;
}
/// <summary>
/// Gets the parts of a stream that are stored, within a specified range.
/// </summary>
/// <param name="start">The offset of the first byte of interest.</param>
/// <param name="count">The number of bytes of interest.</param>
/// <returns>An enumeration of stream extents, indicating stored bytes.</returns>
public override IEnumerable<StreamExtent> GetExtentsInRange(long start, long count)
{
return _buffer.GetExtentsInRange(start, count);
}
}
}
| |
#define USE_TRACING
using System;
using Google.GData.Extensions;
namespace Google.GData.Documents
{
public class ArchiveEntry : DocumentEntry
{
/// <summary>
/// ArchiveConversion collection
/// </summary>
private ExtensionCollection<ArchiveConversion> archiveConversions;
/// <summary>
/// ArchiveFailure collection
/// </summary>
private ExtensionCollection<ArchiveFailure> archiveFailures;
/// <summary>
/// ArchiveResourceId collection
/// </summary>
private ExtensionCollection<ArchiveResourceId> archiveResourceIds;
/// <summary>
/// Constructs a new ArchiveEntry instance.
/// </summary>
public ArchiveEntry()
{
AddExtension(new ArchiveResourceId());
AddExtension(new ArchiveConversion());
AddExtension(new ArchiveNotify());
AddExtension(new ArchiveStatus());
AddExtension(new ArchiveComplete());
AddExtension(new ArchiveTotal());
AddExtension(new ArchiveTotalComplete());
AddExtension(new ArchiveTotalFailure());
AddExtension(new ArchiveFailure());
AddExtension(new ArchiveNotifyStatus());
}
public string ArchiveId
{
get
{
if (Id == null || Id.AbsoluteUri == null)
{
return null;
}
string uri = Id.AbsoluteUri;
return uri.Substring(uri.LastIndexOf('/') + 1);
}
}
/// <summary>
/// ArchiveResourceId collection.
/// </summary>
public ExtensionCollection<ArchiveResourceId> ArchiveResourceIds
{
get
{
if (archiveResourceIds == null)
{
archiveResourceIds = new ExtensionCollection<ArchiveResourceId>(this);
}
return archiveResourceIds;
}
}
/// <summary>
/// ArchiveConversion collection.
/// </summary>
public ExtensionCollection<ArchiveConversion> ArchiveConversions
{
get
{
if (archiveConversions == null)
{
archiveConversions = new ExtensionCollection<ArchiveConversion>(this);
}
return archiveConversions;
}
}
/// <summary>
/// ArchiveFailure collection.
/// </summary>
public ExtensionCollection<ArchiveFailure> ArchiveFailures
{
get
{
if (archiveFailures == null)
{
archiveFailures = new ExtensionCollection<ArchiveFailure>(this);
}
return archiveFailures;
}
}
/// <summary>
/// ArchiveNotify.
/// </summary>
/// <returns></returns>
public string ArchiveNotify
{
get
{
return GetStringValue<ArchiveNotify>(DocumentslistNametable.ArchiveNotify,
DocumentslistNametable.NSDocumentslist);
}
set
{
SetStringValue<ArchiveNotify>(value,
DocumentslistNametable.ArchiveNotify,
DocumentslistNametable.NSDocumentslist);
}
}
/// <summary>
/// ArchiveStatus.
/// </summary>
/// <returns></returns>
public string ArchiveStatus
{
get
{
return GetStringValue<ArchiveStatus>(DocumentslistNametable.ArchiveStatus,
DocumentslistNametable.NSDocumentslist);
}
}
/// <summary>
/// ArchiveComplete.
/// </summary>
/// <returns></returns>
public DateTime ArchiveComplete
{
get
{
string date = GetStringValue<ArchiveComplete>(DocumentslistNametable.ArchiveComplete,
DocumentslistNametable.NSDocumentslist);
DateTime dt;
if (date != null && DateTime.TryParse(date, out dt))
{
return dt;
}
return DateTime.MinValue;
}
}
/// <summary>
/// ArchiveTotal.
/// </summary>
/// <returns></returns>
public int ArchiveTotal
{
get
{
ArchiveTotal element =
FindExtension(DocumentslistNametable.ArchiveTotal, DocumentslistNametable.NSDocumentslist) as
ArchiveTotal;
if (element != null)
{
return element.IntegerValue;
}
return 0;
}
}
/// <summary>
/// ArchiveTotalComplete.
/// </summary>
/// <returns></returns>
public int ArchiveTotalComplete
{
get
{
ArchiveTotalComplete element =
FindExtension(DocumentslistNametable.ArchiveTotalComplete, DocumentslistNametable.NSDocumentslist)
as ArchiveTotalComplete;
if (element != null)
{
return element.IntegerValue;
}
return 0;
}
}
/// <summary>
/// ArchiveTotalFailure.
/// </summary>
/// <returns></returns>
public int ArchiveTotalFailure
{
get
{
ArchiveTotalFailure element =
FindExtension(DocumentslistNametable.ArchiveTotalFailure, DocumentslistNametable.NSDocumentslist) as
ArchiveTotalFailure;
if (element != null)
{
return element.IntegerValue;
}
return 0;
}
}
/// <summary>
/// ArchiveNotifyStatus.
/// </summary>
/// <returns></returns>
public string ArchiveNotifyStatus
{
get
{
return GetStringValue<ArchiveNotifyStatus>(DocumentslistNametable.ArchiveNotifyStatus,
DocumentslistNametable.NSDocumentslist);
}
}
}
public class ArchiveResourceId : SimpleElement
{
/// <summary>
/// default constructor for docs:archiveResourceId
/// </summary>
public ArchiveResourceId()
: base(DocumentslistNametable.ArchiveResourceId,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
public ArchiveResourceId(string value)
: base(DocumentslistNametable.ArchiveResourceId,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist,
value)
{
}
}
public class ArchiveConversion : SimpleElement
{
/// <summary>
/// default constructor for docs:archiveConversion
/// </summary>
public ArchiveConversion()
: base(DocumentslistNametable.ArchiveConversion,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
public ArchiveConversion(string source, string target)
: base(DocumentslistNametable.ArchiveConversion,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
Source = source;
Target = target;
}
/// <summary>
/// Source property accessor
/// </summary>
public string Source
{
get { return Convert.ToString(Attributes[DocumentslistNametable.Source]); }
set { Attributes[DocumentslistNametable.Source] = value; }
}
/// <summary>
/// Target property accessor
/// </summary>
public string Target
{
get { return Convert.ToString(Attributes[DocumentslistNametable.Target]); }
set { Attributes[DocumentslistNametable.Target] = value; }
}
}
public class ArchiveNotify : SimpleElement
{
/// <summary>
/// default constructor for docs:archiveNotify
/// </summary>
public ArchiveNotify()
: base(DocumentslistNametable.ArchiveNotify,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
public ArchiveNotify(string value)
: base(DocumentslistNametable.ArchiveNotify,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist,
value)
{
}
}
public class ArchiveStatus : SimpleElement
{
/// <summary>
/// default constructor for docs:archiveStatus
/// </summary>
public ArchiveStatus()
: base(DocumentslistNametable.ArchiveStatus,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
public class ArchiveComplete : SimpleAttribute
{
/// <summary>
/// default constructor for docs:archiveComplete
/// </summary>
public ArchiveComplete()
: base(DocumentslistNametable.ArchiveComplete,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
public class ArchiveTotal : SimpleAttribute
{
/// <summary>
/// default constructor for docs:archiveTotal
/// </summary>
public ArchiveTotal()
: base(DocumentslistNametable.ArchiveTotal,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
public class ArchiveTotalComplete : SimpleAttribute
{
/// <summary>
/// default constructor for docs:archiveTotalComplete
/// </summary>
public ArchiveTotalComplete()
: base(DocumentslistNametable.ArchiveTotalComplete,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
public class ArchiveTotalFailure : SimpleAttribute
{
/// <summary>
/// default constructor for docs:archiveTotalFailure
/// </summary>
public ArchiveTotalFailure()
: base(DocumentslistNametable.ArchiveTotalFailure,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
public class ArchiveFailure : SimpleAttribute
{
/// <summary>
/// default constructor for docs:archiveFailure
/// </summary>
public ArchiveFailure()
: base(DocumentslistNametable.ArchiveFailure,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
public string Reason
{
get { return Convert.ToString(Attributes[DocumentslistNametable.Reason]); }
}
}
public class ArchiveNotifyStatus : SimpleAttribute
{
/// <summary>
/// default constructor for docs:archiveNotifyStatus
/// </summary>
public ArchiveNotifyStatus()
: base(DocumentslistNametable.ArchiveNotifyStatus,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using Gallio.Runtime.ConsoleSupport;
using MbUnit.Framework;
namespace Gallio.Tests.Runtime.ConsoleSupport
{
[TestFixture]
public class CommandLineArgumentParserTests
{
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void OnlyOneDefaultCommandLineArgumentIsAllowed()
{
new CommandLineArgumentParser(new MainArgumentsDuplicateDefaultCommandLineArgumentStub().GetType());
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void CommandLineArgumentOnlyWithUniqueShortNameIsAllowed()
{
new CommandLineArgumentParser(new MainArgumentsDuplicateShortNameStub().GetType());
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void CommandLineArgumentOnlyWithUniqueLongNameIsAllowed()
{
new CommandLineArgumentParser(new MainArgumentsDuplicateLongNameStub().GetType());
}
[Test]
[Row("/invalid")]
[Row("-invalid")]
public void ParseInvalidArgument(string arg)
{
string errorMsg = string.Empty;
MainArguments arguments = new MainArguments();
CommandLineArgumentParser parser = new CommandLineArgumentParser(arguments.GetType());
Assert.AreEqual(false, parser.Parse(new string[] { arg }, arguments,
delegate(string message) { errorMsg = message; }));
Assert.AreEqual(string.Format("Unrecognized argument '{0}'.", arg), errorMsg);
}
[Test]
public void ParseInvalidValueForBooleanArgument()
{
string errorMsg = string.Empty;
MainArguments arguments = new MainArguments();
CommandLineArgumentParser parser = new CommandLineArgumentParser(arguments.GetType());
Assert.AreEqual(false, parser.Parse(new string[] { "/help:bad" }, arguments,
delegate(string message) { errorMsg = message; }));
Assert.AreEqual("Invalid 'help' argument value 'bad'.", errorMsg);
}
[Test]
[Row("/help", "/help")]
[Row("/help+", "/help")]
public void ParseDuplicatedArgument(string arg1, string arg2)
{
string errorMsg = string.Empty;
MainArguments arguments = new MainArguments();
CommandLineArgumentParser parser = new CommandLineArgumentParser(arguments.GetType());
Assert.AreEqual(false, parser.Parse(new string[] { arg1, arg2 }, arguments,
delegate(string message) { errorMsg = message; }));
Assert.AreEqual("Duplicate 'help' argument.", errorMsg);
}
[Test]
public void ParseResourceFile_InvalidFileTest()
{
string errorMsg = string.Empty;
MainArguments arguments = new MainArguments();
CommandLineArgumentParser parser = new CommandLineArgumentParser(arguments.GetType(),
delegate(string responseFileName)
{
Assert.AreEqual("InvalidFile", responseFileName);
throw new FileNotFoundException();
});
Assert.AreEqual(false, parser.Parse(new string[] { "@InvalidFile" }, arguments,
delegate(string message) { errorMsg = message; }));
Assert.Contains(errorMsg, "Response file '0' does not exist.");
}
[Test]
public void ParseEmptyResourceFile()
{
string errorMsg = string.Empty;
MainArguments arguments = new MainArguments();
CommandLineArgumentParser parser = new CommandLineArgumentParser(arguments.GetType(),
delegate(string responseFileName)
{
Assert.AreEqual("EmptyResourceFile", responseFileName);
return "";
});
Assert.AreEqual(true, parser.Parse(new string[] { "@EmptyResourceFile" }, arguments,
delegate(string message) { errorMsg = message; }));
Console.WriteLine(errorMsg);
}
[Test]
public void ParseResourceFile()
{
string errorMsg = string.Empty;
string fileContent = "C:\\file.dll";
MainArguments arguments = new MainArguments();
CommandLineArgumentParser parser = new CommandLineArgumentParser(arguments.GetType(),
delegate(string responseFileName)
{
Assert.AreEqual("ResourceFile", responseFileName);
return fileContent;
});
Assert.AreEqual(true, parser.Parse(new string[] { "@ResourceFile" },
arguments, delegate(string message) { errorMsg = message; }));
Console.WriteLine(errorMsg);
}
}
public class MainArguments
{
[DefaultCommandLineArgument(
CommandLineArgumentFlags.MultipleUnique,
LongName = "assemblies",
Description = "List of assemblies containing the tests."
)]
public string[] Assemblies;
[CommandLineArgument(
CommandLineArgumentFlags.AtMostOnce,
ShortName = "h",
LongName = "help",
Description = "Display this help text"
)]
public bool Help = false;
[CommandLineArgument(
CommandLineArgumentFlags.MultipleUnique,
ShortName = "hd",
LongName = "hint-directories",
Description = "The list of directories used for loading assemblies and other dependent resources."
)]
public string[] HintDirectories;
}
public class MainArgumentsDuplicateDefaultCommandLineArgumentStub : MainArguments
{
[DefaultCommandLineArgument(
CommandLineArgumentFlags.MultipleUnique,
LongName = "duplicate",
Description = "duplicated default command line argument"
)]
public string[] DuplicateDefault = null;
}
public class MainArgumentsDuplicateLongNameStub : MainArguments
{
[CommandLineArgument(
CommandLineArgumentFlags.MultipleUnique,
ShortName = "unique",
LongName = "help",
Description = "Duplicated long name."
)]
public string[] DuplicateLongName = null;
}
public class MainArgumentsDuplicateShortNameStub : MainArguments
{
[CommandLineArgument(
CommandLineArgumentFlags.MultipleUnique,
ShortName = "h",
LongName = "long name",
Description = "Duplicated short name."
)]
public string[] DuplicateShortName = null;
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Interchange.cs" company="Solidsoft Reply Ltd.">
// Copyright (c) 2015 Solidsoft Reply Limited. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace SolidsoftReply.Esb.Libraries.Facts
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Microsoft.XLANGs.BaseTypes;
using SolidsoftReply.Esb.Libraries.Facts.Dictionaries;
/// <summary>
/// Represents an interchange that will be resolved using the service directory.
/// Objects of this class can be asserted to a policy engine (e.g., MS BRE) as facts.
/// </summary>
[XmlRoot("Interchange", Namespace = "http://solidsoftreply.com/schemas/webservices/esbresolutionservice/2015/05", IsNullable = true)]
[Serializable]
public class Interchange
{
/// <summary>
/// Provider name .
/// </summary>
private string providerName;
/// <summary>
/// Service name.
/// </summary>
private string serviceName;
/// <summary>
/// Binding access point.
/// </summary>
private string bindingAccessPoint;
/// <summary>
/// Binding URL type.
/// </summary>
private string bindingUrlType;
/// <summary>
/// Message type.
/// </summary>
private string messageType;
/// <summary>
/// Operation name.
/// </summary>
private string operationName;
/// <summary>
/// Message label.
/// </summary>
private string messageRole;
/// <summary>
/// Message direction.
/// </summary>
private MessageDirectionTypes messageDirection;
/// <summary>
/// Collection of general purpose parameters.
/// </summary>
private Parameters parameters;
/// <summary>
/// Timestamp value.
/// </summary>
private DateTime timestamp;
/// <summary>
/// A collection of directives representing the results of resolution.
/// </summary>
private DirectivesDictionary directives;
/// <summary>
/// Initializes a new instance of the <see cref="Interchange"/> class.
/// </summary>
public Interchange()
{
this.directives = new DirectivesDictionary();
this.parameters = new Parameters();
}
/// <summary>
/// Enumeration for Message Direction values
/// </summary>
public enum MessageDirectionTypes
{
/// <summary>
/// The message direction is not specified.
/// </summary>
NotSpecified,
/// <summary>
/// The message direction is in.
/// </summary>
MsgIn,
/// <summary>
/// The message direction is out.
/// </summary>
MsgOut,
/// <summary>
/// The message direction is both in and out.
/// </summary>
Both
}
/// <summary>
/// Categories of settings within a directive
/// </summary>
[Flags]
public enum Categories
{
/// <summary>
/// Endpoint directives.
/// </summary>
Endpoint = 1,
/// <summary>
/// Transformation directives.
/// </summary>
Transformation = 2,
/// <summary>
/// BAM interception directives.
/// </summary>
BamInterception = 4,
/// <summary>
/// Validation directives.
/// </summary>
Validation = 8,
/// <summary>
/// Retry directives.
/// </summary>
Retry = 16,
/// <summary>
/// Service window directives.
/// </summary>
ServiceWindow = 32
}
/* The following properties represent UDDI-style attributes
* which we use a criterion in deciding the policy which
* will be applied. They refelect direct attributes of
* UDDI Provider, Service and Binding entities. Language
* specifiers are not supported in this version.
* */
/// <summary>
/// Gets or sets the provider name.
/// </summary>
public string ProviderName
{
get { return this.providerName; }
set { this.providerName = value; }
}
/// <summary>
/// Gets or sets the service name.
/// </summary>
public string ServiceName
{
get { return this.serviceName; }
set { this.serviceName = value; }
}
/// <summary>
/// Gets or sets the binding access point.
/// </summary>
public string BindingAccessPoint
{
get { return this.bindingAccessPoint; }
set { this.bindingAccessPoint = value; }
}
/// <summary>
/// Gets or sets the binding URL type.
/// </summary>
public string BindingUrlType
{
get { return this.bindingUrlType; }
set { this.bindingUrlType = value; }
}
/* End of UDDI-style attributes */
/// <summary>
/// Gets or sets the message type.
/// </summary>
/// <remarks>
/// This is a fully qualified type specification for a message.
/// Will typically be used in respect to BTS messageTypes
/// </remarks>
public string MessageType
{
get { return this.messageType; }
set { this.messageType = value; }
}
/// <summary>
/// Gets or sets the operation name.
/// </summary>
public string OperationName
{
get { return this.operationName; }
set { this.operationName = value; }
}
/// <summary>
/// Gets or sets the message role.
/// </summary>
/// <remarks>
/// A name that identifies the role of a message within a MEP
/// for a specific interface operation. Equivalent to
/// messageLabel in WSDL 2.0
/// </remarks>
public string MessageRole
{
get { return this.messageRole; }
set { this.messageRole = value; }
}
/// <summary>
/// Gets or sets the message direction
/// </summary>
public MessageDirectionTypes MessageDirection
{
get { return this.messageDirection; }
set { this.messageDirection = value; }
}
/// <summary>
/// Gets or sets the collection of general purpose parameters.
/// </summary>
public Parameters Parameters
{
get { return this.parameters; }
set { this.parameters = value; }
}
/// <summary>
/// Gets the date and time at which this property is first evaluated. This can be used to
/// create rules for service windows.
/// </summary>
public DateTime TimeStamp
{
get
{
if (this.timestamp == DateTime.MinValue)
{
this.timestamp = DateTime.Now;
}
return this.timestamp;
}
}
/// <summary>
/// Gets or sets a collection of directives representing the results of resolution.
/// </summary>
public DirectivesDictionary Directives
{
get { return this.directives; }
set { this.directives = value; }
}
/// <summary>
/// Returns a parameter value from the collection of general purpose parameters.
/// </summary>
/// <param name="key">Key value.</param>
/// <returns>Value of keyed parameter as string.</returns>
public string GetParameterValue(string key)
{
object outValue;
this.parameters.TryGetValue(key, out outValue);
return outValue != null ? outValue.ToString() : string.Empty;
}
/// <summary>
/// Set the SOAP action for a directive.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="soapAction">A URI that indicates the intent of the SOAP HTTP request.</param>
public void SetSoapAction(string directiveKey, string soapAction)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(
string.Format(Properties.Resources.ExceptionInvalidDirective, "SOAP action", soapAction ?? "<null>"));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.SoapAction = soapAction;
directive.DirectiveCategories |= Categories.Endpoint;
}
/// <summary>
/// Set the resolved endpoint for a directive.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="endPoint">URI for resolved endpoint.</param>
public void SetEndpoint(string directiveKey, string endPoint)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(
string.Format(Properties.Resources.ExceptionInvalidDirective, "endpoint", endPoint ?? "<null>"));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.EndPoint = endPoint;
directive.DirectiveCategories |= Categories.Endpoint;
}
/// <summary>
/// Set the resolved endpoint for a directive.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="endPoint">URI for resolved endpoint.</param>
/// <param name="transportType">BTS transport type for resolved endpoint.</param>
public void SetEndpoint(string directiveKey, string endPoint, string transportType)
{
this.SetEndpoint(directiveKey, endPoint);
var directive = this.GetDirective(directiveKey);
directive.TransportType = transportType;
}
/// <summary>
/// Set the resolved endpoint for a directive.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="endPoint">URI for resolved endpoint.</param>
/// <param name="transportType">BTS transport type for resolved endpoint.</param>
/// <param name="configurationToken">Configuration token. This way be literal configuration or a reference.</param>
public void SetEndpoint(string directiveKey, string endPoint, string transportType, string configurationToken)
{
this.SetEndpoint(directiveKey, endPoint, transportType);
var directive = this.GetDirective(directiveKey);
directive.EndPointConfiguration = configurationToken;
}
/// <summary>
/// Set the resolved transformation map for a directive.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="mapToApply">Fully qualified .NET assembly and type name of a BTS map.</param>
public void SetTransformation(string directiveKey, string mapToApply)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(
string.Format(
Properties.Resources.ExceptionInvalidDirective,
"transformation map",
mapToApply ?? "<null>"));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.MapToApply = mapToApply;
directive.DirectiveCategories |= Categories.Transformation;
}
/// <summary>
/// Set the resolved XML content formatting requirement for a directive.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="xmlFormat">Formatting required for XML content.</param>
public void SetXmlFormat(string directiveKey, XmlFormat xmlFormat)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(
string.Format(
Properties.Resources.ExceptionInvalidDirective,
"XML formatting of type",
xmlFormat));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.XmlFormat = xmlFormat;
if (xmlFormat != XmlFormat.None)
{
directive.DirectiveCategories |= Categories.Transformation;
}
}
/// <summary>
/// Sets validation policy as part of the policy.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="policyName">Name of the validation policy.</param>
public void SetValidationPolicy(string directiveKey, string policyName)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(string.Format(Properties.Resources.ExceptionInvalidDirective, "Validation policy", policyName ?? "<null>"));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.ValidationPolicyName = policyName;
directive.DirectiveCategories |= Categories.Validation;
}
/// <summary>
/// Sets validation policy as part of the policy.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="policyName">Name of the validation policy.</param>
/// <param name="errorOnInvalid">Indicates whether to throw an error if a validation rule policy indicates invalidity.</param>
public void SetValidationPolicy(string directiveKey, string policyName, bool errorOnInvalid)
{
this.SetValidationPolicy(directiveKey, policyName);
var directive = this.GetDirective(directiveKey);
directive.ErrorOnInvalid = errorOnInvalid;
// We will not set DirectiveCategories here, as the configuration is of no use
// unless we are also doing BAM interception
}
/// <summary>
/// Sets validation policy as part of the policy.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="policyName">Name of the validation policy.</param>
/// <param name="policyVersion">Validation policy version.</param>
public void SetValidationPolicy(string directiveKey, string policyName, string policyVersion)
{
this.SetValidationPolicy(directiveKey, policyName);
var directive = this.GetDirective(directiveKey);
directive.ValidationPolicyVersion = policyVersion;
directive.DirectiveCategories |= Categories.Validation;
}
/// <summary>
/// Sets validation policy as part of the policy.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="policyName">Name of the validation policy.</param>
/// <param name="policyVersion">Validation policy version.</param>
/// <param name="errorOnInvalid">Indicates whether to throw an error if a validation rule policy indicates invalidity.</param>
public void SetValidationPolicy(string directiveKey, string policyName, string policyVersion, bool errorOnInvalid)
{
this.SetValidationPolicy(directiveKey, policyName, policyVersion);
var directive = this.GetDirective(directiveKey);
directive.ErrorOnInvalid = errorOnInvalid;
// We will not set DirectiveCategories here, as the configuration is of no use
// unless we are also doing BAM interception
}
/// <summary>
/// Set a BAM interception tracking point for a directive. This interception point will be
/// placed before any transformation step on the same directive.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="bamActivity">BAM activity name.</param>
/// <param name="bamStepName">Name of a conceptual step within the activity.</param>
public void SetBamInterception(string directiveKey, string bamActivity, string bamStepName)
{
this.SetBamInterception(directiveKey, bamActivity, bamStepName, false);
}
/// <summary>
/// Set a post-transformation BAM interception tracking point for a directive. This
/// interception point will be placed before any transformation step on the same directive.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="bamActivity">BAM activity name.</param>
/// <param name="bamStepName">Name of a conceptual step within the activity.</param>
public void SetBamInterceptionAfterMap(string directiveKey, string bamActivity, string bamStepName)
{
this.SetBamInterception(directiveKey, bamActivity, bamStepName, true);
}
/// <summary>
/// Set a BAM interception step extension for a directive. The directive must set a BAM step to be extended.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="bamExtensionStepName">The name of the BAM step extension.</param>
public void SetBamInterceptionExtension(string directiveKey, string bamExtensionStepName)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
var extensionStepName = string.Format("extension {0}", bamExtensionStepName ?? "<null>");
var message = string.Format(
Properties.Resources.ExceptionInvalidDirective,
"BAM interception step extension",
extensionStepName);
throw new EsbFactsException(message);
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.BamStepExtensions.Add(bamExtensionStepName);
directive.DirectiveCategories |= Categories.BamInterception;
}
/// <summary>
/// Set a BAM interception step extension for a directive. The directive must set a BAM step to be extended.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="bamExtensionStepName">The name of the BAM step extension.</param>
public void SetBamInterceptionExtensionAfterMap(string directiveKey, string bamExtensionStepName)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
var extensionStepName = string.Format("extension {0}", bamExtensionStepName ?? "<null>");
var message = string.Format(
Properties.Resources.ExceptionInvalidDirective,
"BAM post-transformation interception step extension",
extensionStepName);
throw new EsbFactsException(message);
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.BamStepExtensions.Add(bamExtensionStepName);
directive.DirectiveCategories |= Categories.BamInterception;
}
/// <summary>
/// Sets BAM configuration as part of the policy.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="bamConnectionstring">Database connection string to message box or primary import database.</param>
/// <param name="bamIsBuffered">Flag indicates the type of event stream to use.</param>
/// <param name="bamFlushThreshold">
/// Value that determines under what conditions the buffered data will be sent to the tracking database.
/// </param>
public void SetBamConfiguration(string directiveKey, string bamConnectionstring, bool bamIsBuffered, int bamFlushThreshold)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(
string.Format(
Properties.Resources.ExceptionInvalidDirective,
"BAM configuration",
bamConnectionstring ?? "<null>"));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.BamConnectionString = bamConnectionstring;
directive.BamIsBuffered = bamIsBuffered;
directive.BamFlushThreshold = bamFlushThreshold;
// We will not set DirectiveCategories here, as the configuration is of no use
// unless we are also doing BAM interception
}
/// <summary>
/// Sets BAM Trackpoint policy as part of the policy.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="policyName">Database connection string to message box or primary import database.</param>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
public void SetBamTrackpointPolicy(string directiveKey, string policyName)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(string.Format(Properties.Resources.ExceptionInvalidDirective, "BAM trackpoint policy", policyName ?? "<null>"));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.BamTrackpointPolicyName = policyName;
// We will not set DirectiveCategories here, as the trackpoint policy is of no use
// unless we are also doing BAM interception
}
/// <summary>
/// Sets BAM Trackpoint policy as part of the policy.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="policyName">Database connection string to message box or primary import database.</param>
/// <param name="policyVersion">Flag indicates the type of event stream to use.</param>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
public void SetBamTrackpointPolicy(string directiveKey, string policyName, string policyVersion)
{
this.SetBamTrackpointPolicy(directiveKey, policyName);
var directive = this.GetDirective(directiveKey);
directive.BamTrackpointPolicyVersion = policyVersion;
// We will not set DirectiveCategories here, as the trackpoint policy is of no use
// unless we are also doing BAM interception
}
/// <summary>
/// Set the policy for performing retries on failure.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="retryCount">The number of retries to perform.</param>
/// <param name="retryInterval">The interval between each retry.</param>
public void SetRetryPolicy(string directiveKey, int retryCount, int retryInterval)
{
this.SetRetryPolicy(directiveKey, retryCount, retryInterval, 0);
}
/// <summary>
/// Set the policy for performing retries on failure.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="retryCount">The number of retries to perform.</param>
/// <param name="retryInterval">The interval between each retry.</param>
/// <param name="retryLevel">The temporal level of retrys.</param>
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Reviewed. Suppression is OK here.")]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
public void SetRetryPolicy(string directiveKey, int retryCount, int retryInterval, int retryLevel)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(
string.Format(
Properties.Resources.ExceptionInvalidDirective,
"retry policy",
string.Format(
"of {0} retries with an interval of {1} at level {2}",
retryCount,
retryInterval,
retryLevel)));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.RetryCount = retryCount;
directive.RetryInterval = retryInterval;
directive.RetryLevel = retryLevel;
directive.DirectiveCategories |= Categories.Retry;
}
/// <summary>
/// Set service window start and stop times.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="startTime">Time at which the service window opens.</param>
/// <param name="stopTime">Time at which the service window closes.</param>
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Reviewed. Suppression is OK here.")]
public void SetServiceWindow(string directiveKey, DateTime startTime, DateTime stopTime)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(
string.Format(
Properties.Resources.ExceptionInvalidDirective,
"service window",
string.Format(
"that starts at {0} and stops at {1}",
startTime,
stopTime)));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
directive.ServiceWindowStartTime = startTime;
directive.ServiceWindowStopTime = stopTime;
directive.DirectiveCategories |= Categories.ServiceWindow;
}
/// <summary>
/// Set a BTS property name-value pair for a directive. This property will
/// be generally created in message context. NB. This property assumes
/// that the name-value pair is for a property defined in
/// Microsoft.BizTalk.GlobalPropertySchemas.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="name">BTS property name.</param>
/// <param name="value">Value to assign to the property.</param>
public void SetBtsGlobalProperty(string directiveKey, string name, string value)
{
this.SetBtsGlobalProperty(directiveKey, name, value, true);
}
/// <summary>
/// Set a BTS property name-value pair for a directive. This property will
/// be generally created in message context. NB. This property assumes
/// that the name-value pair is for a property defined in
/// Microsoft.BizTalk.GlobalPropertySchemas.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="name">BTS property name.</param>
/// <param name="value">Value to assign to the property.</param>
/// <param name="promoted">Flag indicates if property should be promoted.</param>
public void SetBtsGlobalProperty(string directiveKey, string name, string value, bool promoted)
{
var propOjectHandle = Activator.CreateInstance(Properties.Resources.AssemblyQNameMicrosoftBizTalkGlobalPropertySchemas, name);
if (propOjectHandle == null)
{
throw new EsbFactsException(string.Format(Properties.Resources.ExceptionInvalidProperty, name));
}
var prop = propOjectHandle.Unwrap() as PropertyBase;
if (prop == null)
{
throw new EsbFactsException(string.Format(Properties.Resources.ExceptionInvalidProperty, "ARG0"));
}
this.SetBtsProperty(directiveKey, prop.Name.Name, value, prop.Name.Namespace, promoted);
}
/// <summary>
/// Set a BTS property name-value pair (including namespace) for a directive. This property will
/// be generally created in message context.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="name">BTS property name.</param>
/// <param name="value">Value to assign to the property.</param>
/// <param name="namespace">XML namespace of the property</param>
public void SetBtsProperty(string directiveKey, string name, string value, string @namespace)
{
this.SetBtsProperty(directiveKey, name, value, @namespace, true);
}
/// <summary>
/// Set a BTS property name-value pair (including namespace) for a directive. This property will
/// be generally created in message context.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="name">BTS property name.</param>
/// <param name="value">Value to assign to the property.</param>
/// <param name="namespace">XML namespace of the property</param>
/// <param name="promoted">Flag indicates if property should be promoted.</param>
public void SetBtsProperty(string directiveKey, string name, string value, string @namespace, bool promoted)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(
string.Format(
Properties.Resources.ExceptionInvalidDirective,
"BizTalk property",
name ?? "<null>"));
}
if (string.IsNullOrWhiteSpace(name))
{
throw new EsbFactsException(string.Format(Properties.Resources.ExceptionInvalidBizTalkPropertyName, directiveKey));
}
if (string.IsNullOrWhiteSpace(value))
{
throw new EsbFactsException(string.Format(Properties.Resources.ExceptionInvalidBizTalkPropertyValue, directiveKey));
}
if (string.IsNullOrWhiteSpace(@namespace))
{
throw new EsbFactsException(string.Format(Properties.Resources.ExceptionInvalidBizTalkPropertyNamespace, directiveKey));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
Directive.BtsProperty origPropertyDef;
var propertyDef = new Directive.BtsProperty(name, value, @namespace, promoted);
// Remove any existing property definition for this property
// SolidsoftReply.ESB.Libraries.BizTalk.Facts.Interchange.KeyValue
if (directive.BtsProperties.TryGetValue(name, out origPropertyDef))
{
directive.BtsProperties.Remove(name);
}
directive.BtsProperties.Add(name, propertyDef);
}
/// <summary>
/// Set a general-purpose property name-value pair for a directive.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="name">Property name.</param>
/// <param name="value">Value to assign to the property.</param>
public void SetProperty(string directiveKey, string name, string value)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(
string.Format(
Properties.Resources.ExceptionInvalidDirective,
"property",
name ?? "<null>"));
}
if (string.IsNullOrWhiteSpace(name))
{
throw new EsbFactsException(string.Format(Properties.Resources.ExceptionInvalidPropertyName, directiveKey));
}
if (string.IsNullOrWhiteSpace(value))
{
throw new EsbFactsException(string.Format(Properties.Resources.ExceptionInvalidPropertyValue, directiveKey));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
Directive.Property origPropertyDef;
var propertyDef = new Directive.Property(name, value);
// Remove any existing property definition for this property
if (directive.Properties.TryGetValue(name, out origPropertyDef))
{
directive.Properties.Remove(name);
}
directive.Properties.Add(name, propertyDef);
}
/// <summary>
/// Performs validation at the directive level. These validations cover situations
/// where one instruction must be validated against another.
/// </summary>
public void ValidateDirectives()
{
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
this.directives.All(kvp => kvp.Value.Validate());
}
/// <summary>
/// This method is reserved and is not used.
/// </summary>
/// <returns>
/// An XmlSchema that describes the XML representation of the object that is produced
/// by the WriteXml method and consumed by the ReadXml method.
/// </returns>
public XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The XmlReader stream from which the object is deserialized.</param>
public void ReadXml(XmlReader reader)
{
throw new Exception(Properties.Resources.ExceptionNotImplemented);
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The XmlWriter stream to which the object is serialized. </param>
public void WriteXml(XmlWriter writer)
{
throw new Exception(Properties.Resources.ExceptionNotImplemented);
}
/// <summary>
/// Set a BAM interception tracking point for a directive. This interception point may be
/// placed either before or after any transformation step on the same directive.
/// </summary>
/// <param name="directiveKey">Key name that identifies a directive.</param>
/// <param name="bamActivity">BAM activity name.</param>
/// <param name="bamStepName">Name of a conceptual step within the activity.</param>
/// <param name="afterMap">If true, indicates that the interception tracking point should be set
/// after any transformation defined on this same directive.</param>
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Reviewed. Suppression is OK here.")]
private void SetBamInterception(string directiveKey, string bamActivity, string bamStepName, bool afterMap)
{
if (string.IsNullOrWhiteSpace(directiveKey))
{
throw new EsbFactsException(
string.Format(
Properties.Resources.ExceptionInvalidDirective,
"BAM interception",
string.Format(
"{0}step {1} for activity {2}",
afterMap ? "after-map " : string.Empty,
bamStepName ?? "<null>",
bamActivity ?? "<null>")));
}
var directive = this.GetDirective(directiveKey);
directive.KeyName = directiveKey;
if (!string.IsNullOrWhiteSpace(directive.BamActivity) && directive.BamActivity != bamActivity)
{
throw new EsbFactsException(
string.Format(Properties.Resources.ExceptionBamActivityName, directiveKey));
}
if (!afterMap)
{
// Set the BAM Activity on a pre-transformation step
directive.BamActivity = bamActivity;
}
else
{
// Set the BAM Activity on a post-transformation step
if (string.IsNullOrWhiteSpace(directive.BamActivity))
{
directive.BamActivity = bamActivity;
}
if (!string.IsNullOrWhiteSpace(bamActivity) &&
directive.BamActivity != bamActivity)
{
throw new EsbFactsException(
string.Format(Properties.Resources.ExceptionBamNonMatchingStepNames,
directiveKey,
directive.BamActivity,
string.IsNullOrWhiteSpace(bamActivity) ? "<null or empty>": bamActivity));
}
}
if (afterMap)
{
if (!string.IsNullOrWhiteSpace(directive.BamAfterMapStepName)
&& directive.BamAfterMapStepName != bamStepName)
{
throw new EsbFactsException(
string.Format(Properties.Resources.ExceptionBamAfterMapStepName, directiveKey));
}
directive.BamAfterMapStepName = bamStepName;
}
else
{
if (!string.IsNullOrWhiteSpace(directive.BamStepName) && directive.BamStepName != bamStepName)
{
throw new EsbFactsException(
string.Format(Properties.Resources.ExceptionBamStepName, directiveKey));
}
directive.BamStepName = bamStepName;
}
directive.DirectiveCategories |= Categories.BamInterception;
}
/// <summary>
/// Gets a directive from the directive collection. If the directive does
/// not exist, it is created.
/// </summary>
/// <param name="keyName">Directive key name.</param>
/// <returns>A directive for the given key name.</returns>
private Directive GetDirective(string keyName)
{
Directive directive;
if (this.directives.TryGetValue(keyName, out directive))
{
return directive;
}
directive = new Directive(keyName) { KeyName = keyName };
this.directives.Add(keyName, directive);
return directive;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Data.Core;
using Avalonia.Utilities;
#nullable enable
// Don't need to override GetHashCode as the ISyntax objects will not be stored in a hash; the
// only reason they have overridden Equals methods is for unit testing.
#pragma warning disable 659
namespace Avalonia.Markup.Parsers
{
internal static class SelectorGrammar
{
private enum State
{
Start,
Middle,
Colon,
Class,
Name,
CanHaveType,
Traversal,
TypeName,
Property,
AttachedProperty,
Template,
End,
}
public static IEnumerable<ISyntax> Parse(string s)
{
var r = new CharacterReader(s.AsSpan());
return Parse(ref r, null);
}
private static IEnumerable<ISyntax> Parse(ref CharacterReader r, char? end)
{
var state = State.Start;
var selector = new List<ISyntax>();
while (!r.End && state != State.End)
{
ISyntax? syntax = null;
switch (state)
{
case State.Start:
state = ParseStart(ref r);
break;
case State.Middle:
(state, syntax) = ParseMiddle(ref r, end);
break;
case State.CanHaveType:
state = ParseCanHaveType(ref r);
break;
case State.Colon:
(state, syntax) = ParseColon(ref r);
break;
case State.Class:
(state, syntax) = ParseClass(ref r);
break;
case State.Traversal:
(state, syntax) = ParseTraversal(ref r);
break;
case State.TypeName:
(state, syntax) = ParseTypeName(ref r);
break;
case State.Property:
(state, syntax) = ParseProperty(ref r);
break;
case State.Template:
(state, syntax) = ParseTemplate(ref r);
break;
case State.Name:
(state, syntax) = ParseName(ref r);
break;
case State.AttachedProperty:
(state, syntax) = ParseAttachedProperty(ref r);
break;
}
if (syntax != null)
{
selector.Add(syntax);
}
}
if (state != State.Start && state != State.Middle && state != State.End && state != State.CanHaveType)
{
throw new ExpressionParseException(r.Position, "Unexpected end of selector");
}
return selector;
}
private static State ParseStart(ref CharacterReader r)
{
r.SkipWhitespace();
if (r.End)
{
return State.End;
}
if (r.TakeIf(':'))
{
return State.Colon;
}
else if (r.TakeIf('.'))
{
return State.Class;
}
else if (r.TakeIf('#'))
{
return State.Name;
}
return State.TypeName;
}
private static (State, ISyntax?) ParseMiddle(ref CharacterReader r, char? end)
{
if (r.TakeIf(':'))
{
return (State.Colon, null);
}
else if (r.TakeIf('.'))
{
return (State.Class, null);
}
else if (r.TakeIf(char.IsWhiteSpace) || r.Peek == '>')
{
return (State.Traversal, null);
}
else if (r.TakeIf('/'))
{
return (State.Template, null);
}
else if (r.TakeIf('#'))
{
return (State.Name, null);
}
else if (r.TakeIf(','))
{
return (State.Start, new CommaSyntax());
}
else if (end.HasValue && !r.End && r.Peek == end.Value)
{
return (State.End, null);
}
return (State.TypeName, null);
}
private static State ParseCanHaveType(ref CharacterReader r)
{
if (r.TakeIf('['))
{
return State.Property;
}
return State.Middle;
}
private static (State, ISyntax) ParseColon(ref CharacterReader r)
{
var identifier = r.ParseStyleClass();
if (identifier.IsEmpty)
{
throw new ExpressionParseException(r.Position, "Expected class name, is, nth-child or nth-last-child selector after ':'.");
}
const string IsKeyword = "is";
const string NotKeyword = "not";
const string NthChildKeyword = "nth-child";
const string NthLastChildKeyword = "nth-last-child";
if (identifier.SequenceEqual(IsKeyword.AsSpan()) && r.TakeIf('('))
{
var syntax = ParseType(ref r, new IsSyntax());
Expect(ref r, ')');
return (State.CanHaveType, syntax);
}
if (identifier.SequenceEqual(NotKeyword.AsSpan()) && r.TakeIf('('))
{
var argument = Parse(ref r, ')');
Expect(ref r, ')');
var syntax = new NotSyntax { Argument = argument };
return (State.Middle, syntax);
}
if (identifier.SequenceEqual(NthChildKeyword.AsSpan()) && r.TakeIf('('))
{
var (step, offset) = ParseNthChildArguments(ref r);
var syntax = new NthChildSyntax { Step = step, Offset = offset };
return (State.Middle, syntax);
}
if (identifier.SequenceEqual(NthLastChildKeyword.AsSpan()) && r.TakeIf('('))
{
var (step, offset) = ParseNthChildArguments(ref r);
var syntax = new NthLastChildSyntax { Step = step, Offset = offset };
return (State.Middle, syntax);
}
else
{
return (
State.CanHaveType,
new ClassSyntax
{
Class = ":" + identifier.ToString()
});
}
}
private static (State, ISyntax?) ParseTraversal(ref CharacterReader r)
{
r.SkipWhitespace();
if (r.TakeIf('>'))
{
r.SkipWhitespace();
return (State.Middle, new ChildSyntax());
}
else if (r.TakeIf('/'))
{
return (State.Template, null);
}
else if (!r.End)
{
return (State.Middle, new DescendantSyntax());
}
else
{
return (State.End, null);
}
}
private static (State, ISyntax) ParseClass(ref CharacterReader r)
{
var @class = r.ParseStyleClass();
if (@class.IsEmpty)
{
throw new ExpressionParseException(r.Position, $"Expected a class name after '.'.");
}
return (State.CanHaveType, new ClassSyntax { Class = @class.ToString() });
}
private static (State, ISyntax) ParseTemplate(ref CharacterReader r)
{
var template = r.ParseIdentifier();
const string TemplateKeyword = "template";
if (!template.SequenceEqual(TemplateKeyword.AsSpan()))
{
throw new ExpressionParseException(r.Position, $"Expected 'template', got '{template.ToString()}'");
}
else if (!r.TakeIf('/'))
{
throw new ExpressionParseException(r.Position, "Expected '/'");
}
return (State.Start, new TemplateSyntax());
}
private static (State, ISyntax) ParseName(ref CharacterReader r)
{
var name = r.ParseIdentifier();
if (name.IsEmpty)
{
throw new ExpressionParseException(r.Position, $"Expected a name after '#'.");
}
return (State.CanHaveType, new NameSyntax { Name = name.ToString() });
}
private static (State, ISyntax) ParseTypeName(ref CharacterReader r)
{
return (State.CanHaveType, ParseType(ref r, new OfTypeSyntax()));
}
private static (State, ISyntax?) ParseProperty(ref CharacterReader r)
{
var property = r.ParseIdentifier();
if (r.TakeIf('('))
{
return (State.AttachedProperty, default);
}
else if (!r.TakeIf('='))
{
throw new ExpressionParseException(r.Position, $"Expected '=', got '{r.Peek}'");
}
var value = r.TakeUntil(']');
r.Take();
return (State.CanHaveType, new PropertySyntax { Property = property.ToString(), Value = value.ToString() });
}
private static (State, ISyntax) ParseAttachedProperty(ref CharacterReader r)
{
var syntax = ParseType(ref r, new AttachedPropertySyntax());
if (!r.TakeIf('.'))
{
throw new ExpressionParseException(r.Position, $"Expected '.', got '{r.Peek}'");
}
var property = r.ParseIdentifier();
if (property.IsEmpty)
{
throw new ExpressionParseException(r.Position, $"Expected Attached Property Name, got '{r.Peek}'");
}
syntax.Property = property.ToString();
if (!r.TakeIf(')'))
{
throw new ExpressionParseException(r.Position, $"Expected ')', got '{r.Peek}'");
}
if (!r.TakeIf('='))
{
throw new ExpressionParseException(r.Position, $"Expected '=', got '{r.Peek}'");
}
var value = r.TakeUntil(']');
syntax.Value = value.ToString();
r.Take();
var state = r.End
? State.End
: State.Middle;
return (state, syntax);
}
private static TSyntax ParseType<TSyntax>(ref CharacterReader r, TSyntax syntax)
where TSyntax : ITypeSyntax
{
ReadOnlySpan<char> ns = default;
ReadOnlySpan<char> type;
var namespaceOrTypeName = r.ParseIdentifier();
if (namespaceOrTypeName.IsEmpty)
{
throw new ExpressionParseException(r.Position, $"Expected an identifier, got '{r.Peek}");
}
if (!r.End && r.TakeIf('|'))
{
ns = namespaceOrTypeName;
if (r.End)
{
throw new ExpressionParseException(r.Position, $"Unexpected end of selector.");
}
type = r.ParseIdentifier();
}
else
{
type = namespaceOrTypeName;
}
syntax.Xmlns = ns.ToString();
syntax.TypeName = type.ToString();
return syntax;
}
private static (int step, int offset) ParseNthChildArguments(ref CharacterReader r)
{
int step = 0;
int offset = 0;
if (r.Peek == 'o')
{
var constArg = r.TakeUntil(')').ToString().Trim();
if (constArg.Equals("odd", StringComparison.Ordinal))
{
step = 2;
offset = 1;
}
else
{
throw new ExpressionParseException(r.Position, $"Expected nth-child(odd). Actual '{constArg}'.");
}
}
else if (r.Peek == 'e')
{
var constArg = r.TakeUntil(')').ToString().Trim();
if (constArg.Equals("even", StringComparison.Ordinal))
{
step = 2;
offset = 0;
}
else
{
throw new ExpressionParseException(r.Position, $"Expected nth-child(even). Actual '{constArg}'.");
}
}
else
{
r.SkipWhitespace();
var stepOrOffset = 0;
var stepOrOffsetStr = r.TakeWhile(c => char.IsDigit(c) || c == '-' || c == '+').ToString();
if (stepOrOffsetStr.Length == 0
|| (stepOrOffsetStr.Length == 1
&& stepOrOffsetStr[0] == '+'))
{
stepOrOffset = 1;
}
else if (stepOrOffsetStr.Length == 1
&& stepOrOffsetStr[0] == '-')
{
stepOrOffset = -1;
}
else if (!int.TryParse(stepOrOffsetStr.ToString(), out stepOrOffset))
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child step or offset value. Integer was expected.");
}
r.SkipWhitespace();
if (r.Peek == ')')
{
step = 0;
offset = stepOrOffset;
}
else
{
step = stepOrOffset;
if (r.Peek != 'n')
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child step value, \"xn+y\" pattern was expected.");
}
r.Skip(1); // skip 'n'
r.SkipWhitespace();
if (r.Peek != ')')
{
int sign;
var nextChar = r.Take();
if (nextChar == '+')
{
sign = 1;
}
else if (nextChar == '-')
{
sign = -1;
}
else
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child sign. '+' or '-' was expected.");
}
r.SkipWhitespace();
if (sign != 0
&& !int.TryParse(r.TakeUntil(')').ToString(), out offset))
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child offset value. Integer was expected.");
}
offset *= sign;
}
}
}
Expect(ref r, ')');
return (step, offset);
}
private static void Expect(ref CharacterReader r, char c)
{
if (r.End)
{
throw new ExpressionParseException(r.Position, $"Expected '{c}', got end of selector.");
}
else if (!r.TakeIf(')'))
{
throw new ExpressionParseException(r.Position, $"Expected '{c}', got '{r.Peek}'.");
}
}
public interface ISyntax
{
}
public interface ITypeSyntax
{
string TypeName { get; set; }
string Xmlns { get; set; }
}
public class OfTypeSyntax : ISyntax, ITypeSyntax
{
public string TypeName { get; set; } = string.Empty;
public string Xmlns { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
var other = obj as OfTypeSyntax;
return other != null && other.TypeName == TypeName && other.Xmlns == Xmlns;
}
}
public class AttachedPropertySyntax : ISyntax, ITypeSyntax
{
public string Xmlns { get; set; } = string.Empty;
public string TypeName { get; set; } = string.Empty;
public string Property { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
return obj is AttachedPropertySyntax syntax
&& syntax.Xmlns == Xmlns
&& syntax.TypeName == TypeName
&& syntax.Property == Property
&& syntax.Value == Value;
}
}
public class IsSyntax : ISyntax, ITypeSyntax
{
public string TypeName { get; set; } = string.Empty;
public string Xmlns { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
var other = obj as IsSyntax;
return other != null && other.TypeName == TypeName && other.Xmlns == Xmlns;
}
}
public class ClassSyntax : ISyntax
{
public string Class { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
return obj is ClassSyntax && ((ClassSyntax)obj).Class == Class;
}
}
public class NameSyntax : ISyntax
{
public string Name { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
return obj is NameSyntax && ((NameSyntax)obj).Name == Name;
}
}
public class PropertySyntax : ISyntax
{
public string Property { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
return obj is PropertySyntax &&
((PropertySyntax)obj).Property == Property &&
((PropertySyntax)obj).Value == Value;
}
}
public class ChildSyntax : ISyntax
{
public override bool Equals(object? obj)
{
return obj is ChildSyntax;
}
}
public class DescendantSyntax : ISyntax
{
public override bool Equals(object? obj)
{
return obj is DescendantSyntax;
}
}
public class TemplateSyntax : ISyntax
{
public override bool Equals(object? obj)
{
return obj is TemplateSyntax;
}
}
public class NotSyntax : ISyntax
{
public IEnumerable<ISyntax> Argument { get; set; } = Enumerable.Empty<ISyntax>();
public override bool Equals(object? obj)
{
return (obj is NotSyntax not) && Argument.SequenceEqual(not.Argument);
}
}
public class NthChildSyntax : ISyntax
{
public int Offset { get; set; }
public int Step { get; set; }
public override bool Equals(object? obj)
{
return (obj is NthChildSyntax nth) && nth.Offset == Offset && nth.Step == Step;
}
}
public class NthLastChildSyntax : ISyntax
{
public int Offset { get; set; }
public int Step { get; set; }
public override bool Equals(object? obj)
{
return (obj is NthLastChildSyntax nth) && nth.Offset == Offset && nth.Step == Step;
}
}
public class CommaSyntax : ISyntax
{
public override bool Equals(object? obj)
{
return obj is CommaSyntax or;
}
}
}
}
| |
// 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.Security;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if FEATURE_COMINTEROP
using System.Runtime.InteropServices.WindowsRuntime;
using WFD = Windows.Foundation.Diagnostics;
#endif
namespace System.Threading.Tasks
{
[FriendAccessAllowed]
internal enum CausalityTraceLevel
{
#if FEATURE_COMINTEROP
Required = WFD.CausalityTraceLevel.Required,
Important = WFD.CausalityTraceLevel.Important,
Verbose = WFD.CausalityTraceLevel.Verbose
#else
Required,
Important,
Verbose
#endif
}
[FriendAccessAllowed]
internal enum AsyncCausalityStatus
{
#if FEATURE_COMINTEROP
Canceled = WFD.AsyncCausalityStatus.Canceled,
Completed = WFD.AsyncCausalityStatus.Completed,
Error = WFD.AsyncCausalityStatus.Error,
Started = WFD.AsyncCausalityStatus.Started
#else
Started,
Completed,
Canceled,
Error
#endif
}
internal enum CausalityRelation
{
#if FEATURE_COMINTEROP
AssignDelegate = WFD.CausalityRelation.AssignDelegate,
Join = WFD.CausalityRelation.Join,
Choice = WFD.CausalityRelation.Choice,
Cancel = WFD.CausalityRelation.Cancel,
Error = WFD.CausalityRelation.Error
#else
AssignDelegate,
Join,
Choice,
Cancel,
Error
#endif
}
internal enum CausalitySynchronousWork
{
#if FEATURE_COMINTEROP
CompletionNotification = WFD.CausalitySynchronousWork.CompletionNotification,
ProgressNotification = WFD.CausalitySynchronousWork.ProgressNotification,
Execution = WFD.CausalitySynchronousWork.Execution
#else
CompletionNotification,
ProgressNotification,
Execution
#endif
}
[FriendAccessAllowed]
internal static class AsyncCausalityTracer
{
static internal void EnableToETW(bool enabled)
{
#if FEATURE_COMINTEROP
if (enabled)
f_LoggingOn |= Loggers.ETW;
else
f_LoggingOn &= ~Loggers.ETW;
#endif
}
[FriendAccessAllowed]
internal static bool LoggingOn
{
[FriendAccessAllowed]
get
{
#if FEATURE_COMINTEROP
return f_LoggingOn != 0;
#else
return false;
#endif
}
}
#if FEATURE_COMINTEROP
//s_PlatformId = {4B0171A6-F3D0-41A0-9B33-02550652B995}
private static readonly Guid s_PlatformId = new Guid(0x4B0171A6, 0xF3D0, 0x41A0, 0x9B, 0x33, 0x02, 0x55, 0x06, 0x52, 0xB9, 0x95);
//Indicates this information comes from the BCL Library
private const WFD.CausalitySource s_CausalitySource = WFD.CausalitySource.Library;
//Lazy initialize the actual factory
private static WFD.IAsyncCausalityTracerStatics s_TracerFactory;
// The loggers that this Tracer knows about.
[Flags]
private enum Loggers : byte {
CausalityTracer = 1,
ETW = 2
}
//We receive the actual value for these as a callback
private static Loggers f_LoggingOn; //assumes false by default
// The precise static constructor will run first time somebody attempts to access this class
[SecuritySafeCritical]
static AsyncCausalityTracer()
{
if (!Environment.IsWinRTSupported) return;
//COM Class Id
string ClassId = "Windows.Foundation.Diagnostics.AsyncCausalityTracer";
//COM Interface GUID {50850B26-267E-451B-A890-AB6A370245EE}
Guid guid = new Guid(0x50850B26, 0x267E, 0x451B, 0xA8, 0x90, 0XAB, 0x6A, 0x37, 0x02, 0x45, 0xEE);
Object factory = null;
try
{
int hresult = Microsoft.Win32.UnsafeNativeMethods.RoGetActivationFactory(ClassId, ref guid, out factory);
if (hresult < 0 || factory == null) return; //This prevents having an exception thrown in case IAsyncCausalityTracerStatics isn't registered.
s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory;
EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler<WFD.TracingStatusChangedEventArgs>(TracingStatusChangedHandler));
Contract.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null");
}
catch (Exception ex)
{
// Although catching generic Exception is not recommended, this file is one exception
// since we don't want to propagate any kind of exception to the user since all we are
// doing here depends on internal state.
LogAndDisable(ex);
}
}
[SecuritySafeCritical]
private static void TracingStatusChangedHandler(Object sender, WFD.TracingStatusChangedEventArgs args)
{
if (args.Enabled)
f_LoggingOn |= Loggers.CausalityTracer;
else
f_LoggingOn &= ~Loggers.CausalityTracer;
}
#endif
//
// The TraceXXX methods should be called only if LoggingOn property returned true
//
[FriendAccessAllowed]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Tracking is slow path. Disable inlining for it.
internal static void TraceOperationCreation(CausalityTraceLevel traceLevel, int taskId, string operationName, ulong relatedContext)
{
#if FEATURE_COMINTEROP
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
TplEtwProvider.Log.TraceOperationBegin(taskId, operationName, (long) relatedContext);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceOperationCreation((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), operationName, relatedContext);
}
catch(Exception ex)
{
//view function comment
LogAndDisable(ex);
}
#endif
}
[FriendAccessAllowed]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal static void TraceOperationCompletion(CausalityTraceLevel traceLevel, int taskId, AsyncCausalityStatus status)
{
#if FEATURE_COMINTEROP
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
TplEtwProvider.Log.TraceOperationEnd(taskId, status);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceOperationCompletion((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.AsyncCausalityStatus)status);
}
catch(Exception ex)
{
//view function comment
LogAndDisable(ex);
}
#endif
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal static void TraceOperationRelation(CausalityTraceLevel traceLevel, int taskId, CausalityRelation relation)
{
#if FEATURE_COMINTEROP
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
TplEtwProvider.Log.TraceOperationRelation(taskId, relation);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceOperationRelation((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalityRelation)relation);
}
catch(Exception ex)
{
//view function comment
LogAndDisable(ex);
}
#endif
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal static void TraceSynchronousWorkStart(CausalityTraceLevel traceLevel, int taskId, CausalitySynchronousWork work)
{
#if FEATURE_COMINTEROP
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
TplEtwProvider.Log.TraceSynchronousWorkBegin(taskId, work);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceSynchronousWorkStart((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalitySynchronousWork)work);
}
catch(Exception ex)
{
//view function comment
LogAndDisable(ex);
}
#endif
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal static void TraceSynchronousWorkCompletion(CausalityTraceLevel traceLevel, CausalitySynchronousWork work)
{
#if FEATURE_COMINTEROP
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
TplEtwProvider.Log.TraceSynchronousWorkEnd(work);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceSynchronousWorkCompletion((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, (WFD.CausalitySynchronousWork)work);
}
catch(Exception ex)
{
//view function comment
LogAndDisable(ex);
}
#endif
}
#if FEATURE_COMINTEROP
//fix for 796185: leaking internal exceptions to customers,
//we should catch and log exceptions but never propagate them.
private static void LogAndDisable(Exception ex)
{
f_LoggingOn = 0;
Debugger.Log(0, "AsyncCausalityTracer", ex.ToString());
}
#endif
private static ulong GetOperationId(uint taskId)
{
return (((ulong)AppDomain.CurrentDomain.Id) << 32) + taskId;
}
}
}
| |
// 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;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Crypto
{
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaCreate")]
internal static extern SafeRsaHandle RsaCreate();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaUpRef")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool RsaUpRef(IntPtr rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaDestroy")]
internal static extern void RsaDestroy(IntPtr rsa);
internal static SafeRsaHandle DecodeRsaPublicKey(ReadOnlySpan<byte> buf) =>
DecodeRsaPublicKey(ref MemoryMarshal.GetReference(buf), buf.Length);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeRsaPublicKey")]
private static extern SafeRsaHandle DecodeRsaPublicKey(ref byte buf, int len);
internal static int RsaPublicEncrypt(
int flen,
ReadOnlySpan<byte> from,
Span<byte> to,
SafeRsaHandle rsa,
RsaPadding padding) =>
RsaPublicEncrypt(flen, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa, padding);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaPublicEncrypt")]
private static extern int RsaPublicEncrypt(
int flen,
ref byte from,
ref byte to,
SafeRsaHandle rsa,
RsaPadding padding);
internal static int RsaPrivateDecrypt(
int flen,
ReadOnlySpan<byte> from,
Span<byte> to,
SafeRsaHandle rsa,
RsaPadding padding) =>
RsaPrivateDecrypt(flen, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa, padding);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaPrivateDecrypt")]
private static extern int RsaPrivateDecrypt(
int flen,
ref byte from,
ref byte to,
SafeRsaHandle rsa,
RsaPadding padding);
internal static int RsaSignPrimitive(
ReadOnlySpan<byte> from,
Span<byte> to,
SafeRsaHandle rsa) =>
RsaSignPrimitive(from.Length, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaSignPrimitive")]
private static extern int RsaSignPrimitive(
int flen,
ref byte from,
ref byte to,
SafeRsaHandle rsa);
internal static int RsaVerificationPrimitive(
ReadOnlySpan<byte> from,
Span<byte> to,
SafeRsaHandle rsa) =>
RsaVerificationPrimitive(from.Length, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaVerificationPrimitive")]
private static extern int RsaVerificationPrimitive(
int flen,
ref byte from,
ref byte to,
SafeRsaHandle rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaSize")]
internal static extern int RsaSize(SafeRsaHandle rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaGenerateKeyEx")]
internal static extern int RsaGenerateKeyEx(SafeRsaHandle rsa, int bits, SafeBignumHandle e);
internal static bool RsaSign(int type, ReadOnlySpan<byte> m, int m_len, Span<byte> sigret, out int siglen, SafeRsaHandle rsa) =>
RsaSign(type, ref MemoryMarshal.GetReference(m), m_len, ref MemoryMarshal.GetReference(sigret), out siglen, rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaSign")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RsaSign(int type, ref byte m, int m_len, ref byte sigret, out int siglen, SafeRsaHandle rsa);
internal static bool RsaVerify(int type, ReadOnlySpan<byte> m, ReadOnlySpan<byte> sigbuf, SafeRsaHandle rsa)
{
bool ret = RsaVerify(
type,
ref MemoryMarshal.GetReference(m),
m.Length,
ref MemoryMarshal.GetReference(sigbuf),
sigbuf.Length,
rsa);
if (!ret)
{
ErrClearError();
}
return ret;
}
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaVerify")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RsaVerify(int type, ref byte m, int m_len, ref byte sigbuf, int siglen, SafeRsaHandle rsa);
internal static RSAParameters ExportRsaParameters(SafeRsaHandle key, bool includePrivateParameters)
{
Debug.Assert(
key != null && !key.IsInvalid,
"Callers should check the key is invalid and throw an exception with a message");
if (key == null || key.IsInvalid)
{
throw new CryptographicException();
}
bool addedRef = false;
try
{
key.DangerousAddRef(ref addedRef);
IntPtr n, e, d, p, dmp1, q, dmq1, iqmp;
if (!GetRsaParameters(key, out n, out e, out d, out p, out dmp1, out q, out dmq1, out iqmp))
{
throw new CryptographicException();
}
int modulusSize = Crypto.RsaSize(key);
// RSACryptoServiceProvider expects P, DP, Q, DQ, and InverseQ to all
// be padded up to half the modulus size.
int halfModulus = modulusSize / 2;
RSAParameters rsaParameters = new RSAParameters
{
Modulus = Crypto.ExtractBignum(n, modulusSize),
Exponent = Crypto.ExtractBignum(e, 0),
};
if (includePrivateParameters)
{
rsaParameters.D = Crypto.ExtractBignum(d, modulusSize);
rsaParameters.P = Crypto.ExtractBignum(p, halfModulus);
rsaParameters.DP = Crypto.ExtractBignum(dmp1, halfModulus);
rsaParameters.Q = Crypto.ExtractBignum(q, halfModulus);
rsaParameters.DQ = Crypto.ExtractBignum(dmq1, halfModulus);
rsaParameters.InverseQ = Crypto.ExtractBignum(iqmp, halfModulus);
}
return rsaParameters;
}
finally
{
if (addedRef)
key.DangerousRelease();
}
}
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetRsaParameters")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetRsaParameters(
SafeRsaHandle key,
out IntPtr n,
out IntPtr e,
out IntPtr d,
out IntPtr p,
out IntPtr dmp1,
out IntPtr q,
out IntPtr dmq1,
out IntPtr iqmp);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SetRsaParameters")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetRsaParameters(
SafeRsaHandle key,
byte[] n,
int nLength,
byte[] e,
int eLength,
byte[] d,
int dLength,
byte[] p,
int pLength,
byte[] dmp1,
int dmp1Length,
byte[] q,
int qLength,
byte[] dmq1,
int dmq1Length,
byte[] iqmp,
int iqmpLength);
internal enum RsaPadding : int
{
Pkcs1 = 0,
OaepSHA1 = 1,
NoPadding = 2,
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using gView.Framework.Geometry;
using gView.Framework.FDB;
namespace gView.Framework.Data
{
public class RowData : IRowData
{
protected List<FieldValue> _fields;
private bool _caseSensitivFieldnameMatching;
public RowData()
{
_fields = new List<FieldValue>();
_caseSensitivFieldnameMatching = true;
}
#region IRowData Member
public List<FieldValue> Fields
{
get
{
return _fields;
}
}
public object this[string fieldName]
{
get
{
if (_caseSensitivFieldnameMatching == true)
{
foreach (FieldValue fv in _fields)
{
if (fv.Name == fieldName) return fv.Value;
}
}
else
{
fieldName = fieldName.ToLower();
foreach (FieldValue fv in _fields)
{
if (fv.Name.ToLower() == fieldName) return fv.Value;
}
}
return null;
}
set
{
if (_caseSensitivFieldnameMatching)
{
foreach (FieldValue fv in _fields)
{
if (fv.Name == fieldName)
{
fv.Value = value;
}
}
}
else
{
fieldName = fieldName.ToLower();
foreach (FieldValue fv in _fields)
{
if (fv.Name.ToLower() == fieldName)
{
fv.Value = value;
return;
}
}
}
}
}
public object this[int fieldIndex]
{
get
{
if (fieldIndex < 0 || fieldIndex >= _fields.Count) return null;
return _fields[fieldIndex].Value;
}
set
{
if (fieldIndex < 0 || fieldIndex >= _fields.Count) return;
_fields[fieldIndex].Value = value;
}
}
public FieldValue FindField(string name)
{
if (_caseSensitivFieldnameMatching)
{
foreach (FieldValue field in this.Fields)
{
if (field.Name == name)
return field;
}
}
else
{
name = name.ToLower();
foreach (FieldValue field in this.Fields)
{
if (field.Name.ToLower() == name)
return field;
}
}
return null;
}
public bool CaseSensitivFieldnameMatching
{
get { return _caseSensitivFieldnameMatching; }
set { _caseSensitivFieldnameMatching = value; }
}
#endregion
#region IDBOperations Member
public bool BeforeInsert(ITableClass tClass)
{
if (!(tClass is IFeatureClass)) return false;
IFeatureClass fc = (IFeatureClass)tClass;
foreach (IField field in fc.Fields.ToEnumerable())
{
if (field is IAutoField)
{
if (!((IAutoField)field).OnInsert(fc, this as IFeature)) return false;
}
}
return true;
}
public bool BeforeUpdate(ITableClass tClass)
{
if (!(tClass is IFeatureClass)) return false;
IFeatureClass fc = (IFeatureClass)tClass;
foreach (IField field in fc.Fields.ToEnumerable())
{
if (field is IAutoField)
{
if (!((IAutoField)field).OnUpdate(fc, this as IFeature)) return false;
}
}
return true;
}
public bool BeforeDelete(ITableClass tClass)
{
return true;
}
#endregion
}
public class Row : RowData, IRow
{
protected int _oid;
public Row()
: base()
{
}
#region IOID Member
public int OID
{
get
{
return _oid;
}
set
{
_oid = value;
}
}
#endregion
}
public class GlobalRow : RowData, IGlobalRow
{
protected long _oid;
public GlobalRow()
: base()
{
}
#region IOID Member
public long GlobalOID
{
get
{
return _oid;
}
set
{
_oid = value;
}
}
#endregion
}
public class Feature : Row, IFeature
{
private gView.Framework.Geometry.IGeometry _geometry;
public Feature()
: base()
{
}
public Feature(IRow row)
: base()
{
if (row == null) return;
_oid = row.OID;
_fields = row.Fields;
}
#region IFeature Member
public gView.Framework.Geometry.IGeometry Shape
{
get
{
return _geometry;
}
set
{
_geometry=value;
}
}
#endregion
public static void CopyFrom(IFeature original, IFeature feature)
{
if (feature == null || original == null) return;
original.Shape = feature.Shape;
if (feature.Fields != null)
{
foreach (IFieldValue fv in feature.Fields)
{
original[fv.Name] = fv.Value;
}
}
}
}
public class Features : List<IFeature>
{
}
public class GlobalFeature : GlobalRow, IGlobalFeature, IFeature
{
private gView.Framework.Geometry.IGeometry _geometry;
public GlobalFeature()
: base()
{
}
public GlobalFeature(IGlobalRow row)
: base()
{
if (row == null) return;
_oid = row.GlobalOID;
_fields = row.Fields;
}
#region IGlobalFeature Member
public gView.Framework.Geometry.IGeometry Shape
{
get
{
return _geometry;
}
set
{
_geometry = value;
}
}
#endregion
#region IOID Member
public int OID
{
get { return (int)(_oid & 0xffffffff); }
}
#endregion
}
public class FieldValue : gView.Framework.Data.IFieldValue
{
private string _name;
private object _value;
public FieldValue(string name)
{
_name=name;
}
public FieldValue(string name,object val)
{
_name=name;
_value=val;
}
public void Rename(string newName)
{
_name = newName;
}
#region IFieldValue Member
public string Name
{
get
{
return _name;
}
}
public object Value
{
get
{
return _value;
}
set
{
_value=value;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using Assets.Sources.Scripts.UI.Common;
using Memoria.Prime;
using Memoria.Prime.Text;
using Memoria.Prime.Threading;
using ExtensionMethodsIEnumerable = Memoria.Scenes.ExtensionMethodsIEnumerable;
namespace Memoria.Assets
{
public sealed class FieldImporter : TextImporter
{
private const String EndingTag = "[ENDN]";
private const Int32 EndingLength = 6;
private static String TypeName => nameof(FieldImporter);
private readonly ImportFieldTags _formatter = new ImportFieldTags();
private volatile Dictionary<Int32, String[]> _cache = new Dictionary<Int32, String[]>();
private volatile Boolean _initialized;
private volatile FileSystemWatcher _watcher;
private volatile AutoResetEvent _watcherEvent;
private volatile Task _watcherTask;
private Int32 _fieldZoneId;
private String _fieldFileName;
private String[] _original;
private TxtEntry[] _external;
private Dictionary<String, LinkedList<UInt64>> _dic;
private IList<KeyValuePair<String, TextReplacement>> _customTags;
private IList<KeyValuePair<String, TextReplacement>> _fieldReplacements;
private Dictionary<String, IList<KeyValuePair<String, TextReplacement>>> _fieldTags;
public Task InitializationTask { get; private set; }
public void InitializeAsync()
{
InitializationTask = Task.Run(Initialize);
}
private void Initialize()
{
String directory = ModTextResources.Import.FieldsDirectory;
if (!Directory.Exists(directory))
{
Log.Warning($"[{TypeName}] Import was skipped bacause a directory does not exist: [{directory}].");
return;
}
Log.Message($"[{TypeName}] Initialization...");
try
{
_dic = new Dictionary<String, LinkedList<UInt64>>();
_customTags = LoadCustomTags();
_fieldTags = LoadFieldTags();
KeyValuePair<Int32, String> chocoboForest = new KeyValuePair<Int32, String>(945, "MES_CHOCO");
foreach (KeyValuePair<Int32, String> pair in ExtensionMethodsIEnumerable.Append(FF9DBAll.EventDB, chocoboForest))
{
_fieldZoneId = pair.Key;
_fieldFileName = _fieldZoneId.ToString("D4", CultureInfo.InvariantCulture) + '_' + pair.Value;
if (!ReadEmbadedText(_fieldZoneId, out _original))
{
_cache[_fieldZoneId] = null;
continue;
}
if (!ReadExternalText(out _external))
{
Log.Warning($"[{TypeName}] External file not found: [{Path.Combine(ModTextResources.Import.FieldsDirectory, _fieldFileName + ".strings")}]");
_cache[_fieldZoneId] = _original;
continue;
}
if (_original.Length != _external.Length)
{
Log.Warning($"[{TypeName}] Number of lines in files does not match. [Original: {_original.Length}, External: {_external.Length}]");
_cache[_fieldZoneId] = _original;
continue;
}
_fieldTags.TryGetValue(_fieldFileName, out _fieldReplacements);
_cache[_fieldZoneId] = MergeEntries();
}
ResolveReferences();
_initialized = true;
if (_watcher == null)
{
_watcherEvent = new AutoResetEvent(false);
_watcherTask = Task.Run(DoWatch);
_watcher = new FileSystemWatcher(directory, "*.strings");
GameLoopManager.Quit += _watcher.Dispose;
_watcher.Changed += OnChangedFileInDirectory;
_watcher.Created += OnChangedFileInDirectory;
_watcher.Deleted += OnChangedFileInDirectory;
_watcher.EnableRaisingEvents = true;
}
Log.Message($"[{TypeName}] Initialization completed successfully.");
}
catch (Exception ex)
{
Log.Error(ex, $"[{TypeName}] Initialization failed.");
}
finally
{
_dic = null;
_original = null;
_external = null;
_fieldReplacements = null;
}
}
private void DoWatch()
{
Int32 retryCount = 20;
try
{
while (retryCount > 0)
{
try
{
_watcherEvent.WaitOne();
DateTime beginTime = DateTime.UtcNow;
Log.Message("[TextWatcher] Field's text was changed. Reinitialize...");
FieldImporter importer = new FieldImporter();
importer._watcher = _watcher;
importer.Initialize();
_cache = importer._cache;
_customTags = importer._customTags;
_fieldTags = importer._fieldTags;
importer = null;
LoadExternal();
Log.Message($"[TextWatcher] Reinitialized for {DateTime.UtcNow - beginTime}");
}
catch (Exception ex)
{
retryCount--;
Log.Error(ex, "[TextWatcher] Failed to iterate.");
}
}
}
catch (Exception ex)
{
Log.Error(ex, "[TextWatcher] Failed to watch.");
}
}
private void OnChangedFileInDirectory(Object sender, FileSystemEventArgs e)
{
_watcherEvent.Set();
}
private static IList<KeyValuePair<String, TextReplacement>> LoadCustomTags()
{
String inputPath = ModTextResources.Import.FieldTags;
return ReadTagReplacements(inputPath);
}
private static Dictionary<String, IList<KeyValuePair<String, TextReplacement>>> LoadFieldTags()
{
String fieldsDirectory = ModTextResources.Import.FieldsDirectory;
if (!Directory.Exists(fieldsDirectory))
return new Dictionary<String, IList<KeyValuePair<String, TextReplacement>>>(0);
String[] filePathes = Directory.GetFiles(fieldsDirectory, "*_Tags.strings");
Dictionary<String, IList<KeyValuePair<String, TextReplacement>>> fieldNames = new Dictionary<String, IList<KeyValuePair<String, TextReplacement>>>(filePathes.Length);
foreach (String path in filePathes)
{
String fileName = Path.GetFileName(path);
if (fileName == null)
{
Log.Warning($"[{TypeName}] Invalid file path: [{path}].");
continue;
}
fileName = fileName.Substring(0, fileName.Length - "_Tags.strings".Length);
fieldNames[fileName] = ReadTagReplacements(path);
}
return fieldNames;
}
private static IList<KeyValuePair<String, TextReplacement>> ReadTagReplacements(String inputPath)
{
if (!File.Exists(inputPath))
return new List<KeyValuePair<String, TextReplacement>>();
TxtEntry[] generalNames = TxtReader.ReadStrings(inputPath);
if (generalNames.IsNullOrEmpty())
return new List<KeyValuePair<String, TextReplacement>>();
TextReplacements result = new TextReplacements(generalNames.Length);
foreach (TxtEntry entry in generalNames)
result.Add(entry.Prefix, entry.Value);
return result.Forward;
}
private void ResolveReferences()
{
Int32 currentZoneId = -1;
String[] currentText = null;
foreach (KeyValuePair<String, LinkedList<UInt64>> pair in _dic)
{
Int32 zoneId, lineId;
String target = pair.Key;
do
{
String str = target.Substring(2, 4);
if (!Int32.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out zoneId))
{
Log.Warning($"[{TypeName}] Failed to parse a zone ID from the reference: [{str}].");
break;
}
str = target.Substring(target.Length - 5, 4);
if (!Int32.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out lineId))
{
Log.Warning($"[{TypeName}] Failed to parse a line number from the reference: [{str}].");
break;
}
if (zoneId != currentZoneId)
{
if (!_cache.TryGetValue(zoneId, out currentText))
{
Log.Warning($"[{TypeName}] Failed to find zone by ID: {zoneId}].");
break;
}
currentZoneId = zoneId;
}
if (currentText == null)
{
Log.Warning($"[{TypeName}] Failed to find text by zone ID: {zoneId}].");
break;
}
if (lineId > currentText.Length)
{
Log.Warning($"[{TypeName}] Failed to find line by number: {lineId}].");
break;
}
target = currentText[lineId];
// new
String currentZoneName = GetZoneName(currentZoneId);
IList<KeyValuePair<String, TextReplacement>> tags;
if (_fieldTags.TryGetValue(currentZoneName, out tags))
target = target.ReplaceAll(tags);
} while (target.StartsWith("{$"));
foreach (UInt64 value in pair.Value)
{
zoneId = (Int32)(value >> 32);
lineId = (Int32)(value & UInt32.MaxValue);
_cache[zoneId][lineId] = target;
}
}
}
private String GetZoneName(Int32 zoneId)
{
String name;
if (zoneId == 945)
name = "MES_CHOCO";
else
name = FF9DBAll.EventDB[zoneId];
return zoneId.ToString("D4", CultureInfo.InvariantCulture) + '_' + name;
}
private String[] MergeEntries()
{
String[] result = new String[_original.Length];
for (Int32 index = 0; index < result.Length; index++)
{
String original = _original[index];
if (String.IsNullOrEmpty(original))
{
result[index] = original;
continue;
}
String external = _external[index].Value;
if (external.StartsWith("{$"))
{
LinkedList<UInt64> list;
if (!_dic.TryGetValue(external, out list))
{
list = new LinkedList<UInt64>();
_dic[external] = list;
}
list.AddLast(((UInt64)_fieldZoneId << 32) | (UInt32)index);
result[index] = external;
continue;
}
//external = external.ReplaceAll(_fieldReplacements, _customTags, _formatter.SimpleTags.Backward, _formatter.ComplexTags).TrimEnd();
//external = external.ReplaceAll(_fieldReplacements, _customTags).TrimEnd();
external = external.TrimEnd();
String ending = GetEnding(original);
if (ending != String.Empty)
external += ending;
result[index] = external;
}
return result;
}
public static String GetEnding(String str)
{
StringBuilder sb = new StringBuilder(6);
for (Int32 i = str.Length - 1; i >= 0; i--)
{
Char ch = str[i];
if (ch == '\n' || ch == ' ')
{
sb.Insert(0, ch);
continue;
}
Int32 offset = i - EndingLength + 1;
if (offset < 0)
continue;
if (str.IndexOf(EndingTag, offset, EndingLength, StringComparison.Ordinal) != offset)
break;
sb.Insert(0, EndingTag);
i = offset;
}
return sb.Length > 0 ? sb.ToString() : String.Empty;
}
private Boolean ReadExternalText(out TxtEntry[] entries)
{
String inputPath = Path.Combine(ModTextResources.Import.FieldsDirectory, _fieldFileName + ".strings");
if (!File.Exists(inputPath))
{
entries = null;
return false;
}
entries = TxtReader.ReadStrings(inputPath);
return !entries.IsNullOrEmpty();
}
protected override Boolean LoadInternal()
{
Int32 fieldZoneId = FF9TextTool.FieldZoneId;
String[] text;
if (ReadEmbadedText(fieldZoneId, out text))
{
FF9TextTool.SetFieldText(text);
FF9TextTool.SetTableText(FF9TextTool.ExtractTableText(text));
}
return true;
}
private static Boolean ReadEmbadedText(Int32 fieldZoneId, out String[] text)
{
String path = EmbadedTextResources.GetCurrentPath("/Field/" + FF9TextTool.GetFieldTextFileName(fieldZoneId) + ".mes");
String raw = EmbadedSentenseLoader.LoadText(path);
if (raw != null)
{
raw = TextOpCodeModifier.Modify(raw);
text = FF9TextTool.ExtractSentense(raw);
return true;
}
text = null;
return false;
}
protected override Boolean LoadExternal()
{
try
{
if (!_initialized)
return false;
Int32 fieldZoneId = FF9TextTool.FieldZoneId;
String[] result;
if (!_cache.TryGetValue(fieldZoneId, out result))
{
Log.Warning($"[{TypeName}] Failed to find zone by ID: {fieldZoneId}].");
return true;
}
if (result != null)
{
// new
String fieldZoneName = GetZoneName(fieldZoneId);
IList<KeyValuePair<String, TextReplacement>> filedTags;
if (_fieldTags.TryGetValue(fieldZoneName, out filedTags))
{
for (Int32 i = 0; i < result.Length; i++)
result[i] = result[i].ReplaceAll(filedTags, _customTags);
}
else
{
for (Int32 i = 0; i < result.Length; i++)
result[i] = result[i].ReplaceAll(_customTags);
}
FF9TextTool.SetFieldText(result);
FF9TextTool.SetTableText(FF9TextTool.ExtractTableText(result));
}
return true;
}
catch (Exception ex)
{
_initialized = true;
Log.Error(ex, $"[{TypeName}] Failed to import resource.");
return false;
}
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using ESRI.ArcGIS.Geometry;
using System;
namespace MultiPatchExamples
{
public static class TrianglesExamples
{
private static object _missing = Type.Missing;
public static IGeometry GetExample1()
{
//Triangles: One Triangle Lying On XY Plane
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass();
IPointCollection trianglesPointCollection = new TrianglesClass();
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, 2.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 2.5, 0), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(trianglesPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
public static IGeometry GetExample2()
{
//Triangles: One Upright Triangle
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass();
IPointCollection trianglesPointCollection = new TrianglesClass();
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, 2.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, 2.5, 7.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 2.5, 7.5), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(trianglesPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
public static IGeometry GetExample3()
{
//Triangles: Three Upright Triangles
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass();
IPointCollection trianglesPointCollection = new TrianglesClass();
//Triangle 1
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, 2.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, 2.5, 7.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 2.5, 7.5), ref _missing, ref _missing);
//Triangle 2
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 2.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 2.5, 7.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-2.5, 2.5, 7.5), ref _missing, ref _missing);
//Triangle 3
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-2.5, -2.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-2.5, -2.5, 7.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, -2.5, 7.5), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(trianglesPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
public static IGeometry GetExample4()
{
//Triangles: Six Triangles Lying In Different Planes
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass();
IPointCollection trianglesPointCollection = new TrianglesClass();
//Triangle 1
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 5, 0), ref _missing, ref _missing);
//Triangle 2
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 5, 0), ref _missing, ref _missing);
//Triangle 3
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, -5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, -5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, -7.5, 0), ref _missing, ref _missing);
//Triangle 4
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 7.5, 2.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 7.5, 0), ref _missing, ref _missing);
//Triangle 5
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, -7.5, 2.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, -7.5, 0), ref _missing, ref _missing);
//Triangle 6
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, -7.5, 2.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, -7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, -7.5, 0), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(trianglesPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
public static IGeometry GetExample5()
{
//Triangles: Eighteen Triangles Lying In Different Planes
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass();
IPointCollection trianglesPointCollection = new TrianglesClass();
//Z > 0
//Triangle 1
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 7.5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 7.5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 5, 5), ref _missing, ref _missing);
//Triangle 2
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 7.5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 7.5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 5, 5), ref _missing, ref _missing);
//Triangle 3
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, -5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, -5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, -7.5, 5), ref _missing, ref _missing);
//Triangle 4
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 7.5, 7.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, 7.5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 7.5, 5), ref _missing, ref _missing);
//Triangle 5
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, -7.5, 7.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -7.5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, -7.5, 5), ref _missing, ref _missing);
//Triangle 6
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, -7.5, 7.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, -7.5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, -7.5, 5), ref _missing, ref _missing);
//Z = 0
//Triangle 1
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 5, 0), ref _missing, ref _missing);
//Triangle 2
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 5, 0), ref _missing, ref _missing);
//Triangle 3
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, -5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, -5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, -7.5, 0), ref _missing, ref _missing);
//Triangle 4
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 7.5, 2.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, 7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 7.5, 0), ref _missing, ref _missing);
//Triangle 5
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, -7.5, 2.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, -7.5, 0), ref _missing, ref _missing);
//Triangle 6
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, -7.5, 2.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, -7.5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, -7.5, 0), ref _missing, ref _missing);
//Z < 0
//Triangle 1
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 7.5, -5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 7.5, -5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, 5, -5), ref _missing, ref _missing);
//Triangle 2
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 7.5, -5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 7.5, -5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 5, -5), ref _missing, ref _missing);
//Triangle 3
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, -5, -5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, -5, -5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, -7.5, -5), ref _missing, ref _missing);
//Triangle 4
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 7.5, -2.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, 7.5, -5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 7.5, -5), ref _missing, ref _missing);
//Triangle 5
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, -7.5, -2.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -7.5, -5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, -7.5, -5), ref _missing, ref _missing);
//Triangle 6
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, -7.5, -2.5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, -7.5, -5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, -7.5, -5), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(trianglesPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
public static IGeometry GetExample6()
{
//Triangles: Closed Box Constructed From Single Triangles Part Composed Of 12 Triangles
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass() as IGeometryCollection;
IPointCollection trianglesPointCollection = new TrianglesClass() as IPointCollection;
//Bottom
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 0), ref _missing, ref _missing);
//Side 1
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 5), ref _missing, ref _missing);
//Side 2
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 5), ref _missing, ref _missing);
//Side 3
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 5), ref _missing, ref _missing);
//Side 4
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 0), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 5), ref _missing, ref _missing);
//Top
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 5), ref _missing, ref _missing);
trianglesPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 5), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(trianglesPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
}
}
| |
//
// 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.Specialized;
using System.Data;
using System.Runtime.InteropServices;
using System.Text;
namespace IBM.Data.DB2
{
public class DB2Connection : System.ComponentModel.Component, IDbConnection, ICloneable
{
#region private data members
private ArrayList refCommands;
private WeakReference refTransaction;
private DB2ConnectionSettings connectionSettings = null;
private int connectionTimeout;
internal DB2OpenConnection openConnection;
private bool disposed = false;
#endregion
#region Constructors
public DB2Connection()
{
connectionTimeout = 15;
}
public DB2Connection(string conString)
{
SetConnectionString(conString);
}
#endregion
#region ConnectionString property
public string ConnectionString
{
get
{
return connectionSettings.ConnectionString;
}
set
{
SetConnectionString(value);
}
}
#endregion
#region ConnectionTimeout property
public int ConnectionTimeout
{
get
{
return connectionTimeout;
}
set
{
connectionTimeout = value;
}
}
#endregion
#region Database property
public string Database
{
get
{
return connectionSettings.DatabaseAlias;
}
}
#endregion
#region State property
unsafe public ConnectionState State
{
get
{
//if ((long)dbHandle.ToPointer() == DB2Constants.SQL_NULL_HANDLE)
if (openConnection == null)
return ConnectionState.Closed;
return ConnectionState.Open;
}
}
#endregion
#region events
public event DB2InfoMessageEventHandler InfoMessage;
public event StateChangeEventHandler StateChange;
internal void OnInfoMessage(short handleType, IntPtr handle)
{
if(InfoMessage != null)
{
// Don't get error information until we know for sure someone is listening
try
{
InfoMessage(this,
new DB2InfoMessageEventArgs(new DB2ErrorCollection(handleType, handle)));
}
catch(Exception)
{}
}
}
private void OnStateChange(StateChangeEventArgs args)
{
if(StateChange != null)
StateChange(this, args);
}
#endregion
#region DBHandle
internal IntPtr DBHandle
{
get
{
return (openConnection == null) ? IntPtr.Zero : openConnection.DBHandle;
}
}
#endregion
#region BeginTransaction Method
IDbTransaction IDbConnection.BeginTransaction()
{
return BeginTransaction();
}
IDbTransaction IDbConnection.BeginTransaction(IsolationLevel isolationL)
{
return BeginTransaction(isolationL);
}
public DB2Transaction BeginTransaction()
{
return BeginTransaction(IsolationLevel.ReadCommitted);
}
public DB2Transaction BeginTransaction(IsolationLevel isolationL)
{
if ((refTransaction != null) && (refTransaction.IsAlive))
throw new InvalidOperationException("Cannot open another transaction");
if(State != ConnectionState.Open)
throw new InvalidOperationException("BeginTransaction needs an open connection");
if(refTransaction != null)
{
if(refTransaction.IsAlive)
throw new InvalidOperationException("Parallel transactions not supported");
openConnection.RollbackDeadTransaction();
refTransaction = null;
}
openConnection.transactionOpen = true;
DB2Transaction tran = new DB2Transaction(this, isolationL);
refTransaction = new WeakReference(tran);
return tran;
}
#endregion
#region ChangeDatabase
unsafe public void ChangeDatabase(string newDBName)
{
if(connectionSettings == null)
{
throw new InvalidOperationException("No connection string");
}
this.Close();
SetConnectionString(connectionSettings.ConnectionString.Replace(connectionSettings.DatabaseAlias, newDBName));
this.Open();
}
#endregion
#region ReleaseObjectPool
public static void ReleaseObjectPool()
{
DB2Environment.Instance.Dispose();
}
#endregion
#region Close
public void Close()
{
DB2Transaction transaction = null;
if(refTransaction != null)
transaction = (DB2Transaction)refTransaction.Target;
if((transaction != null) && refTransaction.IsAlive)
{
transaction.Dispose();
}
if(refCommands != null)
{
for(int i = 0; i < refCommands.Count; i++)
{
DB2Command command = null;
if(refCommands[i] != null)
{
command = (DB2Command)((WeakReference)refCommands[i]).Target;
}
if((command != null) && ((WeakReference)refCommands[i]).IsAlive)
{
try
{
command.ConnectionClosed();
}
catch{}
}
//?? refCommands[i] = null;
}
}
if(openConnection != null)
{
openConnection.Close();
openConnection = null;
}
}
#endregion
#region CreateCommand
IDbCommand IDbConnection.CreateCommand()
{
return CreateCommand();
}
public DB2Command CreateCommand()
{
//CheckState();
return new DB2Command(null, this);
}
#endregion
#region Open
unsafe public void Open()
{
if(disposed)
{
throw new ObjectDisposedException("DB2Connection");
}
if (this.State == ConnectionState.Open || this.State == ConnectionState.Connecting || this.State == ConnectionState.Executing || this.State == ConnectionState.Fetching)
{
throw new InvalidOperationException("Connection already open");
}
try
{
openConnection = connectionSettings.GetRealOpenConnection(this);
}
catch (DB2Exception)
{
Close();
throw;
}
}
#endregion
#region Dispose
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
{
// dispose managed resources
Close();
}
}
base.Dispose(disposing);
disposed = true;
}
~DB2Connection()
{
Dispose(false);
}
#endregion
private void CheckState()
{
if (ConnectionState.Closed == State)
throw new InvalidOperationException("Connection is currently closed.");
}
void SetConnectionString (string connectionString)
{
if (State != ConnectionState.Closed)
throw new InvalidOperationException("Connection is not closed.");
this.connectionSettings = DB2ConnectionSettings.GetConnectionSettings(connectionString);
}
internal WeakReference WeakRefTransaction
{
get
{
return refTransaction;
}
set
{
refTransaction = value;
}
}
internal void AddCommand(DB2Command command)
{
if(refCommands == null)
{
refCommands = new ArrayList();
}
for(int i = 0; i < refCommands.Count; i++)
{
WeakReference reference = (WeakReference)refCommands[i];
if((reference == null) || !reference.IsAlive)
{
refCommands[i] = new WeakReference(command);
return;
}
}
refCommands.Add(new WeakReference(command));
}
internal void RemoveCommand(DB2Command command)
{
for(int i = 0; i < refCommands.Count; i++)
{
WeakReference reference = (WeakReference)refCommands[i];
if(object.ReferenceEquals(reference, command))
{
refCommands[i] = null;
return;
}
}
}
#region ICloneable Members
object ICloneable.Clone()
{
DB2Connection clone = new DB2Connection();
clone.connectionSettings = connectionSettings;
clone.connectionTimeout = connectionTimeout;
return clone;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Internal;
using Microsoft.Win32;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Represent a control panel item.
/// </summary>
public sealed class ControlPanelItem
{
/// <summary>
/// Control panel applet name.
/// </summary>
public string Name { get; }
/// <summary>
/// Control panel applet canonical name.
/// </summary>
public string CanonicalName { get; }
/// <summary>
/// Control panel applet category.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Category { get; }
/// <summary>
/// Control panel applet description.
/// </summary>
public string Description { get; }
/// <summary>
/// Control panel applet path.
/// </summary>
internal string Path { get; }
/// <summary>
/// Internal constructor for ControlPanelItem.
/// </summary>
/// <param name="name"></param>
/// <param name="canonicalName"></param>
/// <param name="category"></param>
/// <param name="description"></param>
/// <param name="path"></param>
internal ControlPanelItem(string name, string canonicalName, string[] category, string description, string path)
{
Name = name;
Path = path;
CanonicalName = canonicalName;
Category = category;
Description = description;
}
/// <summary>
/// ToString method.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return this.Name;
}
}
/// <summary>
/// This class implements the base for ControlPanelItem commands.
/// </summary>
public abstract class ControlPanelItemBaseCommand : PSCmdlet
{
/// <summary>
/// Locale specific verb action Open string exposed by the control panel item.
/// </summary>
private static string s_verbActionOpenName = null;
/// <summary>
/// Canonical name of the control panel item used as a reference to fetch the verb
/// action Open string. This control panel item exists on all SKU's.
/// </summary>
private const string RegionCanonicalName = "Microsoft.RegionAndLanguage";
private const string ControlPanelShellFolder = "shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}";
private static readonly string[] s_controlPanelItemFilterList = new string[] { "Folder Options", "Taskbar and Start Menu" };
private const string TestHeadlessServerScript = @"
$result = $false
$serverManagerModule = Get-Module -ListAvailable | Where-Object {$_.Name -eq 'ServerManager'}
if ($serverManagerModule -ne $null)
{
Import-Module ServerManager
$Gui = (Get-WindowsFeature Server-Gui-Shell).Installed
if ($Gui -eq $false)
{
$result = $true
}
}
$result
";
internal readonly Dictionary<string, string> CategoryMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
internal string[] CategoryNames = { "*" };
internal string[] RegularNames = { "*" };
internal string[] CanonicalNames = { "*" };
internal ControlPanelItem[] ControlPanelItems = new ControlPanelItem[0];
/// <summary>
/// Get all executable control panel items.
/// </summary>
internal List<ShellFolderItem> AllControlPanelItems
{
get
{
if (_allControlPanelItems == null)
{
_allControlPanelItems = new List<ShellFolderItem>();
string allItemFolderPath = ControlPanelShellFolder + "\\0";
IShellDispatch4 shell2 = (IShellDispatch4)new Shell();
Folder2 allItemFolder = (Folder2)shell2.NameSpace(allItemFolderPath);
FolderItems3 allItems = (FolderItems3)allItemFolder.Items();
bool applyControlPanelItemFilterList = IsServerCoreOrHeadLessServer();
foreach (ShellFolderItem item in allItems)
{
if (applyControlPanelItemFilterList)
{
bool match = false;
foreach (string name in s_controlPanelItemFilterList)
{
if (name.Equals(item.Name, StringComparison.OrdinalIgnoreCase))
{
match = true;
break;
}
}
if (match)
continue;
}
if (ContainVerbOpen(item))
_allControlPanelItems.Add(item);
}
}
return _allControlPanelItems;
}
}
private List<ShellFolderItem> _allControlPanelItems;
#region Cmdlet Overrides
/// <summary>
/// Does the preprocessing for ControlPanelItem cmdlets.
/// </summary>
protected override void BeginProcessing()
{
System.OperatingSystem osInfo = System.Environment.OSVersion;
PlatformID platform = osInfo.Platform;
Version version = osInfo.Version;
if (platform.Equals(PlatformID.Win32NT) &&
((version.Major < 6) ||
((version.Major == 6) && (version.Minor < 2))
))
{
// Below Win8, this cmdlet is not supported because of Win8:794135
// throw terminating
string message = string.Format(CultureInfo.InvariantCulture,
ControlPanelResources.ControlPanelItemCmdletNotSupported,
this.CommandInfo.Name);
throw new PSNotSupportedException(message);
}
}
#endregion
/// <summary>
/// Test if an item can be invoked.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
private bool ContainVerbOpen(ShellFolderItem item)
{
bool result = false;
FolderItemVerbs verbs = item.Verbs();
foreach (FolderItemVerb verb in verbs)
{
if (!string.IsNullOrEmpty(verb.Name) &&
(verb.Name.Equals(ControlPanelResources.VerbActionOpen, StringComparison.OrdinalIgnoreCase) ||
CompareVerbActionOpen(verb.Name)))
{
result = true;
break;
}
}
return result;
}
/// <summary>
/// CompareVerbActionOpen is a helper function used to perform locale specific
/// comparison of the verb action Open exposed by various control panel items.
/// </summary>
/// <param name="verbActionName">Locale specific verb action exposed by the control panel item.</param>
/// <returns>True if the control panel item supports verb action open or else returns false.</returns>
private static bool CompareVerbActionOpen(string verbActionName)
{
if (s_verbActionOpenName == null)
{
const string allItemFolderPath = ControlPanelShellFolder + "\\0";
IShellDispatch4 shell2 = (IShellDispatch4)new Shell();
Folder2 allItemFolder = (Folder2)shell2.NameSpace(allItemFolderPath);
FolderItems3 allItems = (FolderItems3)allItemFolder.Items();
foreach (ShellFolderItem item in allItems)
{
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
canonicalName = !string.IsNullOrEmpty(canonicalName)
? canonicalName.Substring(0, canonicalName.IndexOf('\0'))
: null;
if (canonicalName != null && canonicalName.Equals(RegionCanonicalName, StringComparison.OrdinalIgnoreCase))
{
// The 'Region' control panel item always has '&Open' (english or other locale) as the first verb name
s_verbActionOpenName = item.Verbs().Item(0).Name;
break;
}
}
Dbg.Assert(s_verbActionOpenName != null, "The 'Region' control panel item is available on all SKUs and it always "
+ "has '&Open' as the first verb item, so VerbActionOpenName should never be null at this point");
}
return s_verbActionOpenName.Equals(verbActionName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// IsServerCoreORHeadLessServer is a helper function that checks if the current SKU is a
/// Server Core machine or if the Server-GUI-Shell feature is removed on the machine.
/// </summary>
/// <returns>True if the current SKU is a Server Core machine or if the Server-GUI-Shell
/// feature is removed on the machine or else returns false.</returns>
private bool IsServerCoreOrHeadLessServer()
{
bool result = false;
using (RegistryKey installation = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"))
{
Dbg.Assert(installation != null, "the CurrentVersion subkey should exist");
string installationType = (string)installation.GetValue("InstallationType", string.Empty);
if (installationType.Equals("Server Core"))
{
result = true;
}
else if (installationType.Equals("Server"))
{
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
{
ps.AddScript(TestHeadlessServerScript);
Collection<PSObject> psObjectCollection = ps.Invoke(Array.Empty<object>());
Dbg.Assert(psObjectCollection != null && psObjectCollection.Count == 1, "invoke should never return null, there should be only one return item");
if (LanguagePrimitives.IsTrue(PSObject.Base(psObjectCollection[0])))
{
result = true;
}
}
}
}
return result;
}
/// <summary>
/// Get the category number and name map.
/// </summary>
internal void GetCategoryMap()
{
if (CategoryMap.Count != 0)
{
return;
}
IShellDispatch4 shell2 = (IShellDispatch4)new Shell();
Folder2 categoryFolder = (Folder2)shell2.NameSpace(ControlPanelShellFolder);
FolderItems3 catItems = (FolderItems3)categoryFolder.Items();
foreach (ShellFolderItem category in catItems)
{
string path = category.Path;
string catNum = path.Substring(path.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase) + 1);
CategoryMap.Add(catNum, category.Name);
}
}
/// <summary>
/// Get control panel item by the category.
/// </summary>
/// <param name="controlPanelItems"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemByCategory(List<ShellFolderItem> controlPanelItems)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string pattern in CategoryNames)
{
bool found = false;
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (ShellFolderItem item in controlPanelItems)
{
string path = item.Path;
int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category");
foreach (int cat in categories)
{
string catStr = (string)LanguagePrimitives.ConvertTo(cat, typeof(string), CultureInfo.InvariantCulture);
Dbg.Assert(CategoryMap.ContainsKey(catStr), "the category should be contained in _categoryMap");
string catName = CategoryMap[catStr];
if (!wildcard.IsMatch(catName))
continue;
if (itemSet.Contains(path))
{
found = true;
break;
}
found = true;
itemSet.Add(path);
list.Add(item);
break;
}
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
string errMsg = StringUtil.Format(ControlPanelResources.NoControlPanelItemFoundForGivenCategory, pattern);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenCategory",
ErrorCategory.InvalidArgument, pattern);
WriteError(error);
}
}
return list;
}
/// <summary>
/// Get control panel item by the regular name.
/// </summary>
/// <param name="controlPanelItems"></param>
/// <param name="withCategoryFilter"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemByName(List<ShellFolderItem> controlPanelItems, bool withCategoryFilter)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string pattern in RegularNames)
{
bool found = false;
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (ShellFolderItem item in controlPanelItems)
{
string name = item.Name;
string path = item.Path;
if (!wildcard.IsMatch(name))
continue;
if (itemSet.Contains(path))
{
found = true;
continue;
}
found = true;
itemSet.Add(path);
list.Add(item);
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
string formatString = withCategoryFilter
? ControlPanelResources.NoControlPanelItemFoundForGivenNameWithCategory
: ControlPanelResources.NoControlPanelItemFoundForGivenName;
string errMsg = StringUtil.Format(formatString, pattern);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenName",
ErrorCategory.InvalidArgument, pattern);
WriteError(error);
}
}
return list;
}
/// <summary>
/// Get control panel item by the canonical name.
/// </summary>
/// <param name="controlPanelItems"></param>
/// <param name="withCategoryFilter"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemByCanonicalName(List<ShellFolderItem> controlPanelItems, bool withCategoryFilter)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (CanonicalNames == null)
{
bool found = false;
foreach (ShellFolderItem item in controlPanelItems)
{
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
if (canonicalName == null)
{
found = true;
list.Add(item);
}
}
if (!found)
{
string errMsg = withCategoryFilter
? ControlPanelResources.NoControlPanelItemFoundWithNullCanonicalNameWithCategory
: ControlPanelResources.NoControlPanelItemFoundWithNullCanonicalName;
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), string.Empty,
ErrorCategory.InvalidArgument, CanonicalNames);
WriteError(error);
}
return list;
}
foreach (string pattern in CanonicalNames)
{
bool found = false;
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (ShellFolderItem item in controlPanelItems)
{
string path = item.Path;
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
canonicalName = canonicalName != null
? canonicalName.Substring(0, canonicalName.IndexOf('\0'))
: null;
if (canonicalName == null)
{
if (pattern.Equals("*", StringComparison.OrdinalIgnoreCase))
{
found = true;
if (!itemSet.Contains(path))
{
itemSet.Add(path);
list.Add(item);
}
}
}
else
{
if (!wildcard.IsMatch(canonicalName))
continue;
if (itemSet.Contains(path))
{
found = true;
continue;
}
found = true;
itemSet.Add(path);
list.Add(item);
}
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
string formatString = withCategoryFilter
? ControlPanelResources.NoControlPanelItemFoundForGivenCanonicalNameWithCategory
: ControlPanelResources.NoControlPanelItemFoundForGivenCanonicalName;
string errMsg = StringUtil.Format(formatString, pattern);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenCanonicalName",
ErrorCategory.InvalidArgument, pattern);
WriteError(error);
}
}
return list;
}
/// <summary>
/// Get control panel item by the ControlPanelItem instances.
/// </summary>
/// <param name="controlPanelItems"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemsByInstance(List<ShellFolderItem> controlPanelItems)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ControlPanelItem controlPanelItem in ControlPanelItems)
{
bool found = false;
foreach (ShellFolderItem item in controlPanelItems)
{
string path = item.Path;
if (!controlPanelItem.Path.Equals(path, StringComparison.OrdinalIgnoreCase))
continue;
if (itemSet.Contains(path))
{
found = true;
break;
}
found = true;
itemSet.Add(path);
list.Add(item);
break;
}
if (!found)
{
string errMsg = StringUtil.Format(ControlPanelResources.NoControlPanelItemFoundForGivenInstance,
controlPanelItem.GetType().Name);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenInstance",
ErrorCategory.InvalidArgument, controlPanelItem);
WriteError(error);
}
}
return list;
}
}
/// <summary>
/// Get all control panel items that is available in the "All Control Panel Items" category.
/// </summary>
[Cmdlet(VerbsCommon.Get, "ControlPanelItem", DefaultParameterSetName = RegularNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=219982")]
[OutputType(typeof(ControlPanelItem))]
public sealed class GetControlPanelItemCommand : ControlPanelItemBaseCommand
{
private const string RegularNameParameterSet = "RegularName";
private const string CanonicalNameParameterSet = "CanonicalName";
#region "Parameters"
/// <summary>
/// Control panel item names.
/// </summary>
[Parameter(Position = 0, ParameterSetName = RegularNameParameterSet, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Name
{
get { return RegularNames; }
set
{
RegularNames = value;
_nameSpecified = true;
}
}
private bool _nameSpecified = false;
/// <summary>
/// Canonical names of control panel items.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = CanonicalNameParameterSet)]
[AllowNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CanonicalName
{
get { return CanonicalNames; }
set
{
CanonicalNames = value;
_canonicalNameSpecified = true;
}
}
private bool _canonicalNameSpecified = false;
/// <summary>
/// Category of control panel items.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Category
{
get { return CategoryNames; }
set
{
CategoryNames = value;
_categorySpecified = true;
}
}
private bool _categorySpecified = false;
#endregion "Parameters"
/// <summary>
/// </summary>
protected override void ProcessRecord()
{
GetCategoryMap();
List<ShellFolderItem> items = GetControlPanelItemByCategory(AllControlPanelItems);
if (_nameSpecified)
{
items = GetControlPanelItemByName(items, _categorySpecified);
}
else if (_canonicalNameSpecified)
{
items = GetControlPanelItemByCanonicalName(items, _categorySpecified);
}
List<ControlPanelItem> results = new List<ControlPanelItem>();
foreach (ShellFolderItem item in items)
{
string name = item.Name;
string path = item.Path;
string description = (string)item.ExtendedProperty("InfoTip");
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
canonicalName = canonicalName != null
? canonicalName.Substring(0, canonicalName.IndexOf('\0'))
: null;
int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category");
string[] cateStrings = new string[categories.Length];
for (int i = 0; i < categories.Length; i++)
{
string catStr = (string)LanguagePrimitives.ConvertTo(categories[i], typeof(string), CultureInfo.InvariantCulture);
Dbg.Assert(CategoryMap.ContainsKey(catStr), "the category should be contained in CategoryMap");
cateStrings[i] = CategoryMap[catStr];
}
ControlPanelItem controlPanelItem = new ControlPanelItem(name, canonicalName, cateStrings, description, path);
results.Add(controlPanelItem);
}
// Sort the results by Canonical Name
results.Sort(CompareControlPanelItems);
foreach (ControlPanelItem controlPanelItem in results)
{
WriteObject(controlPanelItem);
}
}
#region "Private Methods"
private static int CompareControlPanelItems(ControlPanelItem x, ControlPanelItem y)
{
// In the case that at least one of them is null
if (x.CanonicalName == null && y.CanonicalName == null)
return 0;
if (x.CanonicalName == null)
return 1;
if (y.CanonicalName == null)
return -1;
// In the case that both are not null
return string.Compare(x.CanonicalName, y.CanonicalName, StringComparison.OrdinalIgnoreCase);
}
#endregion "Private Methods"
}
/// <summary>
/// Show the specified control panel applet.
/// </summary>
[Cmdlet(VerbsCommon.Show, "ControlPanelItem", DefaultParameterSetName = RegularNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=219983")]
public sealed class ShowControlPanelItemCommand : ControlPanelItemBaseCommand
{
private const string RegularNameParameterSet = "RegularName";
private const string CanonicalNameParameterSet = "CanonicalName";
private const string ControlPanelItemParameterSet = "ControlPanelItem";
#region "Parameters"
/// <summary>
/// Control panel item names.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = RegularNameParameterSet, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Name
{
get { return RegularNames; }
set { RegularNames = value; }
}
/// <summary>
/// Canonical names of control panel items.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = CanonicalNameParameterSet)]
[AllowNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CanonicalName
{
get { return CanonicalNames; }
set { CanonicalNames = value; }
}
/// <summary>
/// Control panel items returned by Get-ControlPanelItem.
/// </summary>
[Parameter(Position = 0, ParameterSetName = ControlPanelItemParameterSet, ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public ControlPanelItem[] InputObject
{
get { return ControlPanelItems; }
set { ControlPanelItems = value; }
}
#endregion "Parameters"
/// <summary>
/// </summary>
protected override void ProcessRecord()
{
List<ShellFolderItem> items;
if (ParameterSetName == RegularNameParameterSet)
{
items = GetControlPanelItemByName(AllControlPanelItems, false);
}
else if (ParameterSetName == CanonicalNameParameterSet)
{
items = GetControlPanelItemByCanonicalName(AllControlPanelItems, false);
}
else
{
items = GetControlPanelItemsByInstance(AllControlPanelItems);
}
foreach (ShellFolderItem item in items)
{
item.InvokeVerb();
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, the libsecondlife development team
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
namespace libsecondlife.Imaging
{
#if !NO_UNSAFE
/// <summary>
/// Capability to load TGAs to Bitmap
/// </summary>
public class LoadTGAClass
{
struct tgaColorMap
{
public ushort FirstEntryIndex;
public ushort Length;
public byte EntrySize;
public void Read(System.IO.BinaryReader br)
{
FirstEntryIndex = br.ReadUInt16();
Length = br.ReadUInt16();
EntrySize = br.ReadByte();
}
}
struct tgaImageSpec
{
public ushort XOrigin;
public ushort YOrigin;
public ushort Width;
public ushort Height;
public byte PixelDepth;
public byte Descriptor;
public void Read(System.IO.BinaryReader br)
{
XOrigin = br.ReadUInt16();
YOrigin = br.ReadUInt16();
Width = br.ReadUInt16();
Height = br.ReadUInt16();
PixelDepth = br.ReadByte();
Descriptor = br.ReadByte();
}
public byte AlphaBits
{
get
{
return (byte)(Descriptor & 0xF);
}
set
{
Descriptor = (byte)((Descriptor & ~0xF) | (value & 0xF));
}
}
public bool BottomUp
{
get
{
return (Descriptor & 0x20) == 0x20;
}
set
{
Descriptor = (byte)((Descriptor & ~0x20) | (value ? 0x20 : 0));
}
}
}
struct tgaHeader
{
public byte IdLength;
public byte ColorMapType;
public byte ImageType;
public tgaColorMap ColorMap;
public tgaImageSpec ImageSpec;
public void Read(System.IO.BinaryReader br)
{
this.IdLength = br.ReadByte();
this.ColorMapType = br.ReadByte();
this.ImageType = br.ReadByte();
this.ColorMap = new tgaColorMap();
this.ImageSpec = new tgaImageSpec();
this.ColorMap.Read(br);
this.ImageSpec.Read(br);
}
public bool RleEncoded
{
get
{
return ImageType >= 9;
}
}
}
struct tgaCD
{
public uint RMask, GMask, BMask, AMask;
public byte RShift, GShift, BShift, AShift;
public uint FinalOr;
public bool NeedNoConvert;
}
static uint UnpackColor(
uint sourceColor, ref tgaCD cd)
{
if (cd.RMask == 0xFF && cd.GMask == 0xFF && cd.BMask == 0xFF)
{
// Special case to deal with 8-bit TGA files that we treat as alpha masks
return sourceColor << 24;
}
else
{
uint rpermute = (sourceColor << cd.RShift) | (sourceColor >> (32 - cd.RShift));
uint gpermute = (sourceColor << cd.GShift) | (sourceColor >> (32 - cd.GShift));
uint bpermute = (sourceColor << cd.BShift) | (sourceColor >> (32 - cd.BShift));
uint apermute = (sourceColor << cd.AShift) | (sourceColor >> (32 - cd.AShift));
uint result =
(rpermute & cd.RMask) | (gpermute & cd.GMask)
| (bpermute & cd.BMask) | (apermute & cd.AMask) | cd.FinalOr;
return result;
}
}
static unsafe void decodeLine(
System.Drawing.Imaging.BitmapData b,
int line,
int byp,
byte[] data,
ref tgaCD cd)
{
if (cd.NeedNoConvert)
{
// fast copy
uint* linep = (uint*)((byte*)b.Scan0.ToPointer() + line * b.Stride);
fixed (byte* ptr = data)
{
uint* sptr = (uint*)ptr;
for (int i = 0; i < b.Width; ++i)
{
linep[i] = sptr[i];
}
}
}
else
{
byte* linep = (byte*)b.Scan0.ToPointer() + line * b.Stride;
uint* up = (uint*)linep;
int rdi = 0;
fixed (byte* ptr = data)
{
for (int i = 0; i < b.Width; ++i)
{
uint x = 0;
for (int j = 0; j < byp; ++j)
{
x |= ((uint)ptr[rdi]) << (j << 3);
++rdi;
}
up[i] = UnpackColor(x, ref cd);
}
}
}
}
static void decodeRle(
System.Drawing.Imaging.BitmapData b,
int byp, tgaCD cd, System.IO.BinaryReader br, bool bottomUp)
{
try
{
int w = b.Width;
// make buffer larger, so in case of emergency I can decode
// over line ends.
byte[] linebuffer = new byte[(w + 128) * byp];
int maxindex = w * byp;
int index = 0;
for (int j = 0; j < b.Height; ++j)
{
while (index < maxindex)
{
byte blocktype = br.ReadByte();
int bytestoread;
int bytestocopy;
if (blocktype >= 0x80)
{
bytestoread = byp;
bytestocopy = byp * (blocktype - 0x80);
}
else
{
bytestoread = byp * (blocktype + 1);
bytestocopy = 0;
}
//if (index + bytestoread > maxindex)
// throw new System.ArgumentException ("Corrupt TGA");
br.Read(linebuffer, index, bytestoread);
index += bytestoread;
for (int i = 0; i != bytestocopy; ++i)
{
linebuffer[index + i] = linebuffer[index + i - bytestoread];
}
index += bytestocopy;
}
if (!bottomUp)
decodeLine(b, b.Height - j - 1, byp, linebuffer, ref cd);
else
decodeLine(b, j, byp, linebuffer, ref cd);
if (index > maxindex)
{
Array.Copy(linebuffer, maxindex, linebuffer, 0, index - maxindex);
index -= maxindex;
}
else
index = 0;
}
}
catch (System.IO.EndOfStreamException)
{
}
}
static void decodePlain(
System.Drawing.Imaging.BitmapData b,
int byp, tgaCD cd, System.IO.BinaryReader br, bool bottomUp)
{
int w = b.Width;
byte[] linebuffer = new byte[w * byp];
for (int j = 0; j < b.Height; ++j)
{
br.Read(linebuffer, 0, w * byp);
if (!bottomUp)
decodeLine(b, b.Height - j - 1, byp, linebuffer, ref cd);
else
decodeLine(b, j, byp, linebuffer, ref cd);
}
}
static void decodeStandard8(
System.Drawing.Imaging.BitmapData b,
tgaHeader hdr,
System.IO.BinaryReader br)
{
tgaCD cd = new tgaCD();
cd.RMask = 0x000000ff;
cd.GMask = 0x000000ff;
cd.BMask = 0x000000ff;
cd.AMask = 0x000000ff;
cd.RShift = 0;
cd.GShift = 0;
cd.BShift = 0;
cd.AShift = 0;
cd.FinalOr = 0x00000000;
if (hdr.RleEncoded)
decodeRle(b, 1, cd, br, hdr.ImageSpec.BottomUp);
else
decodePlain(b, 1, cd, br, hdr.ImageSpec.BottomUp);
}
static void decodeSpecial16(
System.Drawing.Imaging.BitmapData b, tgaHeader hdr, System.IO.BinaryReader br)
{
// i must convert the input stream to a sequence of uint values
// which I then unpack.
tgaCD cd = new tgaCD();
cd.RMask = 0x00f00000;
cd.GMask = 0x0000f000;
cd.BMask = 0x000000f0;
cd.AMask = 0xf0000000;
cd.RShift = 12;
cd.GShift = 8;
cd.BShift = 4;
cd.AShift = 16;
cd.FinalOr = 0;
if (hdr.RleEncoded)
decodeRle(b, 2, cd, br, hdr.ImageSpec.BottomUp);
else
decodePlain(b, 2, cd, br, hdr.ImageSpec.BottomUp);
}
static void decodeStandard16(
System.Drawing.Imaging.BitmapData b,
tgaHeader hdr,
System.IO.BinaryReader br)
{
// i must convert the input stream to a sequence of uint values
// which I then unpack.
tgaCD cd = new tgaCD();
cd.RMask = 0x00f80000; // from 0xF800
cd.GMask = 0x0000fc00; // from 0x07E0
cd.BMask = 0x000000f8; // from 0x001F
cd.AMask = 0x00000000;
cd.RShift = 8;
cd.GShift = 5;
cd.BShift = 3;
cd.AShift = 0;
cd.FinalOr = 0xff000000;
if (hdr.RleEncoded)
decodeRle(b, 2, cd, br, hdr.ImageSpec.BottomUp);
else
decodePlain(b, 2, cd, br, hdr.ImageSpec.BottomUp);
}
static void decodeSpecial24(System.Drawing.Imaging.BitmapData b,
tgaHeader hdr, System.IO.BinaryReader br)
{
// i must convert the input stream to a sequence of uint values
// which I then unpack.
tgaCD cd = new tgaCD();
cd.RMask = 0x00f80000;
cd.GMask = 0x0000fc00;
cd.BMask = 0x000000f8;
cd.AMask = 0xff000000;
cd.RShift = 8;
cd.GShift = 5;
cd.BShift = 3;
cd.AShift = 8;
cd.FinalOr = 0;
if (hdr.RleEncoded)
decodeRle(b, 3, cd, br, hdr.ImageSpec.BottomUp);
else
decodePlain(b, 3, cd, br, hdr.ImageSpec.BottomUp);
}
static void decodeStandard24(System.Drawing.Imaging.BitmapData b,
tgaHeader hdr, System.IO.BinaryReader br)
{
// i must convert the input stream to a sequence of uint values
// which I then unpack.
tgaCD cd = new tgaCD();
cd.RMask = 0x00ff0000;
cd.GMask = 0x0000ff00;
cd.BMask = 0x000000ff;
cd.AMask = 0x00000000;
cd.RShift = 0;
cd.GShift = 0;
cd.BShift = 0;
cd.AShift = 0;
cd.FinalOr = 0xff000000;
if (hdr.RleEncoded)
decodeRle(b, 3, cd, br, hdr.ImageSpec.BottomUp);
else
decodePlain(b, 3, cd, br, hdr.ImageSpec.BottomUp);
}
static void decodeStandard32(System.Drawing.Imaging.BitmapData b,
tgaHeader hdr, System.IO.BinaryReader br)
{
// i must convert the input stream to a sequence of uint values
// which I then unpack.
tgaCD cd = new tgaCD();
cd.RMask = 0x00ff0000;
cd.GMask = 0x0000ff00;
cd.BMask = 0x000000ff;
cd.AMask = 0xff000000;
cd.RShift = 0;
cd.GShift = 0;
cd.BShift = 0;
cd.AShift = 0;
cd.FinalOr = 0x00000000;
cd.NeedNoConvert = true;
if (hdr.RleEncoded)
decodeRle(b, 4, cd, br, hdr.ImageSpec.BottomUp);
else
decodePlain(b, 4, cd, br, hdr.ImageSpec.BottomUp);
}
public static System.Drawing.Size GetTGASize(string filename)
{
System.IO.FileStream f = System.IO.File.OpenRead(filename);
System.IO.BinaryReader br = new System.IO.BinaryReader(f);
tgaHeader header = new tgaHeader();
header.Read(br);
br.Close();
return new System.Drawing.Size(header.ImageSpec.Width, header.ImageSpec.Height);
}
public static System.Drawing.Bitmap LoadTGA(System.IO.Stream source)
{
byte[] buffer = new byte[source.Length];
source.Read(buffer, 0, buffer.Length);
System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
tgaHeader header = new tgaHeader();
header.Read(br);
if (header.ImageSpec.PixelDepth != 8 &&
header.ImageSpec.PixelDepth != 16 &&
header.ImageSpec.PixelDepth != 24 &&
header.ImageSpec.PixelDepth != 32)
throw new ArgumentException("Not a supported tga file.");
if (header.ImageSpec.AlphaBits > 8)
throw new ArgumentException("Not a supported tga file.");
if (header.ImageSpec.Width > 4096 ||
header.ImageSpec.Height > 4096)
throw new ArgumentException("Image too large.");
System.Drawing.Bitmap b = new System.Drawing.Bitmap(
header.ImageSpec.Width, header.ImageSpec.Height);
System.Drawing.Imaging.BitmapData bd = b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height),
System.Drawing.Imaging.ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
switch (header.ImageSpec.PixelDepth)
{
case 8:
decodeStandard8(bd, header, br);
break;
case 16:
if (header.ImageSpec.AlphaBits > 0)
decodeSpecial16(bd, header, br);
else
decodeStandard16(bd, header, br);
break;
case 24:
if (header.ImageSpec.AlphaBits > 0)
decodeSpecial24(bd, header, br);
else
decodeStandard24(bd, header, br);
break;
case 32:
decodeStandard32(bd, header, br);
break;
default:
b.UnlockBits(bd);
b.Dispose();
return null;
}
b.UnlockBits(bd);
br.Close();
return b;
}
public static unsafe ManagedImage LoadTGAImage(System.IO.Stream source)
{
return LoadTGAImage(source, false);
}
public static unsafe ManagedImage LoadTGAImage(System.IO.Stream source, bool mask)
{
byte[] buffer = new byte[source.Length];
source.Read(buffer, 0, buffer.Length);
System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
tgaHeader header = new tgaHeader();
header.Read(br);
if (header.ImageSpec.PixelDepth != 8 &&
header.ImageSpec.PixelDepth != 16 &&
header.ImageSpec.PixelDepth != 24 &&
header.ImageSpec.PixelDepth != 32)
throw new ArgumentException("Not a supported tga file.");
if (header.ImageSpec.AlphaBits > 8)
throw new ArgumentException("Not a supported tga file.");
if (header.ImageSpec.Width > 4096 ||
header.ImageSpec.Height > 4096)
throw new ArgumentException("Image too large.");
byte[] decoded = new byte[header.ImageSpec.Width * header.ImageSpec.Height * 4];
System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData();
fixed (byte* pdecoded = &decoded[0])
{
bd.Width = header.ImageSpec.Width;
bd.Height = header.ImageSpec.Height;
bd.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb;
bd.Stride = header.ImageSpec.Width * 4;
bd.Scan0 = (IntPtr)pdecoded;
switch (header.ImageSpec.PixelDepth)
{
case 8:
decodeStandard8(bd, header, br);
break;
case 16:
if (header.ImageSpec.AlphaBits > 0)
decodeSpecial16(bd, header, br);
else
decodeStandard16(bd, header, br);
break;
case 24:
if (header.ImageSpec.AlphaBits > 0)
decodeSpecial24(bd, header, br);
else
decodeStandard24(bd, header, br);
break;
case 32:
decodeStandard32(bd, header, br);
break;
default:
return null;
}
}
int n = header.ImageSpec.Width * header.ImageSpec.Height;
ManagedImage image;
if (mask && header.ImageSpec.AlphaBits == 0 && header.ImageSpec.PixelDepth == 8)
{
image = new ManagedImage(header.ImageSpec.Width, header.ImageSpec.Height,
ManagedImage.ImageChannels.Alpha);
int p = 3;
for (int i = 0; i < n; i++)
{
image.Alpha[i] = decoded[p];
p += 4;
}
}
else
{
image = new ManagedImage(header.ImageSpec.Width, header.ImageSpec.Height,
ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha);
int p = 0;
for (int i = 0; i < n; i++)
{
image.Blue[i] = decoded[p++];
image.Green[i] = decoded[p++];
image.Red[i] = decoded[p++];
image.Alpha[i] = decoded[p++];
}
}
br.Close();
return image;
}
public static System.Drawing.Bitmap LoadTGA(string filename)
{
try
{
using (System.IO.FileStream f = System.IO.File.OpenRead(filename))
{
return LoadTGA(f);
}
}
catch (System.IO.DirectoryNotFoundException)
{
return null; // file not found
}
catch (System.IO.FileNotFoundException)
{
return null; // file not found
}
}
}
#endif
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using Xunit;
namespace System.Globalization.CalendarsTests
{
public class KoreanCalendarToDateTime
{
#region Positive Test Logic
// PosTest1:Invoke the mthod with min datetime
[Fact]
public void PosTest1()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = DateTime.MinValue;
DateTime expectedValue = dateTime;
DateTime actualValue;
actualValue = kC.ToDateTime(dateTime.Year + 2333, dateTime.Month, dateTime.Day,
dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, kC.GetEra(dateTime));
Assert.Equal(expectedValue, actualValue);
}
// PosTest2:Invoke the mthod with max datetime
[Fact]
public void PosTest2()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = DateTime.MaxValue;
DateTime expectedValue = new GregorianCalendar().ToDateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
DateTime actualValue;
actualValue = kC.ToDateTime(dateTime.Year + 2333, dateTime.Month, dateTime.Day,
dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, kC.GetEra(dateTime));
Assert.Equal(expectedValue, actualValue);
}
// PosTest3:Invoke the mthod with leap year datetime
[Fact]
public void PosTest3()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new GregorianCalendar().ToDateTime(2004, 2, 29, 1, 1, 1, 0);
DateTime expectedValue = dateTime;
DateTime actualValue;
actualValue = kC.ToDateTime(dateTime.Year + 2333, dateTime.Month, dateTime.Day,
dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, kC.GetEra(dateTime));
Assert.Equal(expectedValue, actualValue);
}
// PosTest4:Invoke the mthod with random datetime
[Fact]
public void PosTest4()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
dateTime = new GregorianCalendar().ToDateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, 0);
DateTime expectedValue = dateTime;
DateTime actualValue;
actualValue = kC.ToDateTime(dateTime.Year + 2333, dateTime.Month, dateTime.Day,
dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, kC.GetEra(dateTime));
Assert.Equal(expectedValue, actualValue);
}
#endregion
#region Negative Test Logic
// NegTest1:Invoke the method with year out of range
[Fact]
public void NegTest1()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = 2333;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest2:Invoke the method with year out of range
[Fact]
public void NegTest2()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = 0;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest3:Invoke the method with year out of range
[Fact]
public void NegTest3()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = -1;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest4:Invoke the method with year out of range
[Fact]
public void NegTest4()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = 12333;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest5:Invoke the method with month out of range
[Fact]
public void NegTest5()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = 0;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest6:Invoke the method with month out of range
[Fact]
public void NegTest6()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = -1;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest7:Invoke the method with month out of range
[Fact]
public void NegTest7()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = 13;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest8:Invoke the method with wrong leap day
[Fact]
public void NegTest8()
{
System.Globalization.Calendar kC = new KoreanCalendar();
int year = 2006;
int month = 2;
int day = 29;
int hour = 1;
int minute = 1;
int second = 1;
int msecond = 1;
int era = 1;
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest9:Invoke the method with day out of range
[Fact]
public void NegTest9()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = 0;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest10:Invoke the method with day out of range
[Fact]
public void NegTest10()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = -1;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest11:Invoke the method with day out of range
[Fact]
public void NegTest11()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = -1;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest12:Invoke the method with day out of range
[Fact]
public void NegTest12()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = 32;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest13:Invoke the method with hour out of range
[Fact]
public void NegTest13()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = -1;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest14:Invoke the method with hour out of range
[Fact]
public void NegTest14()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = 25;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest15:Invoke the method with minute out of range
[Fact]
public void NegTest15()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = -1;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest16:Invoke the method with minute out of range
[Fact]
public void NegTest16()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = 60;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest17:Invoke the method with second out of range
[Fact]
public void NegTest17()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = -1;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest18:Invoke the method with second out of range
[Fact]
public void NegTest18()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = 60;
int msecond = dateTime.Millisecond;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest19:Invoke the method with millisecond out of range
[Fact]
public void NegTest19()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = -1;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest20:Invoke the method with millisecond out of range
[Fact]
public void NegTest20()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = 1000;
int era = kC.GetEra(dateTime);
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest21:Invoke the method with era out of range
[Fact]
public void NegTest21()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = -1;
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
// NegTest22:Invoke the method with era out of range
[Fact]
public void NegTest22()
{
System.Globalization.Calendar kC = new KoreanCalendar();
DateTime dateTime = new DateTime(TestLibrary.Generator.GetInt64(-55) % (DateTime.MaxValue.Ticks + 1));
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int msecond = dateTime.Millisecond;
int era = 2;
DateTime actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = kC.ToDateTime(year, month, day, hour, minute, second, msecond, era);
});
}
#endregion
}
}
| |
/* Copyright (C) 2014 Newcastle University
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
using System;
using Android.Content;
using System.Threading.Tasks;
using System.Net;
using System.Threading;
using Bootleg.API.Exceptions;
using Android.Graphics;
using Android.Support.CustomTabs;
using Android.App;
using Android.Support.V4.View;
using Android.Views;
using Bootleg.API;
using Android.Support.V4.Content;
using Firebase.Iid;
using Android.Support.Design.Widget;
using Bootleg.Droid.Screens;
using Android.Widget;
using static Bootleg.Droid.UI.PermissionsDialog;
namespace Bootleg.Droid.UI
{
public static class LoginFuncs
{
public const string LOGIN_PROVIDER = "login_provider";
public const string WINDOW_TYPE = "window_type";
public const string HELP_LINK = "help_link";
public const string LOGIN_PROVIDER_GOOGLE = "google";
public const string LOGIN_PROVIDER_FACEBOOK = "facebook";
public const string LOGIN_PROVIDER_LOCAL = "local";
public const int LOGIN_RESPONSE = 11;
public const int HELP_RESPONSE = 12;
public const int NEW_SHOOT = 13;
public static Task ShowSnackbar(Context context, View root, string text)
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
Snackbar.Make(root, text, Snackbar.LengthIndefinite)
.SetAction(Android.Resource.String.Ok, v => tcs.SetResult(true))
.Show();
return tcs.Task;
}
public static void ShowMessage(Context context, int res)
{
Activity activity = (context ?? Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity) as Activity;
try
{
Snackbar.Make(activity.FindViewById(Resource.Id.main_content), activity.GetString(res), Snackbar.LengthShort).Show();
}
catch
{
Console.WriteLine("Crashed trying to show error");
}
}
public static void ShowError(Context context, Exception e)
{
//detect type of exception and show corrent
//NeedsPermissionsException - acceptperms
//RoleNotSelectedException - norolechosen
//NoNetworkException - no ip based off the back of the IsReallyConnected function
//UnknownNetworkException - not successful network operation, find out why and report
//var message = context.GetString(Resource.String.noconnectionshort);
var message = e.Message;
switch (e)
{
case ApiKeyException ex:
message = context.GetString(Resource.String.apikeynovalid);
break;
case NeedsPermissionsException ex:
case NotGivenPermissionException exx:
message = context.GetString(Resource.String.acceptperms);
break;
case RoleNotSelectedException ex:
message = context.GetString(Resource.String.norolechosen);
break;
case NoNetworkException ex:
message = context.GetString(Resource.String.errornonetwork);
break;
case UnknownNetworkException ex:
message = context.GetString(Resource.String.errorunknown);
break;
case NeedsUpdateException ex:
message = context.GetString(Resource.String.errornonetwork);
break;
case SessionLostException ex:
message = context.GetString(Resource.String.loginagain);
break;
case ServerErrorException ex:
message = context.GetString(Resource.String.errorserver);
break;
case TaskCanceledException ex:
message = context.GetString(Resource.String.errorcanceled);
break;
case StoriesDisabledException ex:
message = context.GetString(Resource.String.storiesdisabled);
break;
}
try
{
Snackbar.Make((context as Activity).FindViewById(Resource.Id.main_content), message, Snackbar.LengthShort).Show();
}
catch
{
Console.WriteLine("Crashed trying to show error");
}
}
public static void ShowHelp(Android.App.Activity context,string link)
{
var builder = new CustomTabsIntent.Builder()
.SetToolbarColor(ContextCompat.GetColor(context,Resource.Color.blue))
.SetSecondaryToolbarColor(Android.Resource.Color.White)
.SetShowTitle(true);
Bitmap icon;
if (ViewCompat.GetLayoutDirection(context.FindViewById<ViewGroup>(Android.Resource.Id.Content).GetChildAt(0)) != ViewCompat.LayoutDirectionRtl)
icon = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.ic_arrow_back_white_24dp);
else
icon = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.ic_arrow_forward_white_24dp);
builder.SetCloseButtonIcon(icon);
var intent = builder.Build();
intent.Intent.PutExtra(Intent.ExtraReferrer, Android.Net.Uri.Parse("app://" + context.PackageName));
intent.LaunchUrl(context, Android.Net.Uri.Parse(context.Resources.GetString(Resource.String.HelpLink) + link));
}
public const int NEW_SHOOT_REQUEST = 34;
//internal static void NewShoot(Android.App.Activity context)
//{
// if ((context.Application as BootleggerApp).IsReallyConnected)
// {
// context.StartActivityForResult(typeof(NewShoot), NEW_SHOOT_REQUEST);
// }
// else
// {
// ShowError(context, new Exception(context.GetString(Resource.String.noconnectionshort)));
// //Toast.MakeText(context, Resource.String.checknetwork, ToastLength.Long).Show();
// }
//}
public static async Task TryLogin(Activity context,CancellationToken cancel)
{
if (Bootlegger.BootleggerClient.Connected)
return;
var allprefs = context.GetSharedPreferences(WhiteLabelConfig.BUILD_VARIANT.ToLower(), FileCreationMode.Private);
if (Bootlegger.BootleggerClient.SessionCookie != null)
{
try
{
//try connecting
try
{
if (!(context.Application as BootleggerApp).IsReallyConnected)
{
throw new NoNetworkException();
}
else
{
await Bootlegger.BootleggerClient.Connect(Bootlegger.BootleggerClient.SessionCookie, cancel);
var edit = allprefs.Edit();
edit.PutBoolean("firstrun", true);
edit.Apply();
if (!WhiteLabelConfig.LOCAL_SERVER)
{
try
{
//FirebaseApp.InitializeApp(context);
var refreshedToken = FirebaseInstanceId.Instance.Token;
//Console.WriteLine("token: " + refreshedToken);
Bootleg.API.Bootlegger.BootleggerClient.RegisterForPush(refreshedToken, API.Bootlegger.Platform.Android);
}
catch (Exception e)
{
ShowError(context, new Exception("Firebase Error"));
}
}
}
}
catch (TaskCanceledException e)
{
throw e;
}
catch (NotSupportedException e)
{
if ((context.Application as BootleggerApp).IsReallyConnected)
{
throw new NeedsUpdateException();
//ShowError(context,new NeedsUpdateException());
}
else
{
throw new NoNetworkException();
//ShowError(context, new NoNetworkException());
}
throw e;
}
catch (ApiKeyException e)
{
if ((context.Application as BootleggerApp).IsReallyConnected)
{
throw new ApiKeyException();
//ShowError(context, new ApiKeyException());
}
else
{
throw new NoNetworkException();
//ShowError(context, new NoNetworkException());
}
throw e;
}
catch (Exception e)
{
//if ((context.Application as BootleggerApp).IsReallyConnected)
//{
//throw new SessionLostException();
//}
//else
//{
throw new NoNetworkException();
//}
}
}
catch (TaskCanceledException e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
}
else
{
//no session stored:
//if its the first time using the app...
var firstrun = allprefs.GetBoolean("firstrun", false);
if (!firstrun)
throw new WebException(context.Resources.GetString(Resource.String.loginagain));
}
}
internal static void ShowToast(Context activity, Exception e)
{
//default: Resource.String.cannotloadvideo
var message = activity.GetString(Resource.String.cannotloadvideo);
switch (e)
{
case StoriesDisabledException ex:
message = activity.GetString(Resource.String.storiesdisabled);
break;
case ApiKeyException ex:
message = activity.GetString(Resource.String.apikeynovalid);
break;
case NeedsPermissionsException ex:
case NotGivenPermissionException exx:
message = activity.GetString(Resource.String.acceptperms);
break;
case RoleNotSelectedException ex:
message = activity.GetString(Resource.String.norolechosen);
break;
case NoNetworkException ex:
message = activity.GetString(Resource.String.errornonetwork);
break;
case UnknownNetworkException ex:
message = activity.GetString(Resource.String.errorunknown);
break;
case NeedsUpdateException ex:
message = activity.GetString(Resource.String.errornonetwork);
break;
case SessionLostException ex:
message = activity.GetString(Resource.String.loginagain);
break;
case ServerErrorException ex:
message = activity.GetString(Resource.String.errorserver);
break;
case TaskCanceledException ex:
message = activity.GetString(Resource.String.errorcanceled);
break;
default:
break;
}
Toast.MakeText(activity, message, ToastLength.Short).Show();
}
internal static void OpenLogin(Activity context,string provider)
{
if (string.IsNullOrEmpty(provider) && Bootlegger.BootleggerClient.CurrentUser!=null)
{
provider = Bootlegger.BootleggerClient.CurrentUser.profile["provider"].ToString();
}
var builder = new CustomTabsIntent.Builder()
.SetToolbarColor(ContextCompat.GetColor(context,Resource.Color.blue))
.SetSecondaryToolbarColor(Android.Resource.Color.White)
.SetShowTitle(true);
Bitmap icon;
if (ViewCompat.GetLayoutDirection(context.FindViewById<ViewGroup>(Android.Resource.Id.Content).GetChildAt(0)) != ViewCompat.LayoutDirectionRtl)
icon = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.ic_arrow_back_white_24dp);
else
icon = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.ic_arrow_forward_white_24dp);
builder.SetCloseButtonIcon(icon);
var intent = builder.Build();
intent.Intent.PutExtra(Intent.ExtraReferrer, Android.Net.Uri.Parse("app://" + context.PackageName));
intent.LaunchUrl(context, Android.Net.Uri.Parse(Bootlegger.BootleggerClient.LoginUrl.ToString() + "/" + provider + "?cbid=" + WhiteLabelConfig.DATASCHEME));
}
}
}
| |
// 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.Tracing;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Diagnostics
{
/// <summary>
/// DiagnosticSourceEventSource serves two purposes
///
/// 1) It allows debuggers to inject code via Function evaluation. This is the purpose of the
/// BreakPointWithDebuggerFuncEval function in the 'OnEventCommand' method. Basically even in
/// release code, debuggers can place a breakpoint in this method and then trigger the
/// DiagnosticSourceEventSource via ETW. Thus from outside the process you can get a hook that
/// is guaranteed to happen BEFORE any DiangosticSource events (if the process is just starting)
/// or as soon as possible afterward if it is on attach.
///
/// 2) It provides a 'bridge' that allows DiagnosticSource messages to be forwarded to EventListers
/// or ETW. You can do this by enabling the Microsoft-Diagnostics-DiagnosticSource with the
/// 'Events' keyword (for diagnostics purposes, you should also turn on the 'Messages' keyword.
///
/// This EventSource defines a EventSource argument called 'FilterAndPayloadSpecs' that defines
/// what DiagnsoticSources to enable and what parts of the payload to serialize into the key-value
/// list that will be forwarded to the EventSource. If it is empty, values of properties of the
/// diagnostic source payload are dumped as strings (using ToString()) and forwarded to the EventSource.
/// For what people think of as serializable object strings, primitives this gives you want you want.
/// (the value of the property in string form) for what people think of as non-serializable objects
/// (e.g. HttpContext) the ToString() method is typically not defined, so you get the Object.ToString()
/// implementation that prints the type name. This is useful since this is the information you need
/// (the type of the property) to discover the field names so you can create a transform specification
/// that will pick off the properties you desire.
///
/// Once you have the particular values you desire, the implicit payload elements are typically not needed
/// anymore and you can prefix the Transform specification with a '-' which suppresses the implicit
/// transform (you only get the values of the properties you specifically ask for.
///
/// Logically a transform specification is simply a fetching specification X.Y.Z along with a name to give
/// it in the output (which defaults to the last name in the fetch specification).
///
/// The FilterAndPayloadSpecs is one long string with the following structures
///
/// * It is a newline separated list of FILTER_AND_PAYLOAD_SPEC
/// * a FILTER_AND_PAYLOAD_SPEC can be
/// * EVENT_NAME : TRANSFORM_SPECS
/// * EMPTY - turns on all sources with implicit payload elements.
/// * an EVENTNAME can be
/// * DIAGNOSTIC_SOURCE_NAME / DIAGNOSTC_EVENT_NAME @ EVENT_SOURCE_EVENTNAME - give the name as well as the EventSource event to log it under.
/// * DIAGNOSTIC_SOURCE_NAME / DIAGNOSTC_EVENT_NAME
/// * DIAGNOSTIC_SOURCE_NAME - which wildcards every event in the Diagnostic source or
/// * EMPTY - which turns on all sources
/// * TRANSFORM_SPEC is a semicolon separated list of TRANSFORM_SPEC, which can be
/// * - TRANSFORM_SPEC - the '-' indicates that implicit payload elements should be suppressed
/// * VARIABLE_NAME = PROPERTY_SPEC - indicates that a payload element 'VARIABLE_NAME' is created from PROPERTY_SPEC
/// * PROPERTY_SPEC - This is a shortcut where VARIABLE_NAME is the LAST property name
/// * a PROPERTY_SPEC is basically a list of names separated by '.'
/// * PROPERTY_NAME - fetches a property from the DiagnosticSource payload object
/// * PROPERTY_NAME . PROPERTY NAME - fetches a sub-property of the object.
///
/// Example1:
///
/// "BridgeTestSource1/TestEvent1:cls_Point_X=cls.Point.X;cls_Point_Y=cls.Point.Y\r\n" +
/// "BridgeTestSource2/TestEvent2:-cls.Url"
///
/// This indicates that two events should be turned on, The 'TestEvent1' event in BridgeTestSource1 and the
/// 'TestEvent2' in BridgeTestSource2. In the first case, because the transform did not begin with a -
/// any primitive type/string of 'TestEvent1's payload will be serialized into the output. In addition if
/// there a property of the payload object called 'cls' which in turn has a property 'Point' which in turn
/// has a property 'X' then that data is also put in the output with the name cls_Point_X. Similarly
/// if cls.Point.Y exists, then that value will also be put in the output with the name cls_Point_Y.
///
/// For the 'BridgeTestSource2/TestEvent2' event, because the - was specified NO implicit fields will be
/// generated, but if there is a property call 'cls' which has a property 'Url' then that will be placed in
/// the output with the name 'Url' (since that was the last property name used and no Variable= clause was
/// specified.
///
/// Example:
///
/// "BridgeTestSource1\r\n" +
/// "BridgeTestSource2"
///
/// This will enable all events for the BridgeTestSource1 and BridgeTestSource2 sources. Any string/primitive
/// properties of any of the events will be serialized into the output.
///
/// Example:
///
/// ""
///
/// This turns on all DiagnosticSources Any string/primitive properties of any of the events will be serialized
/// into the output. This is not likely to be a good idea as it will be very verbose, but is useful to quickly
/// discover what is available.
///
///
/// * How data is logged in the EventSource
///
/// By default all data from DiagnosticSources is logged to the DiagnosticEventSouce event called 'Event'
/// which has three fields
///
/// string SourceName,
/// string EventName,
/// IEnumerable[KeyValuePair[string, string]] Argument
///
/// However to support start-stop activity tracking, there are six other events that can be used
///
/// Activity1Start
/// Activity1Stop
/// Activity2Start
/// Activity2Stop
/// RecursiveActivity1Start
/// RecursiveActivity1Stop
///
/// By using the SourceName/EventName@EventSourceName syntax, you can force particular DiagnosticSource events to
/// be logged with one of these EventSource events. This is useful because the events above have start-stop semantics
/// which means that they create activity IDs that are attached to all logging messages between the start and
/// the stop (see https://blogs.msdn.microsoft.com/vancem/2015/09/14/exploring-eventsource-activity-correlation-and-causation-features/)
///
/// For example the specification
///
/// "MyDiagnosticSource/RequestStart@Activity1Start\r\n" +
/// "MyDiagnosticSource/RequestStop@Activity1Stop\r\n" +
/// "MyDiagnosticSource/SecurityStart@Activity2Start\r\n" +
/// "MyDiagnosticSource/SecurityStop@Activity2Stop\r\n"
///
/// Defines that RequestStart will be logged with the EventSource Event Activity1Start (and the corresponding stop) which
/// means that all events caused between these two markers will have an activity ID associated with this start event.
/// Similarly SecurityStart is mapped to Activity2Start.
///
/// Note you can map many DiangosticSource events to the same EventSource Event (e.g. Activity1Start). As long as the
/// activities don't nest, you can reuse the same event name (since the payloads have the DiagnosticSource name which can
/// disambiguate). However if they nest you need to use another EventSource event because the rules of EventSource
/// activities state that a start of the same event terminates any existing activity of the same name.
///
/// As its name suggests RecursiveActivity1Start, is marked as recursive and thus can be used when the activity can nest with
/// itself. This should not be a 'top most' activity because it is not 'self healing' (if you miss a stop, then the
/// activity NEVER ends).
///
/// See the DiagnosticSourceEventSourceBridgeTest.cs for more explicit examples of using this bridge.
/// </summary>
[EventSource(Name = "Microsoft-Diagnostics-DiagnosticSource")]
internal class DiagnosticSourceEventSource : EventSource
{
public static DiagnosticSourceEventSource Logger = new DiagnosticSourceEventSource();
public class Keywords
{
/// <summary>
/// Indicates diagnostics messages from DiagnosticSourceEventSource should be included.
/// </summary>
public const EventKeywords Messages = (EventKeywords)0x1;
/// <summary>
/// Indicates that all events from all diagnostic sources should be forwarded to the EventSource using the 'Event' event.
/// </summary>
public const EventKeywords Events = (EventKeywords)0x2;
// Some ETW logic does not support passing arguments to the EventProvider. To get around
// this in common cases, we define some keywords that basically stand in for particular common argumnents
// That way at least the common cases can be used by everyone (and it also compresses things).
// We start these keywords at 0x1000. See below for the values these keywords represent
// Because we want all keywords on to still mean 'dump everything by default' we have another keyword
// IgnoreShorcutKeywords which must be OFF in order for the shortcuts to work thus the all 1s keyword
// still means what you expect.
public const EventKeywords IgnoreShortCutKeywords = (EventKeywords)0x0800;
public const EventKeywords AspNetCoreHosting = (EventKeywords)0x1000;
public const EventKeywords EntityFrameworkCoreCommands = (EventKeywords)0x2000;
};
// Setting AspNetCoreHosting is like having this in the FilterAndPayloadSpecs string
// It turns on basic hostig events.
private readonly string AspNetCoreHostingKeywordValue =
"Microsoft.AspNetCore/Microsoft.AspNetCore.Hosting.BeginRequest@Activity1Start:-" +
"httpContext.Request.Method;" +
"httpContext.Request.Host;" +
"httpContext.Request.Path;" +
"httpContext.Request.QueryString" +
"\n" +
"Microsoft.AspNetCore/Microsoft.AspNetCore.Hosting.EndRequest@Activity1Stop:-" +
"httpContext.TraceIdentifier;" +
"httpContext.Response.StatusCode";
// Setting EntityFrameworkCoreCommands is like having this in the FilterAndPayloadSpecs string
// It turns on basic SQL commands.
private readonly string EntityFrameworkCoreCommandsKeywordValue =
"Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.BeforeExecuteCommand@Activity2Start:-" +
"Command.Connection.DataSource;" +
"Command.Connection.Database;" +
"Command.CommandText" +
"\n" +
"Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.AfterExecuteCommand@Activity2Stop:-";
/// <summary>
/// Used to send ad-hoc diagnostics to humans.
/// </summary>
[Event(1, Keywords = Keywords.Messages)]
public void Message(string Message)
{
WriteEvent(1, Message);
}
#if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT
/// <summary>
/// Events from DiagnosticSource can be forwarded to EventSource using this event.
/// </summary>
[Event(2, Keywords = Keywords.Events)]
private void Event(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
{
WriteEvent(2, SourceName, EventName, Arguments);
}
#endif
/// <summary>
/// This is only used on V4.5 systems that don't have the ability to log KeyValuePairs directly.
/// It will eventually go away, but we should always reserve the ID for this.
/// </summary>
[Event(3, Keywords = Keywords.Events)]
private void EventJson(string SourceName, string EventName, string ArgmentsJson)
{
WriteEvent(3, SourceName, EventName, ArgmentsJson);
}
#if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT
/// <summary>
/// Used to mark the beginning of an activity
/// </summary>
[Event(4, Keywords = Keywords.Events)]
private void Activity1Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
{
WriteEvent(4, SourceName, EventName, Arguments);
}
/// <summary>
/// Used to mark the end of an activity
/// </summary>
[Event(5, Keywords = Keywords.Events)]
private void Activity1Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
{
WriteEvent(5, SourceName, EventName, Arguments);
}
/// <summary>
/// Used to mark the beginning of an activity
/// </summary>
[Event(6, Keywords = Keywords.Events)]
private void Activity2Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
{
WriteEvent(6, SourceName, EventName, Arguments);
}
/// <summary>
/// Used to mark the end of an activity that can be recursive.
/// </summary>
[Event(7, Keywords = Keywords.Events)]
private void Activity2Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
{
WriteEvent(7, SourceName, EventName, Arguments);
}
/// <summary>
/// Used to mark the beginning of an activity
/// </summary>
[Event(8, Keywords = Keywords.Events, ActivityOptions = EventActivityOptions.Recursive)]
private void RecursiveActivity1Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
{
WriteEvent(8, SourceName, EventName, Arguments);
}
/// <summary>
/// Used to mark the end of an activity that can be recursive.
/// </summary>
[Event(9, Keywords = Keywords.Events, ActivityOptions = EventActivityOptions.Recursive)]
private void RecursiveActivity1Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments)
{
WriteEvent(9, SourceName, EventName, Arguments);
}
#endif
/// <summary>
/// Fires when a new DiagnosticSource becomes available.
/// </summary>
/// <param name="SourceName"></param>
[Event(10, Keywords = Keywords.Events)]
private void NewDiagnosticListener(string SourceName)
{
WriteEvent(10, SourceName);
}
#region private
#if NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT
/// <summary>
/// Converts a keyvalue bag to JSON. Only used on V4.5 EventSources.
/// </summary>
private static string ToJson(IEnumerable<KeyValuePair<string, string>> keyValues)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("{");
bool first = true;
foreach (var keyValue in keyValues)
{
if (!first)
sb.Append(',').AppendLine();
first = false;
sb.Append('"').Append(keyValue.Key).Append("\":\"");
// Write out the value characters, escaping things as needed.
foreach(var c in keyValue.Value)
{
if (Char.IsControl(c))
{
if (c == '\n')
sb.Append("\\n");
else if (c == '\r')
sb.Append("\\r");
else
sb.Append("\\u").Append(((int)c).ToString("x").PadLeft(4, '0'));
}
else
{
if (c == '"' || c == '\\')
sb.Append('\\');
sb.Append(c);
}
}
sb.Append('"'); // Close the string.
}
sb.AppendLine().AppendLine("}");
return sb.ToString();
}
#endif
#if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT
/// <summary>
/// This constructor uses EventSourceSettings which is only available on V4.6 and above
/// systems. We use the EventSourceSettings to turn on support for complex types.
/// </summary>
private DiagnosticSourceEventSource() : base(EventSourceSettings.EtwSelfDescribingEventFormat) { }
#endif
/// <summary>
/// Called when the EventSource gets a command from a EventListener or ETW.
/// </summary>
[NonEvent]
protected override void OnEventCommand(EventCommandEventArgs command)
{
// On every command (which the debugger can force by turning on this EventSource with ETW)
// call a function that the debugger can hook to do an arbitrary func evaluation.
BreakPointWithDebuggerFuncEval();
lock (this)
{
if ((command.Command == EventCommand.Update || command.Command == EventCommand.Enable) &&
IsEnabled(EventLevel.Informational, Keywords.Events))
{
string filterAndPayloadSpecs;
command.Arguments.TryGetValue("FilterAndPayloadSpecs", out filterAndPayloadSpecs);
if (!IsEnabled(EventLevel.Informational, Keywords.IgnoreShortCutKeywords))
{
if (IsEnabled(EventLevel.Informational, Keywords.AspNetCoreHosting))
filterAndPayloadSpecs = NewLineSeparate(filterAndPayloadSpecs, AspNetCoreHostingKeywordValue);
if (IsEnabled(EventLevel.Informational, Keywords.EntityFrameworkCoreCommands))
filterAndPayloadSpecs = NewLineSeparate(filterAndPayloadSpecs, EntityFrameworkCoreCommandsKeywordValue);
}
FilterAndTransform.CreateFilterAndTransformList(ref _specs, filterAndPayloadSpecs, this);
}
else if (command.Command == EventCommand.Update || command.Command == EventCommand.Disable)
{
FilterAndTransform.DestroyFilterAndTransformList(ref _specs);
}
}
}
// trivial helper to allow you to join two strings the first of which can be null.
private static string NewLineSeparate(string str1, string str2)
{
Debug.Assert(str2 != null);
if (string.IsNullOrEmpty(str1))
return str2;
return str1 + "\n" + str2;
}
#region debugger hooks
private volatile bool _false; // A value that is always false but the compiler does not know this.
/// <summary>
/// A function which is fully interruptible even in release code so we can stop here and
/// do function evaluation in the debugger. Thus this is just a place that is useful
/// for the debugger to place a breakpoint where it can inject code with function evaluation
/// </summary>
[NonEvent, MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private void BreakPointWithDebuggerFuncEval()
{
new object(); // This is only here because it helps old desktop runtimes emit a GC safe point at the start of the method
while (_false)
{
_false = false;
}
}
#endregion
#region EventSource hooks
/// <summary>
/// FilterAndTransform represents on transformation specification from a DiagnosticsSource
/// to EventSource's 'Event' method. (e.g. MySource/MyEvent:out=prop1.prop2.prop3).
/// Its main method is 'Morph' which takes a DiagnosticSource object and morphs it into
/// a list of string,string key value pairs.
///
/// This method also contains that static 'Create/Destroy FilterAndTransformList, which
/// simply parse a series of transformation specifications.
/// </summary>
internal class FilterAndTransform
{
/// <summary>
/// Parses filterAndPayloadSpecs which is a list of lines each of which has the from
///
/// DiagnosticSourceName/EventName:PAYLOAD_SPEC
///
/// where PAYLOADSPEC is a semicolon separated list of specifications of the form
///
/// OutputName=Prop1.Prop2.PropN
///
/// Into linked list of FilterAndTransform that together forward events from the given
/// DiagnosticSource's to 'eventSource'. Sets the 'specList' variable to this value
/// (destroying anything that was there previously).
///
/// By default any serializable properties of the payload object are also included
/// in the output payload, however this feature and be tuned off by prefixing the
/// PAYLOADSPEC with a '-'.
/// </summary>
public static void CreateFilterAndTransformList(ref FilterAndTransform specList, string filterAndPayloadSpecs, DiagnosticSourceEventSource eventSource)
{
DestroyFilterAndTransformList(ref specList); // Stop anything that was on before.
if (filterAndPayloadSpecs == null)
filterAndPayloadSpecs = "";
// Points just beyond the last point in the string that has yet to be parsed. Thus we start with the whole string.
int endIdx = filterAndPayloadSpecs.Length;
for (;;)
{
// Skip trailing whitespace.
while (0 < endIdx && char.IsWhiteSpace(filterAndPayloadSpecs[endIdx - 1]))
--endIdx;
int newlineIdx = filterAndPayloadSpecs.LastIndexOf('\n', endIdx - 1, endIdx);
int startIdx = 0;
if (0 <= newlineIdx)
startIdx = newlineIdx + 1; // starts after the newline, or zero if we don't find one.
// Skip leading whitespace
while (startIdx < endIdx && char.IsWhiteSpace(filterAndPayloadSpecs[startIdx]))
startIdx++;
specList = new FilterAndTransform(filterAndPayloadSpecs, startIdx, endIdx, eventSource, specList);
endIdx = newlineIdx;
if (endIdx < 0)
break;
}
}
/// <summary>
/// This destroys (turns off) the FilterAndTransform stopping the forwarding started with CreateFilterAndTransformList
/// </summary>
/// <param name="specList"></param>
public static void DestroyFilterAndTransformList(ref FilterAndTransform specList)
{
var curSpec = specList;
specList = null; // Null out the list
while (curSpec != null) // Dispose everything in the list.
{
curSpec.Dispose();
curSpec = curSpec.Next;
}
}
/// <summary>
/// Creates one FilterAndTransform specification from filterAndPayloadSpec starting at 'startIdx' and ending just before 'endIdx'.
/// This FilterAndTransform will subscribe to DiagnosticSources specified by the specification and forward them to 'eventSource.
/// For convenience, the 'Next' field is set to the 'next' parameter, so you can easily form linked lists.
/// </summary>
public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx, DiagnosticSourceEventSource eventSource, FilterAndTransform next)
{
#if DEBUG
string spec = filterAndPayloadSpec.Substring(startIdx, endIdx - startIdx);
#endif
Next = next;
_eventSource = eventSource;
string listenerNameFilter = null; // Means WildCard.
string eventNameFilter = null; // Means WildCard.
string activityName = null;
var startTransformIdx = startIdx;
var endEventNameIdx = endIdx;
var colonIdx = filterAndPayloadSpec.IndexOf(':', startIdx, endIdx - startIdx);
if (0 <= colonIdx)
{
endEventNameIdx = colonIdx;
startTransformIdx = colonIdx + 1;
}
// Parse the Source/Event name into listenerNameFilter and eventNameFilter
var slashIdx = filterAndPayloadSpec.IndexOf('/', startIdx, endEventNameIdx - startIdx);
if (0 <= slashIdx)
{
listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, slashIdx - startIdx);
var atIdx = filterAndPayloadSpec.IndexOf('@', slashIdx + 1, endEventNameIdx - slashIdx - 1);
if (0 <= atIdx)
{
activityName = filterAndPayloadSpec.Substring(atIdx + 1, endEventNameIdx - atIdx - 1);
eventNameFilter = filterAndPayloadSpec.Substring(slashIdx + 1, atIdx - slashIdx - 1);
}
else
{
eventNameFilter = filterAndPayloadSpec.Substring(slashIdx + 1, endEventNameIdx - slashIdx - 1);
}
}
else if (startIdx < endEventNameIdx)
{
listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, endEventNameIdx - startIdx);
}
_eventSource.Message("DiagnosticSource: Enabling '" + (listenerNameFilter ?? "*") + "/" + (eventNameFilter ?? "*") + "'");
// If the transform spec begins with a - it means you don't want implicit transforms.
if (startTransformIdx < endIdx && filterAndPayloadSpec[startTransformIdx] == '-')
{
_eventSource.Message("DiagnosticSource: suppressing implicit transforms.");
_noImplicitTransforms = true;
startTransformIdx++;
}
// Parse all the explicit transforms, if present
if (startTransformIdx < endIdx)
{
for (;;)
{
int specStartIdx = startTransformIdx;
int semiColonIdx = filterAndPayloadSpec.LastIndexOf(';', endIdx - 1, endIdx - startTransformIdx);
if (0 <= semiColonIdx)
specStartIdx = semiColonIdx + 1;
// Ignore empty specifications.
if (specStartIdx < endIdx)
{
if (_eventSource.IsEnabled(EventLevel.Informational, Keywords.Messages))
_eventSource.Message("DiagnosticSource: Parsing Explicit Transform '" + filterAndPayloadSpec.Substring(specStartIdx, endIdx - specStartIdx) + "'");
_explicitTransforms = new TransformSpec(filterAndPayloadSpec, specStartIdx, endIdx, _explicitTransforms);
}
if (startTransformIdx == specStartIdx)
break;
endIdx = semiColonIdx;
}
}
Action<string, string, IEnumerable<KeyValuePair<string, string>>> writeEvent = null;
if (activityName != null && activityName.Contains("Activity"))
{
MethodInfo writeEventMethodInfo = typeof(DiagnosticSourceEventSource).GetTypeInfo().GetDeclaredMethod(activityName);
if (writeEventMethodInfo != null)
{
// This looks up the activityName (which needs to be a name of an event on DiagnosticSourceEventSource
// like Activity1Start and returns that method). This allows us to have a number of them and this code
// just works.
try
{
writeEvent = (Action<string, string, IEnumerable<KeyValuePair<string, string>>>)
writeEventMethodInfo.CreateDelegate(typeof(Action<string, string, IEnumerable<KeyValuePair<string, string>>>), _eventSource);
}
catch (Exception) { }
}
if (writeEvent == null)
_eventSource.Message("DiagnosticSource: Could not find Event to log Activity " + activityName);
}
if (writeEvent == null)
{
#if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT
writeEvent = _eventSource.Event;
#else
writeEvent = delegate (string sourceName, string eventName, IEnumerable<KeyValuePair<string, string>> arguments)
{
_eventSource.EventJson(sourceName, eventName, ToJson(arguments));
};
#endif
}
// Set up a subscription that watches for the given Diagnostic Sources and events which will call back
// to the EventSource.
_diagnosticsListenersSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(delegate (DiagnosticListener newListener)
{
if (listenerNameFilter == null || listenerNameFilter == newListener.Name)
{
_eventSource.NewDiagnosticListener(newListener.Name);
Predicate<string> eventNameFilterPredicate = null;
if (eventNameFilter != null)
eventNameFilterPredicate = (string eventName) => eventNameFilter == eventName;
var subscription = newListener.Subscribe(new CallbackObserver<KeyValuePair<string, object>>(delegate (KeyValuePair<string, object> evnt)
{
// The filter given to the DiagnosticSource may not work if users don't is 'IsEnabled' as expected.
// Thus we look for any events that may have snuck through and filter them out before forwarding.
if (eventNameFilter != null && eventNameFilter != evnt.Key)
return;
var outputArgs = this.Morph(evnt.Value);
var eventName = evnt.Key;
writeEvent(newListener.Name, eventName, outputArgs);
}), eventNameFilterPredicate);
_liveSubscriptions = new Subscriptions(subscription, _liveSubscriptions);
}
}));
}
private void Dispose()
{
if (_diagnosticsListenersSubscription != null)
{
_diagnosticsListenersSubscription.Dispose();
_diagnosticsListenersSubscription = null;
}
if (_liveSubscriptions != null)
{
var subscr = _liveSubscriptions;
_liveSubscriptions = null;
while (subscr != null)
{
subscr.Subscription.Dispose();
subscr = subscr.Next;
}
}
}
public List<KeyValuePair<string, string>> Morph(object args)
{
// Transform the args into a bag of key-value strings.
var outputArgs = new List<KeyValuePair<string, string>>();
if (args != null)
{
if (!_noImplicitTransforms)
{
Type argType = args.GetType();
if (_expectedArgType != argType)
{
// Figure out the default properties to send on to EventSource. These are all string or primitive properties.
_implicitTransforms = null;
TransformSpec newSerializableArgs = null;
TypeInfo curTypeInfo = argType.GetTypeInfo();
foreach (var property in curTypeInfo.DeclaredProperties)
{
var propertyType = property.PropertyType;
newSerializableArgs = new TransformSpec(property.Name, 0, property.Name.Length, newSerializableArgs);
}
_expectedArgType = argType;
_implicitTransforms = Reverse(newSerializableArgs);
}
// Fetch all the fields that are already serializable
if (_implicitTransforms != null)
{
for (var serializableArg = _implicitTransforms; serializableArg != null; serializableArg = serializableArg.Next)
outputArgs.Add(serializableArg.Morph(args));
}
}
if (_explicitTransforms != null)
{
for (var explicitTransform = _explicitTransforms; explicitTransform != null; explicitTransform = explicitTransform.Next)
{
var keyValue = explicitTransform.Morph(args);
if (keyValue.Value != null)
outputArgs.Add(keyValue);
}
}
}
return outputArgs;
}
public FilterAndTransform Next;
#region private
// Reverses a linked list (of TransformSpecs) in place.
private static TransformSpec Reverse(TransformSpec list)
{
TransformSpec ret = null;
while (list != null)
{
var next = list.Next;
list.Next = ret;
ret = list;
list = next;
}
return ret;
}
private IDisposable _diagnosticsListenersSubscription; // This is our subscription that listens for new Diagnostic source to appear.
private Subscriptions _liveSubscriptions; // These are the subscriptions that we are currently forwarding to the EventSource.
private bool _noImplicitTransforms; // Listener can say they don't want implicit transforms.
private Type _expectedArgType; // This is the type where 'implicitTransforms is built for'
private TransformSpec _implicitTransforms; // payload to include because the DiagnosticSource's object fields are already serializable
private TransformSpec _explicitTransforms; // payload to include because the user explicitly indicated how to fetch the field.
private DiagnosticSourceEventSource _eventSource; // Where the data is written to.
#endregion
}
/// <summary>
/// Transform spec represents a string that describes how to extract a piece of data from
/// the DiagnosticSource payload. An example string is OUTSTR=EVENT_VALUE.PROP1.PROP2.PROP3
/// It has a Next field so they can be chained together in a linked list.
/// </summary>
internal class TransformSpec
{
/// <summary>
/// parse the strings 'spec' from startIdx to endIdx (points just beyond the last considered char)
/// The syntax is ID1=ID2.ID3.ID4 .... Where ID1= is optional.
/// </summary>
public TransformSpec(string transformSpec, int startIdx, int endIdx, TransformSpec next = null)
{
Debug.Assert(transformSpec != null && startIdx < endIdx);
#if DEBUG
string spec = transformSpec.Substring(startIdx, endIdx - startIdx);
#endif
Next = next;
// Pick off the Var=
int equalsIdx = transformSpec.IndexOf('=', startIdx, endIdx - startIdx);
if (0 <= equalsIdx)
{
_outputName = transformSpec.Substring(startIdx, equalsIdx - startIdx);
startIdx = equalsIdx + 1;
}
// Working from back to front, create a PropertySpec for each .ID in the string.
while (startIdx < endIdx)
{
int dotIdx = transformSpec.LastIndexOf('.', endIdx - 1, endIdx - startIdx);
int idIdx = startIdx;
if (0 <= dotIdx)
idIdx = dotIdx + 1;
string propertName = transformSpec.Substring(idIdx, endIdx - idIdx);
_fetches = new PropertySpec(propertName, _fetches);
// If the user did not explicitly set a name, it is the last one (first to be processed from the end).
if (_outputName == null)
_outputName = propertName;
endIdx = dotIdx; // This works even when LastIndexOf return -1.
}
}
/// <summary>
/// Given the DiagnosticSourcePayload 'obj', compute a key-value pair from it. For example
/// if the spec is OUTSTR=EVENT_VALUE.PROP1.PROP2.PROP3 and the ultimate value of PROP3 is
/// 10 then the return key value pair is KeyValuePair("OUTSTR","10")
/// </summary>
public KeyValuePair<string, string> Morph(object obj)
{
for (PropertySpec cur = _fetches; cur != null; cur = cur.Next)
{
if (obj != null)
obj = cur.Fetch(obj);
}
return new KeyValuePair<string, string>(_outputName, obj?.ToString());
}
/// <summary>
/// A public field that can be used to form a linked list.
/// </summary>
public TransformSpec Next;
#region private
/// <summary>
/// A PropertySpec represents information needed to fetch a property from
/// and efficiently. Thus it represents a '.PROP' in a TransformSpec
/// (and a transformSpec has a list of these).
/// </summary>
internal class PropertySpec
{
/// <summary>
/// Make a new PropertySpec for a property named 'propertyName'.
/// For convenience you can set he 'next' field to form a linked
/// list of PropertySpecs.
/// </summary>
public PropertySpec(string propertyName, PropertySpec next = null)
{
Next = next;
_propertyName = propertyName;
}
/// <summary>
/// Given an object fetch the property that this PropertySpec represents.
/// </summary>
public object Fetch(object obj)
{
Type objType = obj.GetType();
if (objType != _expectedType)
{
var typeInfo = objType.GetTypeInfo();
_fetchForExpectedType = PropertyFetch.FetcherForProperty(typeInfo.GetDeclaredProperty(_propertyName));
_expectedType = objType;
}
return _fetchForExpectedType.Fetch(obj);
}
/// <summary>
/// A public field that can be used to form a linked list.
/// </summary>
public PropertySpec Next;
#region private
/// <summary>
/// PropertyFetch is a helper class. It takes a PropertyInfo and then knows how
/// to efficiently fetch that property from a .NET object (See Fetch method).
/// It hides some slightly complex generic code.
/// </summary>
class PropertyFetch
{
/// <summary>
/// Create a property fetcher from a .NET Reflection PropertyInfo class that
/// represents a property of a particular type.
/// </summary>
public static PropertyFetch FetcherForProperty(PropertyInfo propertyInfo)
{
if (propertyInfo == null)
return new PropertyFetch(); // returns null on any fetch.
var typedPropertyFetcher = typeof(TypedFetchProperty<,>);
var instantiatedTypedPropertyFetcher = typedPropertyFetcher.GetTypeInfo().MakeGenericType(
propertyInfo.DeclaringType, propertyInfo.PropertyType);
return (PropertyFetch)Activator.CreateInstance(instantiatedTypedPropertyFetcher, propertyInfo);
}
/// <summary>
/// Given an object, fetch the property that this propertyFech represents.
/// </summary>
public virtual object Fetch(object obj) { return null; }
#region private
private class TypedFetchProperty<TObject, TProperty> : PropertyFetch
{
public TypedFetchProperty(PropertyInfo property)
{
_propertyFetch = (Func<TObject, TProperty>)property.GetMethod.CreateDelegate(typeof(Func<TObject, TProperty>));
}
public override object Fetch(object obj)
{
return _propertyFetch((TObject)obj);
}
private readonly Func<TObject, TProperty> _propertyFetch;
}
#endregion
}
private string _propertyName;
private Type _expectedType;
private PropertyFetch _fetchForExpectedType;
#endregion
}
private string _outputName;
private PropertySpec _fetches;
#endregion
}
/// <summary>
/// CallbackObserver is an adapter class that creates an observer (which you can pass
/// to IObservable.Subscribe), and calls the given callback every time the 'next'
/// operation on the IObserver happens.
/// </summary>
/// <typeparam name="T"></typeparam>
internal class CallbackObserver<T> : IObserver<T>
{
public CallbackObserver(Action<T> callback) { _callback = callback; }
#region private
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(T value) { _callback(value); }
private Action<T> _callback;
#endregion
}
// A linked list of IObservable subscriptions (which are IDisposable).
// We use this to keep track of the DiagnosticSource subscriptions.
// We use this linked list for thread atomicity
internal class Subscriptions
{
public Subscriptions(IDisposable subscription, Subscriptions next)
{
Subscription = subscription;
Next = next;
}
public IDisposable Subscription;
public Subscriptions Next;
}
#endregion
private FilterAndTransform _specs; // Transformation specifications that indicate which sources/events are forwarded.
#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:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using XenAdmin.Core;
namespace XenAdmin.Wlb
{
public class WlbScheduledTask : WlbConfigurationBase
{
private const string KEY_TASK_NAME = "TaskName";
private const string KEY_TASK_DESCRIPTION = "TaskDescription";
private const string KEY_TASK_ENABLED = "TaskEnabled";
private const string KEY_TASK_OWNER = "TaskOwner";
private const string KEY_TASK_LAST_RUN_RESULT = "TaskLastRunResult";
private const string KEY_TASK_LAST_TOUCHED_BY = "TaskLastTouchedBy";
private const string KEY_TASK_LAST_TOUCHED = "TaskLastTouched";
private const string KEY_TRIGGER_TYPE = "TriggerType";
private const string KEY_TRIGGER_DAYS_OF_WEEK = "TriggerDaysOfWeek";
private const string KEY_TRIGGER_EXECUTE_TIME = "TriggerExecuteTime";
private const string KEY_TRIGGER_LAST_RUN = "TriggerLastRun";
private const string KEY_TRIGGER_ENABLED_DATE = "TriggerEndabledDate";
private const string KEY_TRIGGER_DISABLED_DATE = "TriggerDisabledDate";
private const string KEY_DELETE_TASK = "TaskDelete";
private const string KEY_ACTION_TYPE = "ActionType";
/// <summary>
/// Public enumeration describing the interval period of a WlbTaskTrigger
/// </summary>
public enum WlbTaskTriggerType : int
{
/// <summary>
/// A single-shot trigger
/// </summary>
Once = 0,
/// <summary>
/// A trigger that occurs every day at a particular time
/// </summary>
Daily = 1,
/// <summary>
/// A trigger that occurs every week on a set of days at a particulat time
/// </summary>
Weekly = 2,
/// <summary>
/// A trigger that occurs once every month on a given date
/// </summary>
Monthly = 3
}
public enum WlbTaskActionType : int
{
Unknown = 0,
SetOptimizationMode = 1,
ReportSubscription = 2
}
/// <summary>
/// Public enumeration of the days on which a weekly WlbTaskTrigger will execute
/// </summary>
[FlagsAttribute]
public enum WlbTaskDaysOfWeek
{
/// <summary>
/// None
/// </summary>
None = 0,
/// <summary>
/// Sunday
/// </summary>
Sunday = 1,
/// <summary>
/// Monday
/// </summary>
Monday = 2,
/// <summary>
/// Tuesday
/// </summary>
Tuesday = 4,
/// <summary>
/// Wednesday
/// </summary>
Wednesday = 8,
/// <summary>
/// Thursday
/// </summary>
Thursday = 16,
/// <summary>
/// Friday
/// </summary>
Friday = 32,
/// <summary>
/// Saturday
/// </summary>
Saturday = 64,
/// <summary>
/// All weekdays
/// </summary>
Weekends = Sunday | Saturday,
/// <summary>
/// Only weekend days
/// </summary>
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday,
/// <summary>
/// All days
/// </summary>
All = Weekdays | Weekends
}
public static string DaysOfWeekL10N(WlbTaskDaysOfWeek days)
{
switch (days)
{
case WlbTaskDaysOfWeek.Sunday:
return Messages.SUNDAY_LONG;
case WlbTaskDaysOfWeek.Monday:
return Messages.MONDAY_LONG;
case WlbTaskDaysOfWeek.Tuesday:
return Messages.TUESDAY_LONG;
case WlbTaskDaysOfWeek.Wednesday:
return Messages.WEDNESDAY_LONG;
case WlbTaskDaysOfWeek.Thursday:
return Messages.THURSDAY_LONG;
case WlbTaskDaysOfWeek.Friday:
return Messages.FRIDAY_LONG;
case WlbTaskDaysOfWeek.Saturday:
return Messages.SATURDAY_LONG;
case WlbTaskDaysOfWeek.Weekdays:
return Messages.WLB_DAY_WEEKDAYS;
case WlbTaskDaysOfWeek.Weekends:
return Messages.WLB_DAY_WEEKENDS;
case WlbTaskDaysOfWeek.All:
return Messages.WLB_DAY_ALL;
default:
return "";
}
}
public static WlbPoolPerformanceMode GetTaskOptMode(WlbScheduledTask task)
{
WlbPoolPerformanceMode mode = WlbPoolPerformanceMode.MaximizePerformance;
if (task.TaskParameters["OptMode"] == "0")
{
mode = WlbPoolPerformanceMode.MaximizePerformance;
}
else
{
mode = WlbPoolPerformanceMode.MaximizeDensity;
}
return mode;
}
public static string GetTaskExecuteTime(DateTime TaskExecuteTime)
{
return HelpersGUI.DateTimeToString(TaskExecuteTime, Messages.DATEFORMAT_HM, true);
}
/// <summary>
/// Returns the offset minutes between Utc and local time
/// Add this to local time to get UTC
/// Subtract from UTC to get local time
/// </summary>
/// <returns>(double) number of minutes between Utc and Local time</returns>
private static double LocalOffsetMinutes()
{
TimeSpan difference = DateTime.UtcNow.Subtract(DateTime.Now);
return difference.TotalMinutes;
}
/// <summary>
/// Accepts a client's local time DayOfWeek and ExecuteTime of a scheduled task
/// and returns the DaysOfWeek and ExecuteTime adjusted to UTC time
/// </summary>
/// <param name="LocalDaysOfWeek">Task's DaysOfWeek value in local time</param>
/// <param name="LocalExecuteTime">Task's ExecuteTime in local time</param>
/// <param name="UtcDaysOfWeek">(Output) Task's DaysOfWeek value adjusted to UTC</param>
/// <param name="UtcExecuteTime">(Output) Task's ExecuteTime value adjusted to UTC</param>
public static void GetUTCTaskTimes(WlbScheduledTask.WlbTaskDaysOfWeek LocalDaysOfWeek, DateTime LocalExecuteTime,
out WlbScheduledTask.WlbTaskDaysOfWeek UtcDaysOfWeek, out DateTime UtcExecuteTime)
{
UtcDaysOfWeek = LocalDaysOfWeek;
UtcExecuteTime = LocalExecuteTime.AddMinutes(LocalOffsetMinutes());
if (DateTime.Compare(LocalExecuteTime.Date, UtcExecuteTime.Date) < 0)
{
UtcDaysOfWeek = WlbScheduledTask.NextDay(LocalDaysOfWeek);
}
else if (DateTime.Compare(LocalExecuteTime.Date, UtcExecuteTime.Date) > 0)
{
UtcDaysOfWeek = WlbScheduledTask.PreviousDay(LocalDaysOfWeek);
}
}
/// <summary>
/// Accepts UTC DayOfWeek and ExecuteTime of a scheduled task
/// and returns the DaysOfWeek and ExecuteTime adjusted to client's local time
/// </summary>
/// <param name="UtcDaysOfWeek">Task's DaysOfWeek value in UTC</param>
/// <param name="UtcExecuteTime">Task's ExecuteTime in UTC</param>
/// <param name="LocalDaysOfWeek">(Output) Task's DaysOfWeek value adjusted to local time</param>
/// <param name="LocalExecuteTime">(Output) Task's ExecuteTime value adjusted to local time</param>
public static void GetLocalTaskTimes(WlbScheduledTask.WlbTaskDaysOfWeek UtcDaysOfWeek, DateTime UtcExecuteTime,
out WlbScheduledTask.WlbTaskDaysOfWeek LocalDaysOfWeek, out DateTime LocalExecuteTime)
{
LocalDaysOfWeek = UtcDaysOfWeek;
LocalExecuteTime = UtcExecuteTime.AddMinutes(LocalOffsetMinutes() * -1);
if (UtcDaysOfWeek != WlbTaskDaysOfWeek.None &&
UtcDaysOfWeek != WlbTaskDaysOfWeek.All &&
UtcDaysOfWeek != WlbTaskDaysOfWeek.Weekdays &&
UtcDaysOfWeek != WlbTaskDaysOfWeek.Weekends)
{
if (DateTime.Compare(UtcExecuteTime.Date, LocalExecuteTime.Date) < 0)
{
LocalDaysOfWeek = WlbScheduledTask.NextDay(UtcDaysOfWeek);
}
else if (DateTime.Compare(UtcExecuteTime.Date, LocalExecuteTime.Date) > 0)
{
LocalDaysOfWeek = WlbScheduledTask.PreviousDay(UtcDaysOfWeek);
}
}
}
public static WlbTaskDaysOfWeek NextDay(WlbTaskDaysOfWeek daysOfWeek)
{
// Doing some hackery here to shift days in the enumeration
switch (daysOfWeek)
{
case WlbTaskDaysOfWeek.Saturday:
{
return WlbTaskDaysOfWeek.Sunday;
}
case WlbTaskDaysOfWeek.Weekends:
{
return (WlbTaskDaysOfWeek.Sunday |
WlbTaskDaysOfWeek.Monday);
}
case WlbTaskDaysOfWeek.Weekdays:
{
return (WlbTaskDaysOfWeek.Tuesday |
WlbTaskDaysOfWeek.Wednesday |
WlbTaskDaysOfWeek.Thursday |
WlbTaskDaysOfWeek.Friday |
WlbTaskDaysOfWeek.Saturday);
}
case WlbTaskDaysOfWeek.All:
{
return daysOfWeek;
}
// single days, Sunday through Friday, which can easily be
// shifted back by one. This also handles None (0).
default:
{
//do the circular shift of rightmost 7 bits, discard the rest
int tempDays = (int)daysOfWeek;
tempDays = (tempDays << 1 | tempDays >> 6) & 0x0000007F;
return (WlbTaskDaysOfWeek)tempDays;
//return (WlbTaskDaysOfWeek)(((int)daysOfWeek) * 2);
}
}
}
public static WlbTaskDaysOfWeek PreviousDay(WlbTaskDaysOfWeek daysOfWeek)
{
// Doing some hackery here to shift days in the enumeration
switch (daysOfWeek)
{
case WlbTaskDaysOfWeek.Sunday:
{
return WlbTaskDaysOfWeek.Saturday;
}
case WlbTaskDaysOfWeek.Weekends:
{
return (WlbTaskDaysOfWeek.Friday |
WlbTaskDaysOfWeek.Saturday);
}
case WlbTaskDaysOfWeek.Weekdays:
{
return (WlbTaskDaysOfWeek.Sunday |
WlbTaskDaysOfWeek.Monday |
WlbTaskDaysOfWeek.Tuesday |
WlbTaskDaysOfWeek.Wednesday |
WlbTaskDaysOfWeek.Thursday);
}
case WlbTaskDaysOfWeek.All:
{
return daysOfWeek;
}
// single days, monday through saturday, which can easily be
// shifted back by one. This also handles None (0).
default:
{
//do the circular shift of rightmost 7 bits, discard the rest
int tempDays = (int)daysOfWeek;
tempDays = (tempDays >> 1 | tempDays << 6) & 0x0000007F;
return (WlbTaskDaysOfWeek)tempDays;
//return (WlbTaskDaysOfWeek)(((int)daysOfWeek) / 2);
}
}
}
public static WlbScheduledTask.WlbTaskDaysOfWeek ConvertToWlbTaskDayOfWeek(DayOfWeek dayOfWeek)
{
return (WlbScheduledTask.WlbTaskDaysOfWeek)(Math.Pow(2,(int)dayOfWeek) % 127);
}
public static DayOfWeek ConvertFromWlbTaskDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek wlbDayOfWeek)
{
return (DayOfWeek)(Math.Log((int)wlbDayOfWeek, 2));
}
public WlbScheduledTask(string TaskId)
{
base.Configuration = new Dictionary<string, string>();
base.ItemId = TaskId;
//Define the key base
base.KeyBase = WlbConfigurationKeyBase.schedTask;
//Define the known keys
WlbConfigurationKeys = new List<string>(new string[]
{
KEY_TASK_NAME,
KEY_TASK_DESCRIPTION,
KEY_TASK_ENABLED,
KEY_TASK_OWNER,
KEY_TASK_LAST_RUN_RESULT,
KEY_TASK_LAST_TOUCHED_BY,
KEY_TASK_LAST_TOUCHED,
KEY_TRIGGER_TYPE,
KEY_TRIGGER_DAYS_OF_WEEK,
KEY_TRIGGER_EXECUTE_TIME,
KEY_TRIGGER_LAST_RUN,
KEY_TRIGGER_ENABLED_DATE,
KEY_TRIGGER_DISABLED_DATE,
KEY_DELETE_TASK,
KEY_ACTION_TYPE
});
}
public bool DeleteTask
{
get { return GetConfigValueBool(BuildComplexKey(KEY_DELETE_TASK)); }
set { SetConfigValueBool(BuildComplexKey(KEY_DELETE_TASK), value, true); }
}
public string Name
{
get { return GetConfigValueString(BuildComplexKey(KEY_TASK_NAME)); }
set { SetConfigValueString(BuildComplexKey(KEY_TASK_NAME), value, true); }
}
public string Description
{
get { return GetConfigValueString(BuildComplexKey(KEY_TASK_DESCRIPTION)); }
set { SetConfigValueString(BuildComplexKey(KEY_TASK_DESCRIPTION), value, true); }
}
public bool Enabled
{
get { return GetConfigValueBool(BuildComplexKey(KEY_TASK_ENABLED)); }
set { SetConfigValueBool(BuildComplexKey(KEY_TASK_ENABLED), value, true); }
}
public string Owner
{
get { return GetConfigValueString(BuildComplexKey(KEY_TASK_OWNER)); }
set { SetConfigValueString(BuildComplexKey(KEY_TASK_OWNER), value, true); }
}
public bool LastRunResult
{
get { return GetConfigValueBool(BuildComplexKey(KEY_TASK_LAST_RUN_RESULT)); }
set { SetConfigValueBool(BuildComplexKey(KEY_TASK_LAST_RUN_RESULT), value, true); }
}
public string LastTouchedBy
{
get { return GetConfigValueString(BuildComplexKey(KEY_TASK_LAST_TOUCHED_BY)); }
set { SetConfigValueString(BuildComplexKey(KEY_TASK_LAST_TOUCHED_BY), value, true); }
}
public DateTime LastTouched
{
get { return GetConfigValueUTCDateTime(BuildComplexKey(KEY_TASK_LAST_TOUCHED)); }
set { SetConfigValueUTCDateTime(BuildComplexKey(KEY_TASK_LAST_TOUCHED), value, true); }
}
public WlbTaskTriggerType TriggerInterval
{
get { return (WlbTaskTriggerType)GetConfigValueInt(BuildComplexKey(KEY_TRIGGER_TYPE)); }
set { SetConfigValueInt(BuildComplexKey(KEY_TRIGGER_TYPE), (int)value, true); }
}
public WlbTaskDaysOfWeek DaysOfWeek
{
get { return (WlbTaskDaysOfWeek)GetConfigValueInt(BuildComplexKey(KEY_TRIGGER_DAYS_OF_WEEK)); }
set { SetConfigValueInt(BuildComplexKey(KEY_TRIGGER_DAYS_OF_WEEK), (int)value, true); }
}
public DateTime ExecuteTime
{
get { return GetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_EXECUTE_TIME)); }
set { SetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_EXECUTE_TIME), value, true); }
}
public DateTime LastRunDate
{
get { return GetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_LAST_RUN)); }
set { SetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_LAST_RUN), value, true); }
}
public DateTime EnableDate
{
get { return GetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_ENABLED_DATE)); }
set { SetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_ENABLED_DATE), value, true); }
}
public DateTime DisableTime
{
get { return GetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_DISABLED_DATE)); }
set { SetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_DISABLED_DATE), value, true); }
}
public WlbTaskActionType ActionType
{
get { return (WlbTaskActionType)GetConfigValueInt(BuildComplexKey(KEY_ACTION_TYPE)); }
set { SetConfigValueInt(BuildComplexKey(KEY_ACTION_TYPE), (int)value, true); }
}
public Dictionary<string, string> TaskParameters
{
get { return GetOtherParameters(); }
set { SetOtherParameters(value); }
}
public void AddTaskParameter(string key, string value)
{
SetOtherParameter(key, value);
}
public int TaskId
{
get
{
int taskId = 0;
Int32.TryParse(ItemId, out taskId);
return taskId;
}
}
public WlbScheduledTask Clone()
{
WlbScheduledTask newTask = new WlbScheduledTask(this.TaskId.ToString());
newTask.ActionType = this.ActionType;
newTask.DaysOfWeek = this.DaysOfWeek;
newTask.DeleteTask = this.DeleteTask;
newTask.Description = this.Description;
newTask.DisableTime = this.DisableTime;
newTask.Enabled = this.Enabled;
newTask.EnableDate = this.EnableDate;
newTask.ExecuteTime = this.ExecuteTime;
newTask.LastRunDate = this.LastRunDate;
newTask.LastRunResult = this.LastRunResult;
newTask.LastTouched = this.LastTouched;
newTask.LastTouchedBy = this.LastTouchedBy;
newTask.Name = this.Name;
newTask.Owner = this.Owner;
newTask.TaskParameters = this.TaskParameters;
newTask.TriggerInterval = this.TriggerInterval;
return newTask;
}
}
public class WlbScheduledTasks
{
private Dictionary<string, WlbScheduledTask> _tasks = new Dictionary<string, WlbScheduledTask>();
public WlbScheduledTasks() { ;}
/// <summary>
/// Exposes the actual list of WlbScheduledTasks
/// </summary>
public Dictionary<string, WlbScheduledTask> TaskList
{
set { _tasks = value; }
get { return _tasks; }
}
/// <summary>
/// Exposes a sorted version of the WlbScheduledTasks collection
/// </summary>
public SortedDictionary<int, WlbScheduledTask> SortedTaskList
{
get
{
SortedDictionary<int, WlbScheduledTask> sortedTasks = new SortedDictionary<int, WlbScheduledTask>();
foreach (WlbScheduledTask task in _tasks.Values)
{
if (!task.DeleteTask)
{
WlbScheduledTask.WlbTaskDaysOfWeek localDaysOfWeek;
DateTime localExecuteTime;
WlbScheduledTask.GetLocalTaskTimes((task.DaysOfWeek), task.ExecuteTime, out localDaysOfWeek, out localExecuteTime);
int sortKey = GetSortKey(localDaysOfWeek, localExecuteTime);
//if the task is disabled, bump the sort key to prevent conficts
// with any new tasks. This could start to get wierd after 100 duplicate
// disabled tasks, but then it will be the user's problem.
if (!task.Enabled)
{
sortKey += 1;
while (sortedTasks.ContainsKey(sortKey))
{
sortKey += 1;
}
}
WlbScheduledTask virtualTask = task.Clone();
virtualTask.DaysOfWeek = task.DaysOfWeek;
if (!sortedTasks.ContainsKey(sortKey))
{
sortedTasks.Add(sortKey, virtualTask);
}
}
}
return sortedTasks;
}
}
/// Exposes a virtual representation of the WlbScheduledTasks collection, in which aggregate days
/// are separated into individual days. The entire list is also presorted chronologically.
/// </summary>
public SortedDictionary<int, WlbScheduledTask> VirtualTaskList
{
get
{
SortedDictionary<int, WlbScheduledTask> virtualTasks = new SortedDictionary<int, WlbScheduledTask>();
foreach (WlbScheduledTask task in _tasks.Values)
{
if (!task.DeleteTask)
{
foreach (WlbScheduledTask.WlbTaskDaysOfWeek dayValue in Enum.GetValues(typeof(WlbScheduledTask.WlbTaskDaysOfWeek)))
{
if (dayValue != WlbScheduledTask.WlbTaskDaysOfWeek.None &&
dayValue != WlbScheduledTask.WlbTaskDaysOfWeek.All &&
dayValue != WlbScheduledTask.WlbTaskDaysOfWeek.Weekdays &&
dayValue != WlbScheduledTask.WlbTaskDaysOfWeek.Weekends &&
((task.DaysOfWeek & dayValue) == dayValue))
{
DateTime localExecuteTime;
WlbScheduledTask.WlbTaskDaysOfWeek localDaysOfWeek;
WlbScheduledTask.GetLocalTaskTimes((task.DaysOfWeek & dayValue), task.ExecuteTime, out localDaysOfWeek, out localExecuteTime);
int sortKey = GetSortKey(localDaysOfWeek, localExecuteTime);
//if the task is disabled, bump the sort key to prevent conficts
// with any new tasks. This could start to get wierd after 100 duplicate
// disabled tasks, but then it will be the user's problem.
if (!task.Enabled)
{
sortKey += 1;
while (virtualTasks.ContainsKey(sortKey))
{
sortKey += 1;
}
}
WlbScheduledTask virtualTask = task.Clone();
virtualTask.DaysOfWeek = dayValue;
if (!virtualTasks.ContainsKey(sortKey))
{
virtualTasks.Add(sortKey, virtualTask);
}
}
}
}
}
return virtualTasks;
}
}
/// <summary>
/// Creates an artificial sort key that is used to sort the presentation of scheduled tasks.
/// </summary>
/// <param name="localDaysOfWeek">WlbScheduledTask.DaysOfWeek enumeration of the task denoting on which days it will execute</param>
/// <param name="localExecuteTime">DateTime execute time of the task denoting on when the task </param>
/// <returns></returns>
private static int GetSortKey(WlbScheduledTask.WlbTaskDaysOfWeek localDaysOfWeek, DateTime localExecuteTime)
{
int sortKey;
//The day of week is the primary sort item
switch(localDaysOfWeek)
{
//Put ALL tasks at the front of the list
case WlbScheduledTask.WlbTaskDaysOfWeek.All:
{
sortKey = 0;
break;
}
//Next are WEEKDAY tasks
case WlbScheduledTask.WlbTaskDaysOfWeek.Weekdays:
{
sortKey = 200000;
break;
}
//Next are WEEKEND tasks
case WlbScheduledTask.WlbTaskDaysOfWeek.Weekends:
{
sortKey = 400000;
break;
}
//Finally, single-day tasks
default:
{
sortKey = (int)localDaysOfWeek * 1000000;
break;
}
}
//Add the execute time of day as a secondary sort item
//Multiply it by 100 to allow room for disabled tasks
sortKey += (int)localExecuteTime.TimeOfDay.TotalMinutes * 100;
return sortKey;
}
public WlbScheduledTasks(Dictionary<string,string> Configuration)
{
foreach (string key in Configuration.Keys)
{
if (key.StartsWith("schedTask_"))
{
string[] keyElements = key.Split('_');
string taskId = keyElements[1];
if (!_tasks.ContainsKey(taskId))
{
_tasks.Add(taskId, new WlbScheduledTask(taskId));
_tasks[taskId].AddParameter(key, Configuration[key]);
}
else
{
_tasks[taskId].AddParameter(key, Configuration[key]);
}
}
}
}
public Dictionary<string, string> ToDictionary()
{
Dictionary<string, string> collectionDictionary = null;
foreach (WlbScheduledTask scheduleTask in _tasks.Values)
{
Dictionary<string, string> taskDictionary = scheduleTask.ToDictionary();
foreach (string key in taskDictionary.Keys)
{
if (null == collectionDictionary)
{
collectionDictionary = new Dictionary<string, string>();
}
collectionDictionary.Add(key, taskDictionary[key]);
}
foreach (string key in scheduleTask.TaskParameters.Keys)
{
string complexKey = string.Format("{0}_{1}_{2}", scheduleTask.KeyBase, scheduleTask.TaskId.ToString(), key);
if (collectionDictionary.ContainsKey(complexKey))
{
collectionDictionary[complexKey] = scheduleTask.TaskParameters[key];
}
else
{
collectionDictionary.Add(complexKey, scheduleTask.TaskParameters[key]);
}
}
}
return collectionDictionary;
}
public WlbScheduledTask GetNextExecutingTask()
{
WlbScheduledTask firstTask = null;
int currentTimeSortKey = GetSortKey(WlbScheduledTask.ConvertToWlbTaskDayOfWeek(DateTime.Now.DayOfWeek), DateTime.Now);
foreach (int key in this.VirtualTaskList.Keys)
{
//only consider Enabled tasks
if (this.VirtualTaskList[key].Enabled)
{
if (null == firstTask)
{
firstTask = this.VirtualTaskList[key];
}
if (key > currentTimeSortKey)
{
return this.VirtualTaskList[key];
}
}
}
//we are still here, so we have not found the next task. this means that we
// need to account for week wrapping. This shoudl be the first task of the Virtual
// Task List
return firstTask;
}
public WlbScheduledTask GetLastExecutingTask()
{
int[] taskKeys = new int[this.VirtualTaskList.Keys.Count];
this.VirtualTaskList.Keys.CopyTo(taskKeys,0);
WlbScheduledTask lastTask = this.VirtualTaskList[taskKeys[taskKeys.Length-1]];
int currentTimeSortKey = GetSortKey(WlbScheduledTask.ConvertToWlbTaskDayOfWeek(DateTime.Now.DayOfWeek), DateTime.Now);
for (int i = taskKeys.Length-1; i>=0; i--)
{
//Only consider Enabled tasks
if (this.VirtualTaskList[taskKeys[i]].Enabled)
{
if (taskKeys[i] < currentTimeSortKey)
{
return this.VirtualTaskList[taskKeys[i]];
}
}
}
//we are still here, so we have not found the previous task. this means that we
// need to account for week wrapping. This should be the last task of the Virtual
// Task List
return lastTask;
}
public WlbPoolPerformanceMode GetCurrentScheduledPerformanceMode()
{
WlbScheduledTask lastTask = GetLastExecutingTask();
return (WlbPoolPerformanceMode)int.Parse(lastTask.TaskParameters["OptMode"]);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Xunit;
namespace System.Globalization.Tests
{
public class InvariantModeTests
{
public static IEnumerable<object[]> Cultures_TestData()
{
yield return new object[] { "en-US" };
yield return new object[] { "ja-JP" };
yield return new object[] { "fr-FR" };
yield return new object[] { "tr-TR" };
yield return new object[] { "" };
}
private static readonly string[] s_cultureNames = new string[] { "en-US", "ja-JP", "fr-FR", "tr-TR", "" };
public static IEnumerable<object[]> IndexOf_TestData()
{
// Empty string
yield return new object[] { "foo", "", 0, 3, CompareOptions.None, 0 };
yield return new object[] { "", "", 0, 0, CompareOptions.None, 0 };
// OrdinalIgnoreCase
yield return new object[] { "Hello", "l", 0, 5, CompareOptions.OrdinalIgnoreCase, 2 };
yield return new object[] { "Hello", "L", 0, 5, CompareOptions.OrdinalIgnoreCase, 2 };
yield return new object[] { "Hello", "h", 0, 5, CompareOptions.OrdinalIgnoreCase, 0 };
// Long strings
yield return new object[] { new string('b', 100) + new string('a', 5555), "aaaaaaaaaaaaaaa", 0, 5655, CompareOptions.None, 100 };
yield return new object[] { new string('b', 101) + new string('a', 5555), new string('a', 5000), 0, 5656, CompareOptions.None, 101 };
yield return new object[] { new string('a', 5555), new string('a', 5000) + "b", 0, 5555, CompareOptions.None, -1 };
// Hungarian
yield return new object[] { "foobardzsdzs", "rddzs", 0, 12, CompareOptions.Ordinal, -1 };
yield return new object[] { "foobardzsdzs", "rddzs", 0, 12, CompareOptions.None, -1 };
yield return new object[] { "foobardzsdzs", "rddzs", 0, 12, CompareOptions.Ordinal, -1 };
// Turkish
yield return new object[] { "Hi", "I", 0, 2, CompareOptions.None, -1 };
yield return new object[] { "Hi", "I", 0, 2, CompareOptions.IgnoreCase, 1 };
yield return new object[] { "Hi", "\u0130", 0, 2, CompareOptions.None, -1 };
yield return new object[] { "Hi", "\u0130", 0, 2, CompareOptions.IgnoreCase, -1 };
yield return new object[] { "Hi", "I", 0, 2, CompareOptions.None, -1 };
yield return new object[] { "Hi", "\u0130", 0, 2, CompareOptions.IgnoreCase, -1 };
// Unicode
yield return new object[] { "Hi", "\u0130", 0, 2, CompareOptions.None, -1 };
yield return new object[] { "Exhibit \u00C0", "A\u0300", 0, 9, CompareOptions.None, -1 };
yield return new object[] { "Exhibit \u00C0", "A\u0300", 0, 9, CompareOptions.Ordinal, -1 };
yield return new object[] { "Exhibit \u00C0", "a\u0300", 0, 9, CompareOptions.None, -1 };
yield return new object[] { "Exhibit \u00C0", "a\u0300", 0, 9, CompareOptions.Ordinal, -1 };
yield return new object[] { "Exhibit \u00C0", "a\u0300", 0, 9, CompareOptions.IgnoreCase, -1 };
yield return new object[] { "Exhibit \u00C0", "a\u0300", 0, 9, CompareOptions.OrdinalIgnoreCase, -1 };
yield return new object[] { "FooBar", "Foo\u0400Bar", 0, 6, CompareOptions.Ordinal, -1 };
yield return new object[] { "TestFooBA\u0300R", "FooB\u00C0R", 0, 11, CompareOptions.IgnoreNonSpace, -1 };
// Ignore symbols
yield return new object[] { "More Test's", "Tests", 0, 11, CompareOptions.IgnoreSymbols, -1 };
yield return new object[] { "More Test's", "Tests", 0, 11, CompareOptions.None, -1 };
yield return new object[] { "cbabababdbaba", "ab", 0, 13, CompareOptions.None, 2 };
// Ordinal should be case-se
yield return new object[] { "a", "a", 0, 1, CompareOptions.Ordinal, 0 };
yield return new object[] { "a", "A", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "abc", "aBc", 0, 3, CompareOptions.Ordinal, -1 };
// Ordinal with numbers and
yield return new object[] { "a", "1", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "1", "1", 0, 1, CompareOptions.Ordinal, 0 };
yield return new object[] { "1", "!", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "a", "-", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "-", "-", 0, 1, CompareOptions.Ordinal, 0 };
yield return new object[] { "-", "!", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "!", "!", 0, 1, CompareOptions.Ordinal, 0 };
// Ordinal with unicode
yield return new object[] { "\uFF21", "\uFE57", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "\uFE57", "\uFF21", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "\uFF21", "a\u0400Bc", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "\uFE57", "a\u0400Bc", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "a", "a\u0400Bc", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "a\u0400Bc", "a", 0, 4, CompareOptions.Ordinal, 0 };
// Ordinal with I or i
yield return new object[] { "I", "i", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "I", "I", 0, 1, CompareOptions.Ordinal, 0 };
yield return new object[] { "i", "I", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "i", "i", 0, 1, CompareOptions.Ordinal, 0 };
yield return new object[] { "I", "\u0130", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "\u0130", "I", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "i", "\u0130", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "\u0130", "i", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "I", "\u0131", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "\0131", "I", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "i", "\u0131", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "\u0131", "i", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "\u0130", "\u0130", 0, 1, CompareOptions.Ordinal, 0 };
yield return new object[] { "\u0131", "\u0131", 0, 1, CompareOptions.Ordinal, 0 };
yield return new object[] { "\u0130", "\u0131", 0, 1, CompareOptions.Ordinal, -1 };
yield return new object[] { "\u0131", "\u0130", 0, 1, CompareOptions.Ordinal, -1 };
// Platform differences
yield return new object[] { "foobardzsdzs", "rddzs", 0, 12, CompareOptions.None, -1 };
}
public static IEnumerable<object[]> LastIndexOf_TestData()
{
// Empty strings
yield return new object[] { "foo", "", 2, 3, CompareOptions.None, 2 };
yield return new object[] { "", "", 0, 0, CompareOptions.None, 0 };
yield return new object[] { "", "a", 0, 0, CompareOptions.None, -1 };
yield return new object[] { "", "", -1, 0, CompareOptions.None, 0 };
yield return new object[] { "", "a", -1, 0, CompareOptions.None, -1 };
yield return new object[] { "", "", 0, -1, CompareOptions.None, 0 };
yield return new object[] { "", "a", 0, -1, CompareOptions.None, -1 };
// Start index = source.Length
yield return new object[] { "Hello", "l", 5, 5, CompareOptions.None, 3 };
yield return new object[] { "Hello", "b", 5, 5, CompareOptions.None, -1 };
yield return new object[] { "Hello", "l", 5, 0, CompareOptions.None, -1 };
yield return new object[] { "Hello", "", 5, 5, CompareOptions.None, 4 };
yield return new object[] { "Hello", "", 5, 0, CompareOptions.None, 4 };
// OrdinalIgnoreCase
yield return new object[] { "Hello", "l", 4, 5, CompareOptions.OrdinalIgnoreCase, 3 };
yield return new object[] { "Hello", "L", 4, 5, CompareOptions.OrdinalIgnoreCase, 3 };
yield return new object[] { "Hello", "h", 4, 5, CompareOptions.OrdinalIgnoreCase, 0 };
// Long strings
yield return new object[] { new string('a', 5555) + new string('b', 100), "aaaaaaaaaaaaaaa", 5654, 5655, CompareOptions.None, 5540 };
yield return new object[] { new string('b', 101) + new string('a', 5555), new string('a', 5000), 5655, 5656, CompareOptions.None, 656 };
yield return new object[] { new string('a', 5555), new string('a', 5000) + "b", 5554, 5555, CompareOptions.None, -1 };
// Hungarian
yield return new object[] { "foobardzsdzs", "rddzs", 11, 12, CompareOptions.Ordinal, -1 };
yield return new object[] { "foobardzsdzs", "rddzs", 11, 12, CompareOptions.None, -1 };
yield return new object[] { "foobardzsdzs", "rddzs", 11, 12, CompareOptions.Ordinal, -1 };
// Turkish
yield return new object[] { "Hi", "I", 1, 2, CompareOptions.None, -1 };
yield return new object[] { "Hi", "I", 1, 2, CompareOptions.IgnoreCase, 1 };
yield return new object[] { "Hi", "\u0130", 1, 2, CompareOptions.None, -1 };
yield return new object[] { "Hi", "\u0130", 1, 2, CompareOptions.IgnoreCase, -1 };
yield return new object[] { "Hi", "I", 1, 2, CompareOptions.None, -1 };
yield return new object[] { "Hi", "I", 1, 2, CompareOptions.IgnoreCase, 1 };
yield return new object[] { "Hi", "\u0130", 1, 2, CompareOptions.None, -1 };
yield return new object[] { "Hi", "\u0130", 1, 2, CompareOptions.IgnoreCase, -1 };
// Unicode
yield return new object[] { "Exhibit \u00C0", "A\u0300", 8, 9, CompareOptions.None, -1 };
yield return new object[] { "Exhibit \u00C0", "A\u0300", 8, 9, CompareOptions.Ordinal, -1 };
yield return new object[] { "Exhibit \u00C0", "a\u0300", 8, 9, CompareOptions.None, -1 };
yield return new object[] { "Exhibit \u00C0", "a\u0300", 8, 9, CompareOptions.IgnoreCase, -1 };
yield return new object[] { "Exhibit \u00C0", "a\u0300", 8, 9, CompareOptions.OrdinalIgnoreCase, -1 };
yield return new object[] { "Exhibit \u00C0", "a\u0300", 8, 9, CompareOptions.Ordinal, -1 };
yield return new object[] { "FooBar", "Foo\u0400Bar", 5, 6, CompareOptions.Ordinal, -1 };
yield return new object[] { "TestFooBA\u0300R", "FooB\u00C0R", 10, 11, CompareOptions.IgnoreNonSpace, -1 };
// Ignore symbols
yield return new object[] { "More Test's", "Tests", 10, 11, CompareOptions.IgnoreSymbols, -1 };
yield return new object[] { "More Test's", "Tests", 10, 11, CompareOptions.None, -1 };
yield return new object[] { "cbabababdbaba", "ab", 12, 13, CompareOptions.None, 10 };
// Platform differences
yield return new object[] { "foobardzsdzs", "rddzs", 11, 12, CompareOptions.None, -1 };
}
public static IEnumerable<object[]> IsPrefix_TestData()
{
// Empty strings
yield return new object[] { "foo", "", CompareOptions.None, true };
yield return new object[] { "", "", CompareOptions.None, true };
// Long strings
yield return new object[] { new string('a', 5555), "aaaaaaaaaaaaaaa", CompareOptions.None, true };
yield return new object[] { new string('a', 5555), new string('a', 5000), CompareOptions.None, true };
yield return new object[] { new string('a', 5555), new string('a', 5000) + "b", CompareOptions.None, false };
// Hungarian
yield return new object[] { "dzsdzsfoobar", "ddzsf", CompareOptions.None, false };
yield return new object[] { "dzsdzsfoobar", "ddzsf", CompareOptions.Ordinal, false };
yield return new object[] { "dzsdzsfoobar", "ddzsf", CompareOptions.Ordinal, false };
// Turkish
yield return new object[] { "interesting", "I", CompareOptions.None, false };
yield return new object[] { "interesting", "I", CompareOptions.IgnoreCase, true };
yield return new object[] { "interesting", "\u0130", CompareOptions.None, false };
yield return new object[] { "interesting", "\u0130", CompareOptions.IgnoreCase, false };
// Unicode
yield return new object[] { "\u00C0nimal", "A\u0300", CompareOptions.None, false };
yield return new object[] { "\u00C0nimal", "A\u0300", CompareOptions.Ordinal, false };
yield return new object[] { "\u00C0nimal", "a\u0300", CompareOptions.IgnoreCase, false };
yield return new object[] { "\u00C0nimal", "a\u0300", CompareOptions.OrdinalIgnoreCase, false };
yield return new object[] { "FooBar", "Foo\u0400Bar", CompareOptions.Ordinal, false };
yield return new object[] { "FooBA\u0300R", "FooB\u00C0R", CompareOptions.IgnoreNonSpace, false };
// Ignore symbols
yield return new object[] { "Test's can be interesting", "Tests", CompareOptions.IgnoreSymbols, false };
yield return new object[] { "Test's can be interesting", "Tests", CompareOptions.None, false };
// Platform differences
yield return new object[] { "dzsdzsfoobar", "ddzsf", CompareOptions.None, false };
}
public static IEnumerable<object[]> IsSuffix_TestData()
{
// Empty strings
yield return new object[] { "foo", "", CompareOptions.None, true };
yield return new object[] { "", "", CompareOptions.None, true };
// Long strings
yield return new object[] { new string('a', 5555), "aaaaaaaaaaaaaaa", CompareOptions.None, true };
yield return new object[] { new string('a', 5555), new string('a', 5000), CompareOptions.None, true };
yield return new object[] { new string('a', 5555), new string('a', 5000) + "b", CompareOptions.None, false };
// Hungarian
yield return new object[] { "foobardzsdzs", "rddzs", CompareOptions.Ordinal, false };
yield return new object[] { "foobardzsdzs", "rddzs", CompareOptions.None, false };
// Turkish
yield return new object[] { "Hi", "I", CompareOptions.None, false };
yield return new object[] { "Hi", "I", CompareOptions.IgnoreCase, true };
yield return new object[] { "Hi", "\u0130", CompareOptions.None, false };
yield return new object[] { "Hi", "\u0130", CompareOptions.IgnoreCase, false };
// Unicode
yield return new object[] { "Exhibit \u00C0", "A\u0300", CompareOptions.None, false };
yield return new object[] { "Exhibit \u00C0", "A\u0300", CompareOptions.Ordinal, false };
yield return new object[] { "Exhibit \u00C0", "a\u0300", CompareOptions.IgnoreCase, false };
yield return new object[] { "Exhibit \u00C0", "a\u0300", CompareOptions.OrdinalIgnoreCase, false };
yield return new object[] { "FooBar", "Foo\u0400Bar", CompareOptions.Ordinal, false };
yield return new object[] { "FooBA\u0300R", "FooB\u00C0R", CompareOptions.IgnoreNonSpace, false };
// Ignore symbols
yield return new object[] { "More Test's", "Tests", CompareOptions.IgnoreSymbols, false };
yield return new object[] { "More Test's", "Tests", CompareOptions.None, false };
// Platform differences
yield return new object[] { "foobardzsdzs", "rddzs", CompareOptions.None, false };
}
public static IEnumerable<object[]> Compare_TestData()
{
CompareOptions ignoreKanaIgnoreWidthIgnoreCase = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
yield return new object[] { "\u3042", "\u30A2", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "\u3042", "\uFF71", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "\u304D\u3083", "\u30AD\u30E3", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "\u304D\u3083", "\u30AD\u3083", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "\u304D \u3083", "\u30AD\u3083", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "\u3044", "I", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { "a", "A", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { "a", "\uFF41", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "ABCDE", "\uFF21\uFF22\uFF23\uFF24\uFF25", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "ABCDE", "\uFF21\uFF22\uFF23D\uFF25", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "ABCDE", "a\uFF22\uFF23D\uFF25", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "ABCDE", "\uFF41\uFF42\uFF23D\uFF25", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "\u6FA4", "\u6CA2", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u30D6\u30D9\u30DC", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "ABDDE", "D", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "ABCDE", "\uFF43D", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "ABCDE", "c", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "\u3060", "\u305F", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { "\u3060", "\uFF80\uFF9E", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "\u3060", "\u30C0", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { "\u3042", "\u30A1", CompareOptions.None, -1 };
yield return new object[] { "\u304D \u3083", "\u30AD\u3083", CompareOptions.None, -1 };
yield return new object[] { "\u3044", "I", CompareOptions.None, 1 };
yield return new object[] { "a", "A", CompareOptions.None, 1 };
yield return new object[] { "a", "\uFF41", CompareOptions.None, -1 };
yield return new object[] { "", "'", CompareOptions.None, -1 };
// Hungarian
yield return new object[] { "dzsdzs", "ddzs", CompareOptions.Ordinal, 1 };
yield return new object[] { "dzsdzs", "ddzs", CompareOptions.None, 1 };
// Turkish
yield return new object[] { "i", "I", CompareOptions.None, 1 };
yield return new object[] { "i", "I", CompareOptions.IgnoreCase, 0 };
yield return new object[] { "i", "\u0130", CompareOptions.None, -1 };
yield return new object[] { "i", "\u0130", CompareOptions.IgnoreCase, -1 };
yield return new object[] { "\u00C0", "A\u0300", CompareOptions.None, 1 };
yield return new object[] { "\u00C0", "A\u0300", CompareOptions.Ordinal, 1 };
yield return new object[] { "FooBar", "Foo\u0400Bar", CompareOptions.Ordinal, -1 };
yield return new object[] { "FooBA\u0300R", "FooB\u00C0R", CompareOptions.IgnoreNonSpace, -1 };
yield return new object[] { "Test's", "Tests", CompareOptions.IgnoreSymbols, -1 };
yield return new object[] { "Test's", "Tests", CompareOptions.StringSort, -1 };
// Spanish
yield return new object[] { "llegar", "lugar", CompareOptions.None, -1 };
yield return new object[] { "\u3042", "\u30A1", CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase, -1 };
}
public static IEnumerable<object[]> ToLower_TestData()
{
yield return new object[] { "", "", true };
yield return new object[] { "A", "a", true };
yield return new object[] { "a", "a", true };
yield return new object[] { "ABC", "abc", true };
yield return new object[] { "abc", "abc", true };
yield return new object[] { "1", "1", true };
yield return new object[] { "123", "123", true };
yield return new object[] { "!", "!", true };
yield return new object[] { "HELLOWOR!LD123", "hellowor!ld123", true };
yield return new object[] { "HelloWor!ld123", "hellowor!ld123", true };
yield return new object[] { "Hello\n\0World\u0009!", "hello\n\0world\t!", true };
yield return new object[] { "THIS IS A LONGER TEST CASE", "this is a longer test case", true };
yield return new object[] { "this Is A LONGER mIXEd casE test case", "this is a longer mixed case test case", true };
yield return new object[] { "THIS \t hAs \t SOMe \t tabs", "this \t has \t some \t tabs", true };
yield return new object[] { "EMBEDDED\0NuLL\0Byte\0", "embedded\0null\0byte\0", true };
// LATIN CAPITAL LETTER O WITH ACUTE, which has a lower case variant.
yield return new object[] { "\u00D3", "\u00F3", false };
// SNOWMAN, which does not have a lower case variant.
yield return new object[] { "\u2603", "\u2603", true };
// RAINBOW (outside the BMP and does not case)
yield return new object[] { "\U0001F308", "\U0001F308", true };
// Unicode defines some codepoints which expand into multiple codepoints
// when cased (see SpecialCasing.txt from UNIDATA for some examples). We have never done
// these sorts of expansions, since it would cause string lengths to change when cased,
// which is non-intuitive. In addition, there are some context sensitive mappings which
// we also don't preform.
// Greek Capital Letter Sigma (does not to case to U+03C2 with "final sigma" rule).
yield return new object[] { "\u03A3", "\u03C3", false };
}
public static IEnumerable<object[]> ToUpper_TestData()
{
yield return new object[] { "", "" , true};
yield return new object[] { "a", "A", true };
yield return new object[] { "abc", "ABC", true };
yield return new object[] { "A", "A", true };
yield return new object[] { "ABC", "ABC", true };
yield return new object[] { "1", "1", true };
yield return new object[] { "123", "123", true };
yield return new object[] { "!", "!", true };
yield return new object[] { "HelloWor!ld123", "HELLOWOR!LD123", true };
yield return new object[] { "HELLOWOR!LD123", "HELLOWOR!LD123", true };
yield return new object[] { "Hello\n\0World\u0009!", "HELLO\n\0WORLD\t!", true };
yield return new object[] { "this is a longer test case", "THIS IS A LONGER TEST CASE", true };
yield return new object[] { "this Is A LONGER mIXEd casE test case", "THIS IS A LONGER MIXED CASE TEST CASE", true };
yield return new object[] { "this \t HaS \t somE \t TABS", "THIS \t HAS \t SOME \t TABS", true };
yield return new object[] { "embedded\0NuLL\0Byte\0", "EMBEDDED\0NULL\0BYTE\0", true };
// LATIN SMALL LETTER O WITH ACUTE, which has an upper case variant.
yield return new object[] { "\u00F3", "\u00D3", false };
// SNOWMAN, which does not have an upper case variant.
yield return new object[] { "\u2603", "\u2603", true };
// RAINBOW (outside the BMP and does not case)
yield return new object[] { "\U0001F308", "\U0001F308", true };
// Unicode defines some codepoints which expand into multiple codepoints
// when cased (see SpecialCasing.txt from UNIDATA for some examples). We have never done
// these sorts of expansions, since it would cause string lengths to change when cased,
// which is non-intuitive. In addition, there are some context sensitive mappings which
// we also don't preform.
// es-zed does not case to SS when uppercased.
yield return new object[] { "\u00DF", "\u00DF", true };
// Ligatures do not expand when cased.
yield return new object[] { "\uFB00", "\uFB00", true };
// Precomposed character with no uppercase variant, we don't want to "decompose" this
// as part of casing.
yield return new object[] { "\u0149", "\u0149", true };
yield return new object[] { "\u03C3", "\u03A3", false };
}
public static IEnumerable<object[]> GetAscii_TestData()
{
yield return new object[] { "\u0101", 0, 1, "xn--yda" };
yield return new object[] { "\u0101\u0061\u0041", 0, 3, "xn--aa-cla" };
yield return new object[] { "\u0061\u0101\u0062", 0, 3, "xn--ab-dla" };
yield return new object[] { "\u0061\u0062\u0101", 0, 3, "xn--ab-ela" };
yield return new object[] { "\uD800\uDF00\uD800\uDF01\uD800\uDF02", 0, 6, "xn--097ccd" }; // Surrogate pairs
yield return new object[] { "\uD800\uDF00\u0061\uD800\uDF01\u0042\uD800\uDF02", 0, 8, "xn--ab-ic6nfag" }; // Surrogate pairs separated by ASCII
yield return new object[] { "\uD800\uDF00\u0101\uD800\uDF01\u305D\uD800\uDF02", 0, 8, "xn--yda263v6b6kfag" }; // Surrogate pairs separated by non-ASCII
yield return new object[] { "\uD800\uDF00\u0101\uD800\uDF01\u0061\uD800\uDF02", 0, 8, "xn--a-nha4529qfag" }; // Surrogate pairs separated by ASCII and non-ASCII
yield return new object[] { "\u0061\u0062\u0063", 0, 3, "\u0061\u0062\u0063" }; // ASCII only code points
yield return new object[] { "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067", 0, 7, "xn--d9juau41awczczp" }; // Non-ASCII only code points
yield return new object[] { "\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 0, 9, "xn--de-jg4avhby1noc0d" }; // ASCII and non-ASCII code points
yield return new object[] { "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 0, 21, "abc.xn--d9juau41awczczp.xn--de-jg4avhby1noc0d" }; // Fully qualified domain name
// Embedded domain name conversion (NLS + only)(Priority 1)
// Per the spec [7], "The index and count parameters (when provided) allow the
// conversion to be done on a larger string where the domain name is embedded
// (such as a URI or IRI). The output string is only the converted FQDN or
// label, not the whole input string (if the input string contains more
// character than the substring to convert)."
// Fully Qualified Domain Name (Label1.Label2.Label3)
yield return new object[] { "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 0, 21, "abc.xn--d9juau41awczczp.xn--de-jg4avhby1noc0d" };
yield return new object[] { "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 0, 11, "abc.xn--d9juau41awczczp" };
yield return new object[] { "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 0, 12, "abc.xn--d9juau41awczczp." };
yield return new object[] { "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 4, 17, "xn--d9juau41awczczp.xn--de-jg4avhby1noc0d" };
yield return new object[] { "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 4, 7, "xn--d9juau41awczczp" };
yield return new object[] { "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 4, 8, "xn--d9juau41awczczp." };
yield return new object[] { "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 12, 9, "xn--de-jg4avhby1noc0d" };
}
public static IEnumerable<object[]> GetUnicode_TestData()
{
yield return new object[] { "xn--yda", 0, 7, "\u0101" };
yield return new object[] { "axn--ydab", 1, 7, "\u0101" };
yield return new object[] { "xn--aa-cla", 0, 10, "\u0101\u0061a" };
yield return new object[] { "xn--ab-dla", 0, 10, "\u0061\u0101\u0062" };
yield return new object[] { "xn--ab-ela", 0, 10, "\u0061\u0062\u0101" };
yield return new object[] { "xn--097ccd", 0, 10, "\uD800\uDF00\uD800\uDF01\uD800\uDF02" }; // Surrogate pairs
yield return new object[] { "xn--ab-ic6nfag", 0, 14, "\uD800\uDF00\u0061\uD800\uDF01b\uD800\uDF02" }; // Surrogate pairs separated by ASCII
yield return new object[] { "xn--yda263v6b6kfag", 0, 18, "\uD800\uDF00\u0101\uD800\uDF01\u305D\uD800\uDF02" }; // Surrogate pairs separated by non-ASCII
yield return new object[] { "xn--a-nha4529qfag", 0, 17, "\uD800\uDF00\u0101\uD800\uDF01\u0061\uD800\uDF02" }; // Surrogate pairs separated by ASCII and non-ASCII
yield return new object[] { "\u0061\u0062\u0063", 0, 3, "\u0061\u0062\u0063" }; // ASCII only code points
yield return new object[] { "xn--d9juau41awczczp", 0, 19, "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067" }; // Non-ASCII only code points
yield return new object[] { "xn--de-jg4avhby1noc0d", 0, 21, "\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0" }; // ASCII and non-ASCII code points
yield return new object[] { "abc.xn--d9juau41awczczp.xn--de-jg4avhby1noc0d", 0, 45, "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0" }; // Fully qualified domain name
// Embedded domain name conversion (NLS + only)(Priority 1)
// Per the spec [7], "The index and count parameters (when provided) allow the
// conversion to be done on a larger string where the domain name is embedded
// (such as a URI or IRI). The output string is only the converted FQDN or
// label, not the whole input string (if the input string contains more
// character than the substring to convert)."
// Fully Qualified Domain Name (Label1.Label2.Label3)
yield return new object[] { "abc.xn--d9juau41awczczp.xn--de-jg4avhby1noc0d", 0, 45, "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0" };
yield return new object[] { "abc.xn--d9juau41awczczp", 0, 23, "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067" };
yield return new object[] { "abc.xn--d9juau41awczczp.", 0, 24, "\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067." };
yield return new object[] { "xn--d9juau41awczczp.xn--de-jg4avhby1noc0d", 0, 41, "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0" };
yield return new object[] { "xn--d9juau41awczczp", 0, 19, "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067" };
yield return new object[] { "xn--d9juau41awczczp.", 0, 20, "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067." };
yield return new object[] { "xn--de-jg4avhby1noc0d", 0, 21, "\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0" };
}
[Theory]
[MemberData(nameof(Cultures_TestData))]
public void TestCultureData(string cultureName)
{
CultureInfo ci = new CultureInfo(cultureName);
//
// DateTimeInfo
//
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedDayNames, ci.DateTimeFormat.AbbreviatedDayNames);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthGenitiveNames, ci.DateTimeFormat.AbbreviatedMonthGenitiveNames);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthNames, ci.DateTimeFormat.AbbreviatedMonthNames);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.AMDesignator, ci.DateTimeFormat.AMDesignator);
Assert.True(ci.DateTimeFormat.Calendar is GregorianCalendar);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.CalendarWeekRule, ci.DateTimeFormat.CalendarWeekRule);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.DateSeparator, ci.DateTimeFormat.DateSeparator);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.DayNames, ci.DateTimeFormat.DayNames);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.FirstDayOfWeek, ci.DateTimeFormat.FirstDayOfWeek);
for (DayOfWeek dow = DayOfWeek.Sunday; dow < DayOfWeek.Saturday; dow++)
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.GetAbbreviatedDayName(dow), ci.DateTimeFormat.GetAbbreviatedDayName(dow));
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.GetAbbreviatedEraName(1), ci.DateTimeFormat.GetAbbreviatedEraName(1));
for (int i = 1; i <= 12; i++)
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.GetAbbreviatedMonthName(i), ci.DateTimeFormat.GetAbbreviatedMonthName(i));
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.GetAllDateTimePatterns(), ci.DateTimeFormat.GetAllDateTimePatterns());
for (DayOfWeek dow = DayOfWeek.Sunday; dow < DayOfWeek.Saturday; dow++)
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.GetDayName(dow), ci.DateTimeFormat.GetDayName(dow));
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.GetEra(CultureInfo.InvariantCulture.DateTimeFormat.GetEraName(1)), ci.DateTimeFormat.GetEra(ci.DateTimeFormat.GetEraName(1)));
for (int i = 1; i <= 12; i++)
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i), ci.DateTimeFormat.GetMonthName(i));
for (DayOfWeek dow = DayOfWeek.Sunday; dow < DayOfWeek.Saturday; dow++)
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.GetShortestDayName(dow), ci.DateTimeFormat.GetShortestDayName(dow));
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.LongDatePattern, ci.DateTimeFormat.LongDatePattern);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.LongTimePattern, ci.DateTimeFormat.LongTimePattern);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.MonthDayPattern, ci.DateTimeFormat.MonthDayPattern);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.MonthGenitiveNames, ci.DateTimeFormat.MonthGenitiveNames);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.MonthNames, ci.DateTimeFormat.MonthNames);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.NativeCalendarName, ci.DateTimeFormat.NativeCalendarName);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.PMDesignator, ci.DateTimeFormat.PMDesignator);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.RFC1123Pattern, ci.DateTimeFormat.RFC1123Pattern);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern, ci.DateTimeFormat.ShortDatePattern);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.ShortestDayNames, ci.DateTimeFormat.ShortestDayNames);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.ShortTimePattern, ci.DateTimeFormat.ShortTimePattern);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.TimeSeparator, ci.DateTimeFormat.TimeSeparator);
Assert.Equal(CultureInfo.InvariantCulture.DateTimeFormat.YearMonthPattern, ci.DateTimeFormat.YearMonthPattern);
//
// Culture data
//
Assert.True(ci.Calendar is GregorianCalendar);
CultureTypes ct = ci.Name == "" ? CultureInfo.InvariantCulture.CultureTypes : CultureInfo.InvariantCulture.CultureTypes | CultureTypes.UserCustomCulture;
Assert.Equal(ct, ci.CultureTypes);
Assert.Equal(CultureInfo.InvariantCulture.NativeName, ci.DisplayName);
Assert.Equal(CultureInfo.InvariantCulture.EnglishName, ci.EnglishName);
Assert.Equal(CultureInfo.InvariantCulture.GetConsoleFallbackUICulture(), ci.GetConsoleFallbackUICulture());
Assert.Equal(cultureName, ci.IetfLanguageTag);
Assert.Equal(CultureInfo.InvariantCulture.IsNeutralCulture, ci.IsNeutralCulture);
Assert.Equal(CultureInfo.InvariantCulture.KeyboardLayoutId, ci.KeyboardLayoutId);
Assert.Equal(ci.Name == "" ? 0x7F : 0x1000, ci.LCID);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(CultureInfo.InvariantCulture.NativeName, ci.NativeName);
Assert.Equal(1, ci.OptionalCalendars.Length);
Assert.True(ci.OptionalCalendars[0] is GregorianCalendar);
Assert.Equal(CultureInfo.InvariantCulture.Parent, ci.Parent);
Assert.Equal(CultureInfo.InvariantCulture.ThreeLetterISOLanguageName, ci.ThreeLetterISOLanguageName);
Assert.Equal(CultureInfo.InvariantCulture.ThreeLetterWindowsLanguageName, ci.ThreeLetterWindowsLanguageName);
Assert.Equal(CultureInfo.InvariantCulture.TwoLetterISOLanguageName, ci.TwoLetterISOLanguageName);
Assert.Equal(ci.Name == "" ? false : true, ci.UseUserOverride);
//
// Culture Creations
//
Assert.Equal(CultureInfo.InvariantCulture, CultureInfo.CurrentCulture);
Assert.Equal(CultureInfo.InvariantCulture, CultureInfo.CurrentUICulture);
Assert.Equal(CultureInfo.InvariantCulture, CultureInfo.InstalledUICulture);
Assert.Equal(CultureInfo.InvariantCulture, CultureInfo.CreateSpecificCulture("en"));
Assert.Equal(ci, CultureInfo.GetCultureInfo(cultureName).Clone());
Assert.Equal(ci, CultureInfo.GetCultureInfoByIetfLanguageTag(cultureName));
//
// NumberFormatInfo
//
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.CurrencyDecimalDigits, ci.NumberFormat.CurrencyDecimalDigits);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.CurrencyDecimalSeparator, ci.NumberFormat.CurrencyDecimalSeparator);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.CurrencyGroupSeparator, ci.NumberFormat.CurrencyGroupSeparator);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.CurrencyGroupSizes, ci.NumberFormat.CurrencyGroupSizes);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.CurrencyNegativePattern, ci.NumberFormat.CurrencyNegativePattern);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.CurrencyPositivePattern, ci.NumberFormat.CurrencyPositivePattern);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.CurrencySymbol, ci.NumberFormat.CurrencySymbol);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.DigitSubstitution, ci.NumberFormat.DigitSubstitution);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.NaNSymbol, ci.NumberFormat.NaNSymbol);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.NativeDigits, ci.NumberFormat.NativeDigits);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.NegativeInfinitySymbol, ci.NumberFormat.NegativeInfinitySymbol);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.NegativeSign, ci.NumberFormat.NegativeSign);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalDigits, ci.NumberFormat.NumberDecimalDigits);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator, ci.NumberFormat.NumberDecimalSeparator);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.NumberGroupSeparator, ci.NumberFormat.NumberGroupSeparator);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.NumberGroupSizes, ci.NumberFormat.NumberGroupSizes);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.NumberNegativePattern, ci.NumberFormat.NumberNegativePattern);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.PercentDecimalDigits, ci.NumberFormat.PercentDecimalDigits);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.PercentDecimalSeparator, ci.NumberFormat.PercentDecimalSeparator);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.PercentGroupSeparator, ci.NumberFormat.PercentGroupSeparator);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.PercentGroupSizes, ci.NumberFormat.PercentGroupSizes);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.PercentNegativePattern, ci.NumberFormat.PercentNegativePattern);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.PercentPositivePattern, ci.NumberFormat.PercentPositivePattern);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.PercentSymbol, ci.NumberFormat.PercentSymbol);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.PerMilleSymbol, ci.NumberFormat.PerMilleSymbol);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.PositiveInfinitySymbol, ci.NumberFormat.PositiveInfinitySymbol);
Assert.Equal(CultureInfo.InvariantCulture.NumberFormat.PositiveSign, ci.NumberFormat.PositiveSign);
//
// TextInfo
//
Assert.Equal(CultureInfo.InvariantCulture.TextInfo.ANSICodePage, ci.TextInfo.ANSICodePage);
Assert.Equal(cultureName, ci.TextInfo.CultureName);
Assert.Equal(CultureInfo.InvariantCulture.TextInfo.EBCDICCodePage, ci.TextInfo.EBCDICCodePage);
Assert.Equal(CultureInfo.InvariantCulture.TextInfo.IsRightToLeft, ci.TextInfo.IsRightToLeft);
Assert.Equal(ci.Name == "" ? 0x7F : 0x1000, ci.TextInfo.LCID);
Assert.Equal(CultureInfo.InvariantCulture.TextInfo.ListSeparator, ci.TextInfo.ListSeparator);
Assert.Equal(CultureInfo.InvariantCulture.TextInfo.MacCodePage, ci.TextInfo.MacCodePage);
Assert.Equal(CultureInfo.InvariantCulture.TextInfo.OEMCodePage, ci.TextInfo.OEMCodePage);
//
// CompareInfo
//
Assert.Equal(ci.Name == "" ? 0x7F : 0x1000, ci.CompareInfo.LCID);
Assert.True(cultureName.Equals(ci.CompareInfo.Name, StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void TestEnum()
{
Assert.Equal(new CultureInfo[1] { CultureInfo.InvariantCulture }, CultureInfo.GetCultures(CultureTypes.AllCultures));
}
[Theory]
[MemberData(nameof(Cultures_TestData))]
public void TestSortVersion(string cultureName)
{
SortVersion version = new SortVersion(0, new Guid(0, 0, 0, 0, 0, 0, 0,
(byte)(0x7F >> 24),
(byte)((0x7F & 0x00FF0000) >> 16),
(byte)((0x7F & 0x0000FF00) >> 8),
(byte)(0x7F & 0xFF)));
Assert.Equal(version, new CultureInfo(cultureName).CompareInfo.Version);
}
private static StringComparison GetStringComparison(CompareOptions options)
{
StringComparison sc = (StringComparison) 0;
if ((options & CompareOptions.IgnoreCase) != 0)
sc |= StringComparison.CurrentCultureIgnoreCase;
if ((options & CompareOptions.Ordinal) != 0)
sc |= StringComparison.Ordinal;
if ((options & CompareOptions.OrdinalIgnoreCase) != 0)
sc |= StringComparison.OrdinalIgnoreCase;
if (sc == (StringComparison)0)
{
sc = StringComparison.CurrentCulture;
}
return sc;
}
[Theory]
[MemberData(nameof(IndexOf_TestData))]
public void TestIndexOf(string source, string value, int startIndex, int count, CompareOptions options, int result)
{
foreach (string cul in s_cultureNames)
{
Assert.Equal(result, CultureInfo.GetCultureInfo(cul).CompareInfo.IndexOf(source, value, startIndex, count, options));
Assert.Equal(result, source.IndexOf(value, startIndex, count, GetStringComparison(options)));
}
}
[Theory]
[MemberData(nameof(LastIndexOf_TestData))]
public void TestLastIndexOf(string source, string value, int startIndex, int count, CompareOptions options, int result)
{
foreach (string cul in s_cultureNames)
{
Assert.Equal(result, CultureInfo.GetCultureInfo(cul).CompareInfo.LastIndexOf(source, value, startIndex, count, options));
Assert.Equal(result, source.LastIndexOf(value, startIndex, count, GetStringComparison(options)));
}
}
[Theory]
[MemberData(nameof(IsPrefix_TestData))]
public void TestIsPrefix(string source, string value, CompareOptions options, bool result)
{
foreach (string cul in s_cultureNames)
{
Assert.Equal(result, CultureInfo.GetCultureInfo(cul).CompareInfo.IsPrefix(source, value, options));
Assert.Equal(result, source.StartsWith(value, GetStringComparison(options)));
}
}
[Theory]
[MemberData(nameof(IsSuffix_TestData))]
public void TestIsSuffix(string source, string value, CompareOptions options, bool result)
{
foreach (string cul in s_cultureNames)
{
Assert.Equal(result, CultureInfo.GetCultureInfo(cul).CompareInfo.IsSuffix(source, value, options));
Assert.Equal(result, source.EndsWith(value, GetStringComparison(options)));
}
}
[Theory]
[MemberData(nameof(Compare_TestData))]
public void TestCompare(string source, string value, CompareOptions options, int result)
{
foreach (string cul in s_cultureNames)
{
int res = CultureInfo.GetCultureInfo(cul).CompareInfo.Compare(source, value, options);
if (res < 0) res = -1;
if (res > 0) res = 1;
Assert.Equal(result, res);
res = string.Compare(source, value, GetStringComparison(options));
if (res < 0) res = -1;
if (res > 0) res = 1;
Assert.Equal(result, res);
}
}
[Theory]
[MemberData(nameof(ToLower_TestData))]
public void TestToLower(string upper, string lower, bool result)
{
foreach (string cul in s_cultureNames)
{
Assert.Equal(result, CultureInfo.GetCultureInfo(cul).TextInfo.ToLower(upper).Equals(lower, StringComparison.Ordinal));
Assert.Equal(result, upper.ToLower().Equals(lower, StringComparison.Ordinal));
}
}
[Theory]
[MemberData(nameof(ToUpper_TestData))]
public void TestToUpper(string lower, string upper, bool result)
{
foreach (string cul in s_cultureNames)
{
Assert.Equal(result, CultureInfo.GetCultureInfo(cul).TextInfo.ToUpper(lower).Equals(upper, StringComparison.Ordinal));
Assert.Equal(result, lower.ToUpper().Equals(upper, StringComparison.Ordinal));
}
}
[Theory]
[InlineData("", NormalizationForm.FormC)]
[InlineData("\uFB01", NormalizationForm.FormC)]
[InlineData("\uFB01", NormalizationForm.FormD)]
[InlineData("\uFB01", NormalizationForm.FormKC)]
[InlineData("\uFB01", NormalizationForm.FormKD)]
[InlineData("\u1E9b\u0323", NormalizationForm.FormC)]
[InlineData("\u1E9b\u0323", NormalizationForm.FormD)]
[InlineData("\u1E9b\u0323", NormalizationForm.FormKC)]
[InlineData("\u1E9b\u0323", NormalizationForm.FormKD)]
[InlineData("\u00C4\u00C7", NormalizationForm.FormC)]
[InlineData("\u00C4\u00C7", NormalizationForm.FormD)]
[InlineData("A\u0308C\u0327", NormalizationForm.FormC)]
[InlineData("A\u0308C\u0327", NormalizationForm.FormD)]
public void TestNormalization(string s, NormalizationForm form)
{
Assert.True(s.IsNormalized());
Assert.True(s.IsNormalized(form));
Assert.Equal(s, s.Normalize());
Assert.Equal(s, s.Normalize(form));
}
[Theory]
[MemberData(nameof(GetAscii_TestData))]
public void GetAscii(string unicode, int index, int count, string expected)
{
if (index + count == unicode.Length)
{
if (index == 0)
{
Assert.Equal(expected, new IdnMapping().GetAscii(unicode));
}
Assert.Equal(expected, new IdnMapping().GetAscii(unicode, index));
}
Assert.Equal(expected, new IdnMapping().GetAscii(unicode, index, count));
}
[Theory]
[MemberData(nameof(GetUnicode_TestData))]
public void GetUnicode(string ascii, int index, int count, string expected)
{
if (index + count == ascii.Length)
{
if (index == 0)
{
Assert.Equal(expected, new IdnMapping().GetUnicode(ascii));
}
Assert.Equal(expected, new IdnMapping().GetUnicode(ascii, index));
}
Assert.Equal(expected, new IdnMapping().GetUnicode(ascii, index, count));
}
[Fact]
public void TestHashing()
{
StringComparer cultureComparer = StringComparer.Create(CultureInfo.GetCultureInfo("tr-TR"), true);
StringComparer ordinalComparer = StringComparer.OrdinalIgnoreCase;
string turkishString = "i\u0130";
Assert.Equal(ordinalComparer.GetHashCode(turkishString), cultureComparer.GetHashCode(turkishString));
}
[Theory]
[InlineData('a', 'A', 'a')]
[InlineData('A', 'A', 'a')]
[InlineData('i', 'I', 'i')] // to verify that we don't special-case the Turkish I in the invariant globalization mode
[InlineData('I', 'I', 'i')]
[InlineData(0x00C1, 0x00C1, 0x00C1)] // U+00C1 LATIN CAPITAL LETTER A WITH ACUTE
[InlineData(0x00E1, 0x00E1, 0x00E1)] // U+00E1 LATIN SMALL LETTER A WITH ACUTE
[InlineData(0x00D7, 0x00D7, 0x00D7)] // U+00D7 MULTIPLICATION SIGN
public void TestRune(int original, int expectedToUpper, int expectedToLower)
{
Rune originalRune = new Rune(original);
Assert.Equal(expectedToUpper, Rune.ToUpperInvariant(originalRune).Value);
Assert.Equal(expectedToUpper, Rune.ToUpper(originalRune, CultureInfo.GetCultureInfo("tr-TR")).Value);
Assert.Equal(expectedToLower, Rune.ToLowerInvariant(originalRune).Value);
Assert.Equal(expectedToLower, Rune.ToLower(originalRune, CultureInfo.GetCultureInfo("tr-TR")).Value);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
namespace Microsoft.Zelig.Test
{
public class ExprefTests : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize( )
{
Log.Comment( "Adding set up for the tests." );
// Add your functionality here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp( )
{
Log.Comment( "Cleaning up after the tests" );
}
public override TestResult Run( string[] args )
{
TestResult result = TestResult.Pass;
string testName = "Expref_";
int testNumber = 0;
result |= Assert.CheckFailed( Expref_obj_ref_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_obj_ref_exc_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_class_class_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_class_class_exc_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_inter_struct_exc_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_class_inter_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_class_inter_exc_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_inter_class_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_inter_class2_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_inter_class2_exc1_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_inter_class2_exc2_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_inter_class_exc_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_inter_class_sealed_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_inter_class_sealed_exc_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_inter_inter_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( Expref_inter_inter_exc_Test( ), testName, ++testNumber );
return result;
}
//Expref Test methods
//The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Expref
//obj_ref,obj_ref_exc,class_class,class_class_exc,inter_struct,inter_struct_exc,class_inter,class_inter_exc,inter_class,inter_class2,inter_class2_exc1,inter_class2_exc2,inter_class_exc,inter_class_sealed,inter_class_sealed_exc,inter_inter,inter_inter_exc
//Inter_Struct will not compile
//Test Case Calls
[TestMethod]
public TestResult Expref_obj_ref_Test()
{
Log.Comment(" Converting from 'object' to a reference object. ");
if (ExprefTestClass_obj_ref.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_obj_ref_exc_Test()
{
Log.Comment(" Converting from 'object' to a reference object. ");
if (ExprefTestClass_obj_ref_exc.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_class_class_Test()
{
Log.Comment(" Tests that you can convert from a base class to a derived class");
if (ExprefTestClass_class_class.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_class_class_exc_Test()
{
Log.Comment(" Tests that you can convert from a base class to a derived class");
if (ExprefTestClass_class_class_exc.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_inter_struct_exc_Test()
{
Log.Comment(" Tests that you can convert from an interface to a struct that implements it.");
if (ExprefTestClass_inter_struct_exc.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_class_inter_Test()
{
Log.Comment(" Tests converting from a class to an interface that the class does not implement (but a derived class might).");
if (ExprefTestClass_class_inter.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_class_inter_exc_Test()
{
Log.Comment(" Tests converting from a class to an interface that the class does not implement (but a derived class might).");
if (ExprefTestClass_class_inter_exc.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_inter_class_Test()
{
Log.Comment(" Tests converting from an interface to a class");
Log.Comment("From any interface-type S to any class-type T, provided T is not sealed, or provided T implements S.");
Log.Comment("If T implements S:");
if (ExprefTestClass_inter_class.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_inter_class2_Test()
{
Log.Comment(" Tests converting from an interface to a class");
if (ExprefTestClass_inter_class2.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_inter_class2_exc1_Test()
{
Log.Comment(" Tests converting from an interface to a class");
if (ExprefTestClass_inter_class2_exc1.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_inter_class2_exc2_Test()
{
Log.Comment(" Tests converting from an interface to a class");
if (ExprefTestClass_inter_class2_exc2.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_inter_class_exc_Test()
{
Log.Comment(" Tests converting from an interface to a class");
if (ExprefTestClass_inter_class_exc.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_inter_class_sealed_Test()
{
Log.Comment(" Tests converting from an interface to a class");
if (ExprefTestClass_inter_class_sealed.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_inter_class_sealed_exc_Test()
{
Log.Comment(" Tests converting from an interface to a class");
if (ExprefTestClass_inter_class_sealed_exc.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_inter_inter_Test()
{
Log.Comment(" Tests converting from an interface to an interface");
if (ExprefTestClass_inter_inter.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Expref_inter_inter_exc_Test()
{
Log.Comment(" Tests converting from an interface to an interface");
if (ExprefTestClass_inter_inter_exc.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
//Compiled Test Cases
public class ExprefTestClass_obj_ref_Sub1
{
public void func() {/*Old Print*/}
}
public class ExprefTestClass_obj_ref_Sub2
{
public void func() {/*Old Print*/}
}
public class ExprefTestClass_obj_ref
{
public static bool testMethod()
{
ExprefTestClass_obj_ref_Sub1 test = new ExprefTestClass_obj_ref_Sub1();
object obj;
obj = test; // implicit setup
test = (ExprefTestClass_obj_ref_Sub1) obj;
test.func();
return true;
}
}
public class ExprefTestClass_obj_ref_exc_Sub1
{
int func() {return(1);}
}
public class ExprefTestClass_obj_ref_exc_Sub2
{
int func() {return(1);}
}
public class ExprefTestClass_obj_ref_exc
{
public static bool testMethod()
{
ExprefTestClass_obj_ref_exc_Sub1 test = new ExprefTestClass_obj_ref_exc_Sub1();
ExprefTestClass_obj_ref_exc_Sub2 test2;
object obj;
obj = test; // implicit setup
try
{
test2 = (ExprefTestClass_obj_ref_exc_Sub2) obj; // obj is *not* a test2
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
class ExprefTestClass_class_class_Base1
{
void i() {}
}
class ExprefTestClass_class_class_Base2 : ExprefTestClass_class_class_Base1
{
void j() {}
}
public class ExprefTestClass_class_class
{
public static bool testMethod()
{
ExprefTestClass_class_class_Base2 derivedClass = new ExprefTestClass_class_class_Base2();
ExprefTestClass_class_class_Base1 myBase;
myBase = derivedClass; // implicit conversion
derivedClass = (ExprefTestClass_class_class_Base2)myBase; // test conversion
return true;
}
}
class ExprefTestClass_class_class_exc_Base
{
void i() {}
}
class ExprefTestClass_class_class_exc_Der1 : ExprefTestClass_class_class_exc_Base
{
void j() {}
}
class ExprefTestClass_class_class_exc_Der2 : ExprefTestClass_class_class_exc_Base
{
void k() {}
}
public class ExprefTestClass_class_class_exc
{
public static bool testMethod()
{
ExprefTestClass_class_class_exc_Der1 derivedClass = new ExprefTestClass_class_class_exc_Der1();
ExprefTestClass_class_class_exc_Base myBase;
ExprefTestClass_class_class_exc_Der2 derivedClass3;
myBase = derivedClass; // implicit conversion
try
{
derivedClass3 = (ExprefTestClass_class_class_exc_Der2)myBase; // test conversion
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_inter_struct_exc_Interface1
{
void i();
}
public interface ExprefTestClass_inter_struct_exc_Interface2
{
void j();
}
struct ExprefTestClass_inter_struct_exc_struct1 : ExprefTestClass_inter_struct_exc_Interface1
{
public void i() {//Old Print
}
}
struct TheStruct2 : ExprefTestClass_inter_struct_exc_Interface1
{
public void i() {//Old Print
}
}
public class ExprefTestClass_inter_struct_exc
{
public static bool testMethod()
{
//Old Print
ExprefTestClass_inter_struct_exc_struct1 theStruct1 = new ExprefTestClass_inter_struct_exc_struct1();
//Old Print
return true;
theStruct1.i();
ExprefTestClass_inter_struct_exc_Interface1 ExprefTestClass_inter_struct_exc_Interface1;
ExprefTestClass_inter_struct_exc_Interface1 = theStruct1;
theStruct1 = (ExprefTestClass_inter_struct_exc_struct1) ExprefTestClass_inter_struct_exc_Interface1;
theStruct1.i();
TheStruct2 theStruct2;
theStruct2 = (TheStruct2) ExprefTestClass_inter_struct_exc_Interface1;
theStruct2.i();
//ExprefTestClass_inter_struct_exc.TestRoutine(ExprefTestClass_inter_struct_exc_Interface1);
// NOTE: Currently detects this during compile time; try passing ExprefTestClass_inter_struct_exc_Interface1 to a method
// to see if that will defeat the compile-time flow analysis.
}
}
interface ExprefTestClass_class_inter_I1
{
void i();
}
interface ExprefTestClass_class_inter_I2
{
void j();
}
class ExprefTestClass_class_inter_C1: ExprefTestClass_class_inter_I1
{
public void i() {//Old Print
}
}
class ExprefTestClass_class_inter_C2: ExprefTestClass_class_inter_C1, ExprefTestClass_class_inter_I2
{
public void j() {//Old Print
}
}
public class ExprefTestClass_class_inter
{
public static bool testMethod()
{
ExprefTestClass_class_inter_C1 thebase = new ExprefTestClass_class_inter_C2();
try
{
ExprefTestClass_class_inter_I2 i2 = (ExprefTestClass_class_inter_I2) thebase;
i2.j();
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_class_inter_exc_I1
{
void i();
}
interface ExprefTestClass_class_inter_exc_I2
{
void j();
}
class ExprefTestClass_class_inter_exc_C1: ExprefTestClass_class_inter_exc_I1
{
public void i() {//Old Print
}
}
class ExprefTestClass_class_inter_exc_C2: ExprefTestClass_class_inter_exc_C1
{
}
public class ExprefTestClass_class_inter_exc
{
public static bool testMethod()
{
ExprefTestClass_class_inter_exc_C1 thebase = new ExprefTestClass_class_inter_exc_C2();
try
{
ExprefTestClass_class_inter_exc_I2 i2 = (ExprefTestClass_class_inter_exc_I2) thebase;
i2.j();
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_inter_class_I1
{
void i();
}
class ExprefTestClass_inter_class_C1: ExprefTestClass_inter_class_I1
{
public void i() {/*Old Print*/}
}
class ExprefTestClass_inter_class_C2: ExprefTestClass_inter_class_I1
{
public void i() {/*Old Print*/}
}
public class ExprefTestClass_inter_class
{
public static bool testMethod()
{
ExprefTestClass_inter_class_I1 inter = new ExprefTestClass_inter_class_C1();
try
{
ExprefTestClass_inter_class_C1 c1 = (ExprefTestClass_inter_class_C1) inter;
c1.i();
}
catch (System.Exception)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_inter_class2_I1
{
void i();
}
interface ExprefTestClass_inter_class2_I2
{
void j();
}
class ExprefTestClass_inter_class2_C1: ExprefTestClass_inter_class2_I1
{
public void i() {//Old Print
}
}
class ExprefTestClass_inter_class2_C2: ExprefTestClass_inter_class2_I1
{
public void i() {//Old Print
}
}
class ExprefTestClass_inter_class2_C3: ExprefTestClass_inter_class2_C1, ExprefTestClass_inter_class2_I2
{
public void j() {//Old Print
}
}
public class ExprefTestClass_inter_class2
{
public static bool testMethod()
{
ExprefTestClass_inter_class2_I2 inter = new ExprefTestClass_inter_class2_C3();
try
{
ExprefTestClass_inter_class2_C1 c1 = (ExprefTestClass_inter_class2_C1)inter;
c1.i();
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_inter_class2_exc1_I1
{
void i();
}
interface ExprefTestClass_inter_class2_exc1_I2
{
void j();
}
class ExprefTestClass_inter_class2_exc1_C1: ExprefTestClass_inter_class2_exc1_I1
{
public void i() {//Old Print
}
}
class ExprefTestClass_inter_class2_exc1_C2 : ExprefTestClass_inter_class2_exc1_I2
{
public void j() {//Old Print
}
}
public class ExprefTestClass_inter_class2_exc1
{
public static bool testMethod()
{
ExprefTestClass_inter_class2_exc1_I2 inter = new ExprefTestClass_inter_class2_exc1_C2();
try
{
ExprefTestClass_inter_class2_exc1_C1 c1 = (ExprefTestClass_inter_class2_exc1_C1)inter;
c1.i();
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_inter_class2_exc2_I1
{
void i();
}
interface ExprefTestClass_inter_class2_exc2_I2
{
void j();
}
class ExprefTestClass_inter_class2_exc2_C1: ExprefTestClass_inter_class2_exc2_I1
{
public void i() {//Old Print
}
}
class ExprefTestClass_inter_class2_exc2_C2: ExprefTestClass_inter_class2_exc2_I2
{
public void j() {//Old Print
}
}
class ExprefTestClass_inter_class2_exc2_C3: ExprefTestClass_inter_class2_exc2_C1
{
}
public class ExprefTestClass_inter_class2_exc2
{
public static bool testMethod()
{
ExprefTestClass_inter_class2_exc2_I2 inter = new ExprefTestClass_inter_class2_exc2_C2();
try
{
ExprefTestClass_inter_class2_exc2_C1 c1 = (ExprefTestClass_inter_class2_exc2_C1)inter;
c1.i();
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_inter_class_exc_I1
{
void i();
}
class ExprefTestClass_inter_class_exc_C1: ExprefTestClass_inter_class_exc_I1
{
public void i() {//Old Print
}
}
class ExprefTestClass_inter_class_exc_C2: ExprefTestClass_inter_class_exc_I1
{
public void i() {//Old Print
}
}
public class ExprefTestClass_inter_class_exc
{
public static bool testMethod()
{
ExprefTestClass_inter_class_exc_I1 inter = new ExprefTestClass_inter_class_exc_C1();
try
{
ExprefTestClass_inter_class_exc_C2 c2 = (ExprefTestClass_inter_class_exc_C2) inter;
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_inter_class_sealed_I1
{
void i();
}
sealed class ExprefTestClass_inter_class_sealed_C1: ExprefTestClass_inter_class_sealed_I1
{
public void i() {/*Old Print*/}
}
class ExprefTestClass_inter_class_sealed_C2: ExprefTestClass_inter_class_sealed_I1
{
public void i() {/*Old Print*/}
}
public class ExprefTestClass_inter_class_sealed
{
public static bool testMethod()
{
ExprefTestClass_inter_class_sealed_I1 inter = new ExprefTestClass_inter_class_sealed_C1();
try
{
ExprefTestClass_inter_class_sealed_C1 c1 = (ExprefTestClass_inter_class_sealed_C1) inter;
c1.i();
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_inter_class_sealed_exc_I1
{
void i();
}
sealed class ExprefTestClass_inter_class_sealed_exc_C1: ExprefTestClass_inter_class_sealed_exc_I1
{
public void i() {/*Old Print*/}
}
class ExprefTestClass_inter_class_sealed_exc_C2: ExprefTestClass_inter_class_sealed_exc_I1
{
public void i() {/*Old Print*/}
}
public class ExprefTestClass_inter_class_sealed_exc
{
public static bool testMethod()
{
ExprefTestClass_inter_class_sealed_exc_I1 inter = new ExprefTestClass_inter_class_sealed_exc_C1();
try
{
ExprefTestClass_inter_class_sealed_exc_C2 c2 = (ExprefTestClass_inter_class_sealed_exc_C2) inter;
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_inter_inter_I1
{
void i();
}
interface ExprefTestClass_inter_inter_I2
{
void j();
}
class ExprefTestClass_inter_inter_C1: ExprefTestClass_inter_inter_I1
{
public void i() {/*Old Print*/}
}
class ExprefTestClass_inter_inter_C2: ExprefTestClass_inter_inter_C1, ExprefTestClass_inter_inter_I2
{
public void j() {/*Old Print*/}
}
public class ExprefTestClass_inter_inter
{
public static bool testMethod()
{
ExprefTestClass_inter_inter_I2 i2 = (ExprefTestClass_inter_inter_I2) new ExprefTestClass_inter_inter_C2();
try
{
ExprefTestClass_inter_inter_I1 i1 = (ExprefTestClass_inter_inter_I1) i2;
i1.i();
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
interface ExprefTestClass_inter_inter_exc_I1
{
void i();
}
interface ExprefTestClass_inter_inter_exc_I2
{
void j();
}
interface ExprefTestClass_inter_inter_exc_I3
{
void k();
}
class ExprefTestClass_inter_inter_exc_C1 : ExprefTestClass_inter_inter_exc_I1
{
public void i() {/*Old Print*/}
}
class ExprefTestClass_inter_inter_exc_C2 : ExprefTestClass_inter_inter_exc_C1, ExprefTestClass_inter_inter_exc_I2
{
public void j() {/*Old Print*/}
}
public class ExprefTestClass_inter_inter_exc
{
public static bool testMethod()
{
ExprefTestClass_inter_inter_exc_I2 i2 = (ExprefTestClass_inter_inter_exc_I2)new ExprefTestClass_inter_inter_exc_C2();
try
{
ExprefTestClass_inter_inter_exc_I3 i3 = (ExprefTestClass_inter_inter_exc_I3)i2;
}
catch (System.Exception e)
{
//Old Print
}
return true;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.Http.Features
{
/// <summary>
/// Default implementation for <see cref="IQueryFeature"/>.
/// </summary>
public class QueryFeature : IQueryFeature
{
// Lambda hoisted to static readonly field to improve inlining https://github.com/dotnet/roslyn/issues/13624
private static readonly Func<IFeatureCollection, IHttpRequestFeature?> _nullRequestFeature = f => null;
private FeatureReferences<IHttpRequestFeature> _features;
private string? _original;
private IQueryCollection? _parsedValues;
/// <summary>
/// Initializes a new instance of <see cref="QueryFeature"/>.
/// </summary>
/// <param name="query">The <see cref="IQueryCollection"/> to use as a backing store.</param>
public QueryFeature(IQueryCollection query)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
_parsedValues = query;
}
/// <summary>
/// Initializes a new instance of <see cref="QueryFeature"/>.
/// </summary>
/// <param name="features">The <see cref="IFeatureCollection"/> to initialize.</param>
public QueryFeature(IFeatureCollection features)
{
if (features == null)
{
throw new ArgumentNullException(nameof(features));
}
_features.Initalize(features);
}
private IHttpRequestFeature HttpRequestFeature =>
_features.Fetch(ref _features.Cache, _nullRequestFeature)!;
/// <inheritdoc />
public IQueryCollection Query
{
get
{
if (_features.Collection is null)
{
return _parsedValues ?? QueryCollection.Empty;
}
var current = HttpRequestFeature.QueryString;
if (_parsedValues == null || !string.Equals(_original, current, StringComparison.Ordinal))
{
_original = current;
var result = ParseNullableQueryInternal(current);
_parsedValues = result is not null
? new QueryCollectionInternal(result)
: QueryCollection.Empty;
}
return _parsedValues;
}
set
{
_parsedValues = value;
if (_features.Collection != null)
{
if (value == null)
{
_original = string.Empty;
HttpRequestFeature.QueryString = string.Empty;
}
else
{
_original = QueryString.Create(_parsedValues).ToString();
HttpRequestFeature.QueryString = _original;
}
}
}
}
/// <summary>
/// Parse a query string into its component key and value parts.
/// </summary>
/// <param name="queryString">The raw query string value, with or without the leading '?'.</param>
/// <returns>A collection of parsed keys and values, null if there are no entries.</returns>
[SkipLocalsInit]
internal static AdaptiveCapacityDictionary<string, StringValues>? ParseNullableQueryInternal(string? queryString)
{
if (string.IsNullOrEmpty(queryString) || (queryString.Length == 1 && queryString[0] == '?'))
{
return null;
}
var accumulator = new KvpAccumulator();
var enumerable = new QueryStringEnumerable(queryString);
foreach (var pair in enumerable)
{
accumulator.Append(pair.DecodeName().Span, pair.DecodeValue().Span);
}
return accumulator.HasValues
? accumulator.GetResults()
: null;
}
internal struct KvpAccumulator
{
/// <summary>
/// This API supports infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
private AdaptiveCapacityDictionary<string, StringValues> _accumulator;
private AdaptiveCapacityDictionary<string, List<string>> _expandingAccumulator;
public void Append(ReadOnlySpan<char> key, ReadOnlySpan<char> value)
=> Append(key.ToString(), value.ToString());
/// <summary>
/// This API supports infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public void Append(string key, string value)
{
if (_accumulator is null)
{
_accumulator = new AdaptiveCapacityDictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase);
}
if (!_accumulator.TryGetValue(key, out var values))
{
// First value for this key
_accumulator[key] = new StringValues(value);
}
else
{
AppendToExpandingAccumulator(key, value, values);
}
ValueCount++;
}
private void AppendToExpandingAccumulator(string key, string value, StringValues values)
{
// When there are some values for the same key, so switch to expanding accumulator, and
// add a zero count marker in the accumulator to indicate that switch.
if (values.Count != 0)
{
_accumulator[key] = default;
if (_expandingAccumulator is null)
{
_expandingAccumulator = new AdaptiveCapacityDictionary<string, List<string>>(capacity: 5, StringComparer.OrdinalIgnoreCase);
}
// Already 2 (1 existing + the new one) entries so use List's expansion mechanism for more
var list = new List<string>();
list.AddRange(values);
list.Add(value);
_expandingAccumulator[key] = list;
}
else
{
// The marker indicates we are in the expanding accumulator, so just append to the list.
_expandingAccumulator[key].Add(value);
}
}
/// <summary>
/// This API supports infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public bool HasValues => ValueCount > 0;
/// <summary>
/// This API supports infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public int KeyCount => _accumulator?.Count ?? 0;
/// <summary>
/// This API supports infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public int ValueCount { get; private set; }
/// <summary>
/// This API supports infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public AdaptiveCapacityDictionary<string, StringValues> GetResults()
{
if (_expandingAccumulator != null)
{
// Coalesce count 3+ multi-value entries into _accumulator dictionary
foreach (var entry in _expandingAccumulator)
{
_accumulator[entry.Key] = new StringValues(entry.Value.ToArray());
}
}
return _accumulator ?? new AdaptiveCapacityDictionary<string, StringValues>(0, StringComparer.OrdinalIgnoreCase);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
namespace Cottle.Test
{
public class FunctionTester
{
private static readonly Value Return = 42;
private const string Output = "abc";
private const string State = "test";
[Test]
public void Create_Arbitrary()
{
foreach (var arguments in new[] { new Value[] { 1 }, new Value[] { 1, 2 }, new Value[] { 1, 2, 3 } })
{
var function = Function.Create(FunctionTester.CreateImpureCallback(arguments));
FunctionTester.AssertImpure(function, arguments, FunctionTester.Output);
}
}
[Test]
public void Create_Exact()
{
var arguments = new Value[] { 1, 2, 3 };
var function = Function.Create(FunctionTester.CreateImpureCallback(arguments), 3);
FunctionTester.AssertImpure(function, arguments, FunctionTester.Output);
FunctionTester.AssertImpureFailure(function, new Value[] { 1, 2 });
FunctionTester.AssertImpureFailure(function, new Value[] { 1, 2, 3, 4 });
}
[Test]
public void Create_Range()
{
var arguments2 = new Value[] { 1, 2 };
var function2 = Function.Create(FunctionTester.CreateImpureCallback(arguments2), 2, 3);
FunctionTester.AssertImpure(function2, arguments2, FunctionTester.Output);
FunctionTester.AssertImpureFailure(function2, new Value[] { 1 });
FunctionTester.AssertImpureFailure(function2, new Value[] { 1, 2, 3, 4 });
var arguments3 = new Value[] { 1, 2, 3 };
var function3 = Function.Create(FunctionTester.CreateImpureCallback(arguments3), 2, 3);
FunctionTester.AssertImpure(function3, arguments3, FunctionTester.Output);
FunctionTester.AssertImpureFailure(function3, new Value[] { 1 });
FunctionTester.AssertImpureFailure(function3, new Value[] { 1, 2, 3, 4 });
}
[Test]
public void Create0()
{
var function = Function.Create0((state, output) => FunctionTester.Return);
FunctionTester.AssertImpure(function, Array.Empty<Value>(), string.Empty);
FunctionTester.AssertImpureFailure(function, new Value[] { 1 });
}
[Test]
public void Create1()
{
var argument = (Value)17;
var function = Function.Create1((state, a0, output) =>
{
Assert.That(a0, Is.EqualTo(argument));
return FunctionTester.Return;
});
FunctionTester.AssertImpure(function, new[] { argument }, string.Empty);
FunctionTester.AssertImpureFailure(function, new Value[] { 1, 2 });
}
[Test]
public void Create2()
{
var argument0 = (Value)17;
var argument1 = (Value)23;
var function = Function.Create2((state, a0, a1, output) =>
{
Assert.That(a0, Is.EqualTo(argument0));
Assert.That(a1, Is.EqualTo(argument1));
return FunctionTester.Return;
});
FunctionTester.AssertImpure(function, new[] { argument0, argument1 }, string.Empty);
FunctionTester.AssertImpureFailure(function, new Value[] { 1 });
}
[Test]
public void Create3()
{
var argument0 = (Value)17;
var argument1 = (Value)23;
var argument2 = (Value)42;
var function = Function.Create3((state, a0, a1, a2, output) =>
{
Assert.That(a0, Is.EqualTo(argument0));
Assert.That(a1, Is.EqualTo(argument1));
Assert.That(a2, Is.EqualTo(argument2));
return FunctionTester.Return;
});
FunctionTester.AssertImpure(function, new[] { argument0, argument1, argument2 }, string.Empty);
FunctionTester.AssertImpureFailure(function, new Value[] { 1, 2 });
}
[Test]
public void CreatePure_Arbitrary()
{
foreach (var arguments in new[] { new Value[] { 1 }, new Value[] { 1, 2 }, new Value[] { 1, 2, 3 } })
{
var function = Function.CreatePure(FunctionTester.CreatePureCallback(arguments));
FunctionTester.AssertPure(function, arguments);
}
}
[Test]
public void CreatePure_Exact()
{
var arguments = new Value[] { 1, 2, 3 };
var function = Function.CreatePure(FunctionTester.CreatePureCallback(arguments), 3);
FunctionTester.AssertPure(function, arguments);
FunctionTester.AssertPureFailure(function, new Value[] { 1, 2 });
FunctionTester.AssertPureFailure(function, new Value[] { 1, 2, 3, 4 });
}
[Test]
public void CreatePure_Range()
{
var arguments2 = new Value[] { 1, 2 };
var function2 = Function.CreatePure(FunctionTester.CreatePureCallback(arguments2), 2, 3);
FunctionTester.AssertPure(function2, arguments2);
FunctionTester.AssertPureFailure(function2, new Value[] { 1 });
FunctionTester.AssertPureFailure(function2, new Value[] { 1, 2, 3, 4 });
var arguments3 = new Value[] { 1, 2, 3 };
var function3 = Function.CreatePure(FunctionTester.CreatePureCallback(arguments3), 2, 3);
FunctionTester.AssertPure(function3, arguments3);
FunctionTester.AssertPureFailure(function3, new Value[] { 1 });
FunctionTester.AssertPureFailure(function3, new Value[] { 1, 2, 3, 4 });
}
[Test]
public void CreatePure0()
{
var function = Function.CreatePure0((state) => FunctionTester.Return);
FunctionTester.AssertPure(function, Array.Empty<Value>());
FunctionTester.AssertPureFailure(function, new Value[] { 1 });
}
[Test]
public void CreatePure1()
{
var argument = (Value)17;
var function = Function.CreatePure1((state, a0) =>
{
Assert.That(a0, Is.EqualTo(argument));
return FunctionTester.Return;
});
FunctionTester.AssertPure(function, new[] { argument });
FunctionTester.AssertPureFailure(function, new Value[] { 1, 2 });
}
[Test]
public void CreatePure2()
{
var argument0 = (Value)17;
var argument1 = (Value)23;
var function = Function.CreatePure2((state, a0, a1) =>
{
Assert.That(a0, Is.EqualTo(argument0));
Assert.That(a1, Is.EqualTo(argument1));
return FunctionTester.Return;
});
FunctionTester.AssertPure(function, new[] { argument0, argument1 });
FunctionTester.AssertPureFailure(function, new Value[] { 1 });
}
[Test]
public void CreatePure3()
{
var argument0 = (Value)17;
var argument1 = (Value)23;
var argument2 = (Value)42;
var function = Function.CreatePure3((state, a0, a1, a2) =>
{
Assert.That(a0, Is.EqualTo(argument0));
Assert.That(a1, Is.EqualTo(argument1));
Assert.That(a2, Is.EqualTo(argument2));
return FunctionTester.Return;
});
FunctionTester.AssertPure(function, new[] { argument0, argument1, argument2 });
FunctionTester.AssertPureFailure(function, new Value[] { 1, 2 });
}
private static void AssertImpure(IFunction function, IReadOnlyList<Value> arguments, string output)
{
using (var writer = new StringWriter())
{
var result = function.Invoke(FunctionTester.State, arguments, writer);
Assert.That(function.IsPure, Is.False);
Assert.That(result, Is.EqualTo(FunctionTester.Return));
Assert.That(writer.ToString(), Is.EqualTo(output));
}
}
private static void AssertImpureFailure(IFunction function, IReadOnlyList<Value> arguments)
{
using (var writer = new StringWriter())
{
var result = function.Invoke(FunctionTester.State, arguments, writer);
Assert.That(function.IsPure, Is.False);
Assert.That(result, Is.EqualTo(Value.Undefined));
Assert.That(writer.ToString(), Is.Empty);
}
}
private static void AssertPure(IFunction function, IReadOnlyList<Value> arguments)
{
using (var writer = new StringWriter())
{
var result = function.Invoke(FunctionTester.State, arguments, writer);
Assert.That(function.IsPure, Is.True);
Assert.That(result, Is.EqualTo(FunctionTester.Return));
Assert.That(writer.ToString(), Is.Empty);
}
}
private static void AssertPureFailure(IFunction function, IReadOnlyList<Value> arguments)
{
using (var writer = new StringWriter())
{
var result = function.Invoke(FunctionTester.State, arguments, writer);
Assert.That(function.IsPure, Is.True);
Assert.That(result, Is.EqualTo(Value.Undefined));
Assert.That(writer.ToString(), Is.Empty);
}
}
private static Func<object, IReadOnlyList<Value>, TextWriter, Value> CreateImpureCallback(Value[] expected)
{
return (state, arguments, output) =>
{
Assert.That(arguments, Is.EqualTo(expected));
Assert.That(state, Is.EqualTo(FunctionTester.State));
output.Write(new[] { 'a', 'b', 'c' });
return FunctionTester.Return;
};
}
private static Func<object, IReadOnlyList<Value>, Value> CreatePureCallback(Value[] expected)
{
return (state, arguments) =>
{
Assert.That(arguments, Is.EqualTo(expected));
Assert.That(state, Is.EqualTo(FunctionTester.State));
return FunctionTester.Return;
};
}
}
}
| |
//
// TreeStore.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Collections.Generic;
using Xwt.Backends;
using System.ComponentModel;
namespace Xwt
{
[BackendType (typeof(ITreeStoreBackend))]
public class TreeStore: XwtComponent, ITreeDataSource
{
IDataField[] fields;
class TreeStoreBackendHost: BackendHost<TreeStore,ITreeStoreBackend>
{
protected override IBackend OnCreateBackend ()
{
var b = base.OnCreateBackend ();
if (b == null)
b = new DefaultTreeStoreBackend ();
((ITreeStoreBackend)b).Initialize (Parent.fields.Select (f => f.FieldType).ToArray ());
return b;
}
}
protected override Xwt.Backends.BackendHost CreateBackendHost ()
{
return new TreeStoreBackendHost ();
}
public TreeStore (params IDataField[] fields)
{
for (int n=0; n<fields.Length; n++) {
if (fields[n].Index != -1)
throw new InvalidOperationException ("DataField object already belongs to another data store");
((IDataFieldInternal)fields[n]).SetIndex (n);
}
this.fields = fields;
}
ITreeStoreBackend Backend {
get { return (ITreeStoreBackend)BackendHost.Backend; }
}
public TreeNavigator GetFirstNode ()
{
var p = Backend.GetChild (null, 0);
return new TreeNavigator (Backend, p);
}
public TreeNavigator GetNavigatorAt (TreePosition pos)
{
return new TreeNavigator (Backend, pos);
}
public TreeNavigator AddNode ()
{
var pos = Backend.AddChild (null);
return new TreeNavigator (Backend, pos);
}
public TreeNavigator AddNode (TreePosition position)
{
var pos = Backend.AddChild (position);
return new TreeNavigator (Backend, pos);
}
public TreeNavigator InsertNodeAfter (TreePosition positon)
{
var pos = Backend.InsertAfter (positon);
return new TreeNavigator (Backend, pos);
}
public TreeNavigator InsertNodeBefore (TreePosition positon)
{
var pos = Backend.InsertBefore (positon);
return new TreeNavigator (Backend, pos);
}
public void Clear ()
{
Backend.Clear ();
}
event EventHandler<TreeNodeEventArgs> ITreeDataSource.NodeInserted {
add { Backend.NodeInserted += value; }
remove { Backend.NodeInserted -= value; }
}
event EventHandler<TreeNodeChildEventArgs> ITreeDataSource.NodeDeleted {
add { Backend.NodeDeleted += value; }
remove { Backend.NodeDeleted -= value; }
}
event EventHandler<TreeNodeEventArgs> ITreeDataSource.NodeChanged {
add { Backend.NodeChanged += value; }
remove { Backend.NodeChanged -= value; }
}
event EventHandler<TreeNodeOrderEventArgs> ITreeDataSource.NodesReordered {
add { Backend.NodesReordered += value; }
remove { Backend.NodesReordered -= value; }
}
TreePosition ITreeDataSource.GetChild (TreePosition pos, int index)
{
return Backend.GetChild (pos, index);
}
TreePosition ITreeDataSource.GetParent (TreePosition pos)
{
return Backend.GetParent (pos);
}
int ITreeDataSource.GetChildrenCount (TreePosition pos)
{
return Backend.GetChildrenCount (pos);
}
object ITreeDataSource.GetValue (TreePosition pos, int column)
{
return Backend.GetValue (pos, column);
}
void ITreeDataSource.SetValue (TreePosition pos, int column, object val)
{
Backend.SetValue (pos, column, val);
}
Type[] ITreeDataSource.ColumnTypes {
get {
return fields.Select (f => f.FieldType).ToArray ();
}
}
}
class DefaultTreeStoreBackend: ITreeStoreBackend
{
struct Node {
public object[] Data;
public NodeList Children;
public int NodeId;
}
class NodePosition: TreePosition
{
public NodeList ParentList;
public int NodeIndex;
public int NodeId;
public int StoreVersion;
public override bool Equals (object obj)
{
NodePosition other = (NodePosition) obj;
if (other == null)
return false;
return ParentList == other.ParentList && NodeId == other.NodeId;
}
public override int GetHashCode ()
{
return ParentList.GetHashCode () ^ NodeId;
}
}
class NodeList: List<Node>
{
public NodePosition Parent;
}
Type[] columnTypes;
NodeList rootNodes = new NodeList ();
int version;
int nextNodeId;
public event EventHandler<TreeNodeEventArgs> NodeInserted;
public event EventHandler<TreeNodeChildEventArgs> NodeDeleted;
public event EventHandler<TreeNodeEventArgs> NodeChanged;
public event EventHandler<TreeNodeOrderEventArgs> NodesReordered;
public void InitializeBackend (object frontend, ApplicationContext context)
{
}
public void Initialize (Type[] columnTypes)
{
this.columnTypes = columnTypes;
}
public void Clear ()
{
rootNodes.Clear ();
}
NodePosition GetPosition (TreePosition pos)
{
if (pos == null)
return null;
NodePosition np = (NodePosition)pos;
if (np.StoreVersion != version) {
np.NodeIndex = -1;
for (int i=0; i<np.ParentList.Count; i++) {
if (np.ParentList [i].NodeId == np.NodeId) {
np.NodeIndex = i;
break;
}
}
if (np.NodeIndex == -1)
throw new InvalidOperationException ("Invalid node position");
np.StoreVersion = version;
}
return np;
}
public void SetValue (TreePosition pos, int column, object value)
{
NodePosition n = GetPosition (pos);
Node node = n.ParentList [n.NodeIndex];
if (node.Data == null) {
node.Data = new object [columnTypes.Length];
n.ParentList [n.NodeIndex] = node;
}
node.Data [column] = value;
if (NodeChanged != null)
NodeChanged (this, new TreeNodeEventArgs (pos));
}
public object GetValue (TreePosition pos, int column)
{
NodePosition np = GetPosition (pos);
Node n = np.ParentList[np.NodeIndex];
if (n.Data == null)
return null;
return n.Data [column];
}
public TreePosition GetChild (TreePosition pos, int index)
{
if (pos == null) {
if (rootNodes.Count == 0)
return null;
Node n = rootNodes[index];
return new NodePosition () { ParentList = rootNodes, NodeId = n.NodeId, NodeIndex = index, StoreVersion = version };
} else {
NodePosition np = GetPosition (pos);
Node n = np.ParentList[np.NodeIndex];
if (n.Children == null || index >= n.Children.Count)
return null;
return new NodePosition () { ParentList = n.Children, NodeId = n.Children[index].NodeId, NodeIndex = index, StoreVersion = version };
}
}
public TreePosition GetNext (TreePosition pos)
{
NodePosition np = GetPosition (pos);
if (np.NodeIndex >= np.ParentList.Count - 1)
return null;
Node n = np.ParentList[np.NodeIndex + 1];
return new NodePosition () { ParentList = np.ParentList, NodeId = n.NodeId, NodeIndex = np.NodeIndex + 1, StoreVersion = version };
}
public TreePosition GetPrevious (TreePosition pos)
{
NodePosition np = GetPosition (pos);
if (np.NodeIndex <= 0)
return null;
Node n = np.ParentList[np.NodeIndex - 1];
return new NodePosition () { ParentList = np.ParentList, NodeId = n.NodeId, NodeIndex = np.NodeIndex - 1, StoreVersion = version };
}
public int GetChildrenCount (TreePosition pos)
{
if (pos == null)
return rootNodes.Count;
NodePosition np = GetPosition (pos);
Node n = np.ParentList[np.NodeIndex];
return n.Children != null ? n.Children.Count : 0;
}
public TreePosition InsertBefore (TreePosition pos)
{
NodePosition np = GetPosition (pos);
Node nn = new Node ();
nn.NodeId = nextNodeId++;
np.ParentList.Insert (np.NodeIndex, nn);
version++;
// Update the NodePosition since it is now invalid
np.NodeIndex++;
np.StoreVersion = version;
var node = new NodePosition () { ParentList = np.ParentList, NodeId = nn.NodeId, NodeIndex = np.NodeIndex - 1, StoreVersion = version };
if (NodeInserted != null)
NodeInserted (this, new TreeNodeEventArgs (node));
return node;
}
public TreePosition InsertAfter (TreePosition pos)
{
NodePosition np = GetPosition (pos);
Node nn = new Node ();
nn.NodeId = nextNodeId++;
np.ParentList.Insert (np.NodeIndex + 1, nn);
version++;
// Update the provided position is still valid
np.StoreVersion = version;
var node = new NodePosition () { ParentList = np.ParentList, NodeId = nn.NodeId, NodeIndex = np.NodeIndex + 1, StoreVersion = version };
if (NodeInserted != null)
NodeInserted (this, new TreeNodeEventArgs (node));
return node;
}
public TreePosition AddChild (TreePosition pos)
{
NodePosition np = GetPosition (pos);
Node nn = new Node ();
nn.NodeId = nextNodeId++;
NodeList list;
if (pos == null) {
list = rootNodes;
} else {
Node n = np.ParentList [np.NodeIndex];
if (n.Children == null) {
n.Children = new NodeList ();
n.Children.Parent = new NodePosition () { ParentList = np.ParentList, NodeId = n.NodeId, NodeIndex = np.NodeIndex, StoreVersion = version };
np.ParentList [np.NodeIndex] = n;
}
list = n.Children;
}
list.Add (nn);
version++;
// The provided position is unafected by this change. Keep it valid.
if (np != null)
np.StoreVersion = version;
var node = new NodePosition () { ParentList = list, NodeId = nn.NodeId, NodeIndex = list.Count - 1, StoreVersion = version };
if (NodeInserted != null)
NodeInserted (this, new TreeNodeEventArgs (node));
return node;
}
public void Remove (TreePosition pos)
{
NodePosition np = GetPosition (pos);
np.ParentList.RemoveAt (np.NodeIndex);
var parent = np.ParentList.Parent;
var index = np.NodeIndex;
version++;
if (NodeDeleted != null)
NodeDeleted (this, new TreeNodeChildEventArgs (parent, index));
}
public TreePosition GetParent (TreePosition pos)
{
NodePosition np = GetPosition (pos);
if (np.ParentList == rootNodes)
return null;
var parent = np.ParentList.Parent;
return new NodePosition () { ParentList = parent.ParentList, NodeId = parent.NodeId, NodeIndex = parent.NodeIndex, StoreVersion = version };
}
public Type[] ColumnTypes {
get {
return columnTypes;
}
}
public void EnableEvent (object eventId)
{
}
public void DisableEvent (object eventId)
{
}
}
}
| |
// <copyright file="CubicSplineTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Linq;
using MathNet.Numerics.Interpolation;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.InterpolationTests
{
[TestFixture, Category("Interpolation")]
public class CubicSplineTest
{
readonly double[] _t = { -2.0, -1.0, 0.0, 1.0, 2.0 };
readonly double[] _y = { 1.0, 2.0, -1.0, 0.0, 1.0 };
/// <summary>
/// Verifies that the interpolation matches the given value at all the provided sample points.
/// </summary>
[Test]
public void NaturalFitsAtSamplePoints()
{
IInterpolation it = CubicSpline.InterpolateNatural(_t, _y);
for (int i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i], it.Interpolate(_t[i]), "A Exact Point " + i);
}
}
/// <summary>
/// Verifies that at points other than the provided sample points, the interpolation matches the one computed by Maple as a reference.
/// </summary>
/// <param name="t">Sample point.</param>
/// <param name="x">Sample value.</param>
/// <param name="maxAbsoluteError">Maximum absolute error.</param>
/// <remarks>
/// Maple:
/// with(CurveFitting);
/// evalf(subs({x=-2.4},Spline([[-2,1],[-1,2],[0,-1],[1,0],[2,1]], x, degree=3, endpoints='natural')),20);
/// </remarks>
[TestCase(-2.4, .144, 1e-15)]
[TestCase(-0.9, 1.7906428571428571429, 1e-15)]
[TestCase(-0.5, .47321428571428571431, 1e-15)]
[TestCase(-0.1, -.80992857142857142857, 1e-15)]
[TestCase(0.1, -1.1089285714285714286, 1e-15)]
[TestCase(0.4, -1.0285714285714285714, 1e-15)]
[TestCase(1.2, .30285714285714285716, 1e-15)]
[TestCase(10.0, 189, 1e-15)]
[TestCase(-10.0, 677, 1e-12)]
public void NaturalFitsAtArbitraryPoints(double t, double x, double maxAbsoluteError)
{
IInterpolation it = CubicSpline.InterpolateNatural(_t, _y);
Assert.AreEqual(x, it.Interpolate(t), maxAbsoluteError, "Interpolation at {0}", t);
}
/// <summary>
/// Verifies that the interpolation matches the given value at all the provided sample points.
/// </summary>
[Test]
public void FixedFirstDerivativeFitsAtSamplePoints()
{
IInterpolation it = CubicSpline.InterpolateBoundaries(_t, _y, SplineBoundaryCondition.FirstDerivative, 1.0, SplineBoundaryCondition.FirstDerivative, -1.0);
for (int i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i], it.Interpolate(_t[i]), "A Exact Point " + i);
}
}
/// <summary>
/// Verifies that at points other than the provided sample points, the interpolation matches the one computed by Maple as a reference.
/// </summary>
/// <param name="t">Sample point.</param>
/// <param name="x">Sample value.</param>
/// <param name="maxAbsoluteError">Maximum absolute error.</param>
/// <remarks>
/// Maple:
/// with(CurveFitting);
/// evalf(subs({x=-2.4},Spline([[-2,1],[-1,2],[0,-1],[1,0],[2,1]], x, degree=3, endpoints=[1,-1])),20);
/// </remarks>
[TestCase(-2.4, 1.12, 1e-15)]
[TestCase(-0.9, 1.8243928571428571428, 1e-15)]
[TestCase(-0.5, .54910714285714285715, 1e-15)]
[TestCase(-0.1, -.78903571428571428572, 1e-15)]
[TestCase(0.1, -1.1304642857142857143, 1e-15)]
[TestCase(0.4, -1.1040000000000000000, 1e-15)]
[TestCase(1.2, .4148571428571428571, 1e-15)]
[TestCase(10.0, -608.14285714285714286, 1e-12)]
[TestCase(-10.0, 1330.1428571428571429, 1e-12)]
public void FixedFirstDerivativeFitsAtArbitraryPoints(double t, double x, double maxAbsoluteError)
{
IInterpolation it = CubicSpline.InterpolateBoundaries(_t, _y, SplineBoundaryCondition.FirstDerivative, 1.0, SplineBoundaryCondition.FirstDerivative, -1.0);
Assert.AreEqual(x, it.Interpolate(t), maxAbsoluteError, "Interpolation at {0}", t);
}
/// <summary>
/// Verifies that the interpolation matches the given value at all the provided sample points.
/// </summary>
[Test]
public void FixedSecondDerivativeFitsAtSamplePoints()
{
IInterpolation it = CubicSpline.InterpolateBoundaries(_t, _y, SplineBoundaryCondition.SecondDerivative, -5.0, SplineBoundaryCondition.SecondDerivative, -1.0);
for (int i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i], it.Interpolate(_t[i]), "A Exact Point " + i);
}
}
/// <summary>
/// Verifies that at points other than the provided sample points, the interpolation matches the one computed by Maple as a reference.
/// </summary>
/// <param name="t">Sample point.</param>
/// <param name="x">Sample value.</param>
/// <param name="maxAbsoluteError">Maximum absolute error.</param>
/// <remarks>
/// Maple:
/// with(CurveFitting);
/// evalf(subs({x=-2.4},Spline([[-2,1],[-1,2],[0,-1],[1,0],[2,1]], x, degree=3, endpoints=Matrix(2,13,{(1,3)=1,(1,13)=-5,(2,10)=1,(2,13)=-1}))),20);
/// </remarks>
[TestCase(-2.4, -.8999999999999999993, 1e-15)]
[TestCase(-0.9, 1.7590357142857142857, 1e-15)]
[TestCase(-0.5, .41517857142857142854, 1e-15)]
[TestCase(-0.1, -.82010714285714285714, 1e-15)]
[TestCase(0.1, -1.1026071428571428572, 1e-15)]
[TestCase(0.4, -1.0211428571428571429, 1e-15)]
[TestCase(1.2, .31771428571428571421, 1e-15)]
[TestCase(10.0, 39, 1e-13)]
[TestCase(-10.0, -37, 1e-12)]
public void FixedSecondDerivativeFitsAtArbitraryPoints(double t, double x, double maxAbsoluteError)
{
IInterpolation it = CubicSpline.InterpolateBoundaries(_t, _y, SplineBoundaryCondition.SecondDerivative, -5.0, SplineBoundaryCondition.SecondDerivative, -1.0);
Assert.AreEqual(x, it.Interpolate(t), maxAbsoluteError, "Interpolation at {0}", t);
}
/// <summary>
/// Verifies that the interpolation supports the linear case appropriately
/// </summary>
/// <param name="samples">Samples array.</param>
[TestCase(2)]
[TestCase(4)]
[TestCase(12)]
public void NaturalSupportsLinearCase(int samples)
{
double[] x, y, xtest, ytest;
LinearInterpolationCase.Build(out x, out y, out xtest, out ytest, samples);
IInterpolation it = CubicSpline.InterpolateNatural(x, y);
for (int i = 0; i < xtest.Length; i++)
{
Assert.AreEqual(ytest[i], it.Interpolate(xtest[i]), 1e-15, "Linear with {0} samples, sample {1}", samples, i);
}
}
[Test]
public void FewSamples()
{
Assert.That(() => CubicSpline.InterpolateNatural(new double[0], new double[0]), Throws.ArgumentException);
Assert.That(() => CubicSpline.InterpolateNatural(new double[1], new double[1]), Throws.ArgumentException);
Assert.That(CubicSpline.InterpolateNatural(new[] { 1.0, 2.0 }, new[] { 2.0, 2.0 }).Interpolate(1.0), Is.EqualTo(2.0));
}
#if !NET35 && !PORTABLE
[Test]
public void InterpolateAkimaSorted_MustBeThreadSafe_GitHub219([Values(8, 32, 256, 1024)] int samples)
{
var x = Generate.LinearSpaced(samples + 1, 0.0, 2.0*Math.PI);
var y = new double[samples][];
for (var i = 0; i < samples; ++i)
{
y[i] = x.Select(xx => Math.Sin(xx)/(i + 1)).ToArray();
}
var yipol = new double[samples];
System.Threading.Tasks.Parallel.For(0, samples, i =>
{
var spline = CubicSpline.InterpolateAkimaSorted(x, y[i]);
yipol[i] = spline.Interpolate(1.0);
});
CollectionAssert.DoesNotContain(yipol, Double.NaN);
}
#endif
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations to manage Azure SQL Database and Server
/// blob auditing. Contains operations to: Create, Retrieve and Update
/// blob auditing settings.
/// </summary>
internal partial class BlobAuditingOperations : IServiceOperations<SqlManagementClient>, IBlobAuditingOperations
{
/// <summary>
/// Initializes a new instance of the BlobAuditingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal BlobAuditingOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates or updates an Azure SQL Database blob auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the auditing
/// policy applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a Azure
/// SQL Database auditing policy.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateOrUpdateDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, BlobAuditingCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateDatabasePolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/auditingSettings/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject blobAuditingCreateOrUpdateParametersValue = new JObject();
requestDoc = blobAuditingCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
blobAuditingCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.State != null)
{
propertiesValue["state"] = parameters.Properties.State;
}
if (parameters.Properties.StorageEndpoint != null)
{
propertiesValue["storageEndpoint"] = parameters.Properties.StorageEndpoint;
}
if (parameters.Properties.StorageAccountAccessKey != null)
{
propertiesValue["storageAccountAccessKey"] = parameters.Properties.StorageAccountAccessKey;
}
propertiesValue["retentionDays"] = parameters.Properties.RetentionDays;
if (parameters.Properties.AuditActionsAndGroups != null)
{
if (parameters.Properties.AuditActionsAndGroups is ILazyCollection == false || ((ILazyCollection)parameters.Properties.AuditActionsAndGroups).IsInitialized)
{
JArray auditActionsAndGroupsArray = new JArray();
foreach (string auditActionsAndGroupsItem in parameters.Properties.AuditActionsAndGroups)
{
auditActionsAndGroupsArray.Add(auditActionsAndGroupsItem);
}
propertiesValue["auditActionsAndGroups"] = auditActionsAndGroupsArray;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Creates or updates an Azure SQL Database Server blob auditing
/// policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a Azure
/// SQL Database Server blob auditing policy.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response Azure Sql Server blob auditing operation.
/// </returns>
public async Task<ServerBlobAuditingResponse> CreateOrUpdateServerPolicyAsync(string resourceGroupName, string serverName, BlobAuditingCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateServerPolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/auditingSettings/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject blobAuditingCreateOrUpdateParametersValue = new JObject();
requestDoc = blobAuditingCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
blobAuditingCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.State != null)
{
propertiesValue["state"] = parameters.Properties.State;
}
if (parameters.Properties.StorageEndpoint != null)
{
propertiesValue["storageEndpoint"] = parameters.Properties.StorageEndpoint;
}
if (parameters.Properties.StorageAccountAccessKey != null)
{
propertiesValue["storageAccountAccessKey"] = parameters.Properties.StorageAccountAccessKey;
}
propertiesValue["retentionDays"] = parameters.Properties.RetentionDays;
if (parameters.Properties.AuditActionsAndGroups != null)
{
if (parameters.Properties.AuditActionsAndGroups is ILazyCollection == false || ((ILazyCollection)parameters.Properties.AuditActionsAndGroups).IsInitialized)
{
JArray auditActionsAndGroupsArray = new JArray();
foreach (string auditActionsAndGroupsItem in parameters.Properties.AuditActionsAndGroups)
{
auditActionsAndGroupsArray.Add(auditActionsAndGroupsItem);
}
propertiesValue["auditActionsAndGroups"] = auditActionsAndGroupsArray;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerBlobAuditingResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerBlobAuditingResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns an Azure SQL Database blob auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the auditing
/// policy applies.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a get request for Azure SQL server or
/// database blob auditing policy.
/// </returns>
public async Task<BlobAuditingGetResponse> GetDatabaseBlobAuditingPolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "GetDatabaseBlobAuditingPolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/auditingSettings/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
BlobAuditingGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new BlobAuditingGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
BlobAuditingPolicy auditingPolicyInstance = new BlobAuditingPolicy();
result.AuditingPolicy = auditingPolicyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
BlobAuditingProperties propertiesInstance = new BlobAuditingProperties();
auditingPolicyInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken storageEndpointValue = propertiesValue["storageEndpoint"];
if (storageEndpointValue != null && storageEndpointValue.Type != JTokenType.Null)
{
string storageEndpointInstance = ((string)storageEndpointValue);
propertiesInstance.StorageEndpoint = storageEndpointInstance;
}
JToken storageAccountAccessKeyValue = propertiesValue["storageAccountAccessKey"];
if (storageAccountAccessKeyValue != null && storageAccountAccessKeyValue.Type != JTokenType.Null)
{
string storageAccountAccessKeyInstance = ((string)storageAccountAccessKeyValue);
propertiesInstance.StorageAccountAccessKey = storageAccountAccessKeyInstance;
}
JToken retentionDaysValue = propertiesValue["retentionDays"];
if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null)
{
int retentionDaysInstance = ((int)retentionDaysValue);
propertiesInstance.RetentionDays = retentionDaysInstance;
}
JToken auditActionsAndGroupsArray = propertiesValue["auditActionsAndGroups"];
if (auditActionsAndGroupsArray != null && auditActionsAndGroupsArray.Type != JTokenType.Null)
{
foreach (JToken auditActionsAndGroupsValue in ((JArray)auditActionsAndGroupsArray))
{
propertiesInstance.AuditActionsAndGroups.Add(((string)auditActionsAndGroupsValue));
}
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
auditingPolicyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
auditingPolicyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
auditingPolicyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
auditingPolicyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
auditingPolicyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the status of an Azure Sql Server blob auditing create or
/// update operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Server blob auditing status link returned by the
/// CreateOrUpdate operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql server blob auditing create or
/// update operations.
/// </returns>
public async Task<ServerBlobAuditingOperationResponse> GetOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerBlobAuditingOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerBlobAuditingOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
BlobAuditingOperationResult operationResultInstance = new BlobAuditingOperationResult();
result.OperationResult = operationResultInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
BlobAuditingOperationResultProperties propertiesInstance = new BlobAuditingOperationResultProperties();
operationResultInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
OperationStatus stateInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)stateValue), true));
propertiesInstance.State = stateInstance;
}
JToken startTimeValue = propertiesValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
string startTimeInstance = ((string)startTimeValue);
propertiesInstance.StartTime = startTimeInstance;
}
JToken operationIdValue = propertiesValue["operationId"];
if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
{
string operationIdInstance = ((string)operationIdValue);
propertiesInstance.OperationId = operationIdInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
operationResultInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
operationResultInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
operationResultInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
operationResultInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
operationResultInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns an Azure SQL Database server blob auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a get request for Azure SQL server or
/// database blob auditing policy.
/// </returns>
public async Task<BlobAuditingGetResponse> GetServerPolicyAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "GetServerPolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/auditingSettings/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
BlobAuditingGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new BlobAuditingGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
BlobAuditingPolicy auditingPolicyInstance = new BlobAuditingPolicy();
result.AuditingPolicy = auditingPolicyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
BlobAuditingProperties propertiesInstance = new BlobAuditingProperties();
auditingPolicyInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken storageEndpointValue = propertiesValue["storageEndpoint"];
if (storageEndpointValue != null && storageEndpointValue.Type != JTokenType.Null)
{
string storageEndpointInstance = ((string)storageEndpointValue);
propertiesInstance.StorageEndpoint = storageEndpointInstance;
}
JToken storageAccountAccessKeyValue = propertiesValue["storageAccountAccessKey"];
if (storageAccountAccessKeyValue != null && storageAccountAccessKeyValue.Type != JTokenType.Null)
{
string storageAccountAccessKeyInstance = ((string)storageAccountAccessKeyValue);
propertiesInstance.StorageAccountAccessKey = storageAccountAccessKeyInstance;
}
JToken retentionDaysValue = propertiesValue["retentionDays"];
if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null)
{
int retentionDaysInstance = ((int)retentionDaysValue);
propertiesInstance.RetentionDays = retentionDaysInstance;
}
JToken auditActionsAndGroupsArray = propertiesValue["auditActionsAndGroups"];
if (auditActionsAndGroupsArray != null && auditActionsAndGroupsArray.Type != JTokenType.Null)
{
foreach (JToken auditActionsAndGroupsValue in ((JArray)auditActionsAndGroupsArray))
{
propertiesInstance.AuditActionsAndGroups.Add(((string)auditActionsAndGroupsValue));
}
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
auditingPolicyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
auditingPolicyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
auditingPolicyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
auditingPolicyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
auditingPolicyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using DeOps.Implementation.Protocol;
namespace DeOps.Services.Mail
{
public class MailPacket
{
public const byte MailHeader = 0x10;
public const byte MailInfo = 0x20;
public const byte MailDest = 0x30;
public const byte MailFile = 0x40;
public const byte Ack = 0x50;
}
// 20,000 emails stored locally, the header is ~10MB for 1024bit RSA, 2.5MB for 128bit ECC
public class MailHeader : G2Packet
{
const byte Packet_Source = 0x10;
const byte Packet_Target = 0x20;
const byte Packet_FileKey = 0x30;
const byte Packet_FileHash = 0x40;
const byte Packet_FileSize = 0x50;
const byte Packet_LocalKey = 0x60;
const byte Packet_SourceVersion = 0x70;
const byte Packet_TargetVersion = 0x80;
const byte Packet_MailID = 0x90;
const byte Packet_FileStart = 0xA0;
const byte Packet_Read = 0xB0;
const byte Packet_Received = 0xC0;
const byte Packet_ThreadID = 0xD0;
public byte[] Source;
public byte[] Target;
public byte[] FileKey; // signed with targets public key
public byte[] FileHash;
public long FileSize;
public uint SourceVersion;
public uint TargetVersion;
public byte[] MailID;
public int ThreadID;
public ulong SourceID;
public ulong TargetID;
// only saved in inbox file, **not put out on netork
public byte[] LocalKey;
public long FileStart;
public bool Read;
public DateTime Received;
public MailHeader()
{
}
public override byte[] Encode(G2Protocol protocol)
{
// should not be called
throw new Exception("Mail header encode called");
}
public byte[] Encode(G2Protocol protocol, bool local)
{
lock (protocol.WriteSection)
{
G2Frame header = protocol.WritePacket(null, MailPacket.MailHeader, null);
protocol.WritePacket(header, Packet_Source, Source);
protocol.WritePacket(header, Packet_Target, Target);
protocol.WritePacket(header, Packet_FileKey, FileKey);
protocol.WritePacket(header, Packet_FileHash, FileHash);
protocol.WritePacket(header, Packet_FileSize, BitConverter.GetBytes(FileSize));
protocol.WritePacket(header, Packet_SourceVersion, BitConverter.GetBytes(SourceVersion));
protocol.WritePacket(header, Packet_TargetVersion, BitConverter.GetBytes(TargetVersion));
protocol.WritePacket(header, Packet_MailID, MailID);
protocol.WritePacket(header, Packet_ThreadID, BitConverter.GetBytes(ThreadID));
if (local)
{
protocol.WritePacket(header, Packet_LocalKey, LocalKey);
protocol.WritePacket(header, Packet_FileStart, BitConverter.GetBytes(FileStart));
protocol.WritePacket(header, Packet_Read, BitConverter.GetBytes(Read));
protocol.WritePacket(header, Packet_Received, BitConverter.GetBytes(Received.ToBinary()));
}
return protocol.WriteFinish();
}
}
public static MailHeader Decode(G2Header root)
{
MailHeader header = new MailHeader();
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_Source:
header.Source = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
header.SourceID = Utilities.KeytoID(header.Source);
break;
case Packet_Target:
header.Target = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
header.TargetID = Utilities.KeytoID(header.Target);
break;
case Packet_FileKey:
header.FileKey = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_FileHash:
header.FileHash = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_FileSize:
header.FileSize = BitConverter.ToInt64(child.Data, child.PayloadPos);
break;
case Packet_SourceVersion:
header.SourceVersion = BitConverter.ToUInt32(child.Data, child.PayloadPos);
break;
case Packet_TargetVersion:
header.TargetVersion = BitConverter.ToUInt32(child.Data, child.PayloadPos);
break;
case Packet_MailID:
header.MailID = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_ThreadID:
header.ThreadID = BitConverter.ToInt32(child.Data, child.PayloadPos);
break;
case Packet_LocalKey:
header.LocalKey = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_FileStart:
header.FileStart = BitConverter.ToInt64(child.Data, child.PayloadPos);
break;
case Packet_Read:
header.Read = BitConverter.ToBoolean(child.Data, child.PayloadPos);
break;
case Packet_Received:
header.Received = DateTime.FromBinary(BitConverter.ToInt64(child.Data, child.PayloadPos));
break;
}
}
return header;
}
}
public class MailInfo : G2Packet
{
const byte Packet_Subject = 0x10;
const byte Packet_Format = 0x20;
const byte Packet_Date = 0x30;
const byte Packet_Attachments = 0x40;
const byte Packet_Unique = 0x50;
const byte Packet_Quip = 0x60;
public string Subject;
public TextFormat Format;
public string Quip;
public DateTime Date;
public bool Attachments;
public byte[] Unique = new byte[16];
public MailInfo() { }
public MailInfo(string subject, TextFormat format, string quip, DateTime date, bool attachements)
{
Subject = subject;
Format = format;
Quip = quip;
Date = date;
Attachments = attachements;
RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
rnd.GetBytes(Unique);
}
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame info = protocol.WritePacket(null, MailPacket.MailInfo, null);
protocol.WritePacket(info, Packet_Subject, UTF8Encoding.UTF8.GetBytes(Subject));
protocol.WritePacket(info, Packet_Format, CompactNum.GetBytes((int)Format));
protocol.WritePacket(info, Packet_Quip, UTF8Encoding.UTF8.GetBytes(Quip));
protocol.WritePacket(info, Packet_Date, BitConverter.GetBytes(Date.ToBinary()));
protocol.WritePacket(info, Packet_Attachments, BitConverter.GetBytes(Attachments));
protocol.WritePacket(info, Packet_Unique, Unique);
return protocol.WriteFinish();
}
}
public static MailInfo Decode(G2Header root)
{
MailInfo info = new MailInfo();
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_Subject:
info.Subject = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Format:
info.Format = (TextFormat)CompactNum.ToInt32(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Quip:
info.Quip = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Date:
info.Date = DateTime.FromBinary(BitConverter.ToInt64(child.Data, child.PayloadPos));
break;
case Packet_Attachments:
info.Attachments = BitConverter.ToBoolean(child.Data, child.PayloadPos);
break;
case Packet_Unique:
info.Unique = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
break;
}
}
return info;
}
}
public class MailDestination : G2Packet
{
const byte Packet_Key = 0x10;
const byte Packet_CC = 0x20;
public byte[] Key;
public bool CC;
public ulong KeyID;
public MailDestination()
{
}
public MailDestination(byte[] key, bool cc)
{
Key = key;
CC = cc;
}
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame dest = protocol.WritePacket(null, MailPacket.MailDest, null);
protocol.WritePacket(dest, Packet_Key, Key);
protocol.WritePacket(dest, Packet_CC, BitConverter.GetBytes(CC));
return protocol.WriteFinish();
}
}
public static MailDestination Decode(G2Header root)
{
MailDestination dest = new MailDestination();
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_Key:
dest.Key = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
dest.KeyID = Utilities.KeytoID(dest.Key);
break;
case Packet_CC:
dest.CC = BitConverter.ToBoolean(child.Data, child.PayloadPos);
break;
}
}
return dest;
}
}
public class MailFile : G2Packet
{
const byte Packet_Name = 0x10;
const byte Packet_Size = 0x20;
public string Name;
public long Size;
public MailFile()
{
}
public MailFile(string name, long size)
{
Name = name;
Size = size;
}
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame file = protocol.WritePacket(null, MailPacket.MailFile, null);
protocol.WritePacket(file, Packet_Name, UTF8Encoding.UTF8.GetBytes(Name));
protocol.WritePacket(file, Packet_Size, CompactNum.GetBytes(Size));
return protocol.WriteFinish();
}
}
public static MailFile Decode(G2Header root)
{
MailFile file = new MailFile();
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_Name:
file.Name = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Size:
file.Size = CompactNum.ToInt64(child.Data, child.PayloadPos, child.PayloadSize);
break;
}
}
return file;
}
}
public class MailAck : G2Packet
{
const byte Packet_MailID = 0x10;
const byte Packet_Source = 0x20;
const byte Packet_Target = 0x30;
const byte Packet_TargetVersion = 0x40;
const byte Packet_SourceVersion = 0x50;
public byte[] MailID;
public byte[] Source;
public byte[] Target;
public uint TargetVersion;
public uint SourceVersion;
public ulong SourceID;
public ulong TargetID;
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame ack = protocol.WritePacket(null, MailPacket.Ack, null);
protocol.WritePacket(ack, Packet_MailID, MailID);
protocol.WritePacket(ack, Packet_Source, Source);
protocol.WritePacket(ack, Packet_Target, Target);
protocol.WritePacket(ack, Packet_TargetVersion, BitConverter.GetBytes(TargetVersion));
protocol.WritePacket(ack, Packet_SourceVersion, BitConverter.GetBytes(SourceVersion));
return protocol.WriteFinish();
}
}
public static MailAck Decode(G2Header root)
{
MailAck ack = new MailAck();
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_MailID:
ack.MailID = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Source:
ack.Source = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
ack.SourceID = Utilities.KeytoID(ack.Source);
break;
case Packet_Target:
ack.Target = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
ack.TargetID = Utilities.KeytoID(ack.Target);
break;
case Packet_TargetVersion:
ack.TargetVersion = BitConverter.ToUInt32(child.Data, child.PayloadPos);
break;
case Packet_SourceVersion:
ack.SourceVersion = BitConverter.ToUInt32(child.Data, child.PayloadPos);
break;
}
}
return ack;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Property4U.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
namespace QRCodeSample
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel();
this.skinEngine = new Sunisoft.IrisSkin.SkinEngine();
this.tabMain = new QRCodeSample.NewTabControl();
this.tabEncode = new System.Windows.Forms.TabPage();
this.btnPrint = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.btnEncode = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnFormat = new System.Windows.Forms.Button();
this.txtEncodeData = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.picEncode = new System.Windows.Forms.PictureBox();
this.groupBox6 = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.txtSize = new System.Windows.Forms.TextBox();
this.cboCorrectionLevel = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.cboVersion = new System.Windows.Forms.ComboBox();
this.cboEncoding = new System.Windows.Forms.ComboBox();
this.groupBox7 = new System.Windows.Forms.GroupBox();
this.txtEncodeKey = new System.Windows.Forms.TextBox();
this.cboEncryptAlgo = new System.Windows.Forms.ComboBox();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.tabDecode = new System.Windows.Forms.TabPage();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.txtComManager = new System.Windows.Forms.TextBox();
this.label19 = new System.Windows.Forms.Label();
this.txtBusinessScope = new System.Windows.Forms.TextBox();
this.label13 = new System.Windows.Forms.Label();
this.txtComName = new System.Windows.Forms.TextBox();
this.txtComCode = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnOpen = new System.Windows.Forms.Button();
this.btnDecode = new System.Windows.Forms.Button();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.btnIdentify = new System.Windows.Forms.Button();
this.txtDecodedData = new System.Windows.Forms.TextBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.picDecode = new System.Windows.Forms.PictureBox();
this.groupBox8 = new System.Windows.Forms.GroupBox();
this.cboDecryptAlgo = new System.Windows.Forms.ComboBox();
this.txtDecodeKey = new System.Windows.Forms.TextBox();
this.label10 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.tabSearch = new System.Windows.Forms.TabPage();
this.txtSearch = new System.Windows.Forms.TextBox();
this.btnRemove = new System.Windows.Forms.Button();
this.label17 = new System.Windows.Forms.Label();
this.label15 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.btnSelectPath = new System.Windows.Forms.Button();
this.label12 = new System.Windows.Forms.Label();
this.txtSelectPath = new System.Windows.Forms.TextBox();
this.btnSearch = new System.Windows.Forms.Button();
this.lvFileSearch = new QRCodeSample.DoubleBufferListView();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.label11 = new System.Windows.Forms.Label();
this.txtQRCodePath = new System.Windows.Forms.TextBox();
this.btnOpen2 = new System.Windows.Forms.Button();
this.tabBatchEncode = new System.Windows.Forms.TabPage();
this.btnCreate = new System.Windows.Forms.Button();
this.lvBatchEncode = new QRCodeSample.DoubleBufferListView();
this.columnHeader6 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader7 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader8 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.label18 = new System.Windows.Forms.Label();
this.txtFilePath = new System.Windows.Forms.TextBox();
this.btnOpen3 = new System.Windows.Forms.Button();
this.menuStrip.SuspendLayout();
this.statusStrip.SuspendLayout();
this.tabMain.SuspendLayout();
this.tabEncode.SuspendLayout();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picEncode)).BeginInit();
this.groupBox6.SuspendLayout();
this.groupBox7.SuspendLayout();
this.tabDecode.SuspendLayout();
this.groupBox5.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox4.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picDecode)).BeginInit();
this.groupBox8.SuspendLayout();
this.tabSearch.SuspendLayout();
this.tabBatchEncode.SuspendLayout();
this.SuspendLayout();
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
resources.ApplyResources(this.menuStrip, "menuStrip");
this.menuStrip.Name = "menuStrip";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem");
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1,
this.toolStripStatusLabel2});
resources.ApplyResources(this.statusStrip, "statusStrip");
this.statusStrip.Name = "statusStrip";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
resources.ApplyResources(this.toolStripStatusLabel1, "toolStripStatusLabel1");
//
// toolStripStatusLabel2
//
this.toolStripStatusLabel2.Name = "toolStripStatusLabel2";
resources.ApplyResources(this.toolStripStatusLabel2, "toolStripStatusLabel2");
//
// skinEngine
//
this.skinEngine.@__DrawButtonFocusRectangle = true;
this.skinEngine.DisabledButtonTextColor = System.Drawing.Color.Gray;
this.skinEngine.DisabledMenuFontColor = System.Drawing.SystemColors.GrayText;
this.skinEngine.InactiveCaptionColor = System.Drawing.SystemColors.InactiveCaptionText;
this.skinEngine.SerialNumber = "";
this.skinEngine.SkinFile = null;
//
// tabMain
//
this.tabMain.Controls.Add(this.tabEncode);
this.tabMain.Controls.Add(this.tabDecode);
this.tabMain.Controls.Add(this.tabSearch);
this.tabMain.Controls.Add(this.tabBatchEncode);
resources.ApplyResources(this.tabMain, "tabMain");
this.tabMain.Name = "tabMain";
this.tabMain.SelectedIndex = 0;
this.tabMain.SelectedIndexChanged += new System.EventHandler(this.ShowStatusLabel);
//
// tabEncode
//
this.tabEncode.Controls.Add(this.btnPrint);
this.tabEncode.Controls.Add(this.btnSave);
this.tabEncode.Controls.Add(this.btnEncode);
this.tabEncode.Controls.Add(this.groupBox1);
this.tabEncode.Controls.Add(this.groupBox2);
this.tabEncode.Controls.Add(this.groupBox6);
this.tabEncode.Controls.Add(this.groupBox7);
resources.ApplyResources(this.tabEncode, "tabEncode");
this.tabEncode.Name = "tabEncode";
this.tabEncode.UseVisualStyleBackColor = true;
//
// btnPrint
//
resources.ApplyResources(this.btnPrint, "btnPrint");
this.btnPrint.Name = "btnPrint";
this.btnPrint.UseVisualStyleBackColor = true;
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
//
// btnSave
//
resources.ApplyResources(this.btnSave, "btnSave");
this.btnSave.Name = "btnSave";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// btnEncode
//
resources.ApplyResources(this.btnEncode, "btnEncode");
this.btnEncode.Name = "btnEncode";
this.btnEncode.UseVisualStyleBackColor = true;
this.btnEncode.Click += new System.EventHandler(this.btnEncode_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.btnFormat);
this.groupBox1.Controls.Add(this.txtEncodeData);
this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// btnFormat
//
resources.ApplyResources(this.btnFormat, "btnFormat");
this.btnFormat.Name = "btnFormat";
this.btnFormat.UseVisualStyleBackColor = true;
this.btnFormat.Click += new System.EventHandler(this.btnFormat_Click);
//
// txtEncodeData
//
this.txtEncodeData.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtEncodeData, "txtEncodeData");
this.txtEncodeData.Name = "txtEncodeData";
this.txtEncodeData.TextChanged += new System.EventHandler(this.ShowStatusLabel);
this.txtEncodeData.Enter += new System.EventHandler(this.ShowStatusLabel);
this.txtEncodeData.Leave += new System.EventHandler(this.ShowStatusLabel);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.picEncode);
this.groupBox2.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox2, "groupBox2");
this.groupBox2.Name = "groupBox2";
this.groupBox2.TabStop = false;
//
// picEncode
//
this.picEncode.BackColor = System.Drawing.Color.White;
resources.ApplyResources(this.picEncode, "picEncode");
this.picEncode.Name = "picEncode";
this.picEncode.TabStop = false;
//
// groupBox6
//
this.groupBox6.Controls.Add(this.label2);
this.groupBox6.Controls.Add(this.label5);
this.groupBox6.Controls.Add(this.label4);
this.groupBox6.Controls.Add(this.txtSize);
this.groupBox6.Controls.Add(this.cboCorrectionLevel);
this.groupBox6.Controls.Add(this.label3);
this.groupBox6.Controls.Add(this.cboVersion);
this.groupBox6.Controls.Add(this.cboEncoding);
this.groupBox6.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox6, "groupBox6");
this.groupBox6.Name = "groupBox6";
this.groupBox6.TabStop = false;
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// label5
//
resources.ApplyResources(this.label5, "label5");
this.label5.Name = "label5";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// txtSize
//
this.txtSize.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtSize, "txtSize");
this.txtSize.Name = "txtSize";
//
// cboCorrectionLevel
//
this.cboCorrectionLevel.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cboCorrectionLevel, "cboCorrectionLevel");
this.cboCorrectionLevel.FormattingEnabled = true;
this.cboCorrectionLevel.Items.AddRange(new object[] {
resources.GetString("cboCorrectionLevel.Items"),
resources.GetString("cboCorrectionLevel.Items1"),
resources.GetString("cboCorrectionLevel.Items2"),
resources.GetString("cboCorrectionLevel.Items3")});
this.cboCorrectionLevel.Name = "cboCorrectionLevel";
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// cboVersion
//
this.cboVersion.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cboVersion, "cboVersion");
this.cboVersion.FormattingEnabled = true;
this.cboVersion.Items.AddRange(new object[] {
resources.GetString("cboVersion.Items"),
resources.GetString("cboVersion.Items1"),
resources.GetString("cboVersion.Items2"),
resources.GetString("cboVersion.Items3"),
resources.GetString("cboVersion.Items4"),
resources.GetString("cboVersion.Items5"),
resources.GetString("cboVersion.Items6"),
resources.GetString("cboVersion.Items7"),
resources.GetString("cboVersion.Items8"),
resources.GetString("cboVersion.Items9"),
resources.GetString("cboVersion.Items10"),
resources.GetString("cboVersion.Items11"),
resources.GetString("cboVersion.Items12"),
resources.GetString("cboVersion.Items13"),
resources.GetString("cboVersion.Items14"),
resources.GetString("cboVersion.Items15"),
resources.GetString("cboVersion.Items16"),
resources.GetString("cboVersion.Items17"),
resources.GetString("cboVersion.Items18"),
resources.GetString("cboVersion.Items19"),
resources.GetString("cboVersion.Items20"),
resources.GetString("cboVersion.Items21"),
resources.GetString("cboVersion.Items22"),
resources.GetString("cboVersion.Items23"),
resources.GetString("cboVersion.Items24"),
resources.GetString("cboVersion.Items25"),
resources.GetString("cboVersion.Items26"),
resources.GetString("cboVersion.Items27"),
resources.GetString("cboVersion.Items28"),
resources.GetString("cboVersion.Items29"),
resources.GetString("cboVersion.Items30"),
resources.GetString("cboVersion.Items31"),
resources.GetString("cboVersion.Items32"),
resources.GetString("cboVersion.Items33"),
resources.GetString("cboVersion.Items34"),
resources.GetString("cboVersion.Items35"),
resources.GetString("cboVersion.Items36"),
resources.GetString("cboVersion.Items37"),
resources.GetString("cboVersion.Items38"),
resources.GetString("cboVersion.Items39"),
resources.GetString("cboVersion.Items40")});
this.cboVersion.Name = "cboVersion";
//
// cboEncoding
//
this.cboEncoding.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cboEncoding, "cboEncoding");
this.cboEncoding.FormattingEnabled = true;
this.cboEncoding.Items.AddRange(new object[] {
resources.GetString("cboEncoding.Items"),
resources.GetString("cboEncoding.Items1"),
resources.GetString("cboEncoding.Items2")});
this.cboEncoding.Name = "cboEncoding";
//
// groupBox7
//
this.groupBox7.Controls.Add(this.txtEncodeKey);
this.groupBox7.Controls.Add(this.cboEncryptAlgo);
this.groupBox7.Controls.Add(this.label8);
this.groupBox7.Controls.Add(this.label7);
this.groupBox7.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox7, "groupBox7");
this.groupBox7.Name = "groupBox7";
this.groupBox7.TabStop = false;
//
// txtEncodeKey
//
this.txtEncodeKey.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtEncodeKey, "txtEncodeKey");
this.txtEncodeKey.Name = "txtEncodeKey";
//
// cboEncryptAlgo
//
this.cboEncryptAlgo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cboEncryptAlgo, "cboEncryptAlgo");
this.cboEncryptAlgo.FormattingEnabled = true;
this.cboEncryptAlgo.Items.AddRange(new object[] {
resources.GetString("cboEncryptAlgo.Items"),
resources.GetString("cboEncryptAlgo.Items1"),
resources.GetString("cboEncryptAlgo.Items2"),
resources.GetString("cboEncryptAlgo.Items3")});
this.cboEncryptAlgo.Name = "cboEncryptAlgo";
//
// label8
//
resources.ApplyResources(this.label8, "label8");
this.label8.Name = "label8";
//
// label7
//
resources.ApplyResources(this.label7, "label7");
this.label7.Name = "label7";
//
// tabDecode
//
this.tabDecode.Controls.Add(this.groupBox5);
this.tabDecode.Controls.Add(this.btnOpen);
this.tabDecode.Controls.Add(this.btnDecode);
this.tabDecode.Controls.Add(this.groupBox3);
this.tabDecode.Controls.Add(this.groupBox4);
this.tabDecode.Controls.Add(this.groupBox8);
resources.ApplyResources(this.tabDecode, "tabDecode");
this.tabDecode.Name = "tabDecode";
this.tabDecode.UseVisualStyleBackColor = true;
//
// groupBox5
//
this.groupBox5.Controls.Add(this.txtComManager);
this.groupBox5.Controls.Add(this.label19);
this.groupBox5.Controls.Add(this.txtBusinessScope);
this.groupBox5.Controls.Add(this.label13);
this.groupBox5.Controls.Add(this.txtComName);
this.groupBox5.Controls.Add(this.txtComCode);
this.groupBox5.Controls.Add(this.label6);
this.groupBox5.Controls.Add(this.label1);
this.groupBox5.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox5, "groupBox5");
this.groupBox5.Name = "groupBox5";
this.groupBox5.TabStop = false;
//
// txtComManager
//
this.txtComManager.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtComManager, "txtComManager");
this.txtComManager.Name = "txtComManager";
//
// label19
//
resources.ApplyResources(this.label19, "label19");
this.label19.Name = "label19";
//
// txtBusinessScope
//
this.txtBusinessScope.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtBusinessScope, "txtBusinessScope");
this.txtBusinessScope.Name = "txtBusinessScope";
//
// label13
//
resources.ApplyResources(this.label13, "label13");
this.label13.Name = "label13";
//
// txtComName
//
this.txtComName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtComName, "txtComName");
this.txtComName.Name = "txtComName";
//
// txtComCode
//
this.txtComCode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtComCode, "txtComCode");
this.txtComCode.Name = "txtComCode";
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.Name = "label6";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// btnOpen
//
resources.ApplyResources(this.btnOpen, "btnOpen");
this.btnOpen.Name = "btnOpen";
this.btnOpen.UseVisualStyleBackColor = true;
this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click);
//
// btnDecode
//
resources.ApplyResources(this.btnDecode, "btnDecode");
this.btnDecode.Name = "btnDecode";
this.btnDecode.UseVisualStyleBackColor = true;
this.btnDecode.Click += new System.EventHandler(this.btnDecode_Click);
//
// groupBox3
//
this.groupBox3.Controls.Add(this.btnIdentify);
this.groupBox3.Controls.Add(this.txtDecodedData);
this.groupBox3.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox3, "groupBox3");
this.groupBox3.Name = "groupBox3";
this.groupBox3.TabStop = false;
//
// btnIdentify
//
resources.ApplyResources(this.btnIdentify, "btnIdentify");
this.btnIdentify.Name = "btnIdentify";
this.btnIdentify.UseVisualStyleBackColor = true;
this.btnIdentify.Click += new System.EventHandler(this.btnIdentify_Click);
//
// txtDecodedData
//
this.txtDecodedData.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtDecodedData, "txtDecodedData");
this.txtDecodedData.Name = "txtDecodedData";
this.txtDecodedData.TextChanged += new System.EventHandler(this.ShowStatusLabel);
this.txtDecodedData.Enter += new System.EventHandler(this.ShowStatusLabel);
this.txtDecodedData.Leave += new System.EventHandler(this.ShowStatusLabel);
//
// groupBox4
//
this.groupBox4.Controls.Add(this.picDecode);
this.groupBox4.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox4, "groupBox4");
this.groupBox4.Name = "groupBox4";
this.groupBox4.TabStop = false;
//
// picDecode
//
this.picDecode.BackColor = System.Drawing.Color.White;
resources.ApplyResources(this.picDecode, "picDecode");
this.picDecode.Name = "picDecode";
this.picDecode.TabStop = false;
//
// groupBox8
//
this.groupBox8.Controls.Add(this.cboDecryptAlgo);
this.groupBox8.Controls.Add(this.txtDecodeKey);
this.groupBox8.Controls.Add(this.label10);
this.groupBox8.Controls.Add(this.label9);
this.groupBox8.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox8, "groupBox8");
this.groupBox8.Name = "groupBox8";
this.groupBox8.TabStop = false;
//
// cboDecryptAlgo
//
this.cboDecryptAlgo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cboDecryptAlgo, "cboDecryptAlgo");
this.cboDecryptAlgo.FormattingEnabled = true;
this.cboDecryptAlgo.Items.AddRange(new object[] {
resources.GetString("cboDecryptAlgo.Items"),
resources.GetString("cboDecryptAlgo.Items1"),
resources.GetString("cboDecryptAlgo.Items2"),
resources.GetString("cboDecryptAlgo.Items3")});
this.cboDecryptAlgo.Name = "cboDecryptAlgo";
//
// txtDecodeKey
//
this.txtDecodeKey.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtDecodeKey, "txtDecodeKey");
this.txtDecodeKey.Name = "txtDecodeKey";
//
// label10
//
resources.ApplyResources(this.label10, "label10");
this.label10.Name = "label10";
//
// label9
//
resources.ApplyResources(this.label9, "label9");
this.label9.Name = "label9";
//
// tabSearch
//
this.tabSearch.Controls.Add(this.txtSearch);
this.tabSearch.Controls.Add(this.btnRemove);
this.tabSearch.Controls.Add(this.label17);
this.tabSearch.Controls.Add(this.label15);
this.tabSearch.Controls.Add(this.label14);
this.tabSearch.Controls.Add(this.btnSelectPath);
this.tabSearch.Controls.Add(this.label12);
this.tabSearch.Controls.Add(this.txtSelectPath);
this.tabSearch.Controls.Add(this.btnSearch);
this.tabSearch.Controls.Add(this.lvFileSearch);
this.tabSearch.Controls.Add(this.label11);
this.tabSearch.Controls.Add(this.txtQRCodePath);
this.tabSearch.Controls.Add(this.btnOpen2);
resources.ApplyResources(this.tabSearch, "tabSearch");
this.tabSearch.Name = "tabSearch";
this.tabSearch.UseVisualStyleBackColor = true;
//
// txtSearch
//
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtSearch, "txtSearch");
this.txtSearch.Name = "txtSearch";
//
// btnRemove
//
resources.ApplyResources(this.btnRemove, "btnRemove");
this.btnRemove.Name = "btnRemove";
this.btnRemove.UseVisualStyleBackColor = true;
this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
//
// label17
//
resources.ApplyResources(this.label17, "label17");
this.label17.Name = "label17";
//
// label15
//
resources.ApplyResources(this.label15, "label15");
this.label15.Name = "label15";
//
// label14
//
resources.ApplyResources(this.label14, "label14");
this.label14.Name = "label14";
//
// btnSelectPath
//
resources.ApplyResources(this.btnSelectPath, "btnSelectPath");
this.btnSelectPath.Name = "btnSelectPath";
this.btnSelectPath.UseVisualStyleBackColor = true;
this.btnSelectPath.Click += new System.EventHandler(this.btnSelectPath_Click);
//
// label12
//
resources.ApplyResources(this.label12, "label12");
this.label12.Name = "label12";
//
// txtSelectPath
//
this.txtSelectPath.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtSelectPath, "txtSelectPath");
this.txtSelectPath.Name = "txtSelectPath";
//
// btnSearch
//
resources.ApplyResources(this.btnSearch, "btnSearch");
this.btnSearch.Name = "btnSearch";
this.btnSearch.UseVisualStyleBackColor = true;
this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
//
// lvFileSearch
//
this.lvFileSearch.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lvFileSearch.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2,
this.columnHeader3});
this.lvFileSearch.FullRowSelect = true;
this.lvFileSearch.GridLines = true;
resources.ApplyResources(this.lvFileSearch, "lvFileSearch");
this.lvFileSearch.MultiSelect = false;
this.lvFileSearch.Name = "lvFileSearch";
this.lvFileSearch.UseCompatibleStateImageBehavior = false;
this.lvFileSearch.View = System.Windows.Forms.View.Details;
this.lvFileSearch.SelectedIndexChanged += new System.EventHandler(this.listFileFounded_SelectedIndexChanged);
this.lvFileSearch.DoubleClick += new System.EventHandler(this.listFileFounded_DoubleClick);
//
// columnHeader1
//
resources.ApplyResources(this.columnHeader1, "columnHeader1");
//
// columnHeader2
//
resources.ApplyResources(this.columnHeader2, "columnHeader2");
//
// columnHeader3
//
resources.ApplyResources(this.columnHeader3, "columnHeader3");
//
// label11
//
resources.ApplyResources(this.label11, "label11");
this.label11.Name = "label11";
//
// txtQRCodePath
//
this.txtQRCodePath.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtQRCodePath, "txtQRCodePath");
this.txtQRCodePath.Name = "txtQRCodePath";
//
// btnOpen2
//
resources.ApplyResources(this.btnOpen2, "btnOpen2");
this.btnOpen2.Name = "btnOpen2";
this.btnOpen2.UseVisualStyleBackColor = true;
this.btnOpen2.Click += new System.EventHandler(this.btnOpen2_Click);
//
// tabBatchEncode
//
this.tabBatchEncode.Controls.Add(this.btnCreate);
this.tabBatchEncode.Controls.Add(this.lvBatchEncode);
this.tabBatchEncode.Controls.Add(this.label18);
this.tabBatchEncode.Controls.Add(this.txtFilePath);
this.tabBatchEncode.Controls.Add(this.btnOpen3);
resources.ApplyResources(this.tabBatchEncode, "tabBatchEncode");
this.tabBatchEncode.Name = "tabBatchEncode";
this.tabBatchEncode.UseVisualStyleBackColor = true;
//
// btnCreate
//
resources.ApplyResources(this.btnCreate, "btnCreate");
this.btnCreate.Name = "btnCreate";
this.btnCreate.UseVisualStyleBackColor = true;
this.btnCreate.Click += new System.EventHandler(this.btnCreate_Click);
//
// lvBatchEncode
//
this.lvBatchEncode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lvBatchEncode.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader6,
this.columnHeader7,
this.columnHeader8});
this.lvBatchEncode.FullRowSelect = true;
this.lvBatchEncode.GridLines = true;
resources.ApplyResources(this.lvBatchEncode, "lvBatchEncode");
this.lvBatchEncode.MultiSelect = false;
this.lvBatchEncode.Name = "lvBatchEncode";
this.lvBatchEncode.UseCompatibleStateImageBehavior = false;
this.lvBatchEncode.View = System.Windows.Forms.View.Details;
//
// columnHeader6
//
resources.ApplyResources(this.columnHeader6, "columnHeader6");
//
// columnHeader7
//
resources.ApplyResources(this.columnHeader7, "columnHeader7");
//
// columnHeader8
//
resources.ApplyResources(this.columnHeader8, "columnHeader8");
//
// label18
//
resources.ApplyResources(this.label18, "label18");
this.label18.Name = "label18";
//
// txtFilePath
//
this.txtFilePath.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.txtFilePath, "txtFilePath");
this.txtFilePath.Name = "txtFilePath";
//
// btnOpen3
//
resources.ApplyResources(this.btnOpen3, "btnOpen3");
this.btnOpen3.Name = "btnOpen3";
this.btnOpen3.UseVisualStyleBackColor = true;
this.btnOpen3.Click += new System.EventHandler(this.btnOpen3_Click);
//
// MainForm
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.tabMain);
this.Controls.Add(this.menuStrip);
this.Name = "MainForm";
this.Load += new System.EventHandler(this.frmSample_Load);
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.tabMain.ResumeLayout(false);
this.tabEncode.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.picEncode)).EndInit();
this.groupBox6.ResumeLayout(false);
this.groupBox6.PerformLayout();
this.groupBox7.ResumeLayout(false);
this.groupBox7.PerformLayout();
this.tabDecode.ResumeLayout(false);
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBox4.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.picDecode)).EndInit();
this.groupBox8.ResumeLayout(false);
this.groupBox8.PerformLayout();
this.tabSearch.ResumeLayout(false);
this.tabSearch.PerformLayout();
this.tabBatchEncode.ResumeLayout(false);
this.tabBatchEncode.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private NewTabControl tabMain;
private System.Windows.Forms.TabPage tabEncode;
private System.Windows.Forms.TabPage tabDecode;
private System.Windows.Forms.PictureBox picEncode;
private System.Windows.Forms.TextBox txtEncodeData;
private System.Windows.Forms.ComboBox cboCorrectionLevel;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtSize;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ComboBox cboVersion;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox cboEncoding;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button btnEncode;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Button btnPrint;
private System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.Button btnDecode;
private System.Windows.Forms.TextBox txtDecodedData;
private System.Windows.Forms.PictureBox picDecode;
private System.Windows.Forms.Button btnOpen;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
public System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button btnFormat;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.TextBox txtComName;
private System.Windows.Forms.TextBox txtComCode;
private System.Windows.Forms.Button btnIdentify;
private System.Windows.Forms.ComboBox cboEncryptAlgo;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox txtEncodeKey;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox txtDecodeKey;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.ComboBox cboDecryptAlgo;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TabPage tabSearch;
private System.Windows.Forms.Button btnOpen2;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox txtQRCodePath;
public DoubleBufferListView lvFileSearch;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
public System.Windows.Forms.Button btnSearch;
private System.Windows.Forms.TextBox txtSelectPath;
private System.Windows.Forms.Button btnSelectPath;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.GroupBox groupBox6;
private System.Windows.Forms.GroupBox groupBox7;
private System.Windows.Forms.TextBox txtBusinessScope;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.GroupBox groupBox8;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.TabPage tabBatchEncode;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.TextBox txtFilePath;
private System.Windows.Forms.Button btnOpen3;
public System.Windows.Forms.Button btnCreate;
public DoubleBufferListView lvBatchEncode;
private System.Windows.Forms.ColumnHeader columnHeader6;
private System.Windows.Forms.ColumnHeader columnHeader7;
private System.Windows.Forms.ColumnHeader columnHeader8;
private System.Windows.Forms.TextBox txtComManager;
private System.Windows.Forms.Label label19;
private Sunisoft.IrisSkin.SkinEngine skinEngine;
public System.Windows.Forms.Button btnRemove;
private System.Windows.Forms.TextBox txtSearch;
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using OpenMetaverse.Assets;
namespace OpenMetaverse.Imaging
{
/// <summary>
/// A set of textures that are layered on texture of each other and "baked"
/// in to a single texture, for avatar appearances
/// </summary>
public class Baker
{
#region Properties
/// <summary>Final baked texture</summary>
public AssetTexture BakedTexture { get { return bakedTexture; } }
/// <summary>Component layers</summary>
public List<AppearanceManager.TextureData> Textures { get { return textures; } }
/// <summary>Width of the final baked image and scratchpad</summary>
public int BakeWidth { get { return bakeWidth; } }
/// <summary>Height of the final baked image and scratchpad</summary>
public int BakeHeight { get { return bakeHeight; } }
/// <summary>Bake type</summary>
public BakeType BakeType { get { return bakeType; } }
/// <summary>Is this one of the 3 skin bakes</summary>
private bool IsSkin { get { return bakeType == BakeType.Head || bakeType == BakeType.LowerBody || bakeType == BakeType.UpperBody; } }
#endregion
#region Private fields
/// <summary>Final baked texture</summary>
private AssetTexture bakedTexture;
/// <summary>Component layers</summary>
private List<AppearanceManager.TextureData> textures = new List<AppearanceManager.TextureData>();
/// <summary>Width of the final baked image and scratchpad</summary>
private int bakeWidth;
/// <summary>Height of the final baked image and scratchpad</summary>
private int bakeHeight;
/// <summary>Bake type</summary>
private BakeType bakeType;
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
/// <param name="bakeType">Bake type</param>
public Baker(BakeType bakeType)
{
this.bakeType = bakeType;
if (bakeType == BakeType.Eyes)
{
bakeWidth = 128;
bakeHeight = 128;
}
else
{
bakeWidth = 512;
bakeHeight = 512;
}
}
#endregion
#region Public methods
/// <summary>
/// Adds layer for baking
/// </summary>
/// <param name="tdata">TexturaData struct that contains texture and its params</param>
public void AddTexture(AppearanceManager.TextureData tdata)
{
lock (textures)
{
textures.Add(tdata);
}
}
public void Bake()
{
bakedTexture = new AssetTexture(new ManagedImage(bakeWidth, bakeHeight,
ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha | ManagedImage.ImageChannels.Bump));
// Base color for eye bake is white, color of layer0 for others
if (bakeType == BakeType.Eyes)
{
InitBakedLayerColor(Color4.White);
}
else if (textures.Count > 0)
{
InitBakedLayerColor(textures[0].Color);
}
// Do we have skin texture?
bool SkinTexture = textures.Count > 0 && textures[0].Texture != null;
if (bakeType == BakeType.Head)
{
DrawLayer(LoadResourceLayer("head_color.tga"), false);
AddAlpha(bakedTexture.Image, LoadResourceLayer("head_alpha.tga"));
MultiplyLayerFromAlpha(bakedTexture.Image, LoadResourceLayer("head_skingrain.tga"));
}
if (!SkinTexture && bakeType == BakeType.UpperBody)
{
DrawLayer(LoadResourceLayer("upperbody_color.tga"), false);
}
if (!SkinTexture && bakeType == BakeType.LowerBody)
{
DrawLayer(LoadResourceLayer("lowerbody_color.tga"), false);
}
// Layer each texture on top of one other, applying alpha masks as we go
for (int i = 0; i < textures.Count; i++)
{
// Skip if we have no texture on this layer
if (textures[i].Texture == null) continue;
// Don't draw skin on head bake first
// For head bake skin texture is drawn last, go figure
if (bakeType == BakeType.Head && i == 0) continue;
ManagedImage texture = textures[i].Texture.Image.Clone();
//File.WriteAllBytes(bakeType + "-texture-layer-" + i + ".tga", texture.ExportTGA());
// Resize texture to the size of baked layer
// FIXME: if texture is smaller than the layer, don't stretch it, tile it
if (texture.Width != bakeWidth || texture.Height != bakeHeight)
{
try { texture.ResizeNearestNeighbor(bakeWidth, bakeHeight); }
catch (Exception) { continue; }
}
// Special case for hair layer for the head bake
// If we don't have skin texture, we discard hair alpha
// and apply hair pattern over the texture
if (!SkinTexture && bakeType == BakeType.Head && i == 1)
{
if (texture.Alpha != null)
{
for (int j = 0; j < texture.Alpha.Length; j++) texture.Alpha[j] = (byte)255;
}
MultiplyLayerFromAlpha(texture, LoadResourceLayer("head_hair.tga"));
}
// Aply tint and alpha masks except for skin that has a texture
// on layer 0 which always overrides other skin settings
if (!(IsSkin && i == 0))
{
ApplyTint(texture, textures[i].Color);
// For hair bake, we skip all alpha masks
// and use one from the texture, for both
// alpha and morph layers
if (bakeType == BakeType.Hair)
{
if (texture.Alpha != null)
{
bakedTexture.Image.Bump = texture.Alpha;
}
else
{
for (int j = 0; j < bakedTexture.Image.Bump.Length; j++) bakedTexture.Image.Bump[j] = byte.MaxValue;
}
}
// Apply parametrized alpha masks
else if (textures[i].AlphaMasks != null && textures[i].AlphaMasks.Count > 0)
{
// Combined mask for the layer, fully transparent to begin with
ManagedImage combinedMask = new ManagedImage(bakeWidth, bakeHeight, ManagedImage.ImageChannels.Alpha);
int addedMasks = 0;
// First add mask in normal blend mode
foreach (KeyValuePair<VisualAlphaParam, float> kvp in textures[i].AlphaMasks)
{
if (!MaskBelongsToBake(kvp.Key.TGAFile)) continue;
if (kvp.Key.MultiplyBlend == false && (kvp.Value > 0f || !kvp.Key.SkipIfZero))
{
ApplyAlpha(combinedMask, kvp.Key, kvp.Value);
//File.WriteAllBytes(bakeType + "-layer-" + i + "-mask-" + addedMasks + ".tga", combinedMask.ExportTGA());
addedMasks++;
}
}
// If there were no mask in normal blend mode make aplha fully opaque
if (addedMasks == 0) for (int l = 0; l < combinedMask.Alpha.Length; l++) combinedMask.Alpha[l] = 255;
// Add masks in multiply blend mode
foreach (KeyValuePair<VisualAlphaParam, float> kvp in textures[i].AlphaMasks)
{
if (!MaskBelongsToBake(kvp.Key.TGAFile)) continue;
if (kvp.Key.MultiplyBlend == true && (kvp.Value > 0f || !kvp.Key.SkipIfZero))
{
ApplyAlpha(combinedMask, kvp.Key, kvp.Value);
//File.WriteAllBytes(bakeType + "-layer-" + i + "-mask-" + addedMasks + ".tga", combinedMask.ExportTGA());
addedMasks++;
}
}
if (addedMasks > 0)
{
// Apply combined alpha mask to the cloned texture
AddAlpha(texture, combinedMask);
// Is this layer used for morph mask? If it is, use its
// alpha as the morth for the whole bake
if (i == AppearanceManager.MorphLayerForBakeType(bakeType))
{
bakedTexture.Image.Bump = combinedMask.Alpha;
}
}
//File.WriteAllBytes(bakeType + "-masked-texture-" + i + ".tga", texture.ExportTGA());
}
}
bool useAlpha = i == 0 && (BakeType == BakeType.Skirt || BakeType == BakeType.Hair);
DrawLayer(texture, useAlpha);
//File.WriteAllBytes(bakeType + "-layer-" + i + ".tga", texture.ExportTGA());
}
// For head, we add skin last
if (SkinTexture && bakeType == BakeType.Head)
{
ManagedImage texture = textures[0].Texture.Image.Clone();
if (texture.Width != bakeWidth || texture.Height != bakeHeight)
{
try { texture.ResizeNearestNeighbor(bakeWidth, bakeHeight); }
catch (Exception) { }
}
DrawLayer(texture, false);
}
// We are done, encode asset for finalized bake
bakedTexture.Encode();
//File.WriteAllBytes(bakeType + ".tga", bakedTexture.Image.ExportTGA());
}
private static object ResourceSync = new object();
public static ManagedImage LoadResourceLayer(string fileName)
{
try
{
Bitmap bitmap = null;
lock (ResourceSync)
{
using (Stream stream = Helpers.GetResourceStream(fileName, Settings.RESOURCE_DIR))
{
bitmap = LoadTGAClass.LoadTGA(stream);
}
}
if (bitmap == null)
{
Logger.Log(String.Format("Failed loading resource file: {0}", fileName), Helpers.LogLevel.Error);
return null;
}
else
{
return new ManagedImage(bitmap);
}
}
catch (Exception e)
{
Logger.Log(String.Format("Failed loading resource file: {0} ({1})", fileName, e.Message),
Helpers.LogLevel.Error, e);
return null;
}
}
/// <summary>
/// Converts avatar texture index (face) to Bake type
/// </summary>
/// <param name="index">Face number (AvatarTextureIndex)</param>
/// <returns>BakeType, layer to which this texture belongs to</returns>
public static BakeType BakeTypeFor(AvatarTextureIndex index)
{
switch (index)
{
case AvatarTextureIndex.HeadBodypaint:
return BakeType.Head;
case AvatarTextureIndex.UpperBodypaint:
case AvatarTextureIndex.UpperGloves:
case AvatarTextureIndex.UpperUndershirt:
case AvatarTextureIndex.UpperShirt:
case AvatarTextureIndex.UpperJacket:
return BakeType.UpperBody;
case AvatarTextureIndex.LowerBodypaint:
case AvatarTextureIndex.LowerUnderpants:
case AvatarTextureIndex.LowerSocks:
case AvatarTextureIndex.LowerShoes:
case AvatarTextureIndex.LowerPants:
case AvatarTextureIndex.LowerJacket:
return BakeType.LowerBody;
case AvatarTextureIndex.EyesIris:
return BakeType.Eyes;
case AvatarTextureIndex.Skirt:
return BakeType.Skirt;
case AvatarTextureIndex.Hair:
return BakeType.Hair;
default:
return BakeType.Unknown;
}
}
#endregion
#region Private layer compositing methods
private bool MaskBelongsToBake(string mask)
{
if ((bakeType == BakeType.LowerBody && mask.Contains("upper"))
|| (bakeType == BakeType.LowerBody && mask.Contains("shirt"))
|| (bakeType == BakeType.UpperBody && mask.Contains("lower")))
{
return false;
}
else
{
return true;
}
}
private bool DrawLayer(ManagedImage source, bool addSourceAlpha)
{
if (source == null) return false;
bool sourceHasColor;
bool sourceHasAlpha;
bool sourceHasBump;
int i = 0;
sourceHasColor = ((source.Channels & ManagedImage.ImageChannels.Color) != 0 &&
source.Red != null && source.Green != null && source.Blue != null);
sourceHasAlpha = ((source.Channels & ManagedImage.ImageChannels.Alpha) != 0 && source.Alpha != null);
sourceHasBump = ((source.Channels & ManagedImage.ImageChannels.Bump) != 0 && source.Bump != null);
addSourceAlpha = (addSourceAlpha && sourceHasAlpha);
byte alpha = Byte.MaxValue;
byte alphaInv = (byte)(Byte.MaxValue - alpha);
byte[] bakedRed = bakedTexture.Image.Red;
byte[] bakedGreen = bakedTexture.Image.Green;
byte[] bakedBlue = bakedTexture.Image.Blue;
byte[] bakedAlpha = bakedTexture.Image.Alpha;
byte[] bakedBump = bakedTexture.Image.Bump;
byte[] sourceRed = source.Red;
byte[] sourceGreen = source.Green;
byte[] sourceBlue = source.Blue;
byte[] sourceAlpha = sourceHasAlpha ? source.Alpha : null;
byte[] sourceBump = sourceHasBump ? source.Bump : null;
for (int y = 0; y < bakeHeight; y++)
{
for (int x = 0; x < bakeWidth; x++)
{
if (sourceHasAlpha)
{
alpha = sourceAlpha[i];
alphaInv = (byte)(Byte.MaxValue - alpha);
}
if (sourceHasColor)
{
bakedRed[i] = (byte)((bakedRed[i] * alphaInv + sourceRed[i] * alpha) >> 8);
bakedGreen[i] = (byte)((bakedGreen[i] * alphaInv + sourceGreen[i] * alpha) >> 8);
bakedBlue[i] = (byte)((bakedBlue[i] * alphaInv + sourceBlue[i] * alpha) >> 8);
}
if (addSourceAlpha)
{
if (sourceAlpha[i] < bakedAlpha[i])
{
bakedAlpha[i] = sourceAlpha[i];
}
}
if (sourceHasBump)
bakedBump[i] = sourceBump[i];
++i;
}
}
return true;
}
/// <summary>
/// Make sure images exist, resize source if needed to match the destination
/// </summary>
/// <param name="dest">Destination image</param>
/// <param name="src">Source image</param>
/// <returns>Sanitization was succefull</returns>
private bool SanitizeLayers(ManagedImage dest, ManagedImage src)
{
if (dest == null || src == null) return false;
if ((dest.Channels & ManagedImage.ImageChannels.Alpha) == 0)
{
dest.ConvertChannels(dest.Channels | ManagedImage.ImageChannels.Alpha);
}
if (dest.Width != src.Width || dest.Height != src.Height)
{
try { src.ResizeNearestNeighbor(dest.Width, dest.Height); }
catch (Exception) { return false; }
}
return true;
}
private void ApplyAlpha(ManagedImage dest, VisualAlphaParam param, float val)
{
ManagedImage src = LoadResourceLayer(param.TGAFile);
if (dest == null || src == null || src.Alpha == null) return;
if ((dest.Channels & ManagedImage.ImageChannels.Alpha) == 0)
{
dest.ConvertChannels(ManagedImage.ImageChannels.Alpha | dest.Channels);
}
if (dest.Width != src.Width || dest.Height != src.Height)
{
try { src.ResizeNearestNeighbor(dest.Width, dest.Height); }
catch (Exception) { return; }
}
for (int i = 0; i < dest.Alpha.Length; i++)
{
byte alpha = src.Alpha[i] <= ((1 - val) * 255) ? (byte)0 : (byte)255;
if (param.MultiplyBlend)
{
dest.Alpha[i] = (byte)((dest.Alpha[i] * alpha) >> 8);
}
else
{
if (alpha > dest.Alpha[i])
{
dest.Alpha[i] = alpha;
}
}
}
}
private void AddAlpha(ManagedImage dest, ManagedImage src)
{
if (!SanitizeLayers(dest, src)) return;
for (int i = 0; i < dest.Alpha.Length; i++)
{
if (src.Alpha[i] < dest.Alpha[i])
{
dest.Alpha[i] = src.Alpha[i];
}
}
}
private void MultiplyLayerFromAlpha(ManagedImage dest, ManagedImage src)
{
if (!SanitizeLayers(dest, src)) return;
for (int i = 0; i < dest.Red.Length; i++)
{
dest.Red[i] = (byte)((dest.Red[i] * src.Alpha[i]) >> 8);
dest.Green[i] = (byte)((dest.Green[i] * src.Alpha[i]) >> 8);
dest.Blue[i] = (byte)((dest.Blue[i] * src.Alpha[i]) >> 8);
}
}
private void ApplyTint(ManagedImage dest, Color4 src)
{
if (dest == null) return;
for (int i = 0; i < dest.Red.Length; i++)
{
dest.Red[i] = (byte)((dest.Red[i] * Utils.FloatToByte(src.R, 0f, 1f)) >> 8);
dest.Green[i] = (byte)((dest.Green[i] * Utils.FloatToByte(src.G, 0f, 1f)) >> 8);
dest.Blue[i] = (byte)((dest.Blue[i] * Utils.FloatToByte(src.B, 0f, 1f)) >> 8);
}
}
/// <summary>
/// Fills a baked layer as a solid *appearing* color. The colors are
/// subtly dithered on a 16x16 grid to prevent the JPEG2000 stage from
/// compressing it too far since it seems to cause upload failures if
/// the image is a pure solid color
/// </summary>
/// <param name="color">Color of the base of this layer</param>
private void InitBakedLayerColor(Color4 color)
{
InitBakedLayerColor(color.R, color.G, color.B);
}
/// <summary>
/// Fills a baked layer as a solid *appearing* color. The colors are
/// subtly dithered on a 16x16 grid to prevent the JPEG2000 stage from
/// compressing it too far since it seems to cause upload failures if
/// the image is a pure solid color
/// </summary>
/// <param name="r">Red value</param>
/// <param name="g">Green value</param>
/// <param name="b">Blue value</param>
private void InitBakedLayerColor(float r, float g, float b)
{
byte rByte = Utils.FloatToByte(r, 0f, 1f);
byte gByte = Utils.FloatToByte(g, 0f, 1f);
byte bByte = Utils.FloatToByte(b, 0f, 1f);
byte rAlt, gAlt, bAlt;
rAlt = rByte;
gAlt = gByte;
bAlt = bByte;
if (rByte < Byte.MaxValue)
rAlt++;
else rAlt--;
if (gByte < Byte.MaxValue)
gAlt++;
else gAlt--;
if (bByte < Byte.MaxValue)
bAlt++;
else bAlt--;
int i = 0;
byte[] red = bakedTexture.Image.Red;
byte[] green = bakedTexture.Image.Green;
byte[] blue = bakedTexture.Image.Blue;
byte[] alpha = bakedTexture.Image.Alpha;
byte[] bump = bakedTexture.Image.Bump;
for (int y = 0; y < bakeHeight; y++)
{
for (int x = 0; x < bakeWidth; x++)
{
if (((x ^ y) & 0x10) == 0)
{
red[i] = rAlt;
green[i] = gByte;
blue[i] = bByte;
alpha[i] = Byte.MaxValue;
bump[i] = 0;
}
else
{
red[i] = rByte;
green[i] = gAlt;
blue[i] = bAlt;
alpha[i] = Byte.MaxValue;
bump[i] = 0;
}
++i;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
/// <summary>
/// System.Collections.Generic.List.LastIndexOf(T item, Int32,Int32)
/// </summary>
public class ListLastIndexOf3
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int");
try
{
int[] iArray = new int[1000];
for (int i = 0; i < 1000; i++)
{
iArray[i] = i;
}
List<int> listObject = new List<int>(iArray);
int ob = this.GetInt32(0, 1000);
int result = listObject.LastIndexOf(ob, 999, 1000);
if (result != ob)
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string");
try
{
string[] strArray = { "apple", "dog", "banana", "chocolate", "dog", "food" };
List<string> listObject = new List<string>(strArray);
int result = listObject.LastIndexOf("dog", 3, 3);
if (result != 1)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type");
try
{
MyClass myclass1 = new MyClass();
MyClass myclass2 = new MyClass();
MyClass myclass3 = new MyClass();
MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 };
List<MyClass> listObject = new List<MyClass>(mc);
int result = listObject.LastIndexOf(myclass3, 2, 1);
if (result != 2)
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: There are many element in the list with the same value");
try
{
string[] strArray = { "apple", "banana", "chocolate", "banana", "banana", "dog", "banana", "food" };
List<string> listObject = new List<string>(strArray);
int result = listObject.LastIndexOf("banana", 2, 3);
if (result != 1)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Do not find the element ");
try
{
int[] iArray = { 1, 9, -8, 3, 6, -1, 8, 7, -11, 2, 4 };
List<int> listObject = new List<int>(iArray);
int result = listObject.LastIndexOf(-11, 6, 4);
if (result != -1)
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected,result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The index is negative");
try
{
int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 };
List<int> listObject = new List<int>(iArray);
int result = listObject.LastIndexOf(-11, -4, 3);
TestLibrary.TestFramework.LogError("101", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: index and count do not specify a valid section in the List");
try
{
int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 };
List<int> listObject = new List<int>(iArray);
int result = listObject.LastIndexOf(-11, 6, 10);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: The count is a negative number");
try
{
int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 };
List<int> listObject = new List<int>(iArray);
int result = listObject.LastIndexOf(-11, 1, -1);
TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ListLastIndexOf3 test = new ListLastIndexOf3();
TestLibrary.TestFramework.BeginTestCase("ListLastIndexOf3");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
}
public class MyClass
{
}
| |
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 _03.WebApi.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;
}
}
}
| |
namespace Ocelot.AcceptanceTests
{
using System;
using System.Collections.Generic;
using System.Net;
using Microsoft.AspNetCore.Http;
using Ocelot.Configuration.File;
using TestStack.BDDfy;
using Xunit;
public class RoutingWithQueryStringTests : IDisposable
{
private readonly Steps _steps;
private readonly ServiceHandler _serviceHandler;
public RoutingWithQueryStringTests()
{
_serviceHandler = new ServiceHandler();
_steps = new Steps();
}
[Fact]
public void should_return_response_200_with_query_string_template()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 61879,
}
},
UpstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:61879", $"/api/subscriptions/{subscriptionId}/updates", $"?unitId={unitId}", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/units/{subscriptionId}/{unitId}/updates"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
.BDDfy();
}
[Fact]
public void should_return_response_200_with_odata_query_string()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var port = 57359;
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/{everything}",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = port,
}
},
UpstreamPathTemplate = "/{everything}",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/odata/customers", "?$filter=Name%20eq%20'Sam'", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/odata/customers?$filter=Name eq 'Sam' "))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
.BDDfy();
}
[Fact]
public void should_return_response_200_with_query_string_upstream_template()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 64879,
}
},
UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:64879", $"/api/units/{subscriptionId}/{unitId}/updates", "", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates?unitId={unitId}"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
.BDDfy();
}
[Fact]
public void should_return_response_404_with_query_string_upstream_template_no_query_string()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 64879,
}
},
UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:64879", $"/api/units/{subscriptionId}/{unitId}/updates", "", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.NotFound))
.BDDfy();
}
[Fact]
public void should_return_response_404_with_query_string_upstream_template_different_query_string()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 64879,
}
},
UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:64879", $"/api/units/{subscriptionId}/{unitId}/updates", "", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates?test=1"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.NotFound))
.BDDfy();
}
[Fact]
public void should_return_response_200_with_query_string_upstream_template_multiple_params()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 64879,
}
},
UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:64879", $"/api/units/{subscriptionId}/{unitId}/updates", "?productId=1", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates?unitId={unitId}&productId=1"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
.BDDfy();
}
private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, string queryString, int statusCode, string responseBody)
{
_serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, async context =>
{
if ((context.Request.PathBase.Value != basePath) || context.Request.QueryString.Value != queryString)
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync("downstream path didnt match base path");
}
else
{
context.Response.StatusCode = statusCode;
await context.Response.WriteAsync(responseBody);
}
});
}
public void Dispose()
{
_serviceHandler?.Dispose();
_steps.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace MS.Internal.Xml.XPath
{
using System;
using Microsoft.Xml;
using Microsoft.Xml.XPath;
using Microsoft.Xml.Xsl;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
internal sealed class SortQuery : Query
{
private List<SortKey> _results;
private XPathSortComparer _comparer;
private Query _qyInput;
public SortQuery(Query qyInput)
{
Debug.Assert(qyInput != null, "Sort Query needs an input query tree to work on");
_results = new List<SortKey>();
_comparer = new XPathSortComparer();
_qyInput = qyInput;
count = 0;
}
private SortQuery(SortQuery other) : base(other)
{
_results = new List<SortKey>(other._results);
_comparer = other._comparer.Clone();
_qyInput = Clone(other._qyInput);
count = 0;
}
public override void Reset() { count = 0; }
public override void SetXsltContext(XsltContext xsltContext)
{
_qyInput.SetXsltContext(xsltContext);
if (
_qyInput.StaticType != XPathResultType.NodeSet &&
_qyInput.StaticType != XPathResultType.Any
)
{
throw XPathException.Create(ResXml.Xp_NodeSetExpected);
}
}
private void BuildResultsList()
{
Int32 numSorts = _comparer.NumSorts;
Debug.Assert(numSorts > 0, "Why was the sort query created?");
XPathNavigator eNext;
while ((eNext = _qyInput.Advance()) != null)
{
SortKey key = new SortKey(numSorts, /*originalPosition:*/_results.Count, eNext.Clone());
for (Int32 j = 0; j < numSorts; j++)
{
key[j] = _comparer.Expression(j).Evaluate(_qyInput);
}
_results.Add(key);
}
_results.Sort(_comparer);
}
public override object Evaluate(XPathNodeIterator context)
{
_qyInput.Evaluate(context);
_results.Clear();
BuildResultsList();
count = 0;
return this;
}
public override XPathNavigator Advance()
{
Debug.Assert(0 <= count && count <= _results.Count);
if (count < _results.Count)
{
return _results[count++].Node;
}
return null;
}
public override XPathNavigator Current
{
get
{
Debug.Assert(0 <= count && count <= _results.Count);
if (count == 0)
{
return null;
}
return _results[count - 1].Node;
}
}
internal void AddSort(Query evalQuery, IComparer comparer)
{
_comparer.AddSort(evalQuery, comparer);
}
public override XPathNodeIterator Clone() { return new SortQuery(this); }
public override XPathResultType StaticType { get { return XPathResultType.NodeSet; } }
public override int CurrentPosition { get { return count; } }
public override int Count { get { return _results.Count; } }
public override QueryProps Properties { get { return QueryProps.Cached | QueryProps.Position | QueryProps.Count; } }
public override void PrintQuery(XmlWriter w)
{
w.WriteStartElement(this.GetType().Name);
_qyInput.PrintQuery(w);
w.WriteElementString("XPathSortComparer", "... PrintTree() not implemented ...");
w.WriteEndElement();
}
} // class SortQuery
internal sealed class SortKey
{
private Int32 _numKeys;
private object[] _keys;
private int _originalPosition;
private XPathNavigator _node;
public SortKey(int numKeys, int originalPosition, XPathNavigator node)
{
_numKeys = numKeys;
_keys = new object[numKeys];
_originalPosition = originalPosition;
_node = node;
}
public object this[int index]
{
get { return _keys[index]; }
set { _keys[index] = value; }
}
public int NumKeys { get { return _numKeys; } }
public int OriginalPosition { get { return _originalPosition; } }
public XPathNavigator Node { get { return _node; } }
} // class SortKey
internal sealed class XPathSortComparer : IComparer<SortKey>
{
private const int minSize = 3;
private Query[] _expressions;
private IComparer[] _comparers;
private int _numSorts;
public XPathSortComparer(int size)
{
if (size <= 0) size = minSize;
_expressions = new Query[size];
_comparers = new IComparer[size];
}
public XPathSortComparer() : this(minSize) { }
public void AddSort(Query evalQuery, IComparer comparer)
{
Debug.Assert(_expressions.Length == _comparers.Length);
Debug.Assert(0 < _expressions.Length);
Debug.Assert(0 <= _numSorts && _numSorts <= _expressions.Length);
// Ajust array sizes if needed.
if (_numSorts == _expressions.Length)
{
Query[] newExpressions = new Query[_numSorts * 2];
IComparer[] newComparers = new IComparer[_numSorts * 2];
for (int i = 0; i < _numSorts; i++)
{
newExpressions[i] = _expressions[i];
newComparers[i] = _comparers[i];
}
_expressions = newExpressions;
_comparers = newComparers;
}
Debug.Assert(_numSorts < _expressions.Length);
// Fixup expression to handle node-set return type:
if (evalQuery.StaticType == XPathResultType.NodeSet || evalQuery.StaticType == XPathResultType.Any)
{
evalQuery = new StringFunctions(Function.FunctionType.FuncString, new Query[] { evalQuery });
}
_expressions[_numSorts] = evalQuery;
_comparers[_numSorts] = comparer;
_numSorts++;
}
public int NumSorts { get { return _numSorts; } }
public Query Expression(int i)
{
return _expressions[i];
}
int IComparer<SortKey>.Compare(SortKey x, SortKey y)
{
Debug.Assert(x != null && y != null, "Oops!! what happened?");
int result = 0;
for (int i = 0; i < x.NumKeys; i++)
{
result = _comparers[i].Compare(x[i], y[i]);
if (result != 0)
{
return result;
}
}
// if after all comparisions, the two sort keys are still equal, preserve the doc order
return x.OriginalPosition - y.OriginalPosition;
}
internal XPathSortComparer Clone()
{
XPathSortComparer clone = new XPathSortComparer(_numSorts);
for (int i = 0; i < _numSorts; i++)
{
clone._comparers[i] = _comparers[i];
clone._expressions[i] = (Query)_expressions[i].Clone(); // Expressions should be cloned because Query should be cloned
}
clone._numSorts = _numSorts;
return clone;
}
} // class XPathSortComparer
} // namespace
| |
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Hazelcast.Client.Connection;
using Hazelcast.Client.Protocol.Codec;
using Hazelcast.Client.Proxy;
using Hazelcast.Client.Spi;
using Hazelcast.Config;
using Hazelcast.Core;
using Hazelcast.IO.Serialization;
using Hazelcast.NearCache;
using Hazelcast.Net.Ext;
using Hazelcast.Partition.Strategy;
using Hazelcast.Transaction;
using Hazelcast.Util;
namespace Hazelcast.Client
{
/// <summary>
/// Hazelcast Client enables you to do all Hazelcast operations without
/// being a member of the cluster.
/// </summary>
/// <remarks>
/// Hazelcast Client enables you to do all Hazelcast operations without
/// being a member of the cluster. It connects to one of the
/// cluster members and delegates all cluster wide operations to it.
/// When the connected cluster member dies, client will
/// automatically switch to another live member.
/// </remarks>
public sealed class HazelcastClient : IHazelcastInstance
{
public const string PropPartitioningStrategyClass = "hazelcast.partitioning.strategy.class";
private static readonly AtomicInteger ClientId = new AtomicInteger();
private static readonly ConcurrentDictionary<int, HazelcastClientProxy> Clients =
new ConcurrentDictionary<int, HazelcastClientProxy>();
private readonly ClientClusterService _clusterService;
private readonly ClientConfig _config;
private readonly ClientConnectionManager _connectionManager;
private readonly IClientExecutionService _executionService;
private readonly int _id = ClientId.GetAndIncrement();
private readonly string _instanceName;
private readonly ClientInvocationService _invocationService;
private readonly LifecycleService _lifecycleService;
private readonly ClientListenerService _listenerService;
private readonly ILoadBalancer _loadBalancer;
private readonly ClientPartitionService _partitionService;
private readonly ProxyManager _proxyManager;
private readonly ISerializationService _serializationService;
private readonly ConcurrentDictionary<string, object> _userContext;
private readonly ClientLockReferenceIdGenerator _lockReferenceIdGenerator;
private readonly Statistics _statistics;
private readonly NearCacheManager _nearCacheManager;
private HazelcastClient(ClientConfig config)
{
_config = config;
var groupConfig = config.GetGroupConfig();
_instanceName = "hz.client_" + _id + (groupConfig != null ? "_" + groupConfig.GetName() : string.Empty);
_lifecycleService = new LifecycleService(this);
try
{
//TODO make partition strategy parametric
var partitioningStrategy = new DefaultPartitioningStrategy();
_serializationService =
new SerializationServiceBuilder().SetManagedContext(new HazelcastClientManagedContext(this,
config.GetManagedContext()))
.SetConfig(config.GetSerializationConfig())
.SetPartitioningStrategy(partitioningStrategy)
.SetVersion(SerializationService.SerializerVersion)
.Build();
}
catch (Exception e)
{
throw ExceptionUtil.Rethrow(e);
}
_proxyManager = new ProxyManager(this);
//TODO EXECUTION SERVICE
_executionService = new ClientExecutionService(_instanceName, config.GetExecutorPoolSize());
_clusterService = new ClientClusterService(this);
_loadBalancer = config.GetLoadBalancer() ?? new RoundRobinLB();
_connectionManager = new ClientConnectionManager(this);
_invocationService = CreateInvocationService();
_listenerService = new ClientListenerService(this);
_userContext = new ConcurrentDictionary<string, object>();
_partitionService = new ClientPartitionService(this);
_lockReferenceIdGenerator = new ClientLockReferenceIdGenerator();
_statistics = new Statistics(this);
_nearCacheManager = new NearCacheManager(this);
}
/// <inheritdoc />
public string GetName()
{
return _instanceName;
}
/// <inheritdoc />
public IQueue<T> GetQueue<T>(string name)
{
return GetDistributedObject<IQueue<T>>(ServiceNames.Queue, name);
}
/// <inheritdoc />
public IRingbuffer<T> GetRingbuffer<T>(string name)
{
return GetDistributedObject<IRingbuffer<T>>(ServiceNames.Ringbuffer, name);
}
/// <inheritdoc />
public ITopic<T> GetTopic<T>(string name)
{
return GetDistributedObject<ITopic<T>>(ServiceNames.Topic, name);
}
/// <inheritdoc />
public IHSet<T> GetSet<T>(string name)
{
return GetDistributedObject<IHSet<T>>(ServiceNames.Set, name);
}
/// <inheritdoc />
public IHList<T> GetList<T>(string name)
{
return GetDistributedObject<IHList<T>>(ServiceNames.List, name);
}
/// <inheritdoc />
public IMap<TKey, TValue> GetMap<TKey, TValue>(string name)
{
return GetDistributedObject<IMap<TKey, TValue>>(ServiceNames.Map, name);
}
/// <inheritdoc />
public IMultiMap<TKey, TValue> GetMultiMap<TKey, TValue>(string name)
{
return GetDistributedObject<IMultiMap<TKey, TValue>>(ServiceNames.MultiMap, name);
}
/// <inheritdoc />
public IReplicatedMap<TKey, TValue> GetReplicatedMap<TKey, TValue>(string name)
{
return GetDistributedObject<IReplicatedMap<TKey, TValue>>(ServiceNames.ReplicatedMap, name);
}
/// <inheritdoc />
public ILock GetLock(string key)
{
return GetDistributedObject<ILock>(ServiceNames.Lock, key);
}
/// <inheritdoc />
public ICluster GetCluster()
{
return new ClientClusterProxy(_clusterService);
}
/// <inheritdoc />
public IEndpoint GetLocalEndpoint()
{
return _clusterService.GetLocalClient();
}
/// <inheritdoc />
public ITransactionContext NewTransactionContext()
{
return NewTransactionContext(TransactionOptions.GetDefault());
}
/// <inheritdoc />
public ITransactionContext NewTransactionContext(TransactionOptions options)
{
return new TransactionContextProxy(this, options);
}
/// <inheritdoc />
public IIdGenerator GetIdGenerator(string name)
{
return GetDistributedObject<IIdGenerator>(ServiceNames.IdGenerator, name);
}
/// <inheritdoc />
public IAtomicLong GetAtomicLong(string name)
{
return GetDistributedObject<IAtomicLong>(ServiceNames.AtomicLong, name);
}
/// <inheritdoc />
public ICountDownLatch GetCountDownLatch(string name)
{
return GetDistributedObject<ICountDownLatch>(ServiceNames.CountDownLatch, name);
}
/// <inheritdoc />
public ISemaphore GetSemaphore(string name)
{
return GetDistributedObject<ISemaphore>(ServiceNames.Semaphore, name);
}
/// <inheritdoc />
public ICollection<IDistributedObject> GetDistributedObjects()
{
return _proxyManager.GetDistributedObjects();
}
/// <inheritdoc />
public string AddDistributedObjectListener(IDistributedObjectListener distributedObjectListener)
{
return _proxyManager.AddDistributedObjectListener(distributedObjectListener);
}
/// <inheritdoc />
public bool RemoveDistributedObjectListener(string registrationId)
{
return _proxyManager.RemoveDistributedObjectListener(registrationId);
}
/// <inheritdoc />
public IClientService GetClientService()
{
throw new NotSupportedException();
}
/// <inheritdoc />
public ILifecycleService GetLifecycleService()
{
return _lifecycleService;
}
/// <inheritdoc />
public T GetDistributedObject<T>(string serviceName, string name) where T : IDistributedObject
{
var clientProxy = _proxyManager.GetOrCreateProxy<T>(serviceName, name);
return (T) ((IDistributedObject) clientProxy);
}
/// <inheritdoc />
public ConcurrentDictionary<string, object> GetUserContext()
{
return _userContext;
}
/// <inheritdoc />
public void Shutdown()
{
GetLifecycleService().Shutdown();
}
/// <summary>
/// Gets all Hazelcast clients.
/// </summary>
/// <returns>ICollection<IHazelcastInstance></returns>
public static ICollection<IHazelcastInstance> GetAllHazelcastClients()
{
return (ICollection<IHazelcastInstance>) Clients.Values;
}
/// <summary>
/// Gets the configured <see cref="ILoadBalancer"/> instance
/// </summary>
/// <returns></returns>
public ILoadBalancer GetLoadBalancer()
{
return _loadBalancer;
}
/// <summary>
/// Not supported yet.
/// </summary>
/// <exception cref="NotSupportedException"></exception>
public IClientPartitionService GetPartitionService()
{
throw new NotSupportedException("not supported yet");
}
/// <summary>
/// Creates a new hazelcast client using default configuration.
/// </summary>
/// <remarks>
/// Creates a new hazelcast client using default configuration.
/// </remarks>
/// <returns>IHazelcastInstance.</returns>
/// <example>
/// <code>
/// var hazelcastInstance = Hazelcast.NewHazelcastClient();
/// var myMap = hazelcastInstance.GetMap("myMap");
/// </code>
/// </example>
public static IHazelcastInstance NewHazelcastClient()
{
return NewHazelcastClient(XmlClientConfigBuilder.Build());
}
/// <summary>
/// Creates a new hazelcast client using the given configuration xml file
/// </summary>
/// <param name="configFile">The configuration file with full or relative path.</param>
/// <returns>IHazelcastInstance.</returns>
/// <example>
/// <code>
/// //Full path
/// var hazelcastInstance = Hazelcast.NewHazelcastClient(@"C:\Users\user\Hazelcast.Net\hazelcast-client.xml");
/// var myMap = hazelcastInstance.GetMap("myMap");
///
/// //relative path
/// var hazelcastInstance = Hazelcast.NewHazelcastClient(@"..\Hazelcast.Net\Resources\hazelcast-client.xml");
/// var myMap = hazelcastInstance.GetMap("myMap");
/// </code>
/// </example>
public static IHazelcastInstance NewHazelcastClient(string configFile)
{
return NewHazelcastClient(XmlClientConfigBuilder.Build(configFile));
}
/// <summary>
/// Creates a new hazelcast client using the given configuration object created programmaticly.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>IHazelcastInstance.</returns>
/// <code>
/// var clientConfig = new ClientConfig();
/// //configure clientConfig ...
/// var hazelcastInstance = Hazelcast.NewHazelcastClient(clientConfig);
/// var myMap = hazelcastInstance.GetMap("myMap");
/// </code>
public static IHazelcastInstance NewHazelcastClient(ClientConfig config)
{
if (config == null)
{
config = XmlClientConfigBuilder.Build();
}
var client = new HazelcastClient(config);
client.Start();
var proxy = new HazelcastClientProxy(client);
Clients.TryAdd(client._id, proxy);
return proxy;
}
/// <summary>
/// Shutdowns all Hazelcast Clients .
/// </summary>
public static void ShutdownAll()
{
foreach (var proxy in Clients.Values)
{
try
{
proxy.GetClient().GetLifecycleService().Shutdown();
}
catch
{
// ignored
}
}
Clients.Clear();
}
internal void DoShutdown()
{
HazelcastClientProxy _out;
Clients.TryRemove(_id, out _out);
_statistics.Destroy();
_executionService.Shutdown();
_partitionService.Stop();
_connectionManager.Shutdown();
_proxyManager.Shutdown();
_invocationService.Shutdown();
_nearCacheManager.Shutdown();
_listenerService.Dispose();
_serializationService.Destroy();
}
internal IClientClusterService GetClientClusterService()
{
return _clusterService;
}
internal ClientConfig GetClientConfig()
{
return _config;
}
internal IClientExecutionService GetClientExecutionService()
{
return _executionService;
}
internal IClientPartitionService GetClientPartitionService()
{
return _partitionService;
}
internal ClientConnectionManager GetConnectionManager()
{
return _connectionManager;
}
internal IClientInvocationService GetInvocationService()
{
return _invocationService;
}
internal IClientListenerService GetListenerService()
{
return _listenerService;
}
internal ISerializationService GetSerializationService()
{
return _serializationService;
}
internal ClientLockReferenceIdGenerator GetLockReferenceIdGenerator()
{
return _lockReferenceIdGenerator;
}
internal NearCacheManager GetNearCacheManager()
{
return _nearCacheManager;
}
internal Statistics GetStatistics()
{
return _statistics;
}
private ClientInvocationService CreateInvocationService()
{
return _config.GetNetworkConfig().IsSmartRouting()
? (ClientInvocationService) new ClientSmartInvocationService(this)
: new ClientNonSmartInvocationService(this);
}
private void Start()
{
_lifecycleService.SetStarted();
try
{
_invocationService.Start();
_connectionManager.Start();
_clusterService.Start();
_proxyManager.Init(_config);
_listenerService.Start();
_loadBalancer.Init(GetCluster(), _config);
_partitionService.Start();
_statistics.Start();
}
catch (InvalidOperationException)
{
//there was an authentication failure (todo: perhaps use an AuthenticationException
// ??)
_lifecycleService.Shutdown();
throw;
}
}
}
}
| |
using System;
using System.Net;
using System.Threading;
using Orleans.Messaging;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Messaging
{
internal class MessageCenter : ISiloMessageCenter, IDisposable
{
private Gateway Gateway { get; set; }
private IncomingMessageAcceptor ima;
private static readonly Logger log = LogManager.GetLogger("Orleans.Messaging.MessageCenter");
private Action<Message> rerouteHandler;
internal Func<Message, bool> ShouldDrop;
// ReSharper disable NotAccessedField.Local
private IntValueStatistic sendQueueLengthCounter;
private IntValueStatistic receiveQueueLengthCounter;
// ReSharper restore NotAccessedField.Local
internal IOutboundMessageQueue OutboundQueue { get; set; }
internal IInboundMessageQueue InboundQueue { get; set; }
internal SocketManager SocketManager;
internal bool IsBlockingApplicationMessages { get; private set; }
internal ISiloPerformanceMetrics Metrics { get; private set; }
public bool IsProxying { get { return Gateway != null; } }
public bool TryDeliverToProxy(Message msg)
{
return msg.TargetGrain.IsClient && Gateway != null && Gateway.TryDeliverToProxy(msg);
}
// This is determined by the IMA but needed by the OMS, and so is kept here in the message center itself.
public SiloAddress MyAddress { get; private set; }
public IMessagingConfiguration MessagingConfiguration { get; private set; }
public MessageCenter(SiloInitializationParameters silo, NodeConfiguration nodeConfig, IMessagingConfiguration config, ISiloPerformanceMetrics metrics = null)
{
this.Initialize(silo.SiloAddress.Endpoint, nodeConfig.Generation, config, metrics);
if (nodeConfig.IsGatewayNode)
{
this.InstallGateway(nodeConfig.ProxyGatewayEndpoint);
}
}
private void Initialize(IPEndPoint here, int generation, IMessagingConfiguration config, ISiloPerformanceMetrics metrics = null)
{
if(log.IsVerbose3) log.Verbose3("Starting initialization.");
SocketManager = new SocketManager(config);
ima = new IncomingMessageAcceptor(this, here, SocketDirection.SiloToSilo);
MyAddress = SiloAddress.New((IPEndPoint)ima.AcceptingSocket.LocalEndPoint, generation);
MessagingConfiguration = config;
InboundQueue = new InboundMessageQueue();
OutboundQueue = new OutboundMessageQueue(this, config);
Gateway = null;
Metrics = metrics;
sendQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_SEND_QUEUE_LENGTH, () => SendQueueLength);
receiveQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_RECEIVE_QUEUE_LENGTH, () => ReceiveQueueLength);
if (log.IsVerbose3) log.Verbose3("Completed initialization.");
}
public void InstallGateway(IPEndPoint gatewayAddress)
{
Gateway = new Gateway(this, gatewayAddress);
}
public void Start()
{
IsBlockingApplicationMessages = false;
ima.Start();
OutboundQueue.Start();
}
public void StartGateway(ClientObserverRegistrar clientRegistrar)
{
if (Gateway != null)
Gateway.Start(clientRegistrar);
}
public void PrepareToStop()
{
}
public void Stop()
{
IsBlockingApplicationMessages = true;
try
{
ima.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100108, "Stop failed.", exc);
}
StopAcceptingClientMessages();
try
{
OutboundQueue.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100110, "Stop failed.", exc);
}
try
{
SocketManager.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100111, "Stop failed.", exc);
}
}
public void StopAcceptingClientMessages()
{
if (log.IsVerbose) log.Verbose("StopClientMessages");
if (Gateway == null) return;
try
{
Gateway.Stop();
}
catch (Exception exc) { log.Error(ErrorCode.Runtime_Error_100109, "Stop failed.", exc); }
Gateway = null;
}
public Action<Message> RerouteHandler
{
set
{
if (rerouteHandler != null)
throw new InvalidOperationException("MessageCenter RerouteHandler already set");
rerouteHandler = value;
}
}
public void RerouteMessage(Message message)
{
if (rerouteHandler != null)
rerouteHandler(message);
else
SendMessage(message);
}
public Action<Message> SniffIncomingMessage
{
set
{
ima.SniffIncomingMessage = value;
}
}
public Func<SiloAddress, bool> SiloDeadOracle { get; set; }
public void SendMessage(Message msg)
{
// Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here.
if (IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && (msg.Result != Message.ResponseTypes.Rejection)
&& !Constants.SystemMembershipTableId.Equals(msg.TargetGrain))
{
// Drop the message on the floor if it's an application message that isn't a rejection
}
else
{
if (msg.SendingSilo == null)
msg.SendingSilo = MyAddress;
OutboundQueue.SendMessage(msg);
}
}
internal void SendRejection(Message msg, Message.RejectionTypes rejectionType, string reason)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
if (string.IsNullOrEmpty(reason)) reason = String.Format("Rejection from silo {0} - Unknown reason.", MyAddress);
Message error = msg.CreateRejectionResponse(rejectionType, reason);
// rejection msgs are always originated in the local silo, they are never remote.
InboundQueue.PostMessage(error);
}
public Message WaitMessage(Message.Categories type, CancellationToken ct)
{
return InboundQueue.WaitMessage(type);
}
public void Dispose()
{
if (ima != null)
{
ima.Dispose();
ima = null;
}
OutboundQueue.Dispose();
GC.SuppressFinalize(this);
}
public int SendQueueLength { get { return OutboundQueue.Count; } }
public int ReceiveQueueLength { get { return InboundQueue.Count; } }
/// <summary>
/// Indicates that application messages should be blocked from being sent or received.
/// This method is used by the "fast stop" process.
/// <para>
/// Specifically, all outbound application messages are dropped, except for rejections and messages to the membership table grain.
/// Inbound application requests are rejected, and other inbound application messages are dropped.
/// </para>
/// </summary>
public void BlockApplicationMessages()
{
if(log.IsVerbose) log.Verbose("BlockApplicationMessages");
IsBlockingApplicationMessages = true;
}
}
}
| |
using System;
/*
* $Id: Tree.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $
*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
namespace Raksha.Utilities.Zlib {
internal sealed class Tree{
private const int MAX_BITS=15;
private const int BL_CODES=19;
private const int D_CODES=30;
private const int LITERALS=256;
private const int LENGTH_CODES=29;
private const int L_CODES=(LITERALS+1+LENGTH_CODES);
private const int HEAP_SIZE=(2*L_CODES+1);
// Bit length codes must not exceed MAX_BL_BITS bits
internal const int MAX_BL_BITS=7;
// end of block literal code
internal const int END_BLOCK=256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
internal const int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
internal const int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
internal const int REPZ_11_138=18;
// extra bits for each length code
internal static readonly int[] extra_lbits={
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
internal static readonly int[] extra_dbits={
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
internal static readonly int[] extra_blbits={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
internal static readonly byte[] bl_order={
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
internal const int Buf_size=8*2;
// see definition of array dist_code below
internal const int DIST_CODE_LEN=512;
internal static readonly byte[] _dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
internal static readonly byte[] _length_code={
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
internal static readonly int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
internal static readonly int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
internal static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]);
}
internal short[] dyn_tree; // the dynamic tree
internal int max_code; // largest code with non zero frequency
internal StaticTree stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
internal void gen_bitlen(Deflate s){
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int based = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
for(h=s.heap_max+1; h<HEAP_SIZE; h++){
n = s.heap[h];
bits = tree[tree[n*2+1]*2+1] + 1;
if (bits > max_length){ bits = max_length; overflow++; }
tree[n*2+1] = (short)bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code) continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= based) xbits = extra[n-based];
f = tree[n*2];
s.opt_len += f * (bits + xbits);
if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
}
if (overflow == 0) return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length-1;
while(s.bl_count[bits]==0) bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits+1]+=2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
}
while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) continue;
if (tree[m*2+1] != bits) {
s.opt_len += (int)(((long)bits - (long)tree[m*2+1])*(long)tree[m*2]);
tree[m*2+1] = (short)bits;
}
n--;
}
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
internal void build_tree(Deflate s){
short[] tree=dyn_tree;
short[] stree=stat_desc.static_tree;
int elems=stat_desc.elems;
int n, m; // iterate over heap elements
int max_code=-1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for(n=0; n<elems; n++) {
if(tree[n*2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
}
else{
tree[n*2+1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node*2] = 1;
s.depth[node] = 0;
s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for(n=s.heap_len/2;n>=1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems; // next internal node of the tree
do{
// n = node of least frequency
n=s.heap[1];
s.heap[1]=s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m=s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node*2] = (short)(tree[n*2] + tree[m*2]);
s.depth[node] = (byte)(System.Math.Max(s.depth[n],s.depth[m])+1);
tree[n*2+1] = tree[m*2+1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
}
while(s.heap_len>=2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
internal static void gen_codes(short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count // number of codes at each bit length
){
short[] next_code=new short[MAX_BITS+1]; // next code value for each bit length
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n*2+1];
if (len == 0) continue;
// Now reverse the bits
tree[n*2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
internal static int bi_reverse(int code, // the value to invert
int len // its bit length
){
int res = 0;
do{
res|=code&1;
code>>=1;
res<<=1;
}
while(--len>0);
return res>>1;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService
{
internal partial class ImplementInterfaceCodeAction : CodeAction
{
protected readonly bool Explicitly;
protected readonly bool Abstractly;
protected readonly ISymbol ThroughMember;
protected readonly Document Document;
protected readonly State State;
protected readonly AbstractImplementInterfaceService Service;
private readonly string _equivalenceKey;
internal ImplementInterfaceCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state,
bool explicitly,
bool abstractly,
ISymbol throughMember)
{
this.Service = service;
this.Document = document;
this.State = state;
this.Abstractly = abstractly;
this.Explicitly = explicitly;
this.ThroughMember = throughMember;
_equivalenceKey = ComputeEquivalenceKey(state, explicitly, abstractly, throughMember, this.GetType().FullName);
}
public static ImplementInterfaceCodeAction CreateImplementAbstractlyCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: true, throughMember: null);
}
public static ImplementInterfaceCodeAction CreateImplementCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: null);
}
public static ImplementInterfaceCodeAction CreateImplementExplicitlyCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: true, abstractly: false, throughMember: null);
}
public static ImplementInterfaceCodeAction CreateImplementThroughMemberCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state,
ISymbol throughMember)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: throughMember);
}
public override string Title
{
get
{
if (Explicitly)
{
return FeaturesResources.Implement_interface_explicitly;
}
else if (Abstractly)
{
return FeaturesResources.Implement_interface_abstractly;
}
else if (ThroughMember != null)
{
return string.Format(FeaturesResources.Implement_interface_through_0, GetDescription(ThroughMember));
}
else
{
return FeaturesResources.Implement_interface;
}
}
}
private static string ComputeEquivalenceKey(
State state,
bool explicitly,
bool abstractly,
ISymbol throughMember,
string codeActionTypeName)
{
var interfaceType = state.InterfaceTypes.First();
var typeName = interfaceType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var assemblyName = interfaceType.ContainingAssembly.Name;
return GetCodeActionEquivalenceKey(assemblyName, typeName, explicitly, abstractly, throughMember, codeActionTypeName);
}
// internal for testing purposes.
internal static string GetCodeActionEquivalenceKey(
string interfaceTypeAssemblyName,
string interfaceTypeFullyQualifiedName,
bool explicitly,
bool abstractly,
ISymbol throughMember,
string codeActionTypeName)
{
if (throughMember != null)
{
return null;
}
return explicitly.ToString() + ";" +
abstractly.ToString() + ";" +
interfaceTypeAssemblyName + ";" +
interfaceTypeFullyQualifiedName + ";" +
codeActionTypeName;
}
public override string EquivalenceKey => _equivalenceKey;
private static string GetDescription(ISymbol throughMember)
{
switch (throughMember)
{
case IFieldSymbol field: return field.Name;
case IPropertySymbol property: return property.Name;
default:
throw new InvalidOperationException();
}
}
protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
{
return GetUpdatedDocumentAsync(cancellationToken);
}
public Task<Document> GetUpdatedDocumentAsync(CancellationToken cancellationToken)
{
var unimplementedMembers = Explicitly
? State.UnimplementedExplicitMembers
: State.UnimplementedMembers;
return GetUpdatedDocumentAsync(Document, unimplementedMembers, State.ClassOrStructType, State.ClassOrStructDecl, cancellationToken);
}
public virtual async Task<Document> GetUpdatedDocumentAsync(
Document document,
ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> unimplementedMembers,
INamedTypeSymbol classOrStructType,
SyntaxNode classOrStructDecl,
CancellationToken cancellationToken)
{
var result = document;
var compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var isComImport = unimplementedMembers.Any(t => t.Item1.IsComImport);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var propertyGenerationBehavior = options.GetOption(ImplementTypeOptions.PropertyGenerationBehavior);
var memberDefinitions = GenerateMembers(
compilation, unimplementedMembers, propertyGenerationBehavior, cancellationToken);
// Only group the members in the destination if the user wants that *and*
// it's not a ComImport interface. Member ordering in ComImport interfaces
// matters, so we don't want to much with them.
var insertionBehavior = options.GetOption(ImplementTypeOptions.InsertionBehavior);
var groupMembers = !isComImport &&
insertionBehavior == ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind;
result = await CodeGenerator.AddMemberDeclarationsAsync(
result.Project.Solution, classOrStructType, memberDefinitions,
new CodeGenerationOptions(
contextLocation: classOrStructDecl.GetLocation(),
autoInsertionLocation: groupMembers,
sortMembers: groupMembers),
cancellationToken).ConfigureAwait(false);
return result;
}
private ImmutableArray<ISymbol> GenerateMembers(
Compilation compilation,
ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> unimplementedMembers,
ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
CancellationToken cancellationToken)
{
// As we go along generating members we may end up with conflicts. For example, say
// you have "interface IFoo { string Bar { get; } }" and "interface IQuux { int Bar
// { get; } }" and we need to implement both 'Bar' methods. The second will have to
// be explicitly implemented as it will conflict with the first. So we need to keep
// track of what we've actually implemented so that we can check further interface
// members against both the actual type and that list.
//
// Similarly, if you have two interfaces with the same member, then we don't want to
// implement that member twice.
//
// Note: if we implement a method explicitly then we do *not* add it to this list.
// That's because later members won't conflict with it even if they have the same
// signature otherwise. i.e. if we chose to implement IFoo.Bar explicitly, then we
// could implement IQuux.Bar implicitly (and vice versa).
var implementedVisibleMembers = new List<ISymbol>();
var implementedMembers = ArrayBuilder<ISymbol>.GetInstance();
foreach (var tuple in unimplementedMembers)
{
var interfaceType = tuple.type;
var unimplementedInterfaceMembers = tuple.members;
foreach (var unimplementedInterfaceMember in unimplementedInterfaceMembers)
{
var member = GenerateMember(
compilation, unimplementedInterfaceMember, implementedVisibleMembers,
propertyGenerationBehavior, cancellationToken);
if (member != null)
{
implementedMembers.Add(member);
if (!(member.ExplicitInterfaceImplementations().Any() && Service.HasHiddenExplicitImplementation))
{
implementedVisibleMembers.Add(member);
}
}
}
}
return implementedMembers.ToImmutableAndFree();
}
private bool IsReservedName(string name)
{
return
IdentifiersMatch(State.ClassOrStructType.Name, name) ||
State.ClassOrStructType.TypeParameters.Any(t => IdentifiersMatch(t.Name, name));
}
private string DetermineMemberName(ISymbol member, List<ISymbol> implementedVisibleMembers)
{
if (HasConflictingMember(member, implementedVisibleMembers))
{
var memberNames = State.ClassOrStructType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(State.ClassOrStructType).Select(m => m.Name);
return NameGenerator.GenerateUniqueName(
string.Format("{0}_{1}", member.ContainingType.Name, member.Name),
n => !memberNames.Contains(n) &&
!implementedVisibleMembers.Any(m => IdentifiersMatch(m.Name, n)) &&
!IsReservedName(n));
}
return member.Name;
}
private ISymbol GenerateMember(
Compilation compilation,
ISymbol member,
List<ISymbol> implementedVisibleMembers,
ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
CancellationToken cancellationToken)
{
// First check if we already generate a member that matches the member we want to
// generate. This can happen in C# when you have interfaces that have the same
// method, and you are implementing implicitly. For example:
//
// interface IFoo { void Foo(); }
//
// interface IBar : IFoo { new void Foo(); }
//
// class C : IBar
//
// In this case we only want to generate 'Foo' once.
if (HasMatchingMember(implementedVisibleMembers, member))
{
return null;
}
var memberName = DetermineMemberName(member, implementedVisibleMembers);
// See if we need to generate an invisible member. If we do, then reset the name
// back to what then member wants it to be.
var generateInvisibleMember = GenerateInvisibleMember(member, memberName);
memberName = generateInvisibleMember ? member.Name : memberName;
var generateAbstractly = !generateInvisibleMember && Abstractly;
// Check if we need to add 'new' to the signature we're adding. We only need to do this
// if we're not generating something explicit and we have a naming conflict with
// something in our base class hierarchy.
var addNew = !generateInvisibleMember && HasNameConflict(member, memberName, State.ClassOrStructType.GetBaseTypes());
// Check if we need to add 'unsafe' to the signature we're generating.
var syntaxFacts = Document.GetLanguageService<ISyntaxFactsService>();
var addUnsafe = member.IsUnsafe() && !syntaxFacts.IsUnsafeContext(State.Location);
return GenerateMember(
compilation, member, memberName, generateInvisibleMember, generateAbstractly,
addNew, addUnsafe, propertyGenerationBehavior, cancellationToken);
}
private bool GenerateInvisibleMember(ISymbol member, string memberName)
{
if (Service.HasHiddenExplicitImplementation)
{
// User asked for an explicit (i.e. invisible) member.
if (Explicitly)
{
return true;
}
// Have to create an invisible member if we have constraints we can't express
// with a visible member.
if (HasUnexpressibleConstraint(member))
{
return true;
}
// If we had a conflict with a member of the same name, then we have to generate
// as an invisible member.
if (member.Name != memberName)
{
return true;
}
}
// Can't generate an invisible member if the language doesn't support it.
return false;
}
private bool HasUnexpressibleConstraint(ISymbol member)
{
// interface IFoo<T> { void Bar<U>() where U : T; }
//
// class A : IFoo<int> { }
//
// In this case we cannot generate an implement method for Bar. That's because we'd
// need to say "where U : int" and that's disallowed by the language. So we must
// generate something explicit here.
if (member.Kind != SymbolKind.Method)
{
return false;
}
var method = member as IMethodSymbol;
return method.TypeParameters.Any(IsUnexpressibleTypeParameter);
}
private static bool IsUnexpressibleTypeParameter(ITypeParameterSymbol typeParameter)
{
var condition1 = typeParameter.ConstraintTypes.Count(t => t.TypeKind == TypeKind.Class) >= 2;
var condition2 = typeParameter.ConstraintTypes.Any(ts => ts.IsUnexpressibleTypeParameterConstraint());
var condition3 = typeParameter.HasReferenceTypeConstraint && typeParameter.ConstraintTypes.Any(ts => ts.IsReferenceType && ts.SpecialType != SpecialType.System_Object);
return condition1 || condition2 || condition3;
}
private ISymbol GenerateMember(
Compilation compilation,
ISymbol member,
string memberName,
bool generateInvisibly,
bool generateAbstractly,
bool addNew,
bool addUnsafe,
ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
CancellationToken cancellationToken)
{
var factory = this.Document.GetLanguageService<SyntaxGenerator>();
var modifiers = new DeclarationModifiers(isAbstract: generateAbstractly, isNew: addNew, isUnsafe: addUnsafe);
var useExplicitInterfaceSymbol = generateInvisibly || !Service.CanImplementImplicitly;
var accessibility = member.Name == memberName || generateAbstractly
? Accessibility.Public
: Accessibility.Private;
switch (member)
{
case IMethodSymbol method:
return GenerateMethod(compilation, method, accessibility, modifiers, generateAbstractly, useExplicitInterfaceSymbol, memberName, cancellationToken);
case IPropertySymbol property:
return GenerateProperty(compilation, property, accessibility, modifiers, generateAbstractly, useExplicitInterfaceSymbol, memberName, propertyGenerationBehavior, cancellationToken);
case IEventSymbol @event:
var accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: Accessibility.NotApplicable,
statements: factory.CreateThrowNotImplementedStatementBlock(compilation));
return CodeGenerationSymbolFactory.CreateEventSymbol(
@event,
accessibility: accessibility,
modifiers: modifiers,
explicitInterfaceSymbol: useExplicitInterfaceSymbol ? @event : null,
name: memberName,
addMethod: GetAddOrRemoveMethod(generateInvisibly, accessor, memberName, factory.AddEventHandler),
removeMethod: GetAddOrRemoveMethod(generateInvisibly, accessor, memberName, factory.RemoveEventHandler));
}
return null;
}
private IMethodSymbol GetAddOrRemoveMethod(bool generateInvisibly,
IMethodSymbol accessor,
string memberName,
Func<SyntaxNode, SyntaxNode, SyntaxNode> createAddOrRemoveHandler)
{
if (ThroughMember != null)
{
var factory = Document.GetLanguageService<SyntaxGenerator>();
var throughExpression = CreateThroughExpression(factory);
var statement = factory.ExpressionStatement(createAddOrRemoveHandler(
factory.MemberAccessExpression(throughExpression, memberName), factory.IdentifierName("value")));
return CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: Accessibility.NotApplicable,
statements: ImmutableArray.Create(statement));
}
return generateInvisibly ? accessor : null;
}
private SyntaxNode CreateThroughExpression(SyntaxGenerator factory)
{
var through = ThroughMember.IsStatic
? GenerateName(factory, State.ClassOrStructType.IsGenericType)
: factory.ThisExpression();
through = factory.MemberAccessExpression(
through, factory.IdentifierName(ThroughMember.Name));
var throughMemberType = ThroughMember.GetMemberType();
if ((State.InterfaceTypes != null) && (throughMemberType != null))
{
// In the case of 'implement interface through field / property' , we need to know what
// interface we are implementing so that we can insert casts to this interface on every
// usage of the field in the generated code. Without these casts we would end up generating
// code that fails compilation in certain situations.
//
// For example consider the following code.
// class C : IReadOnlyList<int> { int[] field; }
// When applying the 'implement interface through field' code fix in the above example,
// we need to generate the following code to implement the Count property on IReadOnlyList<int>
// class C : IReadOnlyList<int> { int[] field; int Count { get { ((IReadOnlyList<int>)field).Count; } ...}
// as opposed to the following code which will fail to compile (because the array field
// doesn't have a property named .Count) -
// class C : IReadOnlyList<int> { int[] field; int Count { get { field.Count; } ...}
//
// The 'InterfaceTypes' property on the state object always contains only one item
// in the case of C# i.e. it will contain exactly the interface we are trying to implement.
// This is also the case most of the time in the case of VB, except in certain error conditions
// (recursive / circular cases) where the span of the squiggle for the corresponding
// diagnostic (BC30149) changes and 'InterfaceTypes' ends up including all interfaces
// in the Implements clause. For the purposes of inserting the above cast, we ignore the
// uncommon case and optimize for the common one - in other words, we only apply the cast
// in cases where we can unambiguously figure out which interface we are trying to implement.
var interfaceBeingImplemented = State.InterfaceTypes.SingleOrDefault();
if ((interfaceBeingImplemented != null) && (!throughMemberType.Equals(interfaceBeingImplemented)))
{
through = factory.CastExpression(interfaceBeingImplemented,
through.WithAdditionalAnnotations(Simplifier.Annotation));
var facts = this.Document.GetLanguageService<ISyntaxFactsService>();
through = facts.Parenthesize(through);
}
}
return through.WithAdditionalAnnotations(Simplifier.Annotation);
}
private SyntaxNode GenerateName(SyntaxGenerator factory, bool isGenericType)
{
return isGenericType
? factory.GenericName(State.ClassOrStructType.Name, State.ClassOrStructType.TypeArguments)
: factory.IdentifierName(State.ClassOrStructType.Name);
}
private bool HasNameConflict(
ISymbol member,
string memberName,
IEnumerable<INamedTypeSymbol> baseTypes)
{
// There's a naming conflict if any member in the base types chain is accessible to
// us, has our name. Note: a simple name won't conflict with a generic name (and
// vice versa). A method only conflicts with another method if they have the same
// parameter signature (return type is irrelevant).
return
baseTypes.Any(ts => ts.GetMembers(memberName)
.Where(m => m.IsAccessibleWithin(State.ClassOrStructType))
.Any(m => HasNameConflict(member, memberName, m)));
}
private static bool HasNameConflict(
ISymbol member,
string memberName,
ISymbol baseMember)
{
Contract.Requires(memberName == baseMember.Name);
if (member.Kind == SymbolKind.Method && baseMember.Kind == SymbolKind.Method)
{
// A method only conflicts with another method if they have the same parameter
// signature (return type is irrelevant).
var method1 = (IMethodSymbol)member;
var method2 = (IMethodSymbol)baseMember;
if (method1.MethodKind == MethodKind.Ordinary &&
method2.MethodKind == MethodKind.Ordinary &&
method1.TypeParameters.Length == method2.TypeParameters.Length)
{
return method1.Parameters.Select(p => p.Type)
.SequenceEqual(method2.Parameters.Select(p => p.Type));
}
}
// Any non method members with the same name simple name conflict.
return true;
}
private bool IdentifiersMatch(string identifier1, string identifier2)
{
return this.IsCaseSensitive
? identifier1 == identifier2
: StringComparer.OrdinalIgnoreCase.Equals(identifier1, identifier2);
}
private bool IsCaseSensitive
{
get
{
return this.Document.GetLanguageService<ISyntaxFactsService>().IsCaseSensitive;
}
}
private bool HasMatchingMember(List<ISymbol> implementedVisibleMembers, ISymbol member)
{
// If this is a language that doesn't support implicit implementation then no
// implemented members will ever match. For example, if you have:
//
// Interface IFoo : sub Foo() : End Interface
//
// Interface IBar : Inherits IFoo : Shadows Sub Foo() : End Interface
//
// Class C : Implements IBar
//
// We'll first end up generating:
//
// Public Sub Foo() Implements IFoo.Foo
//
// However, that same method won't be viable for IBar.Foo (unlike C#) because it
// explicitly specifies its interface).
if (!Service.CanImplementImplicitly)
{
return false;
}
return implementedVisibleMembers.Any(m => MembersMatch(m, member));
}
private bool MembersMatch(ISymbol member1, ISymbol member2)
{
if (member1.Kind != member2.Kind)
{
return false;
}
if (member1.DeclaredAccessibility != member2.DeclaredAccessibility ||
member1.IsStatic != member2.IsStatic)
{
return false;
}
if (member1.ExplicitInterfaceImplementations().Any() || member2.ExplicitInterfaceImplementations().Any())
{
return false;
}
return SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(
member1, member2, this.IsCaseSensitive);
}
}
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lucene.Net.Search.Highlight.Test
{
/// <summary>
/// The class performs token processing in strings
/// </summary>
public class Tokenizer : IEnumerator<string>
{
/// Position over the string
private long currentPos = 0;
/// Include demiliters in the results.
private bool includeDelims = false;
/// Char representation of the String to tokenize.
private char[] chars = null;
//The tokenizer uses the default delimiter set: the space character, the tab character, the newline character, and the carriage-return character and the form-feed character
private string delimiters = " \t\n\r\f";
/// <summary>
/// Initializes a new class instance with a specified string to process
/// </summary>
/// <param name="source">String to tokenize</param>
public Tokenizer(System.String source)
{
this.chars = source.ToCharArray();
}
/// <summary>
/// Initializes a new class instance with a specified string to process
/// and the specified token delimiters to use
/// </summary>
/// <param name="source">String to tokenize</param>
/// <param name="delimiters">String containing the delimiters</param>
public Tokenizer(System.String source, System.String delimiters)
: this(source)
{
this.delimiters = delimiters;
}
/// <summary>
/// Initializes a new class instance with a specified string to process, the specified token
/// delimiters to use, and whether the delimiters must be included in the results.
/// </summary>
/// <param name="source">String to tokenize</param>
/// <param name="delimiters">String containing the delimiters</param>
/// <param name="includeDelims">Determines if delimiters are included in the results.</param>
public Tokenizer(System.String source, System.String delimiters, bool includeDelims)
: this(source, delimiters)
{
this.includeDelims = includeDelims;
}
/// <summary>
/// Returns the next token from the token list
/// </summary>
/// <returns>The string value of the token</returns>
public System.String NextToken()
{
return NextToken(this.delimiters);
}
/// <summary>
/// Returns the next token from the source string, using the provided
/// token delimiters
/// </summary>
/// <param name="delimiters">String containing the delimiters to use</param>
/// <returns>The string value of the token</returns>
public System.String NextToken(System.String delimiters)
{
//According to documentation, the usage of the received delimiters should be temporary (only for this call).
//However, it seems it is not true, so the following line is necessary.
this.delimiters = delimiters;
//at the end
if (this.currentPos == this.chars.Length)
throw new System.ArgumentOutOfRangeException();
//if over a delimiter and delimiters must be returned
else if ((System.Array.IndexOf(delimiters.ToCharArray(), chars[this.currentPos]) != -1)
&& this.includeDelims)
return "" + this.chars[this.currentPos++];
//need to get the token wo delimiters.
else
return NextToken(delimiters.ToCharArray());
}
//Returns the nextToken wo delimiters
private System.String NextToken(char[] delimiters)
{
string token = "";
long pos = this.currentPos;
//skip possible delimiters
while (System.Array.IndexOf(delimiters, this.chars[currentPos]) != -1)
//The last one is a delimiter (i.e there is no more tokens)
if (++this.currentPos == this.chars.Length)
{
this.currentPos = pos;
throw new System.ArgumentOutOfRangeException();
}
//getting the token
while (System.Array.IndexOf(delimiters, this.chars[this.currentPos]) == -1)
{
token += this.chars[this.currentPos];
//the last one is not a delimiter
if (++this.currentPos == this.chars.Length)
break;
}
return token;
}
/// <summary>
/// Determines if there are more tokens to return from the source string
/// </summary>
/// <returns>True or false, depending if there are more tokens</returns>
public bool HasMoreTokens()
{
//keeping the current pos
long pos = this.currentPos;
try
{
this.NextToken();
}
catch (System.ArgumentOutOfRangeException)
{
return false;
}
finally
{
this.currentPos = pos;
}
return true;
}
/// <summary>
/// Remaining tokens count
/// </summary>
public int Count
{
get
{
//keeping the current pos
long pos = this.currentPos;
int i = 0;
try
{
while (true)
{
this.NextToken();
i++;
}
}
catch (System.ArgumentOutOfRangeException)
{
this.currentPos = pos;
return i;
}
}
}
/// <summary>
/// Performs the same action as NextToken.
/// </summary>
public string Current
{
get { return this.NextToken(); }
}
/// <summary>
/// Performs the same action as NextToken.
/// </summary>
object IEnumerator.Current
{
get { return Current; }
}
/// <summary>
// Performs the same action as HasMoreTokens.
/// </summary>
/// <returns>True or false, depending if there are more tokens</returns>
public bool MoveNext()
{
return this.HasMoreTokens();
}
/// <summary>
/// Does nothing.
/// </summary>
public void Reset()
{
}
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose()
{
}
}
}
| |
// ------------------------------------------------------------------------------------------------
// KingTomato Script
// ------------------------------------------------------------------------------------------------
$King::Version = "2.4";
$KT::Debug = false; // dont worry bout this
// Presto Resolutions Missing
$Presto::screenSize["720x480"] = "720 480";
$Presto::screenSize["720x576"] = "720 576";
$Presto::screenSize["848x480"] = "848 480";
$Presto::screenSize["1152x864"] = "1152 864";
$Presto::screenSize["1280x720"] = "1280 720";
$Presto::screenSize["1280x768"] = "1280 768";
$Presto::screenSize["1280x960"] = "1280 960";
$Presto::screenSize["1280x1024"] = "1280 1024";
$Presto::screenSize["1360x768"] = "1360 768";
$Presto::screenSize["1600x900"] = "1600 900";
$Presto::screenSize["1600x1024"] = "1600 1024";
$Presto::screenSize["1600x1200"] = "1600 1200";
$King::Beta = false; // No need to change this, won't give
// you special features or anything
// ------------------------------------------------------------------------------------------------
// Preferences
//
// This will handle callbacks to the prefs I have set. If its null, or filled with something
// other than false, assume true. >:P
//
function KingPref::Enabled(%setting)
{
if ($KingPref::[%setting] == "")
$KingPref::[%option] = false;
if ($KingPref::[%setting] != false)
return true;
return false;
}
// ------------------------------------------------------------------------------------------------
// Last Hope Checker
function King::LastHope()
{
return (getWord(timestamp(),3) != "2000");
}
// ------------------------------------------------------------------------------------------------
// Auto Loader
//
// Loads the file in the kingtomato directory, according to the order of their presidence.
// please read SCRIPTORS.TXT under the "File Names" heading for more information.
//
function King::Install::Install()
{
// Load Settings
if (isFile("config\\King_Settings.cs"))
exec("King_Settings.cs");
// Load up preferences file
exec("KingTomato\\KingPrefs.skip.cs"); // Moved down to avoid the prefs bug
// Load default values
exec("KingTomato\\Defaults.skip.cs");
if (KingPref::Enabled(Logging))
$Console::LogMode = 1;
if ((KingPref::Enabled(NudeWalls)) && (!isObject("WallsVolume")))
newObject(WallsVolume, SimVolume, "KingTomato\\vols\\NudeWalls.vol");
else if ((!KingPref::Enabled(NudeWalls)) && (isObject("WallsVolume")))
deleteObject("WallsVolume");
if ((KingPref::Enabled(RedWalls)) && (!isObject("CounterVolume")))
newObject(ForceFieldVolume, SimVolume, "KingTomato\\vols\\RedForceFields.vol");
else if ((!KingPref::Enabled(RedWalls)) && (isObject("RedForceFields")))
deleteObject("RedForceFields");
$King::Install::Count[System] = 0;
$King::Install::Count[Scripts] = 0;
// This File
%this = "KingTomato\\*nstall.cs";
if ($KT::Debug)
echo("Loading Volumes");
// Volumes
for (%file = File::FindFirst("KingTomato\\*.vol"); %file != ""; %file = File::FindNext("KingTomato\\*.vol"))
{
// Add To List
$KingTomato::Load::Volume[%vol++] = %file;
// Register Volume
%base = File::getBase(File::getBase(%file));
EvalSearchPath::addVol(%base, %file);
newObject(%base, SimVolume, %file);
// Increse Counter
%count[Volume]++;
}
if ($KT::Debug)
echo("Loading .sys.cs");
// System Files
for (%file = File::FindFirst("KingTomato\\*.sys.cs"); %file != ""; %file = File::FindNext("KingTomato\\*.sys.cs"))
{
exec(%file);
King::Install::AddFile(%file, System, $Script::Creator, $Script::Version, $Script::Description, $Script::MinVersion);
deleteVariables("$Script::*");
}
if ($KT::Debug)
echo("Loading .cs");
// Other Scripts
for (%file = File::FindFirst("KingTomato\\*.cs"); %file != ""; %file = File::FindNext("KingTomato\\*.cs"))
{
// To avoid an infinite loop, and loading files both already loaded, and
// never to be loaded, we will check what kind of file we have. By testing
// its not this file, we avoid an infitie loop, and stop the program from
// Loading this file, which loads itself again, and again, etc. Also,
// We make sure its not an already loaded sys file, or isn't intended to be
// skipped (.skip.cs).
if (!Match::String(%file, %this) && !Match::String(%file, "*.sys.cs") && !Match::String(%file, "*.skip.cs"))
{
// Load File
exec(%file);
King::Install::AddFile(%file, Script, $Script::Creator, $Script::Version, $Script::Description, $Script::MinVersion);
deleteVariables("$Script::*");
}
}
King::Install::Output();
deleteVariables("$King::Install*");
}
//
// Add files to array
//
function King::Install::AddFile(%file, %type, %creator, %version, %description, %minVer)
{
%count = $King::Install::count[%type]++;
// Check for empty values, and fill them
if (%creator == "") %creator = "unknown Author";
if (%version == "") %version = "?.??";
if (%description == "") %description = "No description given for this item";
$King::Install::File[%count, file] = %file;
$King::Install::File[%count, creator] = %creator;
$King::Install::File[%count, version] = %version;
$King::Install::File[%count, description] = %description;
if ((%minVer != "") && (%minVer > $King::Version))
$King::Install::File[%count, fail] = %minVer;
if ($KT::Debug)
echo("Adding File: " @ %file @ " to load list");
}
//
// Output Installed Scripts
//
function King::Install::Output()
{
%failed = "";
if (!$KT::Debug)
cls();
echo("// --------------------------------------------------------------------------------");
echo("// KingTomato Script");
echo("// Version " @ $King::Version);
echo("// --");
echo("// Presto... Detected (" @ $Presto::Version @ ")");
echo("// NewOpts... Detected (" @ $NewOpts::Version @ ")");
echo("// --");
echo("// Script Files Installed: " @ $King::Install::count[Script]);
echo("// --------------------------------------------------------------------------------");
echo("//");
for (%a = 1; $King::Install::File[%a, file] != ""; %a++)
{
%file = $King::Install::File[%a, file];
%creator = $King::Install::File[%a, creator];
%version = $King::Install::File[%a, version];
%desc = $King::Install::File[%a, description];
%minVer = $King::Install::File[%a, fail];
if (%minVer != "")
%failed = %failed @ %a @ " ";
echo("// " @ File::getBase(%file) @ " (By: " @ %creator @ ", v" @ %version @ ")");
%words = "";
for (%b = 0; %b < String::GetWordCount(%desc); %b++) {
%word = getWord(%desc, %b);
%temp = %words @ %word @ " ";
if (String::Len(%temp) <= 85)
%words = %words @ %word @ " ";
else {
echo("// " @ %words);
%words = %word;
}
}
echo("// " @ %words);
echo("//");
}
if (%failed != "")
{
echo("// --------------------------------------------------------------------------------");
echo("// Warning:");
echo("// Some files did not load correctly.");
echo("// These files include:");
echo("// --------------------------------------------------------------------------------");
echo("//");
for (%a = 0; (%i = getWord(%failed, %a)) != -1; %a++)
{
%file = $King::Install::File[%i, file];
%minVer = $King::Install::File[%i, fail];
echo("// " @ File::getBase(%file));
echo("// File requires KingTomato Pack v" @ %minVer @ " or later");
echo("//");
}
}
echo("// --------------------------------------------------------------------------------");
echo("// Installation Complete");
echo("// --------------------------------------------------------------------------------");
}
if (($Presto::Version != "0.93") || ($NewOpts::version != "0.966"))
{
echo ("KingTomato Script Pack Error");
echo ("-");
echo ("Presto Pack missing or invalid version");
echo ("NewOpts missing or invalid version");
echo ("");
echo ("Please be sure you have Presto Pack 0.93 & NewOpts 0.966");
echo ("");
echo ("Preso Version: " @ $Presto::Version);
echo ("newOpts Version: " @ $newOpts::Version);
}
else
{
King::Install::Install();
Event::Attach(eventConnectionAccepted, King::Install::Advertise);
}
function King::Install::Advertise()
{
// %1 - Player Name
// %2 - version number
// %3 - current tribes ver
// %4 - advertisement
// %5 - "LastHope"/"Tribes"
if ((%msg = $KingPref::AdMessage) == "")
%msg = "I am using KingTomato Pack v%2.%3! %4";
if (KingPref::Enabled(Advertise))
{
if ($King::Beta)
%ad = "Coming soon to www.KingTomato.org";
else
%ad = "Get yours at www.KingTomato.org";
if (King::LastHope())
%five = "LastHope";
else
%five = "Tribes";
%msg = sprintf(%msg, $PCFG::Name, $King::Version, version(), %ad, %five);
say(0, %msg);
}
}
| |
using System;
using FM;
using FM.IceLink;
using FM.IceLink.WebRTC;
namespace Xamarin.Forms.Conference.WebRTC.Droid.Opus
{
public class OpusCodec : AudioCodec
{
private BasicAudioPadep _Padep;
private Encoder _Encoder;
private Decoder _Decoder;
public OpusEchoCanceller EchoCanceller { get; set; }
public int PercentLossToTriggerFEC { get; set; }
public bool DisableFEC { get; set; }
public bool FecActive { get; private set; }
public OpusCodec()
: this(null)
{ }
public OpusCodec(OpusEchoCanceller echoCanceller)
: base(20)
{
EchoCanceller = echoCanceller;
DisableFEC = false;
PercentLossToTriggerFEC = 5;
_Padep = new BasicAudioPadep();
}
/// <summary>
/// Encodes a frame.
/// </summary>
/// <param name="frame">The frame.</param>
/// <returns></returns>
public override byte[] Encode(AudioBuffer frame)
{
if (_Encoder == null)
{
_Encoder = new Encoder(ClockRate, Channels, PacketTime);
_Encoder.Quality = 1.0;
_Encoder.Bitrate = 125;
}
byte[] data; int index; int length;
var echoCanceller = EchoCanceller;
if (echoCanceller == null)
{
data = frame.Data;
index = frame.Index;
length = frame.Length;
}
else
{
data = echoCanceller.capture(frame);
index = 0;
length = data.Length;
}
return _Encoder.Encode(data, index, length);
}
private int _CurrentRTPSequenceNumber = -1;
private int _LastRTPSequenceNumber = -1;
/// <summary>
/// Decodes an encoded frame.
/// </summary>
/// <param name="encodedFrame">The encoded frame.</param>
/// <returns></returns>
public override AudioBuffer Decode(byte[] encodedFrame)
{
if (_Decoder == null)
{
_Decoder = new Decoder(ClockRate, Channels, PacketTime);
Link.GetRemoteStream().DisablePLC = true;
}
if (_LastRTPSequenceNumber == -1)
{
_LastRTPSequenceNumber = _CurrentRTPSequenceNumber;
return DecodeNormal(encodedFrame);
}
else
{
var sequenceNumberDelta = RTPPacket.GetSequenceNumberDelta(_CurrentRTPSequenceNumber, _LastRTPSequenceNumber);
if (sequenceNumberDelta <= 0)
{
return null;
}
_LastRTPSequenceNumber = _CurrentRTPSequenceNumber;
var missingPacketCount = sequenceNumberDelta - 1;
var previousFrames = new AudioBuffer[missingPacketCount];
var plcFrameCount = (missingPacketCount > 1) ? missingPacketCount - 1 : 0;
if (plcFrameCount > 0)
{
Log.InfoFormat("Adding {0} frames of loss concealment to incoming audio stream. Packet sequence violated.", plcFrameCount.ToString());
for (var i = 0; i < plcFrameCount; i++)
{
previousFrames[i] = DecodePLC();
}
}
var fecFrameCount = (missingPacketCount > 0) ? 1 : 0;
if (fecFrameCount > 0)
{
var fecFrame = DecodeFEC(encodedFrame);
var fecFrameIndex = missingPacketCount - 1;
if (fecFrame == null)
{
previousFrames[fecFrameIndex] = DecodePLC();
}
else
{
previousFrames[fecFrameIndex] = fecFrame;
}
}
var frame = DecodeNormal(encodedFrame);
frame.PreviousBuffers = previousFrames;
return frame;
}
}
private AudioBuffer DecodePLC()
{
return Decode(null, false);
}
private AudioBuffer DecodeFEC(byte[] encodedFrame)
{
return Decode(encodedFrame, true);
}
private AudioBuffer DecodeNormal(byte[] encodedFrame)
{
return Decode(encodedFrame, false);
}
private AudioBuffer Decode(byte[] encodedFrame, bool fec)
{
var data = _Decoder.Decode(encodedFrame, fec);
if (data == null)
{
return null;
}
var frame = new AudioBuffer(data, 0, data.Length);
var echoCanceller = EchoCanceller;
if (echoCanceller != null)
{
echoCanceller.render(PeerId, frame);
}
return frame;
}
/// <summary>
/// Packetizes an encoded frame.
/// </summary>
/// <param name="encodedFrame">The encoded frame.</param>
/// <returns></returns>
public override RTPPacket[] Packetize(byte[] encodedFrame)
{
return _Padep.Packetize(encodedFrame, ClockRate, PacketTime, ResetTimestamp);
}
/// <summary>
/// Depacketizes a packet.
/// </summary>
/// <param name="packet">The packet.</param>
/// <returns></returns>
public override byte[] Depacketize(RTPPacket packet)
{
_CurrentRTPSequenceNumber = packet.SequenceNumber;
return _Padep.Depacketize(packet);
}
private int _LossyCount = 0;
private int _LosslessCount = 0;
private int _MinimumReportsBeforeFEC = 1;
private long _ReportsReceived = 0;
/// <summary>
/// Processes RTCP packets.
/// </summary>
/// <param name="packets">The packets to process.</param>
public override void ProcessRTCP(RTCPPacket[] packets)
{
if (_Encoder != null)
{
foreach (var packet in packets)
{
if (packet is RTCPReportPacket)
{
_ReportsReceived++;
var report = (RTCPReportPacket)packet;
foreach (var block in report.ReportBlocks)
{
Log.DebugFormat("Opus report: {0} packet loss ({1} cumulative packets lost)", block.PercentLost.ToString("P2"), block.CumulativeNumberOfPacketsLost.ToString());
if (block.PercentLost > 0)
{
_LosslessCount = 0;
_LossyCount++;
if (_LossyCount > 5 && _Encoder.Quality > 0.0)
{
_LossyCount = 0;
_Encoder.Quality = MathAssistant.Max(0.0, _Encoder.Quality - 0.1);
Log.InfoFormat("Decreasing Opus encoder quality to {0}.", _Encoder.Quality.ToString("P2"));
}
}
else
{
_LossyCount = 0;
_LosslessCount++;
if (_LosslessCount > 5 && _Encoder.Quality < 1.0)
{
_LosslessCount = 0;
_Encoder.Quality = MathAssistant.Min(1.0, _Encoder.Quality + 0.1);
Log.InfoFormat("Increasing Opus encoder quality to {0}.", _Encoder.Quality.ToString("P2"));
}
}
if (!DisableFEC && !FecActive && _ReportsReceived > _MinimumReportsBeforeFEC)
{
if ((block.PercentLost * 100) > PercentLossToTriggerFEC)
{
Log.Info("Activating FEC for Opus audio stream.");
_Encoder.ActivateFEC(PercentLossToTriggerFEC);
FecActive = true;
}
}
}
}
}
}
}
/// <summary>
/// Destroys the codec.
/// </summary>
public override void Destroy()
{
if (_Encoder != null)
{
_Encoder.Destroy();
_Encoder = null;
}
if (_Decoder != null)
{
_Decoder.Destroy();
_Decoder = null;
}
}
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using HETSAPI.Models;
namespace HETSAPI.Models
{
/// <summary>
/// A request from a Project for one or more of a type of equipment from a specific Local Area.
/// </summary>
[MetaDataExtension (Description = "A request from a Project for one or more of a type of equipment from a specific Local Area.")]
public partial class RentalRequest : AuditableEntity, IEquatable<RentalRequest>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public RentalRequest()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="RentalRequest" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for a Request (required).</param>
/// <param name="Project">Project (required).</param>
/// <param name="LocalArea">A foreign key reference to the system-generated unique identifier for a Local Area (required).</param>
/// <param name="Status">The status of the Rental Request - whether it in progress, completed or was cancelled. (required).</param>
/// <param name="DistrictEquipmentType">A foreign key reference to the system-generated unique identifier for an Equipment Type (required).</param>
/// <param name="EquipmentCount">The number of pieces of the equipment type wanted for hire as part of this request. (required).</param>
/// <param name="ExpectedHours">The expected number of rental hours for each piece equipment hired against this request, as provided by the Project Manager making the request..</param>
/// <param name="ExpectedStartDate">The expected start date of each piece of equipment hired against this request, as provided by the Project Manager making the request..</param>
/// <param name="ExpectedEndDate">The expected end date of each piece of equipment hired against this request, as provided by the Project Manager making the request..</param>
/// <param name="FirstOnRotationList">The first piece of equipment on the rotation list at the time of the creation of the request..</param>
/// <param name="Notes">Notes.</param>
/// <param name="Attachments">Attachments.</param>
/// <param name="History">History.</param>
/// <param name="RentalRequestAttachments">RentalRequestAttachments.</param>
/// <param name="RentalRequestRotationList">RentalRequestRotationList.</param>
public RentalRequest(int Id, Project Project, LocalArea LocalArea, string Status, DistrictEquipmentType DistrictEquipmentType, int EquipmentCount, int? ExpectedHours = null, DateTime? ExpectedStartDate = null, DateTime? ExpectedEndDate = null, Equipment FirstOnRotationList = null, List<Note> Notes = null, List<Attachment> Attachments = null, List<History> History = null, List<RentalRequestAttachment> RentalRequestAttachments = null, List<RentalRequestRotationList> RentalRequestRotationList = null)
{
this.Id = Id;
this.Project = Project;
this.LocalArea = LocalArea;
this.Status = Status;
this.DistrictEquipmentType = DistrictEquipmentType;
this.EquipmentCount = EquipmentCount;
this.ExpectedHours = ExpectedHours;
this.ExpectedStartDate = ExpectedStartDate;
this.ExpectedEndDate = ExpectedEndDate;
this.FirstOnRotationList = FirstOnRotationList;
this.Notes = Notes;
this.Attachments = Attachments;
this.History = History;
this.RentalRequestAttachments = RentalRequestAttachments;
this.RentalRequestRotationList = RentalRequestRotationList;
}
/// <summary>
/// A system-generated unique identifier for a Request
/// </summary>
/// <value>A system-generated unique identifier for a Request</value>
[MetaDataExtension (Description = "A system-generated unique identifier for a Request")]
public int Id { get; set; }
/// <summary>
/// Gets or Sets Project
/// </summary>
public Project Project { get; set; }
/// <summary>
/// Foreign key for Project
/// </summary>
[ForeignKey("Project")]
[JsonIgnore]
public int? ProjectId { get; set; }
/// <summary>
/// A foreign key reference to the system-generated unique identifier for a Local Area
/// </summary>
/// <value>A foreign key reference to the system-generated unique identifier for a Local Area</value>
[MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Local Area")]
public LocalArea LocalArea { get; set; }
/// <summary>
/// Foreign key for LocalArea
/// </summary>
[ForeignKey("LocalArea")]
[JsonIgnore]
[MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Local Area")]
public int? LocalAreaId { get; set; }
/// <summary>
/// The status of the Rental Request - whether it in progress, completed or was cancelled.
/// </summary>
/// <value>The status of the Rental Request - whether it in progress, completed or was cancelled.</value>
[MetaDataExtension (Description = "The status of the Rental Request - whether it in progress, completed or was cancelled.")]
[MaxLength(50)]
public string Status { get; set; }
/// <summary>
/// A foreign key reference to the system-generated unique identifier for an Equipment Type
/// </summary>
/// <value>A foreign key reference to the system-generated unique identifier for an Equipment Type</value>
[MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for an Equipment Type")]
public DistrictEquipmentType DistrictEquipmentType { get; set; }
/// <summary>
/// Foreign key for DistrictEquipmentType
/// </summary>
[ForeignKey("DistrictEquipmentType")]
[JsonIgnore]
[MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for an Equipment Type")]
public int? DistrictEquipmentTypeId { get; set; }
/// <summary>
/// The number of pieces of the equipment type wanted for hire as part of this request.
/// </summary>
/// <value>The number of pieces of the equipment type wanted for hire as part of this request.</value>
[MetaDataExtension (Description = "The number of pieces of the equipment type wanted for hire as part of this request.")]
public int EquipmentCount { get; set; }
/// <summary>
/// The expected number of rental hours for each piece equipment hired against this request, as provided by the Project Manager making the request.
/// </summary>
/// <value>The expected number of rental hours for each piece equipment hired against this request, as provided by the Project Manager making the request.</value>
[MetaDataExtension (Description = "The expected number of rental hours for each piece equipment hired against this request, as provided by the Project Manager making the request.")]
public int? ExpectedHours { get; set; }
/// <summary>
/// The expected start date of each piece of equipment hired against this request, as provided by the Project Manager making the request.
/// </summary>
/// <value>The expected start date of each piece of equipment hired against this request, as provided by the Project Manager making the request.</value>
[MetaDataExtension (Description = "The expected start date of each piece of equipment hired against this request, as provided by the Project Manager making the request.")]
public DateTime? ExpectedStartDate { get; set; }
/// <summary>
/// The expected end date of each piece of equipment hired against this request, as provided by the Project Manager making the request.
/// </summary>
/// <value>The expected end date of each piece of equipment hired against this request, as provided by the Project Manager making the request.</value>
[MetaDataExtension (Description = "The expected end date of each piece of equipment hired against this request, as provided by the Project Manager making the request.")]
public DateTime? ExpectedEndDate { get; set; }
/// <summary>
/// The first piece of equipment on the rotation list at the time of the creation of the request.
/// </summary>
/// <value>The first piece of equipment on the rotation list at the time of the creation of the request.</value>
[MetaDataExtension (Description = "The first piece of equipment on the rotation list at the time of the creation of the request.")]
public Equipment FirstOnRotationList { get; set; }
/// <summary>
/// Foreign key for FirstOnRotationList
/// </summary>
[ForeignKey("FirstOnRotationList")]
[JsonIgnore]
[MetaDataExtension (Description = "The first piece of equipment on the rotation list at the time of the creation of the request.")]
public int? FirstOnRotationListId { get; set; }
/// <summary>
/// Gets or Sets Notes
/// </summary>
public List<Note> Notes { get; set; }
/// <summary>
/// Gets or Sets Attachments
/// </summary>
public List<Attachment> Attachments { get; set; }
/// <summary>
/// Gets or Sets History
/// </summary>
public List<History> History { get; set; }
/// <summary>
/// Gets or Sets RentalRequestAttachments
/// </summary>
public List<RentalRequestAttachment> RentalRequestAttachments { get; set; }
/// <summary>
/// Gets or Sets RentalRequestRotationList
/// </summary>
public List<RentalRequestRotationList> RentalRequestRotationList { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class RentalRequest {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Project: ").Append(Project).Append("\n");
sb.Append(" LocalArea: ").Append(LocalArea).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" DistrictEquipmentType: ").Append(DistrictEquipmentType).Append("\n");
sb.Append(" EquipmentCount: ").Append(EquipmentCount).Append("\n");
sb.Append(" ExpectedHours: ").Append(ExpectedHours).Append("\n");
sb.Append(" ExpectedStartDate: ").Append(ExpectedStartDate).Append("\n");
sb.Append(" ExpectedEndDate: ").Append(ExpectedEndDate).Append("\n");
sb.Append(" FirstOnRotationList: ").Append(FirstOnRotationList).Append("\n");
sb.Append(" Notes: ").Append(Notes).Append("\n");
sb.Append(" Attachments: ").Append(Attachments).Append("\n");
sb.Append(" History: ").Append(History).Append("\n");
sb.Append(" RentalRequestAttachments: ").Append(RentalRequestAttachments).Append("\n");
sb.Append(" RentalRequestRotationList: ").Append(RentalRequestRotationList).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((RentalRequest)obj);
}
/// <summary>
/// Returns true if RentalRequest instances are equal
/// </summary>
/// <param name="other">Instance of RentalRequest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RentalRequest other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.Project == other.Project ||
this.Project != null &&
this.Project.Equals(other.Project)
) &&
(
this.LocalArea == other.LocalArea ||
this.LocalArea != null &&
this.LocalArea.Equals(other.LocalArea)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.DistrictEquipmentType == other.DistrictEquipmentType ||
this.DistrictEquipmentType != null &&
this.DistrictEquipmentType.Equals(other.DistrictEquipmentType)
) &&
(
this.EquipmentCount == other.EquipmentCount ||
this.EquipmentCount.Equals(other.EquipmentCount)
) &&
(
this.ExpectedHours == other.ExpectedHours ||
this.ExpectedHours != null &&
this.ExpectedHours.Equals(other.ExpectedHours)
) &&
(
this.ExpectedStartDate == other.ExpectedStartDate ||
this.ExpectedStartDate != null &&
this.ExpectedStartDate.Equals(other.ExpectedStartDate)
) &&
(
this.ExpectedEndDate == other.ExpectedEndDate ||
this.ExpectedEndDate != null &&
this.ExpectedEndDate.Equals(other.ExpectedEndDate)
) &&
(
this.FirstOnRotationList == other.FirstOnRotationList ||
this.FirstOnRotationList != null &&
this.FirstOnRotationList.Equals(other.FirstOnRotationList)
) &&
(
this.Notes == other.Notes ||
this.Notes != null &&
this.Notes.SequenceEqual(other.Notes)
) &&
(
this.Attachments == other.Attachments ||
this.Attachments != null &&
this.Attachments.SequenceEqual(other.Attachments)
) &&
(
this.History == other.History ||
this.History != null &&
this.History.SequenceEqual(other.History)
) &&
(
this.RentalRequestAttachments == other.RentalRequestAttachments ||
this.RentalRequestAttachments != null &&
this.RentalRequestAttachments.SequenceEqual(other.RentalRequestAttachments)
) &&
(
this.RentalRequestRotationList == other.RentalRequestRotationList ||
this.RentalRequestRotationList != null &&
this.RentalRequestRotationList.SequenceEqual(other.RentalRequestRotationList)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode();
if (this.Project != null)
{
hash = hash * 59 + this.Project.GetHashCode();
}
if (this.LocalArea != null)
{
hash = hash * 59 + this.LocalArea.GetHashCode();
} if (this.Status != null)
{
hash = hash * 59 + this.Status.GetHashCode();
}
if (this.DistrictEquipmentType != null)
{
hash = hash * 59 + this.DistrictEquipmentType.GetHashCode();
}
hash = hash * 59 + this.EquipmentCount.GetHashCode(); if (this.ExpectedHours != null)
{
hash = hash * 59 + this.ExpectedHours.GetHashCode();
}
if (this.ExpectedStartDate != null)
{
hash = hash * 59 + this.ExpectedStartDate.GetHashCode();
}
if (this.ExpectedEndDate != null)
{
hash = hash * 59 + this.ExpectedEndDate.GetHashCode();
}
if (this.FirstOnRotationList != null)
{
hash = hash * 59 + this.FirstOnRotationList.GetHashCode();
}
if (this.Notes != null)
{
hash = hash * 59 + this.Notes.GetHashCode();
}
if (this.Attachments != null)
{
hash = hash * 59 + this.Attachments.GetHashCode();
}
if (this.History != null)
{
hash = hash * 59 + this.History.GetHashCode();
}
if (this.RentalRequestAttachments != null)
{
hash = hash * 59 + this.RentalRequestAttachments.GetHashCode();
}
if (this.RentalRequestRotationList != null)
{
hash = hash * 59 + this.RentalRequestRotationList.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(RentalRequest left, RentalRequest right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(RentalRequest left, RentalRequest right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using AllReady.Areas.Admin.Controllers;
using Xunit;
using Moq;
using MediatR;
using AllReady.Areas.Admin.Features.Skills;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using AllReady.Models;
using AllReady.Areas.Admin.Features.Organizations;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Linq;
using AllReady.Areas.Admin.ViewModels.Skill;
using AllReady.UnitTest.Extensions;
using Microsoft.AspNetCore.Routing;
using Shouldly;
namespace AllReady.UnitTest.Areas.Admin.Controllers
{
public class SkillControllerTests
{
private const string OrgName = "Org Name";
private const int OrgAdminOrgId = 1;
#region Index Tests
[Fact]
public async Task SkillIndexForSiteAdminReturnsCorrectViewResult()
{
// Arrange
SkillController controller;
var mockMediator = MockMediatorSkillListQuery(out controller);
var mockContext = MockControllerContextWithUser(SiteAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Index();
// Assert
Assert.IsType<ViewResult>(result);
Assert.True((result as ViewResult).ViewData.ContainsKey("Title"));
var title = (result as ViewResult).ViewData["Title"];
Assert.Equal("Skills", title);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Once);
}
[Fact]
public async Task SkillIndexForValidOrgAdminReturnsCorrectViewResult()
{
// Arrange
SkillController controller;
var mockMediator = MockMediatorSkillListQuery(out controller);
var mockContext = MockControllerContextWithUser(OrgAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Index() as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Index", result.ViewName);
Assert.True(result.ViewData.ContainsKey("Title"));
var title = result.ViewData["Title"];
Assert.Equal("Skills - " + OrgName, title);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationNameQuery>()), Times.Once);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Once);
Assert.Equal(2, (result.ViewData.Model as IEnumerable<SkillSummaryViewModel>).ToList().Count());
}
[Fact]
public async Task SkillIndexForOrgAdminWithNoOrgIdReturns401()
{
// Arrange
SkillController controller;
var mockMediator = MockMediatorSkillListQuery(out controller);
var mockContext = MockControllerContextWithUser(OrgAdminWithMissingOrgId());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Index();
// Assert
Assert.IsType<UnauthorizedResult>(result);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Never);
}
[Fact]
public void IndexHasHttpGetAttribute()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.Index()).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
#endregion
#region Create Tests
[Fact]
public async Task SkillCreateForNonAdminOrUserWithNoOrgIdReturns401()
{
// Arrange
SkillController controller;
var mockMediator = MockMediatorSkillCreateQuery(out controller);
var mockContext = MockControllerContextWithUser(OrgAdminWithMissingOrgId());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Create();
// Assert
Assert.IsType<UnauthorizedResult>(result);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Never);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Never);
}
[Fact]
public async Task SkillCreateForSiteAdminReturnsCorrectResult()
{
// Arrange
SkillController controller;
var mockMediator = MockMediatorSkillCreateQuery(out controller);
var mockContext = MockControllerContextWithUser(SiteAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Create() as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Edit", result.ViewName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Once);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Once);
Assert.Equal(1, (result.ViewData.Model as SkillEditViewModel).OrganizationSelection.ToList().Count());
Assert.Equal(2, (result.ViewData.Model as SkillEditViewModel).ParentSelection.ToList().Count());
}
[Fact]
public async Task SkillCreateForOrgAdminReturnsCorrectResult()
{
// Arrange
SkillController controller;
var mockMediator = MockMediatorSkillCreateQuery(out controller);
var mockContext = MockControllerContextWithUser(OrgAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Create() as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Edit", result.ViewName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Once);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Never);
Assert.Null((result.ViewData.Model as SkillEditViewModel).OrganizationSelection);
Assert.Equal(2, (result.ViewData.Model as SkillEditViewModel).ParentSelection.ToList().Count());
}
[Fact]
public void CreateGetHasHttpGetAttribute()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.Create()).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task SkillCreatePostForSiteAdminWithValidModelStateReturnsRedirectToAction()
{
// Arrange
SkillController controller;
var mockMediator = MockMediatorSkillCreateQuery(out controller);
var mockContext = MockControllerContextWithUser(SiteAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var model = CreateSkillModel();
var result = await controller.Create(model) as RedirectToActionResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Index", result.ActionName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillEditCommand>()), Times.Once);
}
[Fact]
public async Task SkillCreatePostForOrgAdminWithValidModelStateReturnsRedirectToAction()
{
// Arrange
SkillController controller;
var mockMediator = MockMediatorSkillCreateQuery(out controller);
var mockContext = MockControllerContextWithUser(OrgAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var model = CreateSkillModel();
var result = await controller.Create(model) as RedirectToActionResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Index", result.ActionName);
Assert.Equal(OrgAdminOrgId, model.OwningOrganizationId);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillEditCommand>()), Times.Once);
}
[Fact]
public async Task SkillCreatePostForSiteAdminWithInvalidModelStateReturnsViewResult()
{
// Arrange
SkillController controller;
var mockMediator = MockMediatorSkillCreateQuery(out controller);
var mockContext = MockControllerContextWithUser(SiteAdmin());
controller.ControllerContext = mockContext.Object;
controller.ModelState.AddModelError("test", "test");
// Act
var model = CreateSkillModel();
var result = await controller.Create(model) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Edit", result.ViewName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Once);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Once);
Assert.Equal(1, (result.ViewData.Model as SkillEditViewModel).OrganizationSelection.ToList().Count());
Assert.Equal(2, (result.ViewData.Model as SkillEditViewModel).ParentSelection.ToList().Count());
}
[Fact]
public async Task SkillCreatePostForOrgAdminWithInvalidModelStateReturnsViewResult()
{
// Arrange
SkillController controller;
var mockMediator = MockMediatorSkillCreateQuery(out controller);
var mockContext = MockControllerContextWithUser(OrgAdmin());
controller.ControllerContext = mockContext.Object;
controller.ModelState.AddModelError("test", "test");
// Act
var model = CreateSkillModel();
var result = await controller.Create(model) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Edit", result.ViewName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Once);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Never);
Assert.Null((result.ViewData.Model as SkillEditViewModel).OrganizationSelection);
Assert.Equal(2, (result.ViewData.Model as SkillEditViewModel).ParentSelection.ToList().Count());
}
[Fact]
public void CreatePostHasHttpPostAttribute()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.Create(It.IsAny<SkillEditViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void CreatePostHasValidateAntiForgeryTokenAttribute()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.Create(It.IsAny<SkillEditViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
private static SkillEditViewModel CreateSkillModel()
{
return new SkillEditViewModel
{
Name = "Some Name",
Description = "Some Description"
};
}
#endregion
#region Edit Tests
[Fact]
public async Task SkillEditNoSkillReturns404()
{
// Arrange
const int skillId = 0;
SkillController controller;
var mockMediator = MockMediatorSkillEditQueryNullModel(out controller);
// Act
var result = await controller.Edit(skillId);
// Assert
Assert.IsType<NotFoundResult>(result);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillEditQuery>()), Times.Once);
}
[Fact]
public async Task SkilEditForNonAdminUserWithNoOrgIdReturns401()
{
// Arrange
const int skillId = 1;
SkillController controller;
var mockMediator = MockMediatorSkillEditQuery(out controller);
var mockContext = MockControllerContextWithUser(OrgAdminWithMissingOrgId());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Edit(skillId);
// Assert
Assert.IsType<UnauthorizedResult>(result);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Never);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Never);
}
[Fact]
public async Task SkillEditForSiteAdminReturnsCorrectResult()
{
// Arrange
const int skillId = 1;
SkillController controller;
var mockMediator = MockMediatorSkillEditQuery(out controller);
var mockContext = MockControllerContextWithUser(SiteAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Edit(skillId) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Edit", result.ViewName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Once);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Once);
Assert.Equal(1, (result.ViewData.Model as SkillEditViewModel).OrganizationSelection.ToList().Count());
Assert.Equal(1, (result.ViewData.Model as SkillEditViewModel).ParentSelection.ToList().Count()); // We expect 1 since we should have removed self from the list at this point
}
[Fact]
public async Task SkillEditForOrgAdminReturnsCorrectResult()
{
// Arrange
const int skillId = 1;
SkillController controller;
var mockMediator = MockMediatorSkillEditQuery(out controller, new SkillEditViewModel { Id = 1, Name = "Name", Description = "Description", OwningOrganizationId = OrgAdminOrgId });
var mockContext = MockControllerContextWithUser(OrgAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Edit(skillId) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Edit", result.ViewName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Once);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Never);
Assert.Null((result.ViewData.Model as SkillEditViewModel).OrganizationSelection);
Assert.Equal(1, (result.ViewData.Model as SkillEditViewModel).ParentSelection.ToList().Count()); // We expect 1 since we should have removed self from the list at this point
}
[Fact]
public async Task SkillEditForOrgAdminWithWrongOrgIdReturnsCorrectResult()
{
// Arrange
const int skillId = 1;
SkillController controller;
var mockMediator = MockMediatorSkillEditQuery(out controller, new SkillEditViewModel { Id = 1, Name = "Name", Description = "Description", OwningOrganizationId = 2 });
var mockContext = MockControllerContextWithUser(OrgAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Edit(skillId) as UnauthorizedResult;
// Assert
Assert.NotNull(result);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Never);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Never);
}
[Fact]
public void EditGetHasHttpGetAttrbitue()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.Edit(It.IsAny<int>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task SkillEditPostForSiteAdminWithValidModelStateReturnsRedirectToAction()
{
// Arrange
var model = EditSkillModel();
SkillController controller;
var mockMediator = MockMediatorSkillEditQuery(out controller, model);
var mockContext = MockControllerContextWithUser(SiteAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Edit(model) as RedirectToActionResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Index", result.ActionName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillEditCommand>()), Times.Once);
}
[Fact]
public async Task SkillEditGet_ReturnsEmptyParentSelection_WhenNoValidSkillsReturnedByListQuery()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<SkillEditQuery>())).ReturnsAsync(EditSkillModel());
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<SkillListQuery>())).ReturnsAsync(new List<SkillSummaryViewModel>());
var sut = new SkillController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(SiteAdmin());
sut.ControllerContext = mockContext.Object;
// Act
var result = await sut.Edit(1);
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
var model = viewResult.Model as SkillEditViewModel;
model.ParentSelection.ShouldBeEmpty();
}
[Fact]
public async Task SkillEditPostForOrgAdminWithValidModelStateReturnsRedirectToAction()
{
// Arrange
var model = EditSkillModel();
SkillController controller;
var mockMediator = MockMediatorSkillEditQuery(out controller, model);
var mockContext = MockControllerContextWithUser(OrgAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Edit(model) as RedirectToActionResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Index", result.ActionName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillEditCommand>()), Times.Once);
}
[Fact]
public void EditPostHasHttpPostAttrbitue()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.Edit(It.IsAny<SkillEditViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void EditPostHasValidateAntiForgeryTokenttrbitue()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.Edit(It.IsAny<SkillEditViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task SkillEditPostForSiteAdminWithInvalidModelStateReturnsViewResult()
{
// Arrange
var model = EditSkillModel();
SkillController controller;
var mockMediator = MockMediatorSkillEditQuery(out controller, model);
var mockContext = MockControllerContextWithUser(SiteAdmin());
controller.ControllerContext = mockContext.Object;
controller.ModelState.AddModelError("test", "test");
// Act
var result = await controller.Create(model) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Edit", result.ViewName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Once);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Once);
Assert.Equal(1, (result.ViewData.Model as SkillEditViewModel).OrganizationSelection.ToList().Count());
Assert.Equal(2, (result.ViewData.Model as SkillEditViewModel).ParentSelection.ToList().Count());
}
[Fact]
public async Task SkillEditPostForOrgAdminWithInvalidModelStateReturnsViewResult()
{
// Arrange
var model = EditSkillModel();
SkillController controller;
var mockMediator = MockMediatorSkillEditQuery(out controller, model);
var mockContext = MockControllerContextWithUser(OrgAdmin());
controller.ControllerContext = mockContext.Object;
controller.ModelState.AddModelError("test", "test");
// Act
var result = await controller.Create(model) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Edit", result.ViewName);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillListQuery>()), Times.Once);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()), Times.Never);
Assert.Null((result.ViewData.Model as SkillEditViewModel).OrganizationSelection);
Assert.Equal(2, (result.ViewData.Model as SkillEditViewModel).ParentSelection.ToList().Count());
}
private static SkillEditViewModel EditSkillModel()
{
return new SkillEditViewModel
{
Name = "Some Name",
Description = "Some Description",
OwningOrganizationId = OrgAdminOrgId
};
}
#endregion
#region Delete Tests
[Fact]
public async Task SkillDeleteNoSkillReturns404()
{
// Arrange
const int skillId = 0;
SkillController controller;
var mockMediator = MockMediatorSkillDeleteQueryNullModel(out controller);
// Act
var result = await controller.Delete(skillId) as NotFoundResult;
// Assert
Assert.NotNull(result);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<SkillDeleteQuery>()), Times.Once);
}
[Fact]
public async Task SkilllDeleteForNonAdminUserWithNoOrgIdReturns401()
{
// Arrange
const int skillId = 1;
SkillController controller;
MockMediatorSkillDeleteQuery(out controller);
var mockContext = MockControllerContextWithUser(OrgAdminWithMissingOrgId());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Delete(skillId);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task SkillDeleteForSiteAdminReturnsCorrectResult()
{
// Arrange
const int skillId = 1;
SkillController controller;
MockMediatorSkillDeleteQuery(out controller);
var mockContext = MockControllerContextWithUser(SiteAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Delete(skillId) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Delete", result.ViewName);
}
[Fact]
public async Task SkillDeleteForOrgAdminReturnsCorrectResult()
{
// Arrange
const int skillId = 1;
SkillController controller;
MockMediatorSkillDeleteQuery(out controller, new SkillDeleteViewModel { HierarchicalName = "A Name", OwningOrganizationId = OrgAdminOrgId });
var mockContext = MockControllerContextWithUser(OrgAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.Delete(skillId) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Delete", result.ViewName);
}
[Fact]
public void DeleteHasHttpGetAttribute()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.Delete(It.IsAny<int>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task DeleteConfirmedPostReturnsUnauthorizedResult_WhenSkillBelongsToSameOrgAsOrgAdminIsFalse()
{
// Arrange
var viewModel = new SkillDeleteViewModel { SkillBelongsToSameOrgAsOrgAdmin = false };
SkillController controller;
MockMediatorSkillDeleteQueryNullModel(out controller);
// Act
var result = await controller.DeleteConfirmed(viewModel) as UnauthorizedResult;
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task DeleteConfirmedPostSendsSkillDeleteCommandWithCorrectSkillId()
{
// Arrange
const int skillId = 1;
SkillController controller;
var mockMediator = MockMediatorSkillDeleteQuery(out controller);
var viewModel = new SkillDeleteViewModel { SkillBelongsToSameOrgAsOrgAdmin = true, SkillId = skillId };
var mockContext = MockControllerContextWithUser(SiteAdmin());
controller.ControllerContext = mockContext.Object;
// Act
await controller.DeleteConfirmed(viewModel);
// Assert
mockMediator.Verify(mock => mock.SendAsync(It.Is<SkillDeleteCommand>(y => y.Id == skillId)), Times.Once);
}
[Fact]
public async Task DeleteConfirmedPostReturnsRedirectToTheCorrectActionWithTheCorrectRouteValues()
{
// Arrange
SkillController controller;
MockMediatorSkillDeleteQuery(out controller);
var viewModel = new SkillDeleteViewModel { SkillBelongsToSameOrgAsOrgAdmin = true };
var routeValueDictionary = new RouteValueDictionary { ["area"] = "Admin" };
var mockContext = MockControllerContextWithUser(SiteAdmin());
controller.ControllerContext = mockContext.Object;
// Act
var result = await controller.DeleteConfirmed(viewModel) as RedirectToActionResult;
// Assert
Assert.Equal(nameof(SkillController.Index), result.ActionName);
Assert.Equal(routeValueDictionary, result.RouteValues);
}
[Fact]
public void DeleteConfirmedHasHttpPostAttribute()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.DeleteConfirmed(It.IsAny<SkillDeleteViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void DeleteConfirmedHasActionNameAttributeWithCorrerctActionName()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.DeleteConfirmed(It.IsAny<SkillDeleteViewModel>())).OfType<ActionNameAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
Assert.Equal(attribute.Name, "Delete");
}
[Fact]
public void DeleteConfirmedHasValidateAntiForgeryTokenAttribute()
{
SkillController controller = new SkillController(null);
var attribute = controller.GetAttributesOn(x => x.DeleteConfirmed(It.IsAny<SkillDeleteViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
#endregion
#region Helper Methods
private static Mock<IMediator> MockMediatorSkillListQuery(out SkillController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<SkillListQuery>())).ReturnsAsync(SummaryListItems()).Verifiable();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<OrganizationNameQuery>())).ReturnsAsync(OrgName).Verifiable();
controller = new SkillController(mockMediator.Object);
return mockMediator;
}
private static Mock<IMediator> MockMediatorSkillCreateQuery(out SkillController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<SkillListQuery>())).ReturnsAsync(SummaryListItems()).Verifiable();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>())).ReturnsAsync(new List<SelectListItem> { new SelectListItem { Text = "Item 1", Value = "1" }}).Verifiable();
controller = new SkillController(mockMediator.Object);
return mockMediator;
}
private static Mock<IMediator> MockMediatorSkillEditQuery(out SkillController controller, SkillEditViewModel model = null)
{
if (model == null) model = new SkillEditViewModel { Id = 1, Name = "Name", Description = "Description" };
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<SkillEditQuery>())).ReturnsAsync(model).Verifiable();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<SkillListQuery>())).ReturnsAsync(SummaryListItems())
.Verifiable();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<OrganizationSelectListQuery>()))
.ReturnsAsync(new List<SelectListItem> { new SelectListItem { Text = "Item 1", Value = "1" }})
.Verifiable();
controller = new SkillController(mockMediator.Object);
return mockMediator;
}
private static Mock<IMediator> MockMediatorSkillEditQueryNullModel(out SkillController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<SkillEditQuery>())).ReturnsAsync((SkillEditViewModel)null).Verifiable();
controller = new SkillController(mockMediator.Object);
return mockMediator;
}
private static Mock<IMediator> MockMediatorSkillDeleteQuery(out SkillController controller, SkillDeleteViewModel model = null)
{
if (model == null) model = new SkillDeleteViewModel { HierarchicalName = "Name" };
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<SkillDeleteQuery>())).ReturnsAsync(model).Verifiable();
controller = new SkillController(mockMediator.Object);
return mockMediator;
}
private static Mock<IMediator> MockMediatorSkillDeleteQueryNullModel(out SkillController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<SkillDeleteQuery>())).ReturnsAsync((SkillDeleteViewModel)null).Verifiable();
controller = new SkillController(mockMediator.Object);
return mockMediator;
}
private static IEnumerable<SkillSummaryViewModel> SummaryListItems()
{
return new List<SkillSummaryViewModel>
{
new SkillSummaryViewModel { Id = 1, HierarchicalName = "Name", OwningOrganizationName = "Org", DescendantIds = new List<int>() },
new SkillSummaryViewModel { Id = 2, HierarchicalName = "Name 2", OwningOrganizationName = "Org", DescendantIds = new List<int>() }
};
}
private static Mock<ControllerContext> MockControllerContextWithUser(ClaimsPrincipal principle)
{
var mockHttpContext = new Mock<HttpContext>();
mockHttpContext.Setup(mock => mock.User).Returns(() => principle);
var mockContext = new Mock<ControllerContext>();
mockContext.Object.HttpContext = mockHttpContext.Object;
return mockContext;
}
private static ClaimsPrincipal OrgAdminWithMissingOrgId()
{
return new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString())
}));
}
private static ClaimsPrincipal OrgAdmin()
{
return new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(AllReady.Security.ClaimTypes.UserType, nameof(UserType.OrgAdmin)),
new Claim(AllReady.Security.ClaimTypes.Organization, OrgAdminOrgId.ToString())
}));
}
private static ClaimsPrincipal SiteAdmin()
{
return new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(AllReady.Security.ClaimTypes.UserType, nameof(UserType.SiteAdmin))
}));
}
#endregion
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\EnvironmentQuery\Generators\EnvQueryGenerator_OnCircle.h:26
namespace UnrealEngine
{
public partial class UEnvQueryGenerator_OnCircle : UEnvQueryGenerator_ProjectedPoints
{
public UEnvQueryGenerator_OnCircle(IntPtr adress)
: base(adress)
{
}
public UEnvQueryGenerator_OnCircle(UObject Parent = null, string Name = "EnvQueryGenerator_OnCircle")
: base(IntPtr.Zero)
{
NativePointer = E_NewObject_UEnvQueryGenerator_OnCircle(Parent, Name);
NativeManager.AddNativeWrapper(NativePointer, this);
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_UEnvQueryGenerator_OnCircle_AngleRadians_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UEnvQueryGenerator_OnCircle_AngleRadians_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UEnvQueryGenerator_OnCircle_ArcAngle_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UEnvQueryGenerator_OnCircle_ArcAngle_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UEnvQueryGenerator_OnCircle_ArcDirection_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UEnvQueryGenerator_OnCircle_ArcDirection_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_PROP_UEnvQueryGenerator_OnCircle_bIgnoreAnyContextActorsWhenGeneratingCircle_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UEnvQueryGenerator_OnCircle_bIgnoreAnyContextActorsWhenGeneratingCircle_SET(IntPtr Ptr, bool Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UEnvQueryGenerator_OnCircle_CircleCenterZOffset_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UEnvQueryGenerator_OnCircle_CircleCenterZOffset_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UEnvQueryGenerator_OnCircle_CircleRadius_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UEnvQueryGenerator_OnCircle_CircleRadius_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UEnvQueryGenerator_OnCircle_NumberOfPoints_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UEnvQueryGenerator_OnCircle_NumberOfPoints_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_UEnvQueryGenerator_OnCircle_PointOnCircleSpacingMethod_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UEnvQueryGenerator_OnCircle_PointOnCircleSpacingMethod_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UEnvQueryGenerator_OnCircle_SpaceBetween_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UEnvQueryGenerator_OnCircle_SpaceBetween_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_UEnvQueryGenerator_OnCircle_TraceData_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UEnvQueryGenerator_OnCircle_TraceData_SET(IntPtr Ptr, IntPtr Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_NewObject_UEnvQueryGenerator_OnCircle(IntPtr Parent, string Name);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_UEnvQueryGenerator_OnCircle_CalcDirection(IntPtr self, IntPtr queryInstance);
#endregion
#region Property
public float AngleRadians
{
get => E_PROP_UEnvQueryGenerator_OnCircle_AngleRadians_GET(NativePointer);
set => E_PROP_UEnvQueryGenerator_OnCircle_AngleRadians_SET(NativePointer, value);
}
/// <summary>
/// If you generate items on a piece of circle you define angle of Arc cut here
/// </summary>
public FAIDataProviderFloatValue ArcAngle
{
get => E_PROP_UEnvQueryGenerator_OnCircle_ArcAngle_GET(NativePointer);
set => E_PROP_UEnvQueryGenerator_OnCircle_ArcAngle_SET(NativePointer, value);
}
/// <summary>
/// If you generate items on a piece of circle you define direction of Arc cut here
/// </summary>
public FEnvDirection ArcDirection
{
get => E_PROP_UEnvQueryGenerator_OnCircle_ArcDirection_GET(NativePointer);
set => E_PROP_UEnvQueryGenerator_OnCircle_ArcDirection_SET(NativePointer, value);
}
/// <summary>
/// ignore tracing into context actors when generating the circle
/// </summary>
public bool bIgnoreAnyContextActorsWhenGeneratingCircle
{
get => E_PROP_UEnvQueryGenerator_OnCircle_bIgnoreAnyContextActorsWhenGeneratingCircle_GET(NativePointer);
set => E_PROP_UEnvQueryGenerator_OnCircle_bIgnoreAnyContextActorsWhenGeneratingCircle_SET(NativePointer, value);
}
/// <summary>
/// context offset
/// </summary>
public FAIDataProviderFloatValue CircleCenterZOffset
{
get => E_PROP_UEnvQueryGenerator_OnCircle_CircleCenterZOffset_GET(NativePointer);
set => E_PROP_UEnvQueryGenerator_OnCircle_CircleCenterZOffset_SET(NativePointer, value);
}
/// <summary>
/// max distance of path between point and context
/// </summary>
public FAIDataProviderFloatValue CircleRadius
{
get => E_PROP_UEnvQueryGenerator_OnCircle_CircleRadius_GET(NativePointer);
set => E_PROP_UEnvQueryGenerator_OnCircle_CircleRadius_SET(NativePointer, value);
}
/// <summary>
/// this many items will be generated on a circle
/// </summary>
public FAIDataProviderIntValue NumberOfPoints
{
get => E_PROP_UEnvQueryGenerator_OnCircle_NumberOfPoints_GET(NativePointer);
set => E_PROP_UEnvQueryGenerator_OnCircle_NumberOfPoints_SET(NativePointer, value);
}
/// <summary>
/// how we are choosing where the points are in the circle
/// </summary>
public EPointOnCircleSpacingMethod PointOnCircleSpacingMethod
{
get => (EPointOnCircleSpacingMethod)E_PROP_UEnvQueryGenerator_OnCircle_PointOnCircleSpacingMethod_GET(NativePointer);
set => E_PROP_UEnvQueryGenerator_OnCircle_PointOnCircleSpacingMethod_SET(NativePointer, (byte)value);
}
/// <summary>
/// items will be generated on a circle this much apart
/// </summary>
public FAIDataProviderFloatValue SpaceBetween
{
get => E_PROP_UEnvQueryGenerator_OnCircle_SpaceBetween_GET(NativePointer);
set => E_PROP_UEnvQueryGenerator_OnCircle_SpaceBetween_SET(NativePointer, value);
}
/// <summary>
/// horizontal trace for nearest obstacle
/// </summary>
public FEnvTraceData TraceData
{
get => E_PROP_UEnvQueryGenerator_OnCircle_TraceData_GET(NativePointer);
set => E_PROP_UEnvQueryGenerator_OnCircle_TraceData_SET(NativePointer, value);
}
#endregion
#region ExternMethods
protected FVector CalcDirection(FEnvQueryInstance queryInstance)
=> E_UEnvQueryGenerator_OnCircle_CalcDirection(this, queryInstance);
#endregion
public static implicit operator IntPtr(UEnvQueryGenerator_OnCircle self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator UEnvQueryGenerator_OnCircle(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<UEnvQueryGenerator_OnCircle>(PtrDesc);
}
}
}
| |
#region Copyright
//=======================================================================================
// [PLEASE DO NOT MODIFY THIS HEADER INFORMATION]---------------------
// Title: Grouper
// Description: A rounded groupbox with special painting features.
// Date Created: December 17, 2005
// Author: Adam Smith
// Author Email: ibulwark@hotmail.com
// Websites: http://www.ebadgeman.com | http://www.codevendor.com
//
// Version History:
// 1.0a - Beta Version - Release Date: December 17, 2005
//=======================================================================================
#endregion
#region Using Directives
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
#endregion
namespace Microsoft.WindowsAzure.CAT.ServiceBusExplorer
{
/// <summary>A special custom rounding GroupBox with many painting features.</summary>
[ToolboxBitmap(typeof(Grouper), "CodeVendor.Controls.Grouper.bmp")]
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public class Grouper : UserControl
{
#region Enumerations
/// <summary>A special gradient enumeration.</summary>
public enum GroupBoxGradientMode
{
/// <summary>Specifies no gradient mode.</summary>
None = 4,
/// <summary>Specifies a gradient from upper right to lower left.</summary>
BackwardDiagonal = 3,
/// <summary>Specifies a gradient from upper left to lower right.</summary>
ForwardDiagonal = 2,
/// <summary>Specifies a gradient from left to right.</summary>
Horizontal = 0,
/// <summary>Specifies a gradient from top to bottom.</summary>
Vertical = 1
}
#endregion
public event Action<PaintEventArgs> CustomPaint;
#region Variables
private Container components = null;
private int V_RoundCorners = 10;
private string V_GroupTitle = "The Grouper";
private Color V_BorderColor = Color.Black;
private float V_BorderThickness = 1;
private bool V_ShadowControl = false;
private Color V_BackgroundColor = Color.White;
private Color V_BackgroundGradientColor = Color.White;
private GroupBoxGradientMode V_BackgroundGradientMode = GroupBoxGradientMode.None;
private Color V_ShadowColor = Color.DarkGray;
private int V_ShadowThickness = 3;
private Image V_GroupImage = null;
private Color V_CustomGroupBoxColor = Color.White;
private bool V_PaintGroupBox = false;
private Color V_BackColor = Color.Transparent;
#endregion
#region Properties
/// <summary>This feature will paint the background color of the control.</summary>
[Category("Appearance"), Description("This feature will paint the background color of the control.")]
public override Color BackColor{get{return V_BackColor;} set{V_BackColor=value; this.Refresh();}}
/// <summary>This feature will paint the group title background to the specified color if PaintGroupBox is set to true.</summary>
[Category("Appearance"), Description("This feature will paint the group title background to the specified color if PaintGroupBox is set to true.")]
public Color CustomGroupBoxColor{get{return V_CustomGroupBoxColor;} set{V_CustomGroupBoxColor=value; this.Refresh();}}
/// <summary>This feature will paint the group title background to the CustomGroupBoxColor.</summary>
[Category("Appearance"), Description("This feature will paint the group title background to the CustomGroupBoxColor.")]
public bool PaintGroupBox{get{return V_PaintGroupBox;} set{V_PaintGroupBox=value; this.Refresh();}}
/// <summary>This feature can add a 16 x 16 image to the group title bar.</summary>
[Category("Appearance"), Description("This feature can add a 16 x 16 image to the group title bar.")]
public Image GroupImage{get{return V_GroupImage;} set{V_GroupImage=value; this.Refresh();}}
/// <summary>This feature will change the control's shadow color.</summary>
[Category("Appearance"), Description("This feature will change the control's shadow color.")]
public Color ShadowColor{get{return V_ShadowColor;} set{V_ShadowColor=value; this.Refresh();}}
/// <summary>This feature will change the size of the shadow border.</summary>
[Category("Appearance"), Description("This feature will change the size of the shadow border.")]
public int ShadowThickness
{
get{return V_ShadowThickness;}
set
{
if(value>10)
{
V_ShadowThickness=10;
}
else
{
if(value<1){V_ShadowThickness=1;}
else{V_ShadowThickness=value; }
}
this.Refresh();
}
}
/// <summary>This feature will change the group control color. This color can also be used in combination with BackgroundGradientColor for a gradient paint.</summary>
[Category("Appearance"), Description("This feature will change the group control color. This color can also be used in combination with BackgroundGradientColor for a gradient paint.")]
public Color BackgroundColor{get{return V_BackgroundColor;} set{V_BackgroundColor=value; this.Refresh();}}
/// <summary>This feature can be used in combination with BackgroundColor to create a gradient background.</summary>
[Category("Appearance"), Description("This feature can be used in combination with BackgroundColor to create a gradient background.")]
public Color BackgroundGradientColor{get{return V_BackgroundGradientColor;} set{V_BackgroundGradientColor=value; this.Refresh();}}
/// <summary>This feature turns on background gradient painting.</summary>
[Category("Appearance"), Description("This feature turns on background gradient painting.")]
public GroupBoxGradientMode BackgroundGradientMode{get{return V_BackgroundGradientMode;} set{V_BackgroundGradientMode=value; this.Refresh();}}
/// <summary>This feature will round the corners of the control.</summary>
[Category("Appearance"), Description("This feature will round the corners of the control.")]
public int RoundCorners
{
get{return V_RoundCorners;}
set
{
if(value>25)
{
V_RoundCorners=25;
}
else
{
if(value<1){V_RoundCorners=1;}
else{V_RoundCorners=value; }
}
this.Refresh();
}
}
/// <summary>This feature will add a group title to the control.</summary>
[Category("Appearance"), Description("This feature will add a group title to the control.")]
public string GroupTitle{get{return V_GroupTitle;} set{V_GroupTitle=value; this.Refresh();}}
/// <summary>This feature will allow you to change the color of the control's border.</summary>
[Category("Appearance"), Description("This feature will allow you to change the color of the control's border.")]
public Color BorderColor{get{return V_BorderColor;} set{V_BorderColor=value; this.Refresh();}}
/// <summary>This feature will allow you to set the control's border size.</summary>
[Category("Appearance"), Description("This feature will allow you to set the control's border size.")]
public float BorderThickness
{
get{return V_BorderThickness;}
set
{
if(value>3)
{
V_BorderThickness=3;
}
else
{
if(value<1){V_BorderThickness=1;}
else{V_BorderThickness=value;}
}
this.Refresh();
}
}
/// <summary>This feature will allow you to turn on control shadowing.</summary>
[Category("Appearance"), Description("This feature will allow you to turn on control shadowing.")]
public bool ShadowControl{get{return V_ShadowControl;} set{V_ShadowControl=value; this.Refresh();}}
#endregion
#region Constructor
/// <summary>This method will construct a new GroupBox control.</summary>
public Grouper()
{
InitializeStyles();
InitializeGroupBox();
}
#endregion
#region DeConstructor
/// <summary>This method will dispose of the GroupBox control.</summary>
protected override void Dispose( bool disposing )
{
if(disposing){if(components!=null){components.Dispose();}}
base.Dispose(disposing);
}
#endregion
#region Initialization
/// <summary>This method will initialize the controls custom styles.</summary>
private void InitializeStyles()
{
//Set the control styles----------------------------------
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
//--------------------------------------------------------
}
/// <summary>This method will initialize the GroupBox control.</summary>
private void InitializeGroupBox()
{
components = new System.ComponentModel.Container();
this.Resize+=new EventHandler(GroupBox_Resize);
this.DockPadding.All = 20;
this.Name = "GroupBox";
this.Size = new Size(368, 288);
}
#endregion
#region Protected Methods
/// <summary>Overrides the OnPaint method to paint control.</summary>
/// <param name="e">The paint event arguments.</param>
protected override void OnPaint(PaintEventArgs e)
{
PaintBack(e.Graphics);
PaintGroupText(e.Graphics);
if (CustomPaint != null)
{
CustomPaint(e);
}
}
#endregion
#region Private Methods
/// <summary>This method will paint the group title.</summary>
/// <param name="g">The paint event graphics object.</param>
private void PaintGroupText(Graphics g)
{
//Check if string has something-------------
if(GroupTitle==string.Empty){return;}
//------------------------------------------
//Set Graphics smoothing mode to Anit-Alias--
g.SmoothingMode = SmoothingMode.AntiAlias;
//-------------------------------------------
//Declare Variables------------------
SizeF StringSize = g.MeasureString(this.GroupTitle, this.Font);
Size StringSize2 = StringSize.ToSize();
if(this.GroupImage!=null){StringSize2.Width+=18;}
int ArcWidth = this.RoundCorners;
int ArcHeight = this.RoundCorners;
int ArcX1 = 20;
int ArcX2 = (StringSize2.Width+34) - (ArcWidth + 1);
int ArcY1 = 0;
int ArcY2 = 24 - (ArcHeight + 1);
GraphicsPath path = new GraphicsPath();
Brush BorderBrush = new SolidBrush(this.BorderColor);
Pen BorderPen = new Pen(BorderBrush, this.BorderThickness);
LinearGradientBrush BackgroundGradientBrush = null;
Brush BackgroundBrush = (this.PaintGroupBox) ? new SolidBrush(this.CustomGroupBoxColor) : new SolidBrush(this.BackgroundColor);
SolidBrush TextColorBrush = new SolidBrush(this.ForeColor);
SolidBrush ShadowBrush = null;
GraphicsPath ShadowPath = null;
//-----------------------------------
//Check if shadow is needed----------
if(ShadowControl)
{
ShadowBrush = new SolidBrush(this.ShadowColor);
ShadowPath = new GraphicsPath();
ShadowPath.AddArc(ArcX1+(this.ShadowThickness-1), ArcY1+(this.ShadowThickness-1), ArcWidth, ArcHeight, 180, GroupBoxConstants.SweepAngle); // TopCount Left
ShadowPath.AddArc(ArcX2+(this.ShadowThickness-1), ArcY1+(this.ShadowThickness-1), ArcWidth, ArcHeight, 270, GroupBoxConstants.SweepAngle); //TopCount Right
ShadowPath.AddArc(ArcX2+(this.ShadowThickness-1), ArcY2+(this.ShadowThickness-1), ArcWidth, ArcHeight, 360, GroupBoxConstants.SweepAngle); //Bottom Right
ShadowPath.AddArc(ArcX1+(this.ShadowThickness-1), ArcY2+(this.ShadowThickness-1), ArcWidth, ArcHeight, 90, GroupBoxConstants.SweepAngle); //Bottom Left
ShadowPath.CloseAllFigures();
//Paint Rounded Rectangle------------
g.FillPath(ShadowBrush, ShadowPath);
//-----------------------------------
}
//-----------------------------------
//Create Rounded Rectangle Path------
path.AddArc(ArcX1, ArcY1, ArcWidth, ArcHeight, 180, GroupBoxConstants.SweepAngle); // TopCount Left
path.AddArc(ArcX2, ArcY1, ArcWidth, ArcHeight, 270, GroupBoxConstants.SweepAngle); //TopCount Right
path.AddArc(ArcX2, ArcY2, ArcWidth, ArcHeight, 360, GroupBoxConstants.SweepAngle); //Bottom Right
path.AddArc(ArcX1, ArcY2, ArcWidth, ArcHeight, 90, GroupBoxConstants.SweepAngle); //Bottom Left
path.CloseAllFigures();
//-----------------------------------
//Check if Gradient Mode is enabled--
if(this.PaintGroupBox)
{
//Paint Rounded Rectangle------------
g.FillPath(BackgroundBrush, path);
//-----------------------------------
}
else
{
if(this.BackgroundGradientMode==GroupBoxGradientMode.None)
{
//Paint Rounded Rectangle------------
g.FillPath(BackgroundBrush, path);
//-----------------------------------
}
else
{
BackgroundGradientBrush = new LinearGradientBrush(new Rectangle(0,0,this.Width,this.Height), this.BackgroundColor, this.BackgroundGradientColor, (LinearGradientMode)this.BackgroundGradientMode);
//Paint Rounded Rectangle------------
g.FillPath(BackgroundGradientBrush, path);
//-----------------------------------
}
}
//-----------------------------------
//Paint Borded-----------------------
g.DrawPath(BorderPen, path);
//-----------------------------------
//Paint Text-------------------------
int CustomStringWidth = (this.GroupImage!=null) ? 44 : 28;
g.DrawString(this.GroupTitle, this.Font, TextColorBrush, CustomStringWidth, 5);
//-----------------------------------
//Draw GroupImage if there is one----
if(this.GroupImage!=null)
{
g.DrawImage(this.GroupImage, 28,4, 16, 16);
}
//-----------------------------------
//Destroy Graphic Objects------------
if(path!=null){path.Dispose();}
if(BorderBrush!=null){BorderBrush.Dispose();}
if(BorderPen!=null){BorderPen.Dispose();}
if(BackgroundGradientBrush!=null){BackgroundGradientBrush.Dispose();}
if(BackgroundBrush!=null){BackgroundBrush.Dispose();}
if(TextColorBrush!=null){TextColorBrush .Dispose();}
if(ShadowBrush!=null){ShadowBrush.Dispose();}
if(ShadowPath!=null){ShadowPath.Dispose();}
//-----------------------------------
}
/// <summary>This method will paint the control.</summary>
/// <param name="g">The paint event graphics object.</param>
private void PaintBack(Graphics g)
{
//Set Graphics smoothing mode to Anit-Alias--
g.SmoothingMode = SmoothingMode.AntiAlias;
//-------------------------------------------
//Declare Variables------------------
int ArcWidth = this.RoundCorners * 2;
int ArcHeight = this.RoundCorners * 2;
int ArcX1 = 0;
int ArcX2 = (this.ShadowControl) ? (this.Width - (ArcWidth + 1))-this.ShadowThickness : this.Width - (ArcWidth + 1);
int ArcY1 = 10;
int ArcY2 = (this.ShadowControl) ? (this.Height - (ArcHeight + 1))-this.ShadowThickness : this.Height - (ArcHeight + 1);
GraphicsPath path = new GraphicsPath();
Brush BorderBrush = new SolidBrush(this.BorderColor);
Pen BorderPen = new Pen(BorderBrush, this.BorderThickness);
LinearGradientBrush BackgroundGradientBrush = null;
Brush BackgroundBrush = new SolidBrush(this.BackgroundColor);
SolidBrush ShadowBrush = null;
GraphicsPath ShadowPath = null;
//-----------------------------------
//Check if shadow is needed----------
if(this.ShadowControl)
{
ShadowBrush = new SolidBrush(this.ShadowColor);
ShadowPath = new GraphicsPath();
ShadowPath.AddArc(ArcX1+this.ShadowThickness, ArcY1+this.ShadowThickness, ArcWidth, ArcHeight, 180, GroupBoxConstants.SweepAngle); // TopCount Left
ShadowPath.AddArc(ArcX2+this.ShadowThickness, ArcY1+this.ShadowThickness, ArcWidth, ArcHeight, 270, GroupBoxConstants.SweepAngle); //TopCount Right
ShadowPath.AddArc(ArcX2+this.ShadowThickness, ArcY2+this.ShadowThickness, ArcWidth, ArcHeight, 360, GroupBoxConstants.SweepAngle); //Bottom Right
ShadowPath.AddArc(ArcX1+this.ShadowThickness, ArcY2+this.ShadowThickness, ArcWidth, ArcHeight, 90, GroupBoxConstants.SweepAngle); //Bottom Left
ShadowPath.CloseAllFigures();
//Paint Rounded Rectangle------------
g.FillPath(ShadowBrush, ShadowPath);
//-----------------------------------
}
//-----------------------------------
//Create Rounded Rectangle Path------
path.AddArc(ArcX1, ArcY1, ArcWidth, ArcHeight, 180, GroupBoxConstants.SweepAngle); // TopCount Left
path.AddArc(ArcX2, ArcY1, ArcWidth, ArcHeight, 270, GroupBoxConstants.SweepAngle); //TopCount Right
path.AddArc(ArcX2, ArcY2, ArcWidth, ArcHeight, 360, GroupBoxConstants.SweepAngle); //Bottom Right
path.AddArc(ArcX1, ArcY2, ArcWidth, ArcHeight, 90, GroupBoxConstants.SweepAngle); //Bottom Left
path.CloseAllFigures();
//-----------------------------------
//Check if Gradient Mode is enabled--
if(this.BackgroundGradientMode==GroupBoxGradientMode.None)
{
//Paint Rounded Rectangle------------
g.FillPath(BackgroundBrush, path);
//-----------------------------------
}
else
{
BackgroundGradientBrush = new LinearGradientBrush(new Rectangle(0,0,this.Width,this.Height), this.BackgroundColor, this.BackgroundGradientColor, (LinearGradientMode)this.BackgroundGradientMode);
//Paint Rounded Rectangle------------
g.FillPath(BackgroundGradientBrush, path);
//-----------------------------------
}
//-----------------------------------
//Paint Borded-----------------------
g.DrawPath(BorderPen, path);
//-----------------------------------
//Destroy Graphic Objects------------
if(path!=null){path.Dispose();}
if(BorderBrush!=null){BorderBrush.Dispose();}
if(BorderPen!=null){BorderPen.Dispose();}
if(BackgroundGradientBrush!=null){BackgroundGradientBrush.Dispose();}
if(BackgroundBrush!=null){BackgroundBrush.Dispose();}
if(ShadowBrush!=null){ShadowBrush.Dispose();}
if(ShadowPath!=null){ShadowPath.Dispose();}
//-----------------------------------
}
/// <summary>This method fires when the GroupBox resize event occurs.</summary>
/// <param name="sender">The object the sent the event.</param>
/// <param name="e">The event arguments.</param>
private void GroupBox_Resize(object sender, EventArgs e)
{
this.Refresh();
}
#endregion
}
public class GroupBoxConstants
{
#region Constants
/// <summary>The sweep angle of the arc.</summary>
public const int SweepAngle = 90;
/// <summary>The minimum control height.</summary>
public const int MinControlHeight = 32;
/// <summary>The minimum control width.</summary>
public const int MinControlWidth = 96;
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using Xunit;
using LessIO;
using System.Linq;
namespace LessMsi.Tests
{
public class TestBase
{
[DebuggerHidden]
protected void ExtractAndCompareToMaster(string msiFileName)
{
var actualFileEntries = ExtractFilesFromMsi(msiFileName, null);
var expectedEntries = GetExpectedEntriesForMsi(msiFileName);
AssertAreEqual(expectedEntries, actualFileEntries);
}
[DebuggerHidden]
protected static void AssertAreEqual(FileEntryGraph expected, FileEntryGraph actual)
{
string msg;
if (!FileEntryGraph.CompareEntries(expected, actual, out msg))
{
throw new Exception(string.Format("FileEntryGraph entries are not the equal: {0}", msg));
}
}
protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull)
{
return ExtractFilesFromMsi(msiFileName, fileNamesToExtractOrNull, "");
}
protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull, string outputDir)
{
return ExtractFilesFromMsi(msiFileName, fileNamesToExtractOrNull, new Path(outputDir), true);
}
protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull, Path outputDir, bool returnFileEntryGraph)
{
return ExtractFilesFromMsi(msiFileName, fileNamesToExtractOrNull, outputDir, true, true);
}
/// <summary>
/// Extracts some or all of the files from the specified MSI and returns a <see cref="FileEntryGraph"/> representing the files that were extracted.
/// </summary>
/// <param name="msiFileName">The msi file to extract or null to extract all files.</param>
/// <param name="fileNamesToExtractOrNull">The files to extract from the MSI or null to extract all files.</param>
/// <param name="outputDir">A relative directory to extract output to or an empty string to use the default output directory.</param>
/// <param name="skipReturningFileEntryGraph">True to return the <see cref="FileEntryGraph"/>. Otherwise null will be returned.</param>
/// <param name="cleanOutputDirectoryBeforeExtracting">True to delete the output directory before extracting.</param>
protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull, Path outputDir, bool returnFileEntryGraph, bool cleanOutputDirectoryBeforeExtracting)
{
outputDir = GetTestOutputDir(outputDir, msiFileName);
if (cleanOutputDirectoryBeforeExtracting && FileSystem.Exists(outputDir))
{
FileSystem.RemoveDirectory(outputDir, true);
}
Debug.Assert(!FileSystem.Exists(outputDir), "Directory still exists!");
FileSystem.CreateDirectory(outputDir);
//ExtractViaCommandLine(outputDir, msiFileName);
ExtractInProcess(msiFileName, outputDir.PathString, fileNamesToExtractOrNull);
if (returnFileEntryGraph)
{
// build actual file entries extracted
var actualEntries = FileEntryGraph.GetActualEntries(outputDir.PathString, msiFileName);
// dump to actual dir (for debugging and updating tests)
actualEntries.Save(GetActualOutputFile(msiFileName));
return actualEntries;
}
else
{
return null;
}
}
/// <summary>
/// Returns a suitable output directory for test data while running the test.
/// If <paramref name="outputDir"/> is specified it is used and <paramref name="testNameOrMsiFileName"/> is ignored.
/// Alternatively, <paramref name="testNameOrMsiFileName"/> is used to generate a test dir.
/// </summary>
/// <param name="outputDir">The output dir to use or <see cref="Path.Empty"/>.</param>
/// <param name="testNameOrMsiFileName">
/// A test name (often the name of a msi file under test) to use to generate a test dir when <paramref name="testNameOrMsiFileName"/> is not specified.
/// </param>
/// <returns></returns>
protected Path GetTestOutputDir(Path outputDir, string testNameOrMsiFileName)
{
Path baseOutputDir = Path.Combine(AppPath, "MsiOutputTemp");
if (outputDir.IsEmpty || !outputDir.IsPathRooted)
outputDir = Path.Combine(baseOutputDir, "_" + testNameOrMsiFileName);
else
outputDir = Path.Combine(baseOutputDir, outputDir);
return outputDir;
}
private void ExtractInProcess(string msiFileName, string outputDir, string[] fileNamesToExtractOrNull)
{
//LessMsi.Program.DoExtraction(GetMsiTestFile(msiFileName).FullName, outputDir);
if (fileNamesToExtractOrNull == null)
{ //extract everything:
LessMsi.Msi.Wixtracts.ExtractFiles(GetMsiTestFile(msiFileName), outputDir);
}
else
{
LessMsi.Msi.Wixtracts.ExtractFiles(GetMsiTestFile(msiFileName), outputDir, fileNamesToExtractOrNull);
}
}
/// <summary>
/// This is an "old" way and it is difficul to debug (since it runs test out of proc), but it works.
/// </summary>
private void ExtractViaCommandLine(string msiFileName, string outputDir, string[] filenamesToExtractOrNull)
{
string args = string.Format(" /x \"{0}\" \"{1}\"", GetMsiTestFile(msiFileName), outputDir);
if (filenamesToExtractOrNull != null && filenamesToExtractOrNull.Length > 0)
throw new NotImplementedException();
string consoleOutput;
RunCommandLine(args, out consoleOutput);
}
protected int RunCommandLine(string commandlineArgs)
{
string temp;
return RunCommandLine(commandlineArgs, out temp);
}
/// <summary>
/// Runs lessmsi.exe via commandline.
/// </summary>
/// <param name="commandlineArgs">The arguments passed to lessmsi.exe</param>
/// <param name="consoleOutput">The console output.</param>
/// <returns>The exe return code.</returns>
protected int RunCommandLine(string commandlineArgs, out string consoleOutput)
{
// exec & wait
var startInfo = new ProcessStartInfo(LessIO.Path.Combine(AppPath, "lessmsi.exe").PathString, commandlineArgs);
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
var p = Process.Start(startInfo);
// Internal stdout buffer overflows easily if the output is too long (e.g. with a progress indicator enabled), so an async approach is needed here.
// See https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
var outputStringBuilder = new StringBuilder();
var outputWaitHandle = new AutoResetEvent(false);
p.OutputDataReceived += (sender, e) => {
if (e.Data == null) {
outputWaitHandle.Set();
}
else {
outputStringBuilder.AppendLine(e.Data);
}
};
p.BeginOutputReadLine();
bool exited = p.WaitForExit(1000*60) && outputWaitHandle.WaitOne(1000 * 60);
consoleOutput = outputStringBuilder.ToString();
if (!exited)
{
p.Kill();
throw new Exception("Process did not exit for commandlineArgs:" + commandlineArgs + "\n" + consoleOutput + "\n\n" + p.StandardError.ReadToEnd());
}
if (p.ExitCode == 0)
Debug.WriteLine(consoleOutput);
else
{
var errorOutput = p.StandardError.ReadToEnd();
throw new ExitCodeException(p.ExitCode, errorOutput, consoleOutput);
}
return p.ExitCode;
}
/// <summary>
/// Same as <see cref="RunCommandLine"/>, is useful for debugging.
/// </summary>
/// <param name="commandLineArgs"></param>
protected int RunCommandLineInProccess(string commandLineArgs)
{
//NOTE: Obviously oversimplified splitting of args.
var args = commandLineArgs.Split(' ');
for (var i = 0; i < args.Length; i++ )
{
args[i] = args[i].Trim('\"');
}
return LessMsi.Cli.Program.Main(args);
}
internal sealed class ExitCodeException : Exception
{
public ExitCodeException(int exitCode, string errorOutput, string consoleOutput)
: base("lessmsi.exe returned an error code (" + exitCode + "). Error output was:\r\n" + errorOutput + "\r\nConsole output was:\r\n" + consoleOutput)
{
this.ExitCode = exitCode;
}
public int ExitCode { get; set; }
}
/// <summary>
/// Loads the expected entries for the specified MSI file from the standard location.
/// </summary>
/// <param name="forMsi">The msi filename (no path) to load entries for.</param>
/// <returns>The <see cref="FileEntryGraph"/> representing the files that are expected to be extracted from the MSI.</returns>
protected FileEntryGraph GetExpectedEntriesForMsi(string forMsi)
{
return FileEntryGraph.Load(GetExpectedOutputFile(forMsi), forMsi);
}
protected Path GetMsiTestFile(string msiFileName)
{
return Path.Combine(AppPath, "TestFiles", "MsiInput", msiFileName);
}
private Path GetExpectedOutputFile(string msiFileName)
{
return Path.Combine(AppPath, "TestFiles", "ExpectedOutput", msiFileName + ".expected.csv");
}
protected Path GetActualOutputFile(string msiFileName)
{
// strip any subdirectories here since some input msi files have subdirectories.
msiFileName = Path.GetFileName(msiFileName);
var fi = Path.Combine(AppPath, msiFileName + ".actual.csv");
return fi;
}
protected Path AppPath
{
get
{
var codeBase = new Uri(this.GetType().Assembly.CodeBase);
var local = new Path(codeBase.LocalPath);
return local.Parent;
}
}
[DebuggerHidden]
protected void ExpectTables(string sourceFileName, string[] expectedTableNames)
{
using (var msidb = Msi.MsiDatabase.Create(GetMsiTestFile(sourceFileName)))
{
Assert.NotNull(msidb);
var query = "SELECT * FROM `_Tables`";
using (var msiTable = new Msi.ViewWrapper(msidb.OpenExecuteView(query)))
{
Assert.NotNull(msiTable);
var tableNames = from record in msiTable.Records
select record[0] as string;
// Since we don't care about the order, we sort the lists
Assert.Equal(expectedTableNames.OrderBy(s => s), tableNames.OrderBy(s => s));
}
}
}
[DebuggerHidden]
protected void ExpectStreamCabFiles(string sourceFileName, bool hasCab)
{
using (var stg = new OleStorage.OleStorageFile(GetMsiTestFile(sourceFileName)))
{
var strm = stg.GetStreams().Where(elem => OleStorage.OleStorageFile.IsCabStream(elem));
if (strm != null)
{
// Rest of the CAB parsing logic is in the UI, can't extract filenames without duplicating code that we want to test..
Assert.True(hasCab);
}
else
{
// Not expecting to find a cab here
Assert.False(hasCab);
}
}
}
}
}
| |
using Microsoft.Practices.ServiceLocation;
using Prism.Common;
using Prism.Events;
using Prism.Properties;
using Prism.Regions.Behaviors;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;
namespace Prism.Regions
{
/// <summary>
/// This class is responsible for maintaining a collection of regions and attaching regions to controls.
/// </summary>
/// <remarks>
/// This class supplies the attached properties that can be used for simple region creation from XAML.
/// </remarks>
public class RegionManager : IRegionManager
{
#region Static members (for XAML support)
private static readonly WeakDelegatesManager updatingRegionsListeners = new WeakDelegatesManager();
/// <summary>
/// Identifies the RegionName attached property.
/// </summary>
/// <remarks>
/// When a control has both the <see cref="RegionNameProperty"/> and
/// <see cref="RegionManagerProperty"/> attached properties set to
/// a value different than <see langword="null" /> and there is a
/// <see cref="IRegionAdapter"/> mapping registered for the control, it
/// will create and adapt a new region for that control, and register it
/// in the <see cref="IRegionManager"/> with the specified region name.
/// </remarks>
public static readonly DependencyProperty RegionNameProperty = DependencyProperty.RegisterAttached(
"RegionName",
typeof(string),
typeof(RegionManager),
new PropertyMetadata(OnSetRegionNameCallback));
/// <summary>
/// Sets the <see cref="RegionNameProperty"/> attached property.
/// </summary>
/// <param name="regionTarget">The object to adapt. This is typically a container (i.e a control).</param>
/// <param name="regionName">The name of the region to register.</param>
public static void SetRegionName(DependencyObject regionTarget, string regionName)
{
if (regionTarget == null)
throw new ArgumentNullException(nameof(regionTarget));
regionTarget.SetValue(RegionNameProperty, regionName);
}
/// <summary>
/// Gets the value for the <see cref="RegionNameProperty"/> attached property.
/// </summary>
/// <param name="regionTarget">The object to adapt. This is typically a container (i.e a control).</param>
/// <returns>The name of the region that should be created when
/// <see cref="RegionManagerProperty"/> is also set in this element.</returns>
public static string GetRegionName(DependencyObject regionTarget)
{
if (regionTarget == null)
throw new ArgumentNullException(nameof(regionTarget));
return regionTarget.GetValue(RegionNameProperty) as string;
}
private static readonly DependencyProperty ObservableRegionProperty =
DependencyProperty.RegisterAttached("ObservableRegion", typeof(ObservableObject<IRegion>), typeof(RegionManager), null);
/// <summary>
/// Returns an <see cref="ObservableObject{T}"/> wrapper that can hold an <see cref="IRegion"/>. Using this wrapper
/// you can detect when an <see cref="IRegion"/> has been created by the <see cref="RegionAdapterBase{T}"/>.
///
/// If the <see cref="ObservableObject{T}"/> wrapper does not yet exist, a new wrapper will be created. When the region
/// gets created and assigned to the wrapper, you can use the <see cref="ObservableObject{T}.PropertyChanged"/> event
/// to get notified of that change.
/// </summary>
/// <param name="view">The view that will host the region. </param>
/// <returns>Wrapper that can hold an <see cref="IRegion"/> value and can notify when the <see cref="IRegion"/> value changes. </returns>
public static ObservableObject<IRegion> GetObservableRegion(DependencyObject view)
{
if (view == null) throw new ArgumentNullException(nameof(view));
ObservableObject<IRegion> regionWrapper = view.GetValue(ObservableRegionProperty) as ObservableObject<IRegion>;
if (regionWrapper == null)
{
regionWrapper = new ObservableObject<IRegion>();
view.SetValue(ObservableRegionProperty, regionWrapper);
}
return regionWrapper;
}
private static void OnSetRegionNameCallback(DependencyObject element, DependencyPropertyChangedEventArgs args)
{
if (!IsInDesignMode(element))
{
CreateRegion(element);
}
}
private static void CreateRegion(DependencyObject element)
{
IServiceLocator locator = ServiceLocator.Current;
DelayedRegionCreationBehavior regionCreationBehavior = locator.GetInstance<DelayedRegionCreationBehavior>();
regionCreationBehavior.TargetElement = element;
regionCreationBehavior.Attach();
}
/// <summary>
/// Identifies the RegionManager attached property.
/// </summary>
/// <remarks>
/// When a control has both the <see cref="RegionNameProperty"/> and
/// <see cref="RegionManagerProperty"/> attached properties set to
/// a value different than <see langword="null" /> and there is a
/// <see cref="IRegionAdapter"/> mapping registered for the control, it
/// will create and adapt a new region for that control, and register it
/// in the <see cref="IRegionManager"/> with the specified region name.
/// </remarks>
public static readonly DependencyProperty RegionManagerProperty =
DependencyProperty.RegisterAttached("RegionManager", typeof(IRegionManager), typeof(RegionManager), null);
/// <summary>
/// Gets the value of the <see cref="RegionNameProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <returns>The <see cref="IRegionManager"/> attached to the <paramref name="target"/> element.</returns>
public static IRegionManager GetRegionManager(DependencyObject target)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
return (IRegionManager)target.GetValue(RegionManagerProperty);
}
/// <summary>
/// Sets the <see cref="RegionManagerProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <param name="value">The value.</param>
public static void SetRegionManager(DependencyObject target, IRegionManager value)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
target.SetValue(RegionManagerProperty, value);
}
/// <summary>
/// Identifies the RegionContext attached property.
/// </summary>
public static readonly DependencyProperty RegionContextProperty =
DependencyProperty.RegisterAttached("RegionContext", typeof(object), typeof(RegionManager), new PropertyMetadata(OnRegionContextChanged));
private static void OnRegionContextChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
if (RegionContext.GetObservableContext(depObj).Value != e.NewValue)
{
RegionContext.GetObservableContext(depObj).Value = e.NewValue;
}
}
/// <summary>
/// Gets the value of the <see cref="RegionContextProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <returns>The region context to pass to the contained views.</returns>
public static object GetRegionContext(DependencyObject target)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
return target.GetValue(RegionContextProperty);
}
/// <summary>
/// Sets the <see cref="RegionContextProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <param name="value">The value.</param>
public static void SetRegionContext(DependencyObject target, object value)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
target.SetValue(RegionContextProperty, value);
}
/// <summary>
/// Notification used by attached behaviors to update the region managers appropriatelly if needed to.
/// </summary>
/// <remarks>This event uses weak references to the event handler to prevent this static event of keeping the
/// target element longer than expected.</remarks>
public static event EventHandler UpdatingRegions
{
add { updatingRegionsListeners.AddListener(value); }
remove { updatingRegionsListeners.RemoveListener(value); }
}
/// <summary>
/// Notifies attached behaviors to update the region managers appropriatelly if needed to.
/// </summary>
/// <remarks>
/// This method is normally called internally, and there is usually no need to call this from user code.
/// </remarks>
public static void UpdateRegions()
{
try
{
updatingRegionsListeners.Raise(null, EventArgs.Empty);
}
catch (TargetInvocationException ex)
{
Exception rootException = ex.GetRootException();
throw new UpdateRegionsException(string.Format(CultureInfo.CurrentCulture,
Resources.UpdateRegionException, rootException), ex.InnerException);
}
}
private static bool IsInDesignMode(DependencyObject element)
{
return DesignerProperties.GetIsInDesignMode(element);
}
#endregion
private readonly RegionCollection regionCollection;
/// <summary>
/// Initializes a new instance of <see cref="RegionManager"/>.
/// </summary>
public RegionManager()
{
regionCollection = new RegionCollection(this);
}
/// <summary>
/// Gets a collection of <see cref="IRegion"/> that identify each region by name. You can use this collection to add or remove regions to the current region manager.
/// </summary>
/// <value>A <see cref="IRegionCollection"/> with all the registered regions.</value>
public IRegionCollection Regions
{
get { return regionCollection; }
}
/// <summary>
/// Creates a new region manager.
/// </summary>
/// <returns>A new region manager that can be used as a different scope from the current region manager.</returns>
public IRegionManager CreateRegionManager()
{
return new RegionManager();
}
/// <summary>
/// Add a view to the Views collection of a Region. Note that the region must already exist in this regionmanager.
/// </summary>
/// <param name="regionName">The name of the region to add a view to</param>
/// <param name="view">The view to add to the views collection</param>
/// <returns>The RegionManager, to easily add several views. </returns>
public IRegionManager AddToRegion(string regionName, object view)
{
if (!Regions.ContainsRegionWithName(regionName))
throw new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, Resources.RegionNotFound, regionName), nameof(regionName));
return Regions[regionName].Add(view);
}
/// <summary>
/// Associate a view with a region, by registering a type. When the region get's displayed
/// this type will be resolved using the ServiceLocator into a concrete instance. The instance
/// will be added to the Views collection of the region
/// </summary>
/// <param name="regionName">The name of the region to associate the view with.</param>
/// <param name="viewType">The type of the view to register with the </param>
/// <returns>The regionmanager, for adding several views easily</returns>
public IRegionManager RegisterViewWithRegion(string regionName, Type viewType)
{
var regionViewRegistry = ServiceLocator.Current.GetInstance<IRegionViewRegistry>();
regionViewRegistry.RegisterViewWithRegion(regionName, viewType);
return this;
}
/// <summary>
/// Associate a view with a region, using a delegate to resolve a concreate instance of the view.
/// When the region get's displayed, this delelgate will be called and the result will be added to the
/// views collection of the region.
/// </summary>
/// <param name="regionName">The name of the region to associate the view with.</param>
/// <param name="getContentDelegate">The delegate used to resolve a concreate instance of the view.</param>
/// <returns>The regionmanager, for adding several views easily</returns>
public IRegionManager RegisterViewWithRegion(string regionName, Func<object> getContentDelegate)
{
var regionViewRegistry = ServiceLocator.Current.GetInstance<IRegionViewRegistry>();
regionViewRegistry.RegisterViewWithRegion(regionName, getContentDelegate);
return this;
}
/// <summary>
/// Navigates the specified region manager.
/// </summary>
/// <param name="regionName">The name of the region to call Navigate on.</param>
/// <param name="source">The URI of the content to display.</param>
/// <param name="navigationCallback">The navigation callback.</param>
public void RequestNavigate(string regionName, Uri source, Action<NavigationResult> navigationCallback)
{
if (navigationCallback == null) throw new ArgumentNullException(nameof(navigationCallback));
if (Regions.ContainsRegionWithName(regionName))
{
Regions[regionName].RequestNavigate(source, navigationCallback);
}
else
{
navigationCallback(new NavigationResult(new NavigationContext(null, source), false));
}
}
/// <summary>
/// Navigates the specified region manager.
/// </summary>
/// <param name="regionName">The name of the region to call Navigate on.</param>
/// <param name="source">The URI of the content to display.</param>
public void RequestNavigate(string regionName, Uri source)
{
RequestNavigate(regionName, source, nr => { });
}
/// <summary>
/// Navigates the specified region manager.
/// </summary>
/// <param name="regionName">The name of the region to call Navigate on.</param>
/// <param name="source">The URI of the content to display.</param>
/// <param name="navigationCallback">The navigation callback.</param>
public void RequestNavigate(string regionName, string source, Action<NavigationResult> navigationCallback)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
RequestNavigate(regionName, new Uri(source, UriKind.RelativeOrAbsolute), navigationCallback);
}
/// <summary>
/// Navigates the specified region manager.
/// </summary>
/// <param name="regionName">The name of the region to call Navigate on.</param>
/// <param name="source">The URI of the content to display.</param>
public void RequestNavigate(string regionName, string source)
{
RequestNavigate(regionName, source, nr => { });
}
/// <summary>
/// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target Uri, passing a navigation callback and an instance of NavigationParameters, which holds a collection of object parameters.
/// </summary>
/// <param name="regionName">The name of the region where the navigation will occur.</param>
/// <param name="target">A Uri that represents the target where the region will navigate.</param>
/// <param name="navigationCallback">The navigation callback that will be executed after the navigation is completed.</param>
/// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param>
public void RequestNavigate(string regionName, Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters)
{
if (Regions.ContainsRegionWithName(regionName))
{
Regions[regionName].RequestNavigate(target, navigationCallback, navigationParameters);
}
}
/// <summary>
/// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target string, passing a navigation callback and an instance of NavigationParameters, which holds a collection of object parameters.
/// </summary>
/// <param name="regionName">The name of the region where the navigation will occur.</param>
/// <param name="target">A string that represents the target where the region will navigate.</param>
/// <param name="navigationCallback">The navigation callback that will be executed after the navigation is completed.</param>
/// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param>
public void RequestNavigate(string regionName, string target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters)
{
RequestNavigate(regionName, new Uri(target, UriKind.RelativeOrAbsolute), navigationCallback, navigationParameters);
}
/// <summary>
/// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target Uri, passing an instance of NavigationParameters, which holds a collection of object parameters.
/// </summary>
/// <param name="regionName">The name of the region where the navigation will occur.</param>
/// <param name="target">A Uri that represents the target where the region will navigate.</param>
/// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param>
public void RequestNavigate(string regionName, Uri target, NavigationParameters navigationParameters)
{
RequestNavigate(regionName, target, nr => { }, navigationParameters);
}
/// <summary>
/// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target string, passing an instance of NavigationParameters, which holds a collection of object parameters.
/// </summary>
/// <param name="regionName">The name of the region where the navigation will occur.</param>
/// <param name="target">A string that represents the target where the region will navigate.</param>
/// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param>
public void RequestNavigate(string regionName, string target, NavigationParameters navigationParameters)
{
RequestNavigate(regionName, new Uri(target, UriKind.RelativeOrAbsolute), nr => { }, navigationParameters);
}
private class RegionCollection : IRegionCollection
{
private readonly IRegionManager regionManager;
private readonly List<IRegion> regions;
public RegionCollection(IRegionManager regionManager)
{
this.regionManager = regionManager;
this.regions = new List<IRegion>();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public IEnumerator<IRegion> GetEnumerator()
{
UpdateRegions();
return this.regions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IRegion this[string regionName]
{
get
{
UpdateRegions();
IRegion region = GetRegionByName(regionName);
if (region == null)
{
throw new KeyNotFoundException(string.Format(CultureInfo.CurrentUICulture, Resources.RegionNotInRegionManagerException, regionName));
}
return region;
}
}
public void Add(IRegion region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
UpdateRegions();
if (region.Name == null)
{
throw new InvalidOperationException(Resources.RegionNameCannotBeEmptyException);
}
if (this.GetRegionByName(region.Name) != null)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
Resources.RegionNameExistsException, region.Name));
}
this.regions.Add(region);
region.RegionManager = this.regionManager;
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, region, 0));
}
public bool Remove(string regionName)
{
UpdateRegions();
bool removed = false;
IRegion region = GetRegionByName(regionName);
if (region != null)
{
removed = true;
this.regions.Remove(region);
region.RegionManager = null;
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, region, 0));
}
return removed;
}
public bool ContainsRegionWithName(string regionName)
{
UpdateRegions();
return GetRegionByName(regionName) != null;
}
/// <summary>
/// Adds a region to the regionmanager with the name received as argument.
/// </summary>
/// <param name="regionName">The name to be given to the region.</param>
/// <param name="region">The region to be added to the regionmanager.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="region"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="regionName"/> and <paramref name="region"/>'s name do not match and the <paramref name="region"/> <see cref="IRegion.Name"/> is not <see langword="null"/>.</exception>
public void Add(string regionName, IRegion region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
if (region.Name != null && region.Name != regionName)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.RegionManagerWithDifferentNameException, region.Name, regionName), nameof(regionName));
if (region.Name == null)
region.Name = regionName;
Add(region);
}
private IRegion GetRegionByName(string regionName)
{
return this.regions.FirstOrDefault(r => r.Name == regionName);
}
private void OnCollectionChanged(NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
var handler = this.CollectionChanged;
if (handler != null)
{
handler(this, notifyCollectionChangedEventArgs);
}
}
}
}
}
| |
namespace PulsarTales.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Init : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Announsments",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(),
DateAnnounced = c.DateTime(),
Content = c.String(),
IsDeleted = c.Boolean(nullable: false),
UserId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.Comments",
c => new
{
Id = c.Int(nullable: false, identity: true),
Message = c.String(),
DateCommented = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
UserId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
RegistrationDate = c.DateTime(),
IsMarkedAsDeleted = c.Boolean(nullable: false),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
CreateTable(
"dbo.Chapters",
c => new
{
Id = c.Int(nullable: false, identity: true),
Number = c.Int(nullable: false),
Title = c.String(nullable: false),
Content = c.String(nullable: false),
DateAdded = c.DateTime(),
UrlSuffix = c.String(),
IsDeleted = c.Boolean(nullable: false),
NovelId = c.Int(nullable: false),
TranslatorId = c.String(maxLength: 128),
EditorId = c.String(maxLength: 128),
WriterId = c.String(maxLength: 128),
TranslatorCheckerId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.EditorId)
.ForeignKey("dbo.Novels", t => t.NovelId, cascadeDelete: true)
.ForeignKey("dbo.AspNetUsers", t => t.TranslatorId)
.ForeignKey("dbo.AspNetUsers", t => t.TranslatorCheckerId)
.ForeignKey("dbo.AspNetUsers", t => t.WriterId)
.Index(t => t.NovelId)
.Index(t => t.TranslatorId)
.Index(t => t.EditorId)
.Index(t => t.WriterId)
.Index(t => t.TranslatorCheckerId);
CreateTable(
"dbo.Novels",
c => new
{
Id = c.Int(nullable: false, identity: true),
TitleEnglish = c.String(nullable: false),
TitleInOriginalLanguage = c.String(),
AuthorEnglishName = c.String(nullable: false),
AuthorNameInOriginalLanguage = c.String(),
DateAdded = c.DateTime(),
Description = c.String(nullable: false),
IsOngoing = c.Boolean(nullable: false),
IsTranslatedTale = c.Boolean(nullable: false),
IsOriginalTale = c.Boolean(nullable: false),
IsOtherTale = c.Boolean(nullable: false),
CoverImageUrl = c.String(),
Url = c.String(),
IsDeleted = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Genres",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false),
DateAdded = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
CreatorId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.CreatorId)
.Index(t => t.CreatorId);
CreateTable(
"dbo.AspNetUserClaims",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128),
ClaimType = c.String(),
ClaimValue = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUserLogins",
c => new
{
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 128),
UserId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUserRoles",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
RoleId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.RoleId);
CreateTable(
"dbo.FrequentlyAskedQuestions",
c => new
{
Id = c.Int(nullable: false, identity: true),
Question = c.String(),
Answer = c.String(),
DateAsked = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
UserId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex");
CreateTable(
"dbo.ChapterComments",
c => new
{
ChapterId = c.Int(nullable: false),
CommentId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.ChapterId, t.CommentId })
.ForeignKey("dbo.Chapters", t => t.ChapterId)
.ForeignKey("dbo.Comments", t => t.CommentId)
.Index(t => t.ChapterId)
.Index(t => t.CommentId);
CreateTable(
"dbo.NovelEditors",
c => new
{
NovelId = c.Int(nullable: false),
EditorId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.NovelId, t.EditorId })
.ForeignKey("dbo.Novels", t => t.NovelId)
.ForeignKey("dbo.AspNetUsers", t => t.EditorId)
.Index(t => t.NovelId)
.Index(t => t.EditorId);
CreateTable(
"dbo.NovelGenres",
c => new
{
NovelId = c.Int(nullable: false),
GenreId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.NovelId, t.GenreId })
.ForeignKey("dbo.Genres", t => t.NovelId)
.ForeignKey("dbo.Novels", t => t.GenreId)
.Index(t => t.NovelId)
.Index(t => t.GenreId);
CreateTable(
"dbo.NovelTranslationCheckers",
c => new
{
NovelId = c.Int(nullable: false),
TranslationCheckerId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.NovelId, t.TranslationCheckerId })
.ForeignKey("dbo.Novels", t => t.NovelId)
.ForeignKey("dbo.AspNetUsers", t => t.TranslationCheckerId)
.Index(t => t.NovelId)
.Index(t => t.TranslationCheckerId);
CreateTable(
"dbo.NovelTranslators",
c => new
{
NovelId = c.Int(nullable: false),
TranslatorId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.NovelId, t.TranslatorId })
.ForeignKey("dbo.Novels", t => t.NovelId)
.ForeignKey("dbo.AspNetUsers", t => t.TranslatorId)
.Index(t => t.NovelId)
.Index(t => t.TranslatorId);
CreateTable(
"dbo.NovelWriters",
c => new
{
NovelId = c.Int(nullable: false),
WriterId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.NovelId, t.WriterId })
.ForeignKey("dbo.Novels", t => t.NovelId)
.ForeignKey("dbo.AspNetUsers", t => t.WriterId)
.Index(t => t.NovelId)
.Index(t => t.WriterId);
CreateTable(
"dbo.AnnounsmentComments",
c => new
{
AnnounsmentId = c.Int(nullable: false),
CommentId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.AnnounsmentId, t.CommentId })
.ForeignKey("dbo.Announsments", t => t.AnnounsmentId)
.ForeignKey("dbo.Comments", t => t.CommentId)
.Index(t => t.AnnounsmentId)
.Index(t => t.CommentId);
}
public override void Down()
{
DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles");
DropForeignKey("dbo.FrequentlyAskedQuestions", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.Announsments", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AnnounsmentComments", "CommentId", "dbo.Comments");
DropForeignKey("dbo.AnnounsmentComments", "AnnounsmentId", "dbo.Announsments");
DropForeignKey("dbo.Comments", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.Chapters", "WriterId", "dbo.AspNetUsers");
DropForeignKey("dbo.Chapters", "TranslatorCheckerId", "dbo.AspNetUsers");
DropForeignKey("dbo.Chapters", "TranslatorId", "dbo.AspNetUsers");
DropForeignKey("dbo.Chapters", "NovelId", "dbo.Novels");
DropForeignKey("dbo.NovelWriters", "WriterId", "dbo.AspNetUsers");
DropForeignKey("dbo.NovelWriters", "NovelId", "dbo.Novels");
DropForeignKey("dbo.NovelTranslators", "TranslatorId", "dbo.AspNetUsers");
DropForeignKey("dbo.NovelTranslators", "NovelId", "dbo.Novels");
DropForeignKey("dbo.NovelTranslationCheckers", "TranslationCheckerId", "dbo.AspNetUsers");
DropForeignKey("dbo.NovelTranslationCheckers", "NovelId", "dbo.Novels");
DropForeignKey("dbo.Genres", "CreatorId", "dbo.AspNetUsers");
DropForeignKey("dbo.NovelGenres", "GenreId", "dbo.Novels");
DropForeignKey("dbo.NovelGenres", "NovelId", "dbo.Genres");
DropForeignKey("dbo.NovelEditors", "EditorId", "dbo.AspNetUsers");
DropForeignKey("dbo.NovelEditors", "NovelId", "dbo.Novels");
DropForeignKey("dbo.Chapters", "EditorId", "dbo.AspNetUsers");
DropForeignKey("dbo.ChapterComments", "CommentId", "dbo.Comments");
DropForeignKey("dbo.ChapterComments", "ChapterId", "dbo.Chapters");
DropIndex("dbo.AnnounsmentComments", new[] { "CommentId" });
DropIndex("dbo.AnnounsmentComments", new[] { "AnnounsmentId" });
DropIndex("dbo.NovelWriters", new[] { "WriterId" });
DropIndex("dbo.NovelWriters", new[] { "NovelId" });
DropIndex("dbo.NovelTranslators", new[] { "TranslatorId" });
DropIndex("dbo.NovelTranslators", new[] { "NovelId" });
DropIndex("dbo.NovelTranslationCheckers", new[] { "TranslationCheckerId" });
DropIndex("dbo.NovelTranslationCheckers", new[] { "NovelId" });
DropIndex("dbo.NovelGenres", new[] { "GenreId" });
DropIndex("dbo.NovelGenres", new[] { "NovelId" });
DropIndex("dbo.NovelEditors", new[] { "EditorId" });
DropIndex("dbo.NovelEditors", new[] { "NovelId" });
DropIndex("dbo.ChapterComments", new[] { "CommentId" });
DropIndex("dbo.ChapterComments", new[] { "ChapterId" });
DropIndex("dbo.AspNetRoles", "RoleNameIndex");
DropIndex("dbo.FrequentlyAskedQuestions", new[] { "UserId" });
DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" });
DropIndex("dbo.AspNetUserRoles", new[] { "UserId" });
DropIndex("dbo.AspNetUserLogins", new[] { "UserId" });
DropIndex("dbo.AspNetUserClaims", new[] { "UserId" });
DropIndex("dbo.Genres", new[] { "CreatorId" });
DropIndex("dbo.Chapters", new[] { "TranslatorCheckerId" });
DropIndex("dbo.Chapters", new[] { "WriterId" });
DropIndex("dbo.Chapters", new[] { "EditorId" });
DropIndex("dbo.Chapters", new[] { "TranslatorId" });
DropIndex("dbo.Chapters", new[] { "NovelId" });
DropIndex("dbo.AspNetUsers", "UserNameIndex");
DropIndex("dbo.Comments", new[] { "UserId" });
DropIndex("dbo.Announsments", new[] { "UserId" });
DropTable("dbo.AnnounsmentComments");
DropTable("dbo.NovelWriters");
DropTable("dbo.NovelTranslators");
DropTable("dbo.NovelTranslationCheckers");
DropTable("dbo.NovelGenres");
DropTable("dbo.NovelEditors");
DropTable("dbo.ChapterComments");
DropTable("dbo.AspNetRoles");
DropTable("dbo.FrequentlyAskedQuestions");
DropTable("dbo.AspNetUserRoles");
DropTable("dbo.AspNetUserLogins");
DropTable("dbo.AspNetUserClaims");
DropTable("dbo.Genres");
DropTable("dbo.Novels");
DropTable("dbo.Chapters");
DropTable("dbo.AspNetUsers");
DropTable("dbo.Comments");
DropTable("dbo.Announsments");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a set of projects and their source code documents.
/// </summary>
public partial class Solution
{
// SolutionState that doesn't hold onto Project/Document
private readonly SolutionState _state;
// Values for all these are created on demand.
private ImmutableHashMap<ProjectId, Project> _projectIdToProjectMap;
private Solution(SolutionState state)
{
_projectIdToProjectMap = ImmutableHashMap<ProjectId, Project>.Empty;
_state = state;
}
internal Solution(Workspace workspace, SolutionInfo info)
: this(new SolutionState(workspace, info))
{
}
internal SolutionState State => _state;
internal int WorkspaceVersion => _state.WorkspaceVersion;
internal SolutionServices Services => _state.Services;
internal BranchId BranchId => _state.BranchId;
internal ProjectState GetProjectState(ProjectId projectId) => _state.GetProjectState(projectId);
/// <summary>
/// The Workspace this solution is associated with.
/// </summary>
public Workspace Workspace => _state.Workspace;
/// <summary>
/// The Id of the solution. Multiple solution instances may share the same Id.
/// </summary>
public SolutionId Id => _state.Id;
/// <summary>
/// The path to the solution file or null if there is no solution file.
/// </summary>
public string FilePath => _state.FilePath;
/// <summary>
/// The solution version. This equates to the solution file's version.
/// </summary>
public VersionStamp Version => _state.Version;
/// <summary>
/// A list of all the ids for all the projects contained by the solution.
/// </summary>
public IReadOnlyList<ProjectId> ProjectIds => _state.ProjectIds;
/// <summary>
/// A list of all the projects contained by the solution.
/// </summary>
public IEnumerable<Project> Projects => ProjectIds.Select(id => GetProject(id));
/// <summary>
/// The version of the most recently modified project.
/// </summary>
public VersionStamp GetLatestProjectVersion() => _state.GetLatestProjectVersion();
/// <summary>
/// True if the solution contains a project with the specified project ID.
/// </summary>
public bool ContainsProject(ProjectId projectId) => _state.ContainsProject(projectId);
/// <summary>
/// Gets the project in this solution with the specified project ID.
///
/// If the id is not an id of a project that is part of this solution the method returns null.
/// </summary>
public Project GetProject(ProjectId projectId)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (this.ContainsProject(projectId))
{
return ImmutableHashMapExtensions.GetOrAdd(ref _projectIdToProjectMap, projectId, s_createProjectFunction, this);
}
return null;
}
private static readonly Func<ProjectId, Solution, Project> s_createProjectFunction = CreateProject;
private static Project CreateProject(ProjectId projectId, Solution solution)
{
return new Project(solution, solution.State.GetProjectState(projectId));
}
/// <summary>
/// Gets the <see cref="Project"/> associated with an assembly symbol.
/// </summary>
public Project GetProject(IAssemblySymbol assemblySymbol, CancellationToken cancellationToken = default(CancellationToken))
{
var projectState = _state.GetProjectState(assemblySymbol, cancellationToken);
return projectState == null ? null : GetProject(projectState.Id);
}
/// <summary>
/// True if the solution contains the document in one of its projects
/// </summary>
public bool ContainsDocument(DocumentId documentId) => _state.ContainsDocument(documentId);
/// <summary>
/// True if the solution contains the additional document in one of its projects
/// </summary>
public bool ContainsAdditionalDocument(DocumentId documentId) => _state.ContainsAdditionalDocument(documentId);
/// <summary>
/// Gets the documentId in this solution with the specified syntax tree.
/// </summary>
public DocumentId GetDocumentId(SyntaxTree syntaxTree) => GetDocumentId(syntaxTree, projectId: null);
/// <summary>
/// Gets the documentId in this solution with the specified syntax tree.
/// </summary>
public DocumentId GetDocumentId(SyntaxTree syntaxTree, ProjectId projectId)
{
if (syntaxTree != null)
{
// is this tree known to be associated with a document?
var documentId = DocumentState.GetDocumentIdForTree(syntaxTree);
if (documentId != null && (projectId == null || documentId.ProjectId == projectId))
{
// does this solution even have the document?
if (this.ContainsDocument(documentId))
{
return documentId;
}
}
}
return null;
}
/// <summary>
/// Gets the document in this solution with the specified document ID.
/// </summary>
public Document GetDocument(DocumentId documentId)
{
if (documentId != null && this.ContainsDocument(documentId))
{
return this.GetProject(documentId.ProjectId).GetDocument(documentId);
}
return null;
}
/// <summary>
/// Gets the additional document in this solution with the specified document ID.
/// </summary>
public TextDocument GetAdditionalDocument(DocumentId documentId)
{
if (documentId != null && this.ContainsAdditionalDocument(documentId))
{
return this.GetProject(documentId.ProjectId).GetAdditionalDocument(documentId);
}
return null;
}
/// <summary>
/// Gets the document in this solution with the specified syntax tree.
/// </summary>
public Document GetDocument(SyntaxTree syntaxTree)
{
return this.GetDocument(syntaxTree, projectId: null);
}
internal Document GetDocument(SyntaxTree syntaxTree, ProjectId projectId)
{
if (syntaxTree != null)
{
// is this tree known to be associated with a document?
var docId = DocumentState.GetDocumentIdForTree(syntaxTree);
if (docId != null && (projectId == null || docId.ProjectId == projectId))
{
// does this solution even have the document?
var document = this.GetDocument(docId);
if (document != null)
{
// does this document really have the syntax tree?
if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree)
{
return document;
}
}
}
}
return null;
}
/// <summary>
/// Creates a new solution instance that includes a project with the specified language and names.
/// Returns the new project.
/// </summary>
public Project AddProject(string name, string assemblyName, string language)
{
var id = ProjectId.CreateNewId(debugName: name);
return this.AddProject(id, name, assemblyName, language).GetProject(id);
}
/// <summary>
/// Creates a new solution instance that includes a project with the specified language and names.
/// </summary>
public Solution AddProject(ProjectId projectId, string name, string assemblyName, string language)
{
return this.AddProject(ProjectInfo.Create(projectId, VersionStamp.Create(), name, assemblyName, language));
}
/// <summary>
/// Create a new solution instance that includes a project with the specified project information.
/// </summary>
public Solution AddProject(ProjectInfo projectInfo)
{
var newState = _state.AddProject(projectInfo);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance without the project specified.
/// </summary>
public Solution RemoveProject(ProjectId projectId)
{
var newState = _state.RemoveProject(projectId);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the new
/// assembly name.
/// </summary>
public Solution WithProjectAssemblyName(ProjectId projectId, string assemblyName)
{
var newState = _state.WithProjectAssemblyName(projectId, assemblyName);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the output file path.
/// </summary>
public Solution WithProjectOutputFilePath(ProjectId projectId, string outputFilePath)
{
var newState = _state.WithProjectOutputFilePath(projectId, outputFilePath);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the name.
/// </summary>
public Solution WithProjectName(ProjectId projectId, string name)
{
var newState = _state.WithProjectName(projectId, name);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the project file path.
/// </summary>
public Solution WithProjectFilePath(ProjectId projectId, string filePath)
{
var newState = _state.WithProjectFilePath(projectId, filePath);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified compilation options.
/// </summary>
public Solution WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options)
{
var newState = _state.WithProjectCompilationOptions(projectId, options);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified parse options.
/// </summary>
public Solution WithProjectParseOptions(ProjectId projectId, ParseOptions options)
{
var newState = _state.WithProjectParseOptions(projectId, options);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified hasAllInformation.
/// </summary>
// TODO: make it public
internal Solution WithHasAllInformation(ProjectId projectId, bool hasAllInformation)
{
var newState = _state.WithHasAllInformation(projectId, hasAllInformation);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include
/// the specified project reference.
/// </summary>
public Solution AddProjectReference(ProjectId projectId, ProjectReference projectReference)
{
var newState = _state.AddProjectReference(projectId, projectReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include
/// the specified project references.
/// </summary>
public Solution AddProjectReferences(ProjectId projectId, IEnumerable<ProjectReference> projectReferences)
{
var newState = _state.AddProjectReferences(projectId, projectReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer
/// include the specified project reference.
/// </summary>
public Solution RemoveProjectReference(ProjectId projectId, ProjectReference projectReference)
{
var newState = _state.RemoveProjectReference(projectId, projectReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to contain
/// the specified list of project references.
/// </summary>
public Solution WithProjectReferences(ProjectId projectId, IEnumerable<ProjectReference> projectReferences)
{
var newState = _state.WithProjectReferences(projectId, projectReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified metadata reference.
/// </summary>
public Solution AddMetadataReference(ProjectId projectId, MetadataReference metadataReference)
{
var newState = _state.AddMetadataReference(projectId, metadataReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified metadata references.
/// </summary>
public Solution AddMetadataReferences(ProjectId projectId, IEnumerable<MetadataReference> metadataReferences)
{
var newState = _state.AddMetadataReferences(projectId, metadataReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer include
/// the specified metadata reference.
/// </summary>
public Solution RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference)
{
var newState = _state.RemoveMetadataReference(projectId, metadataReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include only the
/// specified metadata references.
/// </summary>
public Solution WithProjectMetadataReferences(ProjectId projectId, IEnumerable<MetadataReference> metadataReferences)
{
var newState = _state.WithProjectMetadataReferences(projectId, metadataReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified analyzer reference.
/// </summary>
public Solution AddAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference)
{
var newState = _state.AddAnalyzerReference(projectId, analyzerReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified analyzer references.
/// </summary>
public Solution AddAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences)
{
var newState = _state.AddAnalyzerReferences(projectId, analyzerReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer include
/// the specified analyzer reference.
/// </summary>
public Solution RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference)
{
var newState = _state.RemoveAnalyzerReference(projectId, analyzerReference);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include only the
/// specified analyzer references.
/// </summary>
public Solution WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences)
{
var newState = _state.WithProjectAnalyzerReferences(projectId, analyzerReferences);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
private static SourceCodeKind GetSourceCodeKind(ProjectState project)
{
return project.ParseOptions != null ? project.ParseOptions.Kind : SourceCodeKind.Regular;
}
/// <summary>
/// Creates a new solution instance with the corresponding project updated to include a new
/// document instance defined by its name and text.
/// </summary>
public Solution AddDocument(DocumentId documentId, string name, string text, IEnumerable<string> folders = null, string filePath = null)
{
return this.AddDocument(documentId, name, SourceText.From(text), folders, filePath);
}
/// <summary>
/// Creates a new solution instance with the corresponding project updated to include a new
/// document instance defined by its name and text.
/// </summary>
public Solution AddDocument(DocumentId documentId, string name, SourceText text, IEnumerable<string> folders = null, string filePath = null, bool isGenerated = false)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
var project = _state.GetProjectState(documentId.ProjectId);
var version = VersionStamp.Create();
var loader = TextLoader.From(TextAndVersion.Create(text, version, name));
var info = DocumentInfo.Create(
documentId,
name: name,
folders: folders,
sourceCodeKind: GetSourceCodeKind(project),
loader: loader,
filePath: filePath,
isGenerated: isGenerated);
return this.AddDocument(info);
}
/// <summary>
/// Creates a new solution instance with the corresponding project updated to include a new
/// document instance defined by its name and root <see cref="SyntaxNode"/>.
/// </summary>
public Solution AddDocument(DocumentId documentId, string name, SyntaxNode syntaxRoot, IEnumerable<string> folders = null, string filePath = null, bool isGenerated = false, PreservationMode preservationMode = PreservationMode.PreserveValue)
{
return this.AddDocument(documentId, name, SourceText.From(string.Empty), folders, filePath, isGenerated).WithDocumentSyntaxRoot(documentId, syntaxRoot, preservationMode);
}
/// <summary>
/// Creates a new solution instance with the project updated to include a new document with
/// the arguments specified.
/// </summary>
public Solution AddDocument(DocumentId documentId, string name, TextLoader loader, IEnumerable<string> folders = null)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (loader == null)
{
throw new ArgumentNullException(nameof(loader));
}
var project = _state.GetProjectState(documentId.ProjectId);
var info = DocumentInfo.Create(
documentId,
name: name,
folders: folders,
sourceCodeKind: GetSourceCodeKind(project),
loader: loader);
return this.AddDocument(info);
}
/// <summary>
/// Create a new solution instance with the corresponding project updated to include a new
/// document instanced defined by the document info.
/// </summary>
public Solution AddDocument(DocumentInfo documentInfo)
{
var newState = _state.AddDocument(documentInfo);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the corresponding project updated to include a new
/// additional document instance defined by its name and text.
/// </summary>
public Solution AddAdditionalDocument(DocumentId documentId, string name, string text, IEnumerable<string> folders = null, string filePath = null)
{
return this.AddAdditionalDocument(documentId, name, SourceText.From(text), folders, filePath);
}
/// <summary>
/// Creates a new solution instance with the corresponding project updated to include a new
/// additional document instance defined by its name and text.
/// </summary>
public Solution AddAdditionalDocument(DocumentId documentId, string name, SourceText text, IEnumerable<string> folders = null, string filePath = null)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
var project = _state.GetProjectState(documentId.ProjectId);
var version = VersionStamp.Create();
var loader = TextLoader.From(TextAndVersion.Create(text, version, name));
var info = DocumentInfo.Create(
documentId,
name: name,
folders: folders,
sourceCodeKind: GetSourceCodeKind(project),
loader: loader,
filePath: filePath);
return this.AddAdditionalDocument(info);
}
public Solution AddAdditionalDocument(DocumentInfo documentInfo)
{
var newState = _state.AddAdditionalDocument(documentInfo);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance that no longer includes the specified document.
/// </summary>
public Solution RemoveDocument(DocumentId documentId)
{
var newState = _state.RemoveDocument(documentId);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance that no longer includes the specified additional document.
/// </summary>
public Solution RemoveAdditionalDocument(DocumentId documentId)
{
var newState = _state.RemoveAdditionalDocument(documentId);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the new name.
/// </summary>
public Solution WithDocumentName(DocumentId documentId, string name)
{
var newState = _state.WithDocumentName(documentId, name);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to be contained in
/// the sequence of logical folders.
/// </summary>
public Solution WithDocumentFolders(DocumentId documentId, IEnumerable<string> folders)
{
var newState = _state.WithDocumentFolders(documentId, folders);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the specified file path.
/// </summary>
public Solution WithDocumentFilePath(DocumentId documentId, string filePath)
{
var newState = _state.WithDocumentFilePath(documentId, filePath);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// specified.
/// </summary>
public Solution WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithDocumentText(documentId, text, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// specified.
/// </summary>
public Solution WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithAdditionalDocumentText(documentId, text, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// and version specified.
/// </summary>
public Solution WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithDocumentText(documentId, textAndVersion, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// and version specified.
/// </summary>
public Solution WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithAdditionalDocumentText(documentId, textAndVersion, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have a syntax tree
/// rooted by the specified syntax node.
/// </summary>
public Solution WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithDocumentSyntaxRoot(documentId, root, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the source
/// code kind specified.
/// </summary>
public Solution WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind)
{
var newState = _state.WithDocumentSourceCodeKind(documentId, sourceCodeKind);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// supplied by the text loader.
/// </summary>
public Solution WithDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode)
{
return WithDocumentTextLoader(documentId, loader, textOpt: null, mode: mode);
}
internal Solution WithDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText textOpt, PreservationMode mode)
{
var newState = _state.WithDocumentTextLoader(documentId, loader, textOpt, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// supplied by the text loader.
/// </summary>
public Solution WithAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode)
{
var newState = _state.WithAdditionalDocumentTextLoader(documentId, loader, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is
/// busy building this compilations.
///
/// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document.
///
/// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead.
/// </summary>
internal async Task<Solution> WithFrozenPartialCompilationIncludingSpecificDocumentAsync(DocumentId documentId, CancellationToken cancellationToken)
{
var newState = await _state.WithFrozenPartialCompilationIncludingSpecificDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
return new Solution(newState);
}
internal async Task<Solution> WithMergedLinkedFileChangesAsync(
Solution oldSolution,
SolutionChanges? solutionChanges = null,
IMergeConflictHandler mergeConflictHandler = null,
CancellationToken cancellationToken = default(CancellationToken))
{
// we only log sessioninfo for actual changes committed to workspace which should exclude ones from preview
var session = new LinkedFileDiffMergingSession(oldSolution, this, solutionChanges ?? this.GetChanges(oldSolution), logSessionInfo: solutionChanges != null);
return (await session.MergeDiffsAsync(mergeConflictHandler, cancellationToken).ConfigureAwait(false)).MergedSolution;
}
internal ImmutableArray<DocumentId> GetRelatedDocumentIds(DocumentId documentId)
{
var projectState = _state.GetProjectState(documentId.ProjectId);
if (projectState == null)
{
// this document no longer exist
return ImmutableArray<DocumentId>.Empty;
}
var documentState = projectState.GetDocumentState(documentId);
if (documentState == null)
{
// this document no longer exist
return ImmutableArray<DocumentId>.Empty;
}
var filePath = documentState.FilePath;
if (string.IsNullOrEmpty(filePath))
{
// this document can't have any related document. only related document is itself.
return ImmutableArray.Create<DocumentId>(documentId);
}
var documentIds = this.GetDocumentIdsWithFilePath(filePath);
return this.FilterDocumentIdsByLanguage(documentIds, projectState.ProjectInfo.Language).ToImmutableArray();
}
internal Solution WithNewWorkspace(Workspace workspace, int workspaceVersion)
{
var newState = _state.WithNewWorkspace(workspace, workspaceVersion);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Gets a copy of the solution isolated from the original so that they do not share computed state.
///
/// Use isolated solutions when doing operations that are likely to access a lot of text,
/// syntax trees or compilations that are unlikely to be needed again after the operation is done.
/// When the isolated solution is reclaimed so will the computed state.
/// </summary>
public Solution GetIsolatedSolution()
{
var newState = _state.GetIsolatedSolution();
return new Solution(newState);
}
/// <summary>
/// Creates a new solution instance with all the documents specified updated to have the same specified text.
/// </summary>
public Solution WithDocumentText(IEnumerable<DocumentId> documentIds, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var newState = _state.WithDocumentText(documentIds, text, mode);
if (newState == _state)
{
return this;
}
return new Solution(newState);
}
/// <summary>
/// Gets an objects that lists the added, changed and removed projects between
/// this solution and the specified solution.
/// </summary>
public SolutionChanges GetChanges(Solution oldSolution)
{
if (oldSolution == null)
{
throw new ArgumentNullException(nameof(oldSolution));
}
return new SolutionChanges(this, oldSolution);
}
/// <summary>
/// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a
/// <see cref="TextDocument.FilePath"/> that matches the given file path.
/// </summary>
public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string filePath) => _state.GetDocumentIdsWithFilePath(filePath);
/// <summary>
/// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution.
/// </summary>
public ProjectDependencyGraph GetProjectDependencyGraph() => _state.GetProjectDependencyGraph();
/// <summary>
/// Returns the options that should be applied to this solution. This is equivalent to <see cref="Workspace.Options" /> when the <see cref="Solution"/>
/// instance was created.
/// </summary>
public OptionSet Options
{
get
{
// TODO: actually make this a snapshot
return this.Workspace.Options;
}
}
}
}
| |
using System;
using UnityEngine;
using UnityEngine.Assertions;
/// TODO handle lives / Game over
/// TODO handle character alignment
/// TODO handle Damage direction here or in the HitBox but must be done :)
namespace UnityPlatformer {
/// <summary>
/// Tracks character health and lives.
///
/// Triggers character damage/death
/// </summary>
public class CharacterHealth : MonoBehaviour {
/// <summary>
/// Character alignment
/// </summary>
public Alignment alignment = Alignment.None;
/// <summary>
/// Can recieve Damage from friends? (same alignment)
/// </summary>
public bool friendlyFire = false;
/// <summary>
/// Health the character will have when game starts
/// </summary>
[Comment("Health the character will have when game starts")]
public int startingHealth = 1;
/// <summary>
/// Maximum health (-1 no maximum). NOTE if startingHealth == maxHealth will trigger onMaxHealth on Start.
/// </summary>
[Comment("Maximum health (-1 no maximum). NOTE if startingHealth == maxHealth will trigger onMaxHealth on Start.")]
public int maxHealth = 1;
/// <summary>
/// Lives the character starts with (-1 no lives)
/// </summary>
[Comment("Lives the character starts with (-1 no lives)")]
public int startingLives = 1;
/// <summary>
/// Maximum lives of the character. 2,147,483,647 is the maximum :)
/// </summary>
[Comment("Maximum lives of the character. 2,147,483,647 is the maximum :)")]
public int maxLives = 1;
/// <summary>
/// After any Damage how much time the character will be invulnerable to any Damage (0 to disable)
/// </summary>
[Comment("After any Damage how much time the character will be invulnerable to any Damage (0 to disable)")]
public float invulnerabilityTimeAfterDamage = 2.0f;
/// <summary>
/// List of damages that are ignored
///
/// NOTE: this can give your character super powers! use it with caution!
/// </summary>
[Comment("List of damages that are ignored")]
[EnumFlagsAttribute]
public DamageType immunity = 0;
/// <summary>
/// Fired when Character heal and now it's at maxHealth
/// </summary>
public Action onMaxHealth;
/// <summary>
/// Fired when character is damaged.
///
/// Will be fired even it the character is inmmune
/// </summary>
public Action onDamage;
/// <summary>
/// Fired after onDamage and Character is inmmune to given Damage
/// </summary>
public Action onImmunity;
/// <summary>
/// Callback type for onHurt
/// </summary>
public delegate void HurtCallback(Damage dt, CharacterHealth to);
/// <summary>
/// This Character health is reduced, will fire after onDamage
///
/// dt is the Damage dealed
/// to is the CharacterHealth that hurt me, if possible, could be null
/// </summary>
public HurtCallback onInjured;
/// <summary>
/// This Character deal damage to other
///
/// dt is the Damage dealed
/// to is the CharacterHealth hurted
/// </summary>
public HurtCallback onHurt;
/// <summary>
/// Display some greenish starts floating around!
/// </summary>
public Action onHeal;
/// <summary>
/// Play death animation, turn off the music... those sort of things
/// </summary>
public Action onDeath;
/// <summary>
/// Credits...
/// </summary>
public Action onGameOver;
/// <summary>
/// Play that funky music! Quake-damage!
///
/// NOTE this can be fired many times before onInvulnerabilityEnd
/// </summary>
public Action onInvulnerabilityStart;
/// <summary>
/// Stop that funky music!
/// </summary>
public Action onInvulnerabilityEnd;
/// <summary>
/// After death when there are lives player can respawn
/// </summary>
public Action onRespawn;
// NOTE do not use setter/getter to trigger death, we need to preserve
// logical Action dispacthing
/// <summary>
/// Character health
/// </summary>
[HideInInspector]
public int health = 0;
/// <summary>
/// Character lives
/// </summary>
[HideInInspector]
public int lives = 0;
/// <summary>
/// Character owner of this CharacterHealth
/// </summary>
[HideInInspector]
public Character character;
/// <summary>
/// Time counter for invulnerability
/// </summary>
private Cooldown invulnerability;
/// <summary>
/// check missconfiguration and initialization
/// </summary>
public void Start() {
Assert.IsFalse(startingHealth < maxHealth, "(CharacterHealth) startingHealth < maxHealth: " + gameObject.GetFullName());
Assert.IsFalse(startingLives < maxLives, "(CharacterHealth) startingLives < maxLives: " + gameObject.GetFullName());
character = GetComponent<Character>();
Assert.IsNotNull(character, "(CharacterHealth) Character is required: " + gameObject.GetFullName());
Heal(startingHealth);
lives = startingLives;
invulnerability = new Cooldown(invulnerabilityTimeAfterDamage);
invulnerability.onReady += () => {
if (onInvulnerabilityEnd != null) {
onInvulnerabilityEnd();
}
};
invulnerability.onReset += () => {
if (onInvulnerabilityStart != null) {
onInvulnerabilityStart();
}
};
}
/// <summary>
/// Turns a character invulnerable, but still can be killed using Kill
///
/// NOTE use float.MaxValue for unlimited time
/// </summary>
public void SetInvulnerable(float time) {
invulnerability.Set(time);
invulnerability.Reset();
}
/// <summary>
/// disable invulnerability
/// </summary>
public void SetVulnerable() {
invulnerability.Clear();
}
/// <summary>
/// Character is invulnerable?
/// </summary>
public bool IsInvulnerable() {
// is death? leave him alone...
return health <= 0 || !invulnerability.Ready();
}
/// <summary>
/// Kill the character even if it's invulnerable
/// </summary>
public void Kill() {
health = 0;
Die();
}
/// <summary>
/// Try to Damage the Character
/// </summary>
public void Damage(Damage dmg) {
Debug.LogFormat("Object: {0} recieve damage {1} health {2} from: {3}",
gameObject.GetFullName(), dmg.amount, health, dmg.causer.gameObject.GetFullName());
Assert.IsNotNull(dmg.causer, "(CharacterHealth) Damage without causer: " + dmg.gameObject.GetFullName());
if (friendlyFire && dmg.causer.alignment == alignment && !dmg.friendlyFire) {
Debug.LogFormat("Damage is not meant for friends, ignore");
return;
}
if (Damage(dmg.amount, dmg.type, dmg.causer)) {
if (dmg.causer.onHurt != null) {
dmg.causer.onHurt(dmg, this);
}
}
}
/// <summary>
/// Try to Damage the Character
/// </summary>
public bool Damage(int amount, DamageType dt, CharacterHealth causer = null) {
Debug.LogFormat("immunity {0} DamageType {1} alignment {2}", immunity, dt, alignment);
if (!friendlyFire && causer.alignment == alignment) {
Debug.LogFormat("Cannot recieve damage from the same alignment");
return false;
}
if ((immunity & dt) == dt) {
Debug.LogFormat("Inmune to {0} attacks", dt);
if (onDamage != null) {
onDamage();
}
if (onImmunity != null) {
onImmunity();
}
return false;
}
return Damage(amount, causer);
}
/// <summary>
/// Try to Damage the Character
///
/// triggers onDamage
/// triggers onDeath
/// NOTE this won't trigger onHurtCharacter
/// </summary>
public bool Damage(int amount = 1, CharacterHealth causer = null) {
if (amount <= 0) {
Debug.LogWarning("amount <= 0 ??");
}
if (IsInvulnerable()) {
Debug.Log(gameObject.GetFullName() + " is invulnerable, ignore damage");
if (onDamage != null) {
onDamage();
}
if (onImmunity != null) {
onImmunity();
}
return false;
}
health -= amount;
// do not set invulnerable a dead Character
if (health > 0) {
SetInvulnerable(invulnerabilityTimeAfterDamage);
}
if (onDamage != null) {
onDamage();
}
if (onInjured != null) {
onInjured(null, causer);
}
if (health <= 0) {
Die();
}
return true;
}
/// <summary>
/// No healt
/// </summary>
public bool isDead() {
return health <= 0;
}
/// <summary>
/// increse health character if possible maxHealth not reached.
/// Trigger onMaxHealth
/// </summary>
public void Heal(int amount = 1) {
health += amount;
if (onHeal != null) {
onHeal();
}
if (maxHealth != -1 && health >= maxHealth) {
health = maxHealth;
if (onMaxHealth != null) {
onMaxHealth();
}
}
}
public void DisableAllHitBoxes() {
Debug.Log(gameObject.GetFullName() + " disable all HitBox(es)");
var lch = GetComponentsInChildren<HitBox> ();
foreach (var x in lch) {
x.gameObject.SetActive(false);
}
Debug.Log(gameObject.GetFullName() + " disable all Damage(s)");
var ldt = GetComponentsInChildren<Damage> ();
foreach (var x in ldt) {
x.gameObject.SetActive(false);
}
}
/// <summary>
/// Disable HitBox(es) and DamageType(s)
/// Trigger onDeath
/// </summary>
public void Die() {
--lives;
if (onDeath != null) {
Debug.Log(gameObject.GetFullName() + " died!");
onDeath();
}
if (lives == 0) {
if (onGameOver != null) {
Debug.Log(gameObject.GetFullName() + " game-over!");
onGameOver();
}
} else {
// disable invulnerability
// respawn
Heal(startingHealth);
if (onRespawn != null) {
onRespawn();
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
public static unsafe class DateTimeTests
{
[Fact]
public static void TestConstructors()
{
DateTime dt = new DateTime(2012, 6, 11);
ValidateYearMonthDay(dt, 2012, 6, 11);
dt = new DateTime(2012, 12, 31, 13, 50, 10);
ValidateYearMonthDay(dt, 2012, 12, 31, 13, 50, 10);
dt = new DateTime(1973, 10, 6, 14, 30, 0, 500);
ValidateYearMonthDay(dt, 1973, 10, 6, 14, 30, 0, 500);
dt = new DateTime(1986, 8, 15, 10, 20, 5, DateTimeKind.Local);
ValidateYearMonthDay(dt, 1986, 8, 15, 10, 20, 5);
}
[Fact]
public static void TestDateTimeLimits()
{
DateTime dt = DateTime.MaxValue;
ValidateYearMonthDay(dt, 9999, 12, 31);
dt = DateTime.MinValue;
ValidateYearMonthDay(dt, 1, 1, 1);
}
[Fact]
public static void TestLeapYears()
{
Assert.Equal(true, DateTime.IsLeapYear(2004));
Assert.Equal(false, DateTime.IsLeapYear(2005));
}
[Fact]
public static void TestAddition()
{
DateTime dt = new DateTime(1986, 8, 15, 10, 20, 5, 70);
Assert.Equal(17, dt.AddDays(2).Day);
Assert.Equal(13, dt.AddDays(-2).Day);
Assert.Equal(10, dt.AddMonths(2).Month);
Assert.Equal(6, dt.AddMonths(-2).Month);
Assert.Equal(1996, dt.AddYears(10).Year);
Assert.Equal(1976, dt.AddYears(-10).Year);
Assert.Equal(13, dt.AddHours(3).Hour);
Assert.Equal(7, dt.AddHours(-3).Hour);
Assert.Equal(25, dt.AddMinutes(5).Minute);
Assert.Equal(15, dt.AddMinutes(-5).Minute);
Assert.Equal(35, dt.AddSeconds(30).Second);
Assert.Equal(2, dt.AddSeconds(-3).Second);
Assert.Equal(80, dt.AddMilliseconds(10).Millisecond);
Assert.Equal(60, dt.AddMilliseconds(-10).Millisecond);
}
[Fact]
public static void TestDayOfWeek()
{
DateTime dt = new DateTime(2012, 6, 18);
Assert.Equal(DayOfWeek.Monday, dt.DayOfWeek);
}
[Fact]
public static void TestTimeSpan()
{
DateTime dt = new DateTime(2012, 6, 18, 10, 5, 1, 0);
TimeSpan ts = dt.TimeOfDay;
DateTime newDate = dt.Subtract(ts);
Assert.Equal(new DateTime(2012, 6, 18, 0, 0, 0, 0).Ticks, newDate.Ticks);
Assert.Equal(dt.Ticks, newDate.Add(ts).Ticks);
}
[Fact]
public static void TestToday()
{
DateTime today = DateTime.Today;
DateTime now = DateTime.Now;
ValidateYearMonthDay(today, now.Year, now.Month, now.Day);
today = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc);
Assert.Equal(DateTimeKind.Utc, today.Kind);
Assert.Equal(false, today.IsDaylightSavingTime());
}
[Fact]
public static void TestCoversion()
{
DateTime today = DateTime.Today;
long dateTimeRaw = today.ToBinary();
Assert.Equal(today, DateTime.FromBinary(dateTimeRaw));
dateTimeRaw = today.ToFileTime();
Assert.Equal(today, DateTime.FromFileTime(dateTimeRaw));
dateTimeRaw = today.ToFileTimeUtc();
Assert.Equal(today, DateTime.FromFileTimeUtc(dateTimeRaw).ToLocalTime());
}
[Fact]
public static void TestOperators()
{
System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0);
// diff1 gets 185 days, 14 hours, and 47 minutes.
System.TimeSpan diff1 = date2.Subtract(date1);
Assert.Equal(new TimeSpan(185, 14, 47, 0), diff1);
// date4 gets 4/9/1996 5:55:00 PM.
System.DateTime date4 = date3.Subtract(diff1);
Assert.Equal(new DateTime(1996, 4, 9, 17, 55, 0), date4);
// diff2 gets 55 days 4 hours and 20 minutes.
System.TimeSpan diff2 = date2 - date3;
Assert.Equal(new TimeSpan(55, 4, 20, 0), diff2);
// date5 gets 4/9/1996 5:55:00 PM.
System.DateTime date5 = date1 - diff2;
Assert.Equal(new DateTime(1996, 4, 9, 17, 55, 0), date5);
}
[Fact]
public static void TestParsingDateTimeWithTimeDesignator()
{
DateTime result;
Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(5, result.Hour);
Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(17, result.Hour);
}
public class MyFormater : IFormatProvider
{
public object GetFormat(Type formatType)
{
if (typeof(IFormatProvider) == formatType)
{
return this;
}
else
{
return null;
}
}
}
[Fact]
public static void TestParseWithAdjustToUniversal()
{
var formater = new MyFormater();
var dateBefore = DateTime.Now.ToString();
var dateAfter = DateTime.ParseExact(dateBefore, "G", formater, DateTimeStyles.AdjustToUniversal);
Assert.Equal(dateBefore, dateAfter.ToString());
}
[Fact]
public static void TestFormatParse()
{
DateTime dt = new DateTime(2012, 12, 21, 10, 8, 6);
CultureInfo ci = new CultureInfo("ja-JP");
string s = string.Format(ci, "{0}", dt);
Assert.Equal(dt, DateTime.Parse(s, ci));
}
[Fact]
public static void TestParse1()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString();
DateTime in_1 = DateTime.Parse(s);
String actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParse2()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString();
DateTime in_1 = DateTime.Parse(s, null);
String actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParse3()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString();
DateTime in_1 = DateTime.Parse(s, null, DateTimeStyles.None);
String actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact3()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
DateTime in_1 = DateTime.ParseExact(s, "g", null);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact4()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
DateTime in_1 = DateTime.ParseExact(s, "g", null, DateTimeStyles.None);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact4a()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
String[] formats = { "g" };
DateTime in_1 = DateTime.ParseExact(s, formats, null, DateTimeStyles.None);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParse2()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
DateTime in_1;
bool b = DateTime.TryParse(s, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParse4()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
DateTime in_1;
bool b = DateTime.TryParse(s, null, DateTimeStyles.None, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParseExact()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
DateTime in_1;
bool b = DateTime.TryParseExact(s, "g", null, DateTimeStyles.None, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParseExactA()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
String[] formats = { "g" };
DateTime in_1;
bool b = DateTime.TryParseExact(s, formats, null, DateTimeStyles.None, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestGetDateTimeFormats()
{
char[] allStandardFormats =
{
'd', 'D', 'f', 'F', 'g', 'G',
'm', 'M', 'o', 'O', 'r', 'R',
's', 't', 'T', 'u', 'U', 'y', 'Y',
};
DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15);
List<string> july28Formats = new List<string>();
foreach (char format in allStandardFormats)
{
string[] dates = july28.GetDateTimeFormats(format);
Assert.True(dates.Length > 0);
DateTime parsedDate;
Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate));
july28Formats.AddRange(dates);
}
List<string> actualJuly28Formats = july28.GetDateTimeFormats().ToList();
Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t));
actualJuly28Formats = july28.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList();
Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t));
}
[Theory]
[InlineData("fi-FI")]
[InlineData("nb-NO")]
[InlineData("nb-SJ")]
[InlineData("sr-Cyrl-XK")]
[InlineData("sr-Latn-ME")]
[InlineData("sr-Latn-RS")]
[InlineData("sr-Latn-XK")]
[ActiveIssue(3391)]
public static void TestDateTimeParsingWithSpecialCultures(string cultureName)
{
// Test DateTime parsing with cultures which has the date separator and time separator are same
CultureInfo ci;
try
{
ci = new CultureInfo(cultureName);
}
catch (CultureNotFoundException)
{
// ignore un-supported culture in current platform
return;
}
DateTime date = DateTime.Now;
// truncate the milliseconds as it is not showing in time formatting patterns
date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);
string dateString = date.ToString(ci.DateTimeFormat.ShortDatePattern, ci);
DateTime parsedDate;
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date.Date, parsedDate);
dateString = date.ToString(ci.DateTimeFormat.LongDatePattern, ci);
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date.Date, parsedDate);
dateString = date.ToString(ci.DateTimeFormat.FullDateTimePattern, ci);
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date, parsedDate);
dateString = date.ToString(ci.DateTimeFormat.LongTimePattern, ci);
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date.TimeOfDay, parsedDate.TimeOfDay);
}
[Fact]
public static void TestGetDateTimeFormats_FormatSpecifier_InvalidFormat()
{
DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15);
Assert.Throws<FormatException>(() => july28.GetDateTimeFormats('x'));
}
internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day)
{
Assert.Equal(dt.Year, year);
Assert.Equal(dt.Month, month);
Assert.Equal(dt.Day, day);
}
internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day, int hour, int minute, int second)
{
ValidateYearMonthDay(dt, year, month, day);
Assert.Equal(dt.Hour, hour);
Assert.Equal(dt.Minute, minute);
Assert.Equal(dt.Second, second);
}
internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day, int hour, int minute, int second, int millisecond)
{
ValidateYearMonthDay(dt, year, month, day, hour, minute, second);
Assert.Equal(dt.Millisecond, millisecond);
}
}
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using ZXing.Aztec.Internal;
using ZXing.Common;
namespace ZXing.Aztec.Test
{
/// <summary>
/// Tests for the Detector
/// @author Frank Yellin
/// </summary>
public class DetectorTest
{
private static readonly Encoding LATIN_1 = Encoding.GetEncoding("ISO-8859-1");
[Test]
public void testErrorInParameterLocatorZeroZero()
{
// Layers=1, CodeWords=1. So the parameter info and its Reed-Solomon info
// will be completely zero!
testErrorInParameterLocator("X");
}
[Test]
public void testErrorInParameterLocatorCompact()
{
testErrorInParameterLocator("This is an example Aztec symbol for Wikipedia.");
}
[Test]
public void testErrorInParameterLocatorNotCompact()
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz";
testErrorInParameterLocator(alphabet + alphabet + alphabet);
}
// Test that we can tolerate errors in the parameter locator bits
private static void testErrorInParameterLocator(String data)
{
var aztec = Internal.Encoder.encode(LATIN_1.GetBytes(data), 25, Internal.Encoder.DEFAULT_AZTEC_LAYERS);
var random = new Random(aztec.Matrix.GetHashCode()); // pseudo-random, but deterministic
var layers = aztec.Layers;
var compact = aztec.isCompact;
var orientationPoints = getOrientationPoints(aztec);
foreach (bool isMirror in new[] {false, true})
{
foreach (BitMatrix matrix in getRotations(aztec.Matrix))
{
// Systematically try every possible 1- and 2-bit error.
for (int error1 = 0; error1 < orientationPoints.Count; error1++)
{
for (int error2 = error1; error2 < orientationPoints.Count; error2++)
{
BitMatrix copy = isMirror ? transpose(matrix) : clone(matrix);
copy.flip(orientationPoints[error1].X, orientationPoints[error1].Y);
if (error2 > error1)
{
// if error2 == error1, we only test a single error
copy.flip(orientationPoints[error2].X, orientationPoints[error2].Y);
}
// The detector doesn't seem to work when matrix bits are only 1x1. So magnify.
AztecDetectorResult r = new Detector(makeLarger(copy, 3)).detect(isMirror);
Assert.IsNotNull(r);
Assert.AreEqual(r.NbLayers, layers);
Assert.AreEqual(r.Compact, compact);
DecoderResult res = new Internal.Decoder().decode(r);
Assert.AreEqual(data, res.Text);
}
}
// Try a few random three-bit errors;
for (int i = 0; i < 5; i++)
{
BitMatrix copy = clone(matrix);
#if !SILVERLIGHT
ISet<int> errors = new SortedSet<int>();
#else
ISet<int> errors = new HashSet<int>();
#endif
while (errors.Count < 3)
{
// Quick and dirty way of getting three distinct integers between 1 and n.
errors.Add(random.Next(orientationPoints.Count));
}
foreach (int error in errors)
{
copy.flip(orientationPoints[error].X, orientationPoints[error].Y);
}
var result = new Detector(makeLarger(copy, 3)).detect(false);
if (result != null)
{
Assert.Fail("Should not reach here");
}
}
}
}
}
// Zooms a bit matrix so that each bit is factor x factor
private static BitMatrix makeLarger(BitMatrix input, int factor)
{
var width = input.Width;
var output = new BitMatrix(width*factor);
for (var inputY = 0; inputY < width; inputY++)
{
for (var inputX = 0; inputX < width; inputX++)
{
if (input[inputX, inputY])
{
output.setRegion(inputX*factor, inputY*factor, factor, factor);
}
}
}
return output;
}
// Returns a list of the four rotations of the BitMatrix.
private static List<BitMatrix> getRotations(BitMatrix matrix0)
{
BitMatrix matrix90 = rotateRight(matrix0);
BitMatrix matrix180 = rotateRight(matrix90);
BitMatrix matrix270 = rotateRight(matrix180);
return new List<BitMatrix> {matrix0, matrix90, matrix180, matrix270};
}
// Rotates a square BitMatrix to the right by 90 degrees
private static BitMatrix rotateRight(BitMatrix input)
{
var width = input.Width;
var result = new BitMatrix(width);
for (var x = 0; x < width; x++)
{
for (var y = 0; y < width; y++)
{
if (input[x, y])
{
result[y, width - x - 1] = true;
}
}
}
return result;
}
// Returns the transpose of a bit matrix, which is equivalent to rotating the
// matrix to the right, and then flipping it left-to-right
private static BitMatrix transpose(BitMatrix input)
{
var width = input.Width;
var result = new BitMatrix(width);
for (var x = 0; x < width; x++)
{
for (var y = 0; y < width; y++)
{
if (input[x, y])
{
result[y, x] = true;
}
}
}
return result;
}
private static BitMatrix clone(BitMatrix input)
{
var width = input.Width;
var result = new BitMatrix(width);
for (var x = 0; x < width; x++)
{
for (var y = 0; y < width; y++)
{
if (input[x, y])
{
result[x, y] = true;
}
}
}
return result;
}
private static List<Detector.Point> getOrientationPoints(AztecCode code)
{
var center = code.Matrix.Width/2;
var offset = code.isCompact ? 5 : 7;
var result = new List<Detector.Point>();
for (var xSign = -1; xSign <= 1; xSign += 2)
{
for (var ySign = -1; ySign <= 1; ySign += 2)
{
result.Add(new Detector.Point(center + xSign*offset, center + ySign*offset));
result.Add(new Detector.Point(center + xSign*(offset - 1), center + ySign*offset));
result.Add(new Detector.Point(center + xSign*offset, center + ySign*(offset - 1)));
}
}
return result;
}
public static void Shuffle<T>(IList<T> list, Random random)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = random.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
| |
using System;
using System.Text;
using BloomFilter;
using System.Collections;
using System.Collections.Generic;
namespace BloomFilterApp
{
class MainClass
{
private static Dictionary<string, string> Arguments;
private static string FastaPath;
private static double ErrorRate;
private static int WordSize;
private static Filter bloomFilter;
public static void Main(string[] args)
{
#region Parse Arguments.
Arguments = new Dictionary<string, string>();
// Load arguments into a dictionary.
foreach (string argument in args)
{
string[] splitted = argument.Split('=');
if (splitted.Length == 2)
{
Arguments[splitted[0]] = splitted[1];
}
}
// Check FASTA argument
FastaPath = GetArgument("fasta");
if (FastaPath == null)
Console.WriteLine("No FASTA file selected.");
else
{
Console.WriteLine("Selected FASTA file: " + FastaPath);
// Check word size argument
int tempWordSize;
if (int.TryParse(GetArgument("wordSize"), out tempWordSize))
{
if (tempWordSize <= 0)
{
Console.WriteLine("Invalid word size. Has to be > 0.");
Console.WriteLine("Using default word size value of 20.");
WordSize = 20;
}
else
{
WordSize = tempWordSize;
}
}
else
{
Console.WriteLine("Word size not specified.");
Console.WriteLine("Using default word size value of 20.");
WordSize = 20;
}
}
// Check false positive probability argument
double tempErrorRate;
if (double.TryParse(GetArgument("errorRate"), out tempErrorRate))
{
if (tempErrorRate <= 0 || tempErrorRate >= 1)
{
Console.WriteLine("Invalid error rate range. Has to be in interval <0,1>.");
Console.WriteLine("Using default error rate value of 0.05.");
ErrorRate = 0.05;
}
else
{
ErrorRate = tempErrorRate;
}
}
else
{
Console.WriteLine("Error rate not specified.");
Console.WriteLine("Using default value of 0.05.");
ErrorRate = 0.05;
}
#endregion
if (FastaPath != null)
{
#region FASTA input,
// Read FASTA.
FASTAReader fastaReader = new FASTAReader(FastaPath, WordSize);
fastaReader.ReadFASTA();
fastaReader.SplitIntoWords();
// Create filter.
bloomFilter = new Filter(fastaReader.Words.Count, ErrorRate);
PrintFilterInfo();
// Add words from FASTA to filter.
foreach (string word in fastaReader.Words)
{
bloomFilter.Add(word);
}
// Check membership.
TestMembershipLoop();
#endregion
}
else
{
#region Manual input.
// Get number of elements that user wishes to insert.
bool validNumElements = false;
int numElements = 0;
while (!validNumElements)
{
Console.WriteLine("How many elements would you like to add? ");
string numElementsString = Console.ReadLine();
if (int.TryParse(numElementsString, out numElements))
{
if (numElements <= 0)
{
Console.WriteLine("Must be > 0.");
}
else
{
validNumElements = true;
}
}
else
{
Console.WriteLine("Invalid input.");
}
if (!validNumElements)
{
Console.WriteLine("Please enter again.");
}
}
// Create bloom filter.
bloomFilter = new Filter(numElements, ErrorRate);
PrintFilterInfo();
// Insert elements.
while (numElements > 0)
{
Console.WriteLine("Please enter item you wish to add: ");
string toAdd = Console.ReadLine();
if (toAdd.Length > 0)
{
bloomFilter.Add(toAdd);
numElements--;
}
else
{
Console.WriteLine("Invalid input.");
}
}
// Check membership.
TestMembershipLoop();
#endregion
}
}
/// <summary>
/// Loops and prompts user for input that will be checked if it exists in filter.
/// </summary>
public static void TestMembershipLoop()
{
Console.WriteLine("You can now test if item is in filter.");
while (true)
{
Console.WriteLine("Please enter item to be checked: ");
string toCheck = Console.ReadLine();
if (toCheck.Length > 0)
{
bool inFilter = bloomFilter.InFilter(toCheck);
if (inFilter)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(toCheck + " probably is in filter (" + ((1 - ErrorRate) * 100) + "%).");
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(toCheck + " is not in filter.");
Console.ResetColor();
}
}
else
{
Console.WriteLine("Invalid input.");
}
}
}
/// <summary>
/// Gets the argument.
/// </summary>
/// <returns>The argument.</returns>
/// <param name="argName">Argument name.</param>
public static string GetArgument(string argName)
{
if (Arguments.ContainsKey(argName))
return Arguments[argName];
else
return null;
}
/// <summary>
/// Prints basic information about bloom filter.
/// </summary>
public static void PrintFilterInfo()
{
Console.WriteLine("Bloom filter info: ");
Console.WriteLine("\t- Expected number of elements (N): " + bloomFilter.N);
Console.WriteLine("\t- Number of hash functions (K): " + bloomFilter.K);
Console.WriteLine("\t- Lengh of bit array (M): " + bloomFilter.M);
}
/// <summary>
/// Prints values of BitArray in a nice grid.
/// </summary>
/// <param name="myList">BitArray.</param>
/// <param name="myWidth">Number of columns.</param>
public static void PrintFilterValues( IEnumerable myList, int myWidth ) {
Console.WriteLine("Bit Array Values:");
int i = myWidth;
foreach ( Object obj in myList ) {
if ( i <= 0 ) {
i = myWidth;
Console.WriteLine();
}
i--;
Console.Write( "{0,8}", obj );
}
Console.WriteLine();
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Courses
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SC : EduHubEntity
{
#region Navigation Property Cache
private SU Cache_SUBJ01_SU;
private SU Cache_SUBJ02_SU;
private SU Cache_SUBJ03_SU;
private SU Cache_SUBJ04_SU;
private SU Cache_SUBJ05_SU;
private SU Cache_SUBJ06_SU;
private SU Cache_SUBJ07_SU;
private SU Cache_SUBJ08_SU;
private SU Cache_SUBJ09_SU;
private SU Cache_SUBJ10_SU;
private SU Cache_SUBJ11_SU;
private SU Cache_SUBJ12_SU;
private SU Cache_SUBJ13_SU;
private SU Cache_SUBJ14_SU;
private SU Cache_SUBJ15_SU;
private SU Cache_SUBJ16_SU;
private SU Cache_SUBJ17_SU;
private SU Cache_SUBJ18_SU;
private SU Cache_SUBJ19_SU;
private SU Cache_SUBJ20_SU;
private KCY Cache_SUBJECT_ACADEMIC_YEAR_KCY;
#endregion
#region Foreign Navigation Properties
private IReadOnlyList<STMA> Cache_COURSE_STMA_CKEY;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Course code (same type as SU)
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string COURSE { get; internal set; }
/// <summary>
/// Course name
/// [Alphanumeric (30)]
/// </summary>
public string NAME { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ01 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ02 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ03 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ04 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ05 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ06 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ07 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ08 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ09 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ10 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ11 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ12 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ13 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ14 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ15 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ16 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ17 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ18 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ19 { get; internal set; }
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ20 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS01 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS02 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS03 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS04 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS05 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS06 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS07 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS08 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS09 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS10 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS11 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS12 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS13 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS14 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS15 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS16 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS17 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS18 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS19 { get; internal set; }
/// <summary>
/// Class set
/// </summary>
public short? CLASS20 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK01 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK02 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK03 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK04 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK05 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK06 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK07 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK08 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK09 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK10 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK11 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK12 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK13 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK14 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK15 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK16 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK17 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK18 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK19 { get; internal set; }
/// <summary>
/// Whether a student is locked into the class
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string LOCK20 { get; internal set; }
/// <summary>
/// Default academic year of subjects
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string SUBJECT_ACADEMIC_YEAR { get; internal set; }
/// <summary>
/// Default semester of subjsects
/// </summary>
public short? SEMESTER { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last write operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ01]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ01_SU
{
get
{
if (SUBJ01 == null)
{
return null;
}
if (Cache_SUBJ01_SU == null)
{
Cache_SUBJ01_SU = Context.SU.FindBySUKEY(SUBJ01);
}
return Cache_SUBJ01_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ02]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ02_SU
{
get
{
if (SUBJ02 == null)
{
return null;
}
if (Cache_SUBJ02_SU == null)
{
Cache_SUBJ02_SU = Context.SU.FindBySUKEY(SUBJ02);
}
return Cache_SUBJ02_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ03]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ03_SU
{
get
{
if (SUBJ03 == null)
{
return null;
}
if (Cache_SUBJ03_SU == null)
{
Cache_SUBJ03_SU = Context.SU.FindBySUKEY(SUBJ03);
}
return Cache_SUBJ03_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ04]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ04_SU
{
get
{
if (SUBJ04 == null)
{
return null;
}
if (Cache_SUBJ04_SU == null)
{
Cache_SUBJ04_SU = Context.SU.FindBySUKEY(SUBJ04);
}
return Cache_SUBJ04_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ05]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ05_SU
{
get
{
if (SUBJ05 == null)
{
return null;
}
if (Cache_SUBJ05_SU == null)
{
Cache_SUBJ05_SU = Context.SU.FindBySUKEY(SUBJ05);
}
return Cache_SUBJ05_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ06]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ06_SU
{
get
{
if (SUBJ06 == null)
{
return null;
}
if (Cache_SUBJ06_SU == null)
{
Cache_SUBJ06_SU = Context.SU.FindBySUKEY(SUBJ06);
}
return Cache_SUBJ06_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ07]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ07_SU
{
get
{
if (SUBJ07 == null)
{
return null;
}
if (Cache_SUBJ07_SU == null)
{
Cache_SUBJ07_SU = Context.SU.FindBySUKEY(SUBJ07);
}
return Cache_SUBJ07_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ08]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ08_SU
{
get
{
if (SUBJ08 == null)
{
return null;
}
if (Cache_SUBJ08_SU == null)
{
Cache_SUBJ08_SU = Context.SU.FindBySUKEY(SUBJ08);
}
return Cache_SUBJ08_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ09]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ09_SU
{
get
{
if (SUBJ09 == null)
{
return null;
}
if (Cache_SUBJ09_SU == null)
{
Cache_SUBJ09_SU = Context.SU.FindBySUKEY(SUBJ09);
}
return Cache_SUBJ09_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ10]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ10_SU
{
get
{
if (SUBJ10 == null)
{
return null;
}
if (Cache_SUBJ10_SU == null)
{
Cache_SUBJ10_SU = Context.SU.FindBySUKEY(SUBJ10);
}
return Cache_SUBJ10_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ11]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ11_SU
{
get
{
if (SUBJ11 == null)
{
return null;
}
if (Cache_SUBJ11_SU == null)
{
Cache_SUBJ11_SU = Context.SU.FindBySUKEY(SUBJ11);
}
return Cache_SUBJ11_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ12]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ12_SU
{
get
{
if (SUBJ12 == null)
{
return null;
}
if (Cache_SUBJ12_SU == null)
{
Cache_SUBJ12_SU = Context.SU.FindBySUKEY(SUBJ12);
}
return Cache_SUBJ12_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ13]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ13_SU
{
get
{
if (SUBJ13 == null)
{
return null;
}
if (Cache_SUBJ13_SU == null)
{
Cache_SUBJ13_SU = Context.SU.FindBySUKEY(SUBJ13);
}
return Cache_SUBJ13_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ14]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ14_SU
{
get
{
if (SUBJ14 == null)
{
return null;
}
if (Cache_SUBJ14_SU == null)
{
Cache_SUBJ14_SU = Context.SU.FindBySUKEY(SUBJ14);
}
return Cache_SUBJ14_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ15]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ15_SU
{
get
{
if (SUBJ15 == null)
{
return null;
}
if (Cache_SUBJ15_SU == null)
{
Cache_SUBJ15_SU = Context.SU.FindBySUKEY(SUBJ15);
}
return Cache_SUBJ15_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ16]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ16_SU
{
get
{
if (SUBJ16 == null)
{
return null;
}
if (Cache_SUBJ16_SU == null)
{
Cache_SUBJ16_SU = Context.SU.FindBySUKEY(SUBJ16);
}
return Cache_SUBJ16_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ17]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ17_SU
{
get
{
if (SUBJ17 == null)
{
return null;
}
if (Cache_SUBJ17_SU == null)
{
Cache_SUBJ17_SU = Context.SU.FindBySUKEY(SUBJ17);
}
return Cache_SUBJ17_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ18]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ18_SU
{
get
{
if (SUBJ18 == null)
{
return null;
}
if (Cache_SUBJ18_SU == null)
{
Cache_SUBJ18_SU = Context.SU.FindBySUKEY(SUBJ18);
}
return Cache_SUBJ18_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ19]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ19_SU
{
get
{
if (SUBJ19 == null)
{
return null;
}
if (Cache_SUBJ19_SU == null)
{
Cache_SUBJ19_SU = Context.SU.FindBySUKEY(SUBJ19);
}
return Cache_SUBJ19_SU;
}
}
/// <summary>
/// SU (Subjects) related entity by [SC.SUBJ20]->[SU.SUKEY]
/// Subject code
/// </summary>
public SU SUBJ20_SU
{
get
{
if (SUBJ20 == null)
{
return null;
}
if (Cache_SUBJ20_SU == null)
{
Cache_SUBJ20_SU = Context.SU.FindBySUKEY(SUBJ20);
}
return Cache_SUBJ20_SU;
}
}
/// <summary>
/// KCY (Year Levels) related entity by [SC.SUBJECT_ACADEMIC_YEAR]->[KCY.KCYKEY]
/// Default academic year of subjects
/// </summary>
public KCY SUBJECT_ACADEMIC_YEAR_KCY
{
get
{
if (SUBJECT_ACADEMIC_YEAR == null)
{
return null;
}
if (Cache_SUBJECT_ACADEMIC_YEAR_KCY == null)
{
Cache_SUBJECT_ACADEMIC_YEAR_KCY = Context.KCY.FindByKCYKEY(SUBJECT_ACADEMIC_YEAR);
}
return Cache_SUBJECT_ACADEMIC_YEAR_KCY;
}
}
#endregion
#region Foreign Navigation Properties
/// <summary>
/// STMA (Subject Selections & Marks) related entities by [SC.COURSE]->[STMA.CKEY]
/// Course code (same type as SU)
/// </summary>
public IReadOnlyList<STMA> COURSE_STMA_CKEY
{
get
{
if (Cache_COURSE_STMA_CKEY == null &&
!Context.STMA.TryFindByCKEY(COURSE, out Cache_COURSE_STMA_CKEY))
{
Cache_COURSE_STMA_CKEY = new List<STMA>().AsReadOnly();
}
return Cache_COURSE_STMA_CKEY;
}
}
#endregion
}
}
| |
namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class CompilerErrorsTestFixture : AbstractCompilerErrorsTestFixture
{
[Test]
public void BCE0000_1()
{
RunCompilerTestCase(@"BCE0000-1.boo");
}
[Test]
public void BCE0004_1()
{
RunCompilerTestCase(@"BCE0004-1.boo");
}
[Test]
public void BCE0004_2()
{
RunCompilerTestCase(@"BCE0004-2.boo");
}
[Test]
public void BCE0004_3()
{
RunCompilerTestCase(@"BCE0004-3.boo");
}
[Test]
public void BCE0005_1()
{
RunCompilerTestCase(@"BCE0005-1.boo");
}
[Test]
public void BCE0005_2()
{
RunCompilerTestCase(@"BCE0005-2.boo");
}
[Test]
public void BCE0006_1()
{
RunCompilerTestCase(@"BCE0006-1.boo");
}
[Test]
public void BCE0007_1()
{
RunCompilerTestCase(@"BCE0007-1.boo");
}
[Test]
public void BCE0017_1()
{
RunCompilerTestCase(@"BCE0017-1.boo");
}
[Test]
public void BCE0017_2()
{
RunCompilerTestCase(@"BCE0017-2.boo");
}
[Test]
public void BCE0017_3()
{
RunCompilerTestCase(@"BCE0017-3.boo");
}
[Test]
public void BCE0017_4()
{
RunCompilerTestCase(@"BCE0017-4.boo");
}
[Test]
public void BCE0018_1()
{
RunCompilerTestCase(@"BCE0018-1.boo");
}
[Test]
public void BCE0018_2()
{
RunCompilerTestCase(@"BCE0018-2.boo");
}
[Test]
public void BCE0018_3()
{
RunCompilerTestCase(@"BCE0018-3.boo");
}
[Test]
public void BCE0018_4()
{
RunCompilerTestCase(@"BCE0018-4.boo");
}
[Test]
public void BCE0019_1()
{
RunCompilerTestCase(@"BCE0019-1.boo");
}
[Test]
public void BCE0019_2()
{
RunCompilerTestCase(@"BCE0019-2.boo");
}
[Test]
public void BCE0020_1()
{
RunCompilerTestCase(@"BCE0020-1.boo");
}
[Test]
public void BCE0020_2()
{
RunCompilerTestCase(@"BCE0020-2.boo");
}
[Test]
public void BCE0020_3()
{
RunCompilerTestCase(@"BCE0020-3.boo");
}
[Test]
public void BCE0020_4()
{
RunCompilerTestCase(@"BCE0020-4.boo");
}
[Test]
public void BCE0021_1()
{
RunCompilerTestCase(@"BCE0021-1.boo");
}
[Test]
public void BCE0022_1()
{
RunCompilerTestCase(@"BCE0022-1.boo");
}
[Test]
public void BCE0022_10()
{
RunCompilerTestCase(@"BCE0022-10.boo");
}
[Test]
public void BCE0022_11()
{
RunCompilerTestCase(@"BCE0022-11.boo");
}
[Test]
public void BCE0022_12()
{
RunCompilerTestCase(@"BCE0022-12.boo");
}
[Test]
public void BCE0022_13()
{
RunCompilerTestCase(@"BCE0022-13.boo");
}
[Test]
public void BCE0022_14()
{
RunCompilerTestCase(@"BCE0022-14.boo");
}
[Test]
public void BCE0022_15_strict()
{
RunCompilerTestCase(@"BCE0022-15-strict.boo");
}
[Test]
public void BCE0022_16_strict()
{
RunCompilerTestCase(@"BCE0022-16-strict.boo");
}
[Test]
public void BCE0022_2()
{
RunCompilerTestCase(@"BCE0022-2.boo");
}
[Test]
public void BCE0022_3()
{
RunCompilerTestCase(@"BCE0022-3.boo");
}
[Test]
public void BCE0022_4()
{
RunCompilerTestCase(@"BCE0022-4.boo");
}
[Test]
public void BCE0022_5()
{
RunCompilerTestCase(@"BCE0022-5.boo");
}
[Test]
public void BCE0022_6()
{
RunCompilerTestCase(@"BCE0022-6.boo");
}
[Test]
public void BCE0022_8()
{
RunCompilerTestCase(@"BCE0022-8.boo");
}
[Test]
public void BCE0022_9()
{
RunCompilerTestCase(@"BCE0022-9.boo");
}
[Test]
public void BCE0023_1()
{
RunCompilerTestCase(@"BCE0023-1.boo");
}
[Test]
public void BCE0024_1()
{
RunCompilerTestCase(@"BCE0024-1.boo");
}
[Test]
public void BCE0024_2()
{
RunCompilerTestCase(@"BCE0024-2.boo");
}
[Test]
public void BCE0024_3()
{
RunCompilerTestCase(@"BCE0024-3.boo");
}
[Test]
public void BCE0024_4()
{
RunCompilerTestCase(@"BCE0024-4.boo");
}
[Test]
public void BCE0032_1()
{
RunCompilerTestCase(@"BCE0032-1.boo");
}
[Test]
public void BCE0035_1()
{
RunCompilerTestCase(@"BCE0035-1.boo");
}
[Test]
public void BCE0035_2()
{
RunCompilerTestCase(@"BCE0035-2.boo");
}
[Test]
public void BCE0035_3()
{
RunCompilerTestCase(@"BCE0035-3.boo");
}
[Test]
public void BCE0035_4()
{
RunCompilerTestCase(@"BCE0035-4.boo");
}
[Test]
public void BCE0038_1()
{
RunCompilerTestCase(@"BCE0038-1.boo");
}
[Test]
public void BCE0045_1()
{
RunCompilerTestCase(@"BCE0045-1.boo");
}
[Test]
public void BCE0045_2()
{
RunCompilerTestCase(@"BCE0045-2.boo");
}
[Test]
public void BCE0045_3()
{
RunCompilerTestCase(@"BCE0045-3.boo");
}
[Test]
public void BCE0045_4()
{
RunCompilerTestCase(@"BCE0045-4.boo");
}
[Test]
public void BCE0046_1()
{
RunCompilerTestCase(@"BCE0046-1.boo");
}
[Test]
public void BCE0046_2()
{
RunCompilerTestCase(@"BCE0046-2.boo");
}
[Test]
public void BCE0047_1()
{
RunCompilerTestCase(@"BCE0047-1.boo");
}
[Test]
public void BCE0047_2()
{
RunCompilerTestCase(@"BCE0047-2.boo");
}
[Test]
public void BCE0047_3()
{
RunCompilerTestCase(@"BCE0047-3.boo");
}
[Test]
public void BCE0047_4()
{
RunCompilerTestCase(@"BCE0047-4.boo");
}
[Test]
public void BCE0047_5()
{
RunCompilerTestCase(@"BCE0047-5.boo");
}
[Test]
public void BCE0049_1()
{
RunCompilerTestCase(@"BCE0049-1.boo");
}
[Test]
public void BCE0051_1()
{
RunCompilerTestCase(@"BCE0051-1.boo");
}
[Test]
public void BCE0051_2()
{
RunCompilerTestCase(@"BCE0051-2.boo");
}
[Test]
public void BCE0053_1()
{
RunCompilerTestCase(@"BCE0053-1.boo");
}
[Test]
public void BCE0053_2()
{
RunCompilerTestCase(@"BCE0053-2.boo");
}
[Test]
public void BCE0053_3()
{
RunCompilerTestCase(@"BCE0053-3.boo");
}
[Test]
public void BCE0057_1()
{
RunCompilerTestCase(@"BCE0057-1.boo");
}
[Test]
public void BCE0058_1()
{
RunCompilerTestCase(@"BCE0058-1.boo");
}
[Test]
public void BCE0060_1()
{
RunCompilerTestCase(@"BCE0060-1.boo");
}
[Test]
public void BCE0060_2()
{
RunCompilerTestCase(@"BCE0060-2.boo");
}
[Test]
public void BCE0060_3()
{
RunCompilerTestCase(@"BCE0060-3.boo");
}
[Test]
public void BCE0061_1()
{
RunCompilerTestCase(@"BCE0061-1.boo");
}
[Test]
public void BCE0063_1()
{
RunCompilerTestCase(@"BCE0063-1.boo");
}
[Test]
public void BCE0063_2()
{
RunCompilerTestCase(@"BCE0063-2.boo");
}
[Test]
public void BCE0063_3()
{
RunCompilerTestCase(@"BCE0063-3.boo");
}
[Test]
public void BCE0063_4()
{
RunCompilerTestCase(@"BCE0063-4.boo");
}
[Test]
public void BCE0063_5()
{
RunCompilerTestCase(@"BCE0063-5.boo");
}
[Test]
public void BCE0063_6()
{
RunCompilerTestCase(@"BCE0063-6.boo");
}
[Test]
public void BCE0063_7()
{
RunCompilerTestCase(@"BCE0063-7.boo");
}
[Test]
public void BCE0063_8()
{
RunCompilerTestCase(@"BCE0063-8.boo");
}
[Test]
public void BCE0065_1()
{
RunCompilerTestCase(@"BCE0065-1.boo");
}
[Test]
public void BCE0065_2()
{
RunCompilerTestCase(@"BCE0065-2.boo");
}
[Test]
public void BCE0067_1()
{
RunCompilerTestCase(@"BCE0067-1.boo");
}
[Test]
public void BCE0067_2()
{
RunCompilerTestCase(@"BCE0067-2.boo");
}
[Test]
public void BCE0067_3()
{
RunCompilerTestCase(@"BCE0067-3.boo");
}
[Test]
public void BCE0070_1()
{
RunCompilerTestCase(@"BCE0070-1.boo");
}
[Test]
public void BCE0070_2()
{
RunCompilerTestCase(@"BCE0070-2.boo");
}
[Test]
public void BCE0070_3()
{
RunCompilerTestCase(@"BCE0070-3.boo");
}
[Test]
public void BCE0071_1()
{
RunCompilerTestCase(@"BCE0071-1.boo");
}
[Test]
public void BCE0071_2()
{
RunCompilerTestCase(@"BCE0071-2.boo");
}
[Test]
public void BCE0072_1()
{
RunCompilerTestCase(@"BCE0072-1.boo");
}
[Test]
public void BCE0072_2()
{
RunCompilerTestCase(@"BCE0072-2.boo");
}
[Test]
public void BCE0073_1()
{
RunCompilerTestCase(@"BCE0073-1.boo");
}
[Test]
public void BCE0079_1()
{
RunCompilerTestCase(@"BCE0079-1.boo");
}
[Test]
public void BCE0080_1()
{
RunCompilerTestCase(@"BCE0080-1.boo");
}
[Test]
public void BCE0081_1()
{
RunCompilerTestCase(@"BCE0081-1.boo");
}
[Test]
public void BCE0081_2()
{
RunCompilerTestCase(@"BCE0081-2.boo");
}
[Test]
public void BCE0081_3()
{
RunCompilerTestCase(@"BCE0081-3.boo");
}
[Test]
public void BCE0081_4()
{
RunCompilerTestCase(@"BCE0081-4.boo");
}
[Test]
public void BCE0081_5()
{
RunCompilerTestCase(@"BCE0081-5.boo");
}
[Test]
public void BCE0082_1()
{
RunCompilerTestCase(@"BCE0082-1.boo");
}
[Test]
public void BCE0083_1()
{
RunCompilerTestCase(@"BCE0083-1.boo");
}
[Test]
public void BCE0084_1()
{
RunCompilerTestCase(@"BCE0084-1.boo");
}
[Test]
public void BCE0085_1()
{
RunCompilerTestCase(@"BCE0085-1.boo");
}
[Test]
public void BCE0085_3()
{
RunCompilerTestCase(@"BCE0085-3.boo");
}
[Test]
public void BCE0086_1()
{
RunCompilerTestCase(@"BCE0086-1.boo");
}
[Test]
public void BCE0087_1()
{
RunCompilerTestCase(@"BCE0087-1.boo");
}
[Test]
public void BCE0089_1()
{
RunCompilerTestCase(@"BCE0089-1.boo");
}
[Test]
public void BCE0089_10()
{
RunCompilerTestCase(@"BCE0089-10.boo");
}
[Test]
public void BCE0089_11()
{
RunCompilerTestCase(@"BCE0089-11.boo");
}
[Test]
public void BCE0089_12()
{
RunCompilerTestCase(@"BCE0089-12.boo");
}
[Test]
public void BCE0089_13()
{
RunCompilerTestCase(@"BCE0089-13.boo");
}
[Test]
public void BCE0089_14()
{
RunCompilerTestCase(@"BCE0089-14.boo");
}
[Test]
public void BCE0089_15()
{
RunCompilerTestCase(@"BCE0089-15.boo");
}
[Test]
public void BCE0089_16()
{
RunCompilerTestCase(@"BCE0089-16.boo");
}
[Test]
public void BCE0089_2()
{
RunCompilerTestCase(@"BCE0089-2.boo");
}
[Test]
public void BCE0089_3()
{
RunCompilerTestCase(@"BCE0089-3.boo");
}
[Test]
public void BCE0089_4()
{
RunCompilerTestCase(@"BCE0089-4.boo");
}
[Test]
public void BCE0089_5()
{
RunCompilerTestCase(@"BCE0089-5.boo");
}
[Test]
public void BCE0089_6()
{
RunCompilerTestCase(@"BCE0089-6.boo");
}
[Test]
public void BCE0089_7()
{
RunCompilerTestCase(@"BCE0089-7.boo");
}
[Test]
public void BCE0089_8()
{
RunCompilerTestCase(@"BCE0089-8.boo");
}
[Test]
public void BCE0089_9()
{
RunCompilerTestCase(@"BCE0089-9.boo");
}
[Test]
public void BCE0090_1()
{
RunCompilerTestCase(@"BCE0090-1.boo");
}
[Test]
public void BCE0090_2()
{
RunCompilerTestCase(@"BCE0090-2.boo");
}
[Test]
public void BCE0090_3()
{
RunCompilerTestCase(@"BCE0090-3.boo");
}
[Test]
public void BCE0091_1()
{
RunCompilerTestCase(@"BCE0091-1.boo");
}
[Test]
public void BCE0092_1()
{
RunCompilerTestCase(@"BCE0092-1.boo");
}
[Test]
public void BCE0093_1()
{
RunCompilerTestCase(@"BCE0093-1.boo");
}
[Test]
public void BCE0093_2()
{
RunCompilerTestCase(@"BCE0093-2.boo");
}
[Test]
public void BCE0094_1()
{
RunCompilerTestCase(@"BCE0094-1.boo");
}
[Test]
public void BCE0095_1()
{
RunCompilerTestCase(@"BCE0095-1.boo");
}
[Test]
public void BCE0095_2()
{
RunCompilerTestCase(@"BCE0095-2.boo");
}
[Test]
public void BCE0096_1()
{
RunCompilerTestCase(@"BCE0096-1.boo");
}
[Test]
public void BCE0097_1()
{
RunCompilerTestCase(@"BCE0097-1.boo");
}
[Test]
public void BCE0097_2()
{
RunCompilerTestCase(@"BCE0097-2.boo");
}
[Test]
public void BCE0099_1()
{
RunCompilerTestCase(@"BCE0099-1.boo");
}
[Test]
public void BCE0099_2()
{
RunCompilerTestCase(@"BCE0099-2.boo");
}
[Test]
public void BCE0100_1()
{
RunCompilerTestCase(@"BCE0100-1.boo");
}
[Test]
public void BCE0101_1()
{
RunCompilerTestCase(@"BCE0101-1.boo");
}
[Test]
public void BCE0101_2()
{
RunCompilerTestCase(@"BCE0101-2.boo");
}
[Test]
public void BCE0102_1()
{
RunCompilerTestCase(@"BCE0102-1.boo");
}
[Test]
public void BCE0103_1()
{
RunCompilerTestCase(@"BCE0103-1.boo");
}
[Test]
public void BCE0103_2()
{
RunCompilerTestCase(@"BCE0103-2.boo");
}
[Test]
public void BCE0103_3()
{
RunCompilerTestCase(@"BCE0103-3.boo");
}
[Test]
public void BCE0103_cannot_extend_array()
{
RunCompilerTestCase(@"BCE0103-cannot-extend-array.boo");
}
[Test]
public void BCE0104_1()
{
RunCompilerTestCase(@"BCE0104-1.boo");
}
[Test]
public void BCE0105_1()
{
RunCompilerTestCase(@"BCE0105-1.boo");
}
[Test]
public void BCE0107_1()
{
RunCompilerTestCase(@"BCE0107-1.boo");
}
[Test]
public void BCE0108_1()
{
RunCompilerTestCase(@"BCE0108-1.boo");
}
[Test]
public void BCE0111_1()
{
RunCompilerTestCase(@"BCE0111-1.boo");
}
[Test]
public void BCE0112_1()
{
RunCompilerTestCase(@"BCE0112-1.boo");
}
[Test]
public void BCE0114_1()
{
RunCompilerTestCase(@"BCE0114-1.boo");
}
[Test]
public void BCE0115_1()
{
RunCompilerTestCase(@"BCE0115-1.boo");
}
[Test]
public void BCE0116_1()
{
RunCompilerTestCase(@"BCE0116-1.boo");
}
[Test]
public void BCE0117_1()
{
RunCompilerTestCase(@"BCE0117-1.boo");
}
[Test]
public void BCE0120_1()
{
RunCompilerTestCase(@"BCE0120-1.boo");
}
[Test]
public void BCE0120_2()
{
RunCompilerTestCase(@"BCE0120-2.boo");
}
[Test]
public void BCE0120_3()
{
RunCompilerTestCase(@"BCE0120-3.boo");
}
[Test]
public void BCE0120_4()
{
RunCompilerTestCase(@"BCE0120-4.boo");
}
[Test]
public void BCE0120_5()
{
RunCompilerTestCase(@"BCE0120-5.boo");
}
[Test]
public void BCE0120_6()
{
RunCompilerTestCase(@"BCE0120-6.boo");
}
[Test]
public void BCE0121_1()
{
RunCompilerTestCase(@"BCE0121-1.boo");
}
[Test]
public void BCE0122_1()
{
RunCompilerTestCase(@"BCE0122-1.boo");
}
[Test]
public void BCE0123_1()
{
RunCompilerTestCase(@"BCE0123-1.boo");
}
[Test]
public void BCE0123_2()
{
RunCompilerTestCase(@"BCE0123-2.boo");
}
[Test]
public void BCE0124_1()
{
RunCompilerTestCase(@"BCE0124-1.boo");
}
[Test]
public void BCE0125_1()
{
RunCompilerTestCase(@"BCE0125-1.boo");
}
[Test]
public void BCE0126_1()
{
RunCompilerTestCase(@"BCE0126-1.boo");
}
[Test]
public void BCE0126_2()
{
RunCompilerTestCase(@"BCE0126-2.boo");
}
[Test]
public void BCE0126_3()
{
RunCompilerTestCase(@"BCE0126-3.boo");
}
[Test]
public void BCE0126_4()
{
RunCompilerTestCase(@"BCE0126-4.boo");
}
[Test]
public void BCE0126_5()
{
RunCompilerTestCase(@"BCE0126-5.boo");
}
[Test]
public void BCE0126_6()
{
RunCompilerTestCase(@"BCE0126-6.boo");
}
[Test]
public void BCE0126_7()
{
RunCompilerTestCase(@"BCE0126-7.boo");
}
[Test]
public void BCE0127_1()
{
RunCompilerTestCase(@"BCE0127-1.boo");
}
[Test]
public void BCE0127_2()
{
RunCompilerTestCase(@"BCE0127-2.boo");
}
[Test]
public void BCE0128_1()
{
RunCompilerTestCase(@"BCE0128-1.boo");
}
[Test]
public void BCE0129_1()
{
RunCompilerTestCase(@"BCE0129-1.boo");
}
[Test]
public void BCE0130_1()
{
RunCompilerTestCase(@"BCE0130-1.boo");
}
[Test]
public void BCE0131_1()
{
RunCompilerTestCase(@"BCE0131-1.boo");
}
[Test]
public void BCE0131_2()
{
RunCompilerTestCase(@"BCE0131-2.boo");
}
[Test]
public void BCE0132_1()
{
RunCompilerTestCase(@"BCE0132-1.boo");
}
[Test]
public void BCE0132_2()
{
RunCompilerTestCase(@"BCE0132-2.boo");
}
[Test]
public void BCE0132_3()
{
RunCompilerTestCase(@"BCE0132-3.boo");
}
[Test]
public void BCE0132_4()
{
RunCompilerTestCase(@"BCE0132-4.boo");
}
[Test]
public void BCE0132_5()
{
RunCompilerTestCase(@"BCE0132-5.boo");
}
[Test]
public void BCE0133_1()
{
RunCompilerTestCase(@"BCE0133-1.boo");
}
[Test]
public void BCE0133_2()
{
RunCompilerTestCase(@"BCE0133-2.boo");
}
[Test]
public void BCE0134_1()
{
RunCompilerTestCase(@"BCE0134-1.boo");
}
[Test]
public void BCE0134_2()
{
RunCompilerTestCase(@"BCE0134-2.boo");
}
[Test]
public void BCE0136_1()
{
RunCompilerTestCase(@"BCE0136-1.boo");
}
[Test]
public void BCE0137_1()
{
RunCompilerTestCase(@"BCE0137-1.boo");
}
[Test]
public void BCE0137_2()
{
RunCompilerTestCase(@"BCE0137-2.boo");
}
[Test]
public void BCE0137_3()
{
RunCompilerTestCase(@"BCE0137-3.boo");
}
[Test]
public void BCE0141()
{
RunCompilerTestCase(@"BCE0141.boo");
}
[Test]
public void BCE0142()
{
RunCompilerTestCase(@"BCE0142.boo");
}
[Test]
public void BCE0143_1()
{
RunCompilerTestCase(@"BCE0143-1.boo");
}
[Test]
public void BCE0144_1()
{
RunCompilerTestCase(@"BCE0144-1.boo");
}
[Test]
public void BCE0144_2()
{
RunCompilerTestCase(@"BCE0144-2.boo");
}
[Test]
public void BCE0145_1()
{
RunCompilerTestCase(@"BCE0145-1.boo");
}
[Test]
public void BCE0150_1()
{
RunCompilerTestCase(@"BCE0150-1.boo");
}
[Test]
public void BCE0151_1()
{
RunCompilerTestCase(@"BCE0151-1.boo");
}
[Test]
public void BCE0151_2()
{
RunCompilerTestCase(@"BCE0151-2.boo");
}
[Test]
public void BCE0152_1()
{
RunCompilerTestCase(@"BCE0152-1.boo");
}
[Test]
public void BCE0153_1()
{
RunCompilerTestCase(@"BCE0153-1.boo");
}
[Test]
public void BCE0153_2()
{
RunCompilerTestCase(@"BCE0153-2.boo");
}
[Test]
public void BCE0154_1()
{
RunCompilerTestCase(@"BCE0154-1.boo");
}
[Test]
public void BCE0154_2()
{
RunCompilerTestCase(@"BCE0154-2.boo");
}
[Test]
public void BCE0155_1()
{
RunCompilerTestCase(@"BCE0155-1.boo");
}
[Test]
public void BCE0156_1()
{
RunCompilerTestCase(@"BCE0156-1.boo");
}
[Test]
public void BCE0157_1()
{
RunCompilerTestCase(@"BCE0157-1.boo");
}
[Test]
public void BCE0158_1()
{
RunCompilerTestCase(@"BCE0158-1.boo");
}
[Test]
public void BCE0165_1()
{
RunCompilerTestCase(@"BCE0165-1.boo");
}
[Test]
public void BCE0166_1()
{
RunCompilerTestCase(@"BCE0166-1.boo");
}
[Test]
public void BCE0167_1()
{
RunCompilerTestCase(@"BCE0167-1.boo");
}
[Test]
public void BCE0169_1()
{
RunCompilerTestCase(@"BCE0169-1.boo");
}
[Test]
public void BCE0170_1()
{
RunCompilerTestCase(@"BCE0170-1.boo");
}
[Test]
public void BCE0171_1()
{
RunCompilerTestCase(@"BCE0171-1.boo");
}
[Test]
public void BCE0173_1()
{
RunCompilerTestCase(@"BCE0173-1.boo");
}
[Test]
public void BCE0175()
{
RunCompilerTestCase(@"BCE0175.boo");
}
[Test]
public void BCE0176_1()
{
RunCompilerTestCase(@"BCE0176-1.boo");
}
[Test]
public void cannot_convert_enum_to_single()
{
RunCompilerTestCase(@"cannot-convert-enum-to-single.boo");
}
[Test]
public void CannotConvertFooToInt()
{
RunCompilerTestCase(@"CannotConvertFooToInt.boo");
}
[Test]
public void error_doesnt_cascade_to_cast()
{
RunCompilerTestCase(@"error-doesnt-cascade-to-cast.boo");
}
[Test]
public void error_doesnt_cascade_to_raise()
{
RunCompilerTestCase(@"error-doesnt-cascade-to-raise.boo");
}
[Test]
public void invalid_array_slice()
{
RunCompilerTestCase(@"invalid-array-slice.boo");
}
[Test]
public void invalid_generic_extension_1()
{
RunCompilerTestCase(@"invalid-generic-extension-1.boo");
}
[Test]
public void invalid_generic_extension_2()
{
RunCompilerTestCase(@"invalid-generic-extension-2.boo");
}
[Test]
public void invalid_matrix_index()
{
RunCompilerTestCase(@"invalid-matrix-index.boo");
}
[Test]
public void mismatched_collection_initializers()
{
RunCompilerTestCase(@"mismatched-collection-initializers.boo");
}
[Test]
public void selective_import_2()
{
RunCompilerTestCase(@"selective-import-2.boo");
}
[Test]
public void selective_import()
{
RunCompilerTestCase(@"selective-import.boo");
}
[Test]
public void single_error_on_missing_import_namespace()
{
RunCompilerTestCase(@"single-error-on-missing-import-namespace.boo");
}
[Test]
public void strict_1()
{
RunCompilerTestCase(@"strict-1.boo");
}
[Test]
public void warnaserror_1()
{
RunCompilerTestCase(@"warnaserror-1.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "errors";
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary object.
/// </summary>
internal class BinaryObject : IBinaryObject
{
/** Cache empty dictionary. */
private static readonly IDictionary<int, int> EmptyFields = new Dictionary<int, int>();
/** Marshaller. */
private readonly Marshaller _marsh;
/** Raw data of this binary object. */
private readonly byte[] _data;
/** Offset in data array. */
private readonly int _offset;
/** Header. */
private readonly BinaryObjectHeader _header;
/** Fields. */
private volatile IDictionary<int, int> _fields;
/** Deserialized value. */
private object _deserialized;
/// <summary>
/// Initializes a new instance of the <see cref="BinaryObject" /> class.
/// </summary>
/// <param name="marsh">Marshaller.</param>
/// <param name="data">Raw data of this binary object.</param>
/// <param name="offset">Offset in data array.</param>
/// <param name="header">The header.</param>
public BinaryObject(Marshaller marsh, byte[] data, int offset, BinaryObjectHeader header)
{
Debug.Assert(marsh != null);
Debug.Assert(data != null);
Debug.Assert(offset >= 0 && offset < data.Length);
_marsh = marsh;
_data = data;
_offset = offset;
_header = header;
}
/** <inheritdoc /> */
public int TypeId
{
get { return _header.TypeId; }
}
/** <inheritdoc /> */
public T GetField<T>(string fieldName)
{
IgniteArgumentCheck.NotNullOrEmpty(fieldName, "fieldName");
int pos;
return TryGetFieldPosition(fieldName, out pos) ? GetField<T>(pos, null) : default(T);
}
/** <inheritdoc /> */
public bool HasField(string fieldName)
{
IgniteArgumentCheck.NotNullOrEmpty(fieldName, "fieldName");
int pos;
return TryGetFieldPosition(fieldName, out pos);
}
/// <summary>
/// Gets field value on the given object.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="builder">Builder.</param>
/// <returns>Field value.</returns>
public T GetField<T>(int pos, BinaryObjectBuilder builder)
{
IBinaryStream stream = new BinaryHeapStream(_data);
stream.Seek(pos + _offset, SeekOrigin.Begin);
return _marsh.Unmarshal<T>(stream, BinaryMode.ForceBinary, builder);
}
/** <inheritdoc /> */
public T Deserialize<T>()
{
return Deserialize<T>(BinaryMode.Deserialize);
}
/** <inheritdoc /> */
public int EnumValue
{
get
{
throw new NotSupportedException("IBinaryObject.Value is only supported for enums. " +
"Check IBinaryObject.IsEnum property before accessing Value.");
}
}
/// <summary>
/// Internal deserialization routine.
/// </summary>
/// <param name="mode">The mode.</param>
/// <returns>
/// Deserialized object.
/// </returns>
private T Deserialize<T>(BinaryMode mode)
{
if (_deserialized == null)
{
IBinaryStream stream = new BinaryHeapStream(_data);
stream.Seek(_offset, SeekOrigin.Begin);
T res = _marsh.Unmarshal<T>(stream, mode);
IBinaryTypeDescriptor desc = _marsh.GetDescriptor(true, _header.TypeId);
if (!desc.KeepDeserialized)
return res;
_deserialized = res;
}
return (T)_deserialized;
}
/** <inheritdoc /> */
public IBinaryType GetBinaryType()
{
return _marsh.GetBinaryType(_header.TypeId);
}
/// <summary>
/// Raw data of this binary object.
/// </summary>
public byte[] Data
{
get { return _data; }
}
/// <summary>
/// Offset in data array.
/// </summary>
public int Offset
{
get { return _offset; }
}
public bool TryGetFieldPosition(string fieldName, out int pos)
{
var desc = _marsh.GetDescriptor(true, _header.TypeId);
InitializeFields();
int fieldId = BinaryUtils.FieldId(_header.TypeId, fieldName, desc.NameMapper, desc.IdMapper);
return _fields.TryGetValue(fieldId, out pos);
}
/// <summary>
/// Lazy fields initialization routine.
/// </summary>
private void InitializeFields()
{
if (_fields != null)
return;
var stream = new BinaryHeapStream(_data);
var hdr = BinaryObjectHeader.Read(stream, _offset);
_fields = hdr.ReadSchemaAsDictionary(stream, _offset) ?? EmptyFields;
}
/** <inheritdoc /> */
public override int GetHashCode()
{
return _header.HashCode;
}
/** <inheritdoc /> */
public override bool Equals(object obj)
{
if (this == obj)
return true;
BinaryObject that = obj as BinaryObject;
if (that != null)
{
if (_data == that._data && _offset == that._offset)
return true;
// 1. Check headers
if (_header == that._header)
{
// 2. Check if objects have the same field sets.
InitializeFields();
that.InitializeFields();
if (_fields.Keys.Count != that._fields.Keys.Count)
return false;
foreach (int id in _fields.Keys)
{
if (!that._fields.ContainsKey(id))
return false;
}
// 3. Check if objects have the same field values.
foreach (KeyValuePair<int, int> field in _fields)
{
object fieldVal = GetField<object>(field.Value, null);
object thatFieldVal = that.GetField<object>(that._fields[field.Key], null);
if (!Equals(fieldVal, thatFieldVal))
return false;
}
// 4. Check if objects have the same raw data.
// ReSharper disable ImpureMethodCallOnReadonlyValueField (method is not impure)
var stream = new BinaryHeapStream(_data);
var rawOffset = _header.GetRawOffset(stream, _offset);
var thatStream = new BinaryHeapStream(that._data);
var thatRawOffset = that._header.GetRawOffset(thatStream, that._offset);
// ReSharper restore ImpureMethodCallOnReadonlyValueField
return BinaryUtils.CompareArrays(_data, _offset + rawOffset, _header.Length - rawOffset,
that._data, that._offset + thatRawOffset, that._header.Length - thatRawOffset);
}
}
return false;
}
/** <inheritdoc /> */
public override string ToString()
{
return ToString(new Dictionary<int, int>());
}
/// <summary>
/// ToString implementation.
/// </summary>
/// <param name="handled">Already handled objects.</param>
/// <returns>Object string.</returns>
private string ToString(IDictionary<int, int> handled)
{
int idHash;
bool alreadyHandled = handled.TryGetValue(_offset, out idHash);
if (!alreadyHandled)
idHash = RuntimeHelpers.GetHashCode(this);
StringBuilder sb;
IBinaryTypeDescriptor desc = _marsh.GetDescriptor(true, _header.TypeId);
IBinaryType meta;
try
{
meta = _marsh.GetBinaryType(_header.TypeId);
}
catch (IgniteException)
{
meta = null;
}
if (meta == null)
sb = new StringBuilder("BinaryObject [typeId=").Append(_header.TypeId).Append(", idHash=" + idHash);
else
{
sb = new StringBuilder(meta.TypeName).Append(" [idHash=" + idHash);
if (!alreadyHandled)
{
handled[_offset] = idHash;
InitializeFields();
foreach (string fieldName in meta.Fields)
{
sb.Append(", ");
int fieldId = BinaryUtils.FieldId(_header.TypeId, fieldName, desc.NameMapper, desc.IdMapper);
int fieldPos;
if (_fields.TryGetValue(fieldId, out fieldPos))
{
sb.Append(fieldName).Append('=');
ToString0(sb, GetField<object>(fieldPos, null), handled);
}
}
}
else
sb.Append(", ...");
}
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// Internal ToString routine with correct collections printout.
/// </summary>
/// <param name="sb">String builder.</param>
/// <param name="obj">Object to print.</param>
/// <param name="handled">Already handled objects.</param>
/// <returns>The same string builder.</returns>
private static void ToString0(StringBuilder sb, object obj, IDictionary<int, int> handled)
{
IEnumerable col = (obj is string) ? null : obj as IEnumerable;
if (col == null)
{
BinaryObject obj0 = obj as BinaryObject;
sb.Append(obj0 == null ? obj : obj0.ToString(handled));
}
else
{
sb.Append('[');
bool first = true;
foreach (object elem in col)
{
if (first)
first = false;
else
sb.Append(", ");
ToString0(sb, elem, handled);
}
sb.Append(']');
}
}
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace IronScheme.Editor.Collections
{
public sealed class FastDoubleLinkedList<T> : DoubleLinkedList<T> where T:class
{
}
/// <summary>
/// DoubleLinkedList.
/// </summary>
public class DoubleLinkedList<T> : ICollection<T>, ICloneable where T : class
{
/// <summary>
/// Interface for position within the list
/// </summary>
public interface IPosition
{
/// <summary>
/// Retrieves the data
/// </summary>
T Data { get;}
/// <summary>
/// The previous IPosition, or null, if it is the first position/sentinel
/// </summary>
IPosition Previous { get;}
/// <summary>
/// The next IPosition, or null, if it is the last position/sentinel
/// </summary>
IPosition Next { get;}
}
class Position : IPosition
{
internal T data;
internal Position prev;
internal Position next;
public T Data { get { return data; } }
public IPosition Previous { get { return prev; } }
public IPosition Next { get { return next; } }
#if PROBE
protected bool visited = false;
public virtual bool Probe(Position caller)
{
if (visited)
{
Debug.Assert(caller.prev == this);
visited = false;
return prev.Probe(this);
}
else
{
Debug.Assert(caller.next == this);
visited = true;
return next.Probe(this);
}
}
#endif
}
#region Enumerators
enum EnumerationFlags
{
Forward,
Reverse,
ForwardPosition,
ReversePosition,
}
class Enumerator : IEnumerator<T>, ICloneable
{
readonly DoubleLinkedList<T> dll;
readonly int version;
IPosition current;
public Enumerator(DoubleLinkedList<T> dll)
{
this.dll = dll;
this.version = dll.version;
Reset();
}
public void Reset()
{
current = dll.startsentinel;
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
void IDisposable.Dispose()
{
}
public T Current
{
get
{
if (current == dll.startsentinel)
{
throw new InvalidOperationException("enumerator has not been initialized");
}
return current.Data;
}
}
public bool MoveNext()
{
if (version != dll.version)
{
throw new InvalidOperationException("collection has been modified");
}
if (current.Next == dll.endsentinel)
{
return false;
}
else
{
current = current.Next;
return true;
}
}
public object Clone()
{
return MemberwiseClone();
}
}
class ReverseEnumerator : IEnumerator<T>, ICloneable
{
readonly DoubleLinkedList<T> dll;
readonly int version;
IPosition current;
public ReverseEnumerator(DoubleLinkedList<T> dll)
{
this.dll = dll;
this.version = dll.version;
Reset();
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
void IDisposable.Dispose()
{
}
public void Reset()
{
current = dll.endsentinel;
}
public T Current
{
get
{
if (current == dll.endsentinel)
{
throw new InvalidOperationException("enumerator has not been initialized");
}
return current.Data;
}
}
public bool MoveNext()
{
if (version != dll.version)
{
throw new InvalidOperationException("collection has been modified");
}
if (current.Previous == dll.startsentinel)
{
return false;
}
else
{
current = current.Previous;
return true;
}
}
public object Clone()
{
return MemberwiseClone();
}
}
class PostionEnumerator : IEnumerator<IPosition>, ICloneable
{
readonly DoubleLinkedList<T> dll;
readonly int version;
IPosition current;
public PostionEnumerator(DoubleLinkedList<T> dll)
{
this.dll = dll;
this.version = dll.version;
Reset();
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
void IDisposable.Dispose()
{
}
public void Reset()
{
current = dll.startsentinel;
}
public IPosition Current
{
get
{
if (current == dll.startsentinel)
{
throw new InvalidOperationException("enumerator has not been initialized");
}
return current;
}
}
public bool MoveNext()
{
if (version != dll.version)
{
throw new InvalidOperationException("collection has been modified");
}
if (current.Next == dll.endsentinel)
{
return false;
}
else
{
current = current.Next;
return true;
}
}
public object Clone()
{
return MemberwiseClone();
}
}
class ReversePostionEnumerator : IEnumerator<IPosition>, ICloneable
{
readonly DoubleLinkedList<T> dll;
readonly int version;
IPosition current;
public ReversePostionEnumerator(DoubleLinkedList<T> dll)
{
this.dll = dll;
this.version = dll.version;
Reset();
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
void IDisposable.Dispose()
{
}
public void Reset()
{
current = dll.endsentinel;
}
public IPosition Current
{
get
{
if (current == dll.endsentinel)
{
throw new InvalidOperationException("enumerator has not been initialized");
}
return current;
}
}
public bool MoveNext()
{
if (version != dll.version)
{
throw new InvalidOperationException("collection has been modified");
}
if (current.Previous == dll.startsentinel)
{
return false;
}
else
{
current = current.Previous;
return true;
}
}
public object Clone()
{
return MemberwiseClone();
}
}
#endregion
sealed class EndSentinel : Position
{
#if PROBE
public override bool Probe(Position caller)
{
Debug.Assert(caller.next == this);
Debug.Assert(caller == prev);
return prev.Probe(this);
}
#endif
}
sealed class StartSentinel : Position
{
#if PROBE
public override bool Probe(Position caller)
{
if (visited)
{
Debug.Assert(caller.prev == this);
visited = false;
return true;
}
else
{
Debug.Assert(caller == null);
visited = true;
return next.Probe(this);
}
}
#endif
}
#if PROBE
internal void SendProbe()
{
Timers.HiPerfTimer hp = new IronScheme.Editor.Timers.HiPerfTimer();
hp.Start();
Debug.Assert(startsentinel.Probe(null));
hp.Stop();
// Trace.WriteLine(string.Format("Probe returned successfully (hash: {1:X8} count: {0} time: {2:f0}ms)",
// count, GetHashCode(), hp.Duration));
}
#endif
/// <summary>
/// Gets a synchronized wrapper for a list
/// </summary>
/// <param name="list">the list to wrap</param>
/// <returns>the synchronized list</returns>
public static DoubleLinkedList<T> Syncronized(DoubleLinkedList<T> list)
{
return new SyncDoubleLinkList(list);
}
readonly Position startsentinel = new StartSentinel();
readonly Position endsentinel = new EndSentinel();
readonly object synclock = new object();
Type keytype;
int count;
int version;
EnumerationFlags flags = 0;
readonly Dictionary<T, IPosition> reversemapping = new Dictionary<T, IPosition>();
/// <summary>
/// The position of the first element, or null, if list is empty
/// </summary>
public virtual IPosition First
{
get{return startsentinel.next != endsentinel ? startsentinel.next : null;}
}
/// <summary>
/// The position of the last element, or null, if list is empty
/// </summary>
public virtual IPosition Last
{
get{return endsentinel.prev != startsentinel ? endsentinel.prev : null;}
}
/// <summary>
/// Creates an empty list
/// </summary>
public DoubleLinkedList()
{
startsentinel.next = endsentinel;
endsentinel.prev = startsentinel;
count = 0;
version = 0;
}
/// <summary>
/// Creates a list from an ICollection
/// </summary>
/// <param name="icol">The collections elements to copy from</param>
public DoubleLinkedList(ICollection<T> icol) : this()
{
foreach (T o in icol)
{
Add(o);
}
}
/// <summary>
/// Returns the position of an object
/// </summary>
/// <param name="obj">the object to lookup</param>
/// <returns>the postion containing the object, or null, if not found</returns>
public virtual IPosition PositionOf(T obj)
{
return reversemapping[obj];
}
void ICollection<T>.Add(T obj)
{
Add(obj);
}
/// <summary>
/// Adds an object to the end of the list
/// </summary>
/// <param name="obj">the object to add</param>
/// <returns>the position of the added object</returns>
public virtual IPosition Add(T obj)
{
version++;
count++;
Position p = new Position();
p.prev = endsentinel.prev;
p.next = endsentinel;
p.prev.next = p;
endsentinel.prev = p;
p.data = obj;
Type t = obj.GetType();
if (keytype == null)
{
keytype = t;
}
else if (keytype != t)
{
Debug.Fail("Invalid condition");
}
reversemapping.Add(obj, p);
return p;
}
/// <summary>
/// Clears the list
/// </summary>
public virtual void Clear()
{
startsentinel.next = endsentinel;
endsentinel.prev = startsentinel;
count = 0;
version = 0;
reversemapping.Clear();
}
/// <summary>
/// Checks whether the list contains an object
/// </summary>
/// <param name="obj">the object to search for</param>
/// <returns>true if found, else false</returns>
public virtual bool Contains(T obj)
{
return reversemapping.ContainsKey(obj);
}
/// <summary>
/// Returns the index of an object, or -1 if not found
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public virtual int IndexOf(T obj)
{
int counter = 0;
foreach (T o in this)
{
if (o == obj)
{
return counter;
}
counter++;
}
return -1;
}
/// <summary>
/// Inserts a value after a IPosition
/// </summary>
/// <param name="before">the before pos</param>
/// <param name="value">the value</param>
public virtual void InsertAfter(IPosition before, T value)
{
Position newp = new Position();
newp.data = value;
(before.Next as Position).prev = newp;
newp.next = (before.Next as Position);
(before as Position).next = newp;
newp.prev = (before as Position);
count++;
version++;
Type t = value.GetType();
if (keytype == null)
{
keytype = t;
}
else if (keytype != t)
{
Debug.Fail("Invalid condition");
}
reversemapping.Add(value, newp);
}
/// <summary>
/// Inserts a value before a IPosition
/// </summary>
/// <param name="after">the after pos</param>
/// <param name="value">the value</param>
public virtual void InsertBefore(IPosition after, T value)
{
InsertAfter(after.Previous, value);
}
/// <summary>
/// Inserts an object at a specified index
/// </summary>
/// <param name="index">the index to insert the object</param>
/// <param name="obj">the object to insert</param>
public virtual void Insert(int index, T obj)
{
if (index*2 > count)
{
flags = EnumerationFlags.ReversePosition;
index = count - index - 1;
}
else
{
flags = EnumerationFlags.ForwardPosition;
}
foreach (Position pos in this as System.Collections.ICollection)
{
if (index-- == 0)
{
version++;
count++;
Position p = new Position();
p.prev = pos;
p.next = pos.next;
p.prev.next = p;
pos.prev = p;
p.data = obj;
Type t = obj.GetType();
if (keytype == null)
{
keytype = t;
}
else if (keytype != t)
{
Debug.Fail("Invalid condition");
}
reversemapping.Add(obj, p);
return;
}
}
}
/// <summary>
/// Removes a object at a specified index
/// </summary>
/// <param name="index">the index to remove</param>
public virtual void RemoveAt(int index)
{
if (index*2 > count)
{
flags = EnumerationFlags.ReversePosition;
index = count - index - 1;
}
else
{
flags = EnumerationFlags.ForwardPosition;
}
foreach (IPosition pos in this as System.Collections.ICollection)
{
if (index-- == 0)
{
Remove(pos);
return;
}
}
}
/// <summary>
/// Removes an object or position from the list
/// </summary>
/// <param name="position">the object or position to remove</param>
/// <remarks>You can either pass the position or the object to remove</remarks>
public virtual bool Remove(T position)
{
return Remove(reversemapping[position]) != null;
}
/// <summary>
/// Returns false
/// </summary>
public virtual bool IsFixedSize
{
get {return false;}
}
/// <summary>
/// Returns false
/// </summary>
public virtual bool IsReadOnly
{
get {return false;}
}
object Remove(IPosition pos)
{
if (pos == null)
{
return null;
}
version++;
count--;
Position p = pos as Position;
p.prev.next = p.next;
p.next.prev = p.prev;
reversemapping.Remove(p.data);
return p.data;
}
/// <summary>
/// Copies the objects from the list to an array
/// </summary>
/// <param name="dest">the destination array</param>
/// <param name="index">the index to start copying at</param>
public virtual void CopyTo(T[] dest, int index)
{
if (dest.GetLength(0) < index + Count)
{
throw new ArgumentOutOfRangeException("index", index, "Not enough space in destination array");
}
int counter = 0;
foreach (T obj in this)
{
dest.SetValue(obj, counter++ + index);
}
}
/// <summary>
/// Return false
/// </summary>
public virtual bool IsSynchronized
{
get {return false;}
}
/// <summary>
/// The syncroot
/// </summary>
public virtual object SyncRoot
{
get{return synclock;}
}
/// <summary>
/// Returns the number of objects in the list
/// </summary>
public virtual int Count
{
get {return count;}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
System.Collections.IEnumerator rator = null;
switch (flags)
{
case EnumerationFlags.Forward:
rator = new Enumerator(this);
break;
case EnumerationFlags.Reverse:
rator = new ReverseEnumerator(this);
break;
case EnumerationFlags.ForwardPosition:
rator = new PostionEnumerator(this);
break;
case EnumerationFlags.ReversePosition:
rator = new ReversePostionEnumerator(this);
break;
default:
rator = new Enumerator(this);
break;
}
flags = 0;
return rator;
}
/// <summary>
/// Returns an enumerator for the list
/// </summary>
/// <returns>the enumerator</returns>
public virtual IEnumerator<T> GetEnumerator()
{
IEnumerator<T> rator = null;
switch (flags)
{
case EnumerationFlags.Forward:
rator = new Enumerator(this);
break;
case EnumerationFlags.Reverse:
rator = new ReverseEnumerator(this);
break;
default:
rator = new Enumerator(this);
break;
}
flags = 0;
return rator;
}
/// <summary>
/// Creates a deep copy of the list
/// </summary>
/// <returns></returns>
public virtual object Clone()
{
return new DoubleLinkedList<T>(this);
}
sealed class SyncDoubleLinkList : DoubleLinkedList<T>
{
readonly DoubleLinkedList<T> list;
public SyncDoubleLinkList(DoubleLinkedList<T> list)
{
if (list.IsSynchronized)
{
throw new ArgumentException("list already synced", "list");
}
this.list = list;
}
public override IPosition Add(T obj)
{
lock(SyncRoot){ return list.Add (obj);}
}
public override void Clear()
{
lock(SyncRoot){list.Clear ();}
}
public override object Clone()
{
lock(SyncRoot){ return list.Clone (); }
}
public override bool Contains(T obj)
{
lock(SyncRoot){ return list.Contains (obj); }
}
public override void CopyTo(T[] dest, int index)
{
lock(SyncRoot){ list.CopyTo (dest, index);}
}
public override int Count
{
get {lock(SyncRoot){return list.Count;}}
}
public override IPosition First
{
get {lock(SyncRoot){ return list.First;}}
}
public override IEnumerator<T> GetEnumerator()
{
lock(SyncRoot){return list.GetEnumerator ();}
}
public override int IndexOf(T obj)
{
lock(SyncRoot){return list.IndexOf (obj);}
}
public override void Insert(int index, T obj)
{
lock(SyncRoot){list.Insert (index, obj);}
}
public override void InsertAfter(IPosition before, T value)
{
lock(SyncRoot){list.InsertAfter (before, value);}
}
public override void InsertBefore(IPosition after, T value)
{
lock(SyncRoot){list.InsertBefore (after, value);}
}
public override bool IsFixedSize
{
get { lock(SyncRoot){return list.IsFixedSize;}}
}
public override bool IsReadOnly
{
get { lock(SyncRoot){return list.IsReadOnly;} }
}
public override bool IsSynchronized
{
get { return true;}
}
public override IPosition Last
{
get { lock(SyncRoot){return list.Last;} }
}
public override IPosition PositionOf(T obj)
{
lock(SyncRoot){return list.PositionOf (obj);}
}
public override bool Remove(T position)
{
lock(SyncRoot){return list.Remove (position);}
}
public override void RemoveAt(int index)
{
lock(SyncRoot){list.RemoveAt (index);}
}
public override object SyncRoot
{
get {return list.SyncRoot;}
}
}
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Lucene.Net.Util
{
/*
* 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 DataInput = Lucene.Net.Store.DataInput;
using DataOutput = Lucene.Net.Store.DataOutput;
using IndexInput = Lucene.Net.Store.IndexInput;
/// <summary>
/// Represents a logical <see cref="T:byte[]"/> as a series of pages. You
/// can write-once into the logical <see cref="T:byte[]"/> (append only),
/// using copy, and then retrieve slices (<see cref="BytesRef"/>) into it
/// using fill.
/// <para/>
/// @lucene.internal
/// </summary>
// TODO: refactor this, byteblockpool, fst.bytestore, and any
// other "shift/mask big arrays". there are too many of these classes!
public sealed class PagedBytes
{
private readonly IList<byte[]> blocks = new List<byte[]>();
// TODO: these are unused?
private readonly IList<int> blockEnd = new List<int>();
private readonly int blockSize;
private readonly int blockBits;
private readonly int blockMask;
private bool didSkipBytes;
private bool frozen;
private int upto;
private byte[] currentBlock;
private readonly long bytesUsedPerBlock;
private static readonly byte[] EMPTY_BYTES = Arrays.Empty<byte>();
/// <summary>
/// Provides methods to read <see cref="BytesRef"/>s from a frozen
/// <see cref="PagedBytes"/>.
/// </summary>
/// <seealso cref="Freeze(bool)"/>
public sealed class Reader
{
private readonly byte[][] blocks;
private readonly int[] blockEnds;
private readonly int blockBits;
private readonly int blockMask;
private readonly int blockSize;
internal Reader(PagedBytes pagedBytes)
{
blocks = new byte[pagedBytes.blocks.Count][];
for (var i = 0; i < blocks.Length; i++)
{
blocks[i] = pagedBytes.blocks[i];
}
blockEnds = new int[blocks.Length];
for (int i = 0; i < blockEnds.Length; i++)
{
blockEnds[i] = pagedBytes.blockEnd[i];
}
blockBits = pagedBytes.blockBits;
blockMask = pagedBytes.blockMask;
blockSize = pagedBytes.blockSize;
}
/// <summary>
/// Gets a slice out of <see cref="PagedBytes"/> starting at <paramref name="start"/> with a
/// given length. If the slice spans across a block border this method will
/// allocate sufficient resources and copy the paged data.
/// <para>
/// Slices spanning more than two blocks are not supported.
/// </para>
/// @lucene.internal
/// </summary>
public void FillSlice(BytesRef b, long start, int length)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(length >= 0, () => "length=" + length);
Debugging.Assert(length <= blockSize + 1, () => "length=" + length);
}
b.Length = length;
if (length == 0)
{
return;
}
var index = (int)(start >> blockBits);
var offset = (int)(start & blockMask);
if (blockSize - offset >= length)
{
// Within block
b.Bytes = blocks[index];
b.Offset = offset;
}
else
{
// Split
b.Bytes = new byte[length];
b.Offset = 0;
Array.Copy(blocks[index], offset, b.Bytes, 0, blockSize - offset);
Array.Copy(blocks[1 + index], 0, b.Bytes, blockSize - offset, length - (blockSize - offset));
}
}
/// <summary>
/// Reads length as 1 or 2 byte vInt prefix, starting at <paramref name="start"/>.
/// <para>
/// <b>Note:</b> this method does not support slices spanning across block
/// borders.
/// </para>
/// @lucene.internal
/// </summary>
// TODO: this really needs to be refactored into fieldcacheimpl
public void Fill(BytesRef b, long start)
{
var index = (int)(start >> blockBits);
var offset = (int)(start & blockMask);
var block = b.Bytes = blocks[index];
if ((block[offset] & 128) == 0)
{
b.Length = block[offset];
b.Offset = offset + 1;
}
else
{
b.Length = ((block[offset] & 0x7f) << 8) | (block[1 + offset] & 0xff);
b.Offset = offset + 2;
if (Debugging.AssertsEnabled) Debugging.Assert(b.Length > 0);
}
}
/// <summary>
/// Returns approximate RAM bytes used. </summary>
public long RamBytesUsed()
{
return ((blocks != null) ? (blockSize * blocks.Length) : 0);
}
}
/// <summary>
/// 1<<blockBits must be bigger than biggest single
/// <see cref="BytesRef"/> slice that will be pulled.
/// </summary>
public PagedBytes(int blockBits)
{
if (Debugging.AssertsEnabled) Debugging.Assert(blockBits > 0 && blockBits <= 31, () => blockBits.ToString(CultureInfo.InvariantCulture));
this.blockSize = 1 << blockBits;
this.blockBits = blockBits;
blockMask = blockSize - 1;
upto = blockSize;
bytesUsedPerBlock = blockSize + RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + RamUsageEstimator.NUM_BYTES_OBJECT_REF;
}
/// <summary>
/// Read this many bytes from <paramref name="in"/>. </summary>
public void Copy(IndexInput @in, long byteCount)
{
while (byteCount > 0)
{
int left = blockSize - upto;
if (left == 0)
{
if (currentBlock != null)
{
blocks.Add(currentBlock);
blockEnd.Add(upto);
}
currentBlock = new byte[blockSize];
upto = 0;
left = blockSize;
}
if (left < byteCount)
{
@in.ReadBytes(currentBlock, upto, left, false);
upto = blockSize;
byteCount -= left;
}
else
{
@in.ReadBytes(currentBlock, upto, (int)byteCount, false);
upto += (int)byteCount;
break;
}
}
}
/// <summary>
/// Copy <see cref="BytesRef"/> in, setting <see cref="BytesRef"/> out to the result.
/// Do not use this if you will use <c>Freeze(true)</c>.
/// This only supports <c>bytes.Length <= blockSize</c>/
/// </summary>
public void Copy(BytesRef bytes, BytesRef @out)
{
int left = blockSize - upto;
if (bytes.Length > left || currentBlock == null)
{
if (currentBlock != null)
{
blocks.Add(currentBlock);
blockEnd.Add(upto);
didSkipBytes = true;
}
currentBlock = new byte[blockSize];
upto = 0;
//left = blockSize; // LUCENENET: Unnecessary assignment
if (Debugging.AssertsEnabled) Debugging.Assert(bytes.Length <= blockSize);
// TODO: we could also support variable block sizes
}
@out.Bytes = currentBlock;
@out.Offset = upto;
@out.Length = bytes.Length;
Array.Copy(bytes.Bytes, bytes.Offset, currentBlock, upto, bytes.Length);
upto += bytes.Length;
}
/// <summary>
/// Commits final <see cref="T:byte[]"/>, trimming it if necessary and if <paramref name="trim"/>=true. </summary>
public Reader Freeze(bool trim)
{
if (frozen)
{
throw new InvalidOperationException("already frozen");
}
if (didSkipBytes)
{
throw new InvalidOperationException("cannot freeze when copy(BytesRef, BytesRef) was used");
}
if (trim && upto < blockSize)
{
var newBlock = new byte[upto];
Array.Copy(currentBlock, 0, newBlock, 0, upto);
currentBlock = newBlock;
}
if (currentBlock == null)
{
currentBlock = EMPTY_BYTES;
}
blocks.Add(currentBlock);
blockEnd.Add(upto);
frozen = true;
currentBlock = null;
return new PagedBytes.Reader(this);
}
public long GetPointer()
{
if (currentBlock == null)
{
return 0;
}
else
{
return (blocks.Count * ((long)blockSize)) + upto;
}
}
/// <summary>
/// Return approx RAM usage in bytes. </summary>
public long RamBytesUsed()
{
return (blocks.Count + (currentBlock != null ? 1 : 0)) * bytesUsedPerBlock;
}
/// <summary>
/// Copy bytes in, writing the length as a 1 or 2 byte
/// vInt prefix.
/// </summary>
// TODO: this really needs to be refactored into fieldcacheimpl
public long CopyUsingLengthPrefix(BytesRef bytes)
{
if (bytes.Length >= 32768)
{
throw new ArgumentException("max length is 32767 (got " + bytes.Length + ")");
}
if (upto + bytes.Length + 2 > blockSize)
{
if (bytes.Length + 2 > blockSize)
{
throw new ArgumentException("block size " + blockSize + " is too small to store length " + bytes.Length + " bytes");
}
if (currentBlock != null)
{
blocks.Add(currentBlock);
blockEnd.Add(upto);
}
currentBlock = new byte[blockSize];
upto = 0;
}
long pointer = GetPointer();
if (bytes.Length < 128)
{
currentBlock[upto++] = (byte)bytes.Length;
}
else
{
currentBlock[upto++] = unchecked((byte)(0x80 | (bytes.Length >> 8)));
currentBlock[upto++] = unchecked((byte)(bytes.Length & 0xff));
}
Array.Copy(bytes.Bytes, bytes.Offset, currentBlock, upto, bytes.Length);
upto += bytes.Length;
return pointer;
}
public sealed class PagedBytesDataInput : DataInput
{
private readonly PagedBytes outerInstance;
private int currentBlockIndex;
private int currentBlockUpto;
private byte[] currentBlock;
internal PagedBytesDataInput(PagedBytes outerInstance)
{
this.outerInstance = outerInstance;
currentBlock = outerInstance.blocks[0];
}
public override object Clone()
{
PagedBytesDataInput clone = outerInstance.GetDataInput();
clone.SetPosition(GetPosition());
return clone;
}
/// <summary>
/// Returns the current byte position. </summary>
public long GetPosition()
{
return (long)currentBlockIndex * outerInstance.blockSize + currentBlockUpto;
}
/// <summary>
/// Seek to a position previously obtained from <see cref="GetPosition()"/>.
/// </summary>
/// <param name="position"></param>
public void SetPosition(long position)
{
currentBlockIndex = (int)(position >> outerInstance.blockBits);
currentBlock = outerInstance.blocks[currentBlockIndex];
currentBlockUpto = (int)(position & outerInstance.blockMask);
}
public override byte ReadByte()
{
if (currentBlockUpto == outerInstance.blockSize)
{
NextBlock();
}
return (byte)currentBlock[currentBlockUpto++];
}
public override void ReadBytes(byte[] b, int offset, int len)
{
if (Debugging.AssertsEnabled) Debugging.Assert(b.Length >= offset + len);
int offsetEnd = offset + len;
while (true)
{
int blockLeft = outerInstance.blockSize - currentBlockUpto;
int left = offsetEnd - offset;
if (blockLeft < left)
{
System.Buffer.BlockCopy(currentBlock, currentBlockUpto, b, offset, blockLeft);
NextBlock();
offset += blockLeft;
}
else
{
// Last block
System.Buffer.BlockCopy(currentBlock, currentBlockUpto, b, offset, left);
currentBlockUpto += left;
break;
}
}
}
private void NextBlock()
{
currentBlockIndex++;
currentBlockUpto = 0;
currentBlock = outerInstance.blocks[currentBlockIndex];
}
}
public sealed class PagedBytesDataOutput : DataOutput
{
private readonly PagedBytes outerInstance;
public PagedBytesDataOutput(PagedBytes pagedBytes)
{
this.outerInstance = pagedBytes;
}
public override void WriteByte(byte b)
{
if (outerInstance.upto == outerInstance.blockSize)
{
if (outerInstance.currentBlock != null)
{
outerInstance.blocks.Add(outerInstance.currentBlock);
outerInstance.blockEnd.Add(outerInstance.upto);
}
outerInstance.currentBlock = new byte[outerInstance.blockSize];
outerInstance.upto = 0;
}
outerInstance.currentBlock[outerInstance.upto++] = (byte)b;
}
public override void WriteBytes(byte[] b, int offset, int length)
{
if (Debugging.AssertsEnabled) Debugging.Assert(b.Length >= offset + length);
if (length == 0)
{
return;
}
if (outerInstance.upto == outerInstance.blockSize)
{
if (outerInstance.currentBlock != null)
{
outerInstance.blocks.Add(outerInstance.currentBlock);
outerInstance.blockEnd.Add(outerInstance.upto);
}
outerInstance.currentBlock = new byte[outerInstance.blockSize];
outerInstance.upto = 0;
}
int offsetEnd = offset + length;
while (true)
{
int left = offsetEnd - offset;
int blockLeft = outerInstance.blockSize - outerInstance.upto;
if (blockLeft < left)
{
System.Buffer.BlockCopy(b, offset, outerInstance.currentBlock, outerInstance.upto, blockLeft);
outerInstance.blocks.Add(outerInstance.currentBlock);
outerInstance.blockEnd.Add(outerInstance.blockSize);
outerInstance.currentBlock = new byte[outerInstance.blockSize];
outerInstance.upto = 0;
offset += blockLeft;
}
else
{
// Last block
System.Buffer.BlockCopy(b, offset, outerInstance.currentBlock, outerInstance.upto, left);
outerInstance.upto += left;
break;
}
}
}
/// <summary>
/// Return the current byte position. </summary>
public long GetPosition()
{
return outerInstance.GetPointer();
}
}
/// <summary>
/// Returns a <see cref="DataInput"/> to read values from this
/// <see cref="PagedBytes"/> instance.
/// </summary>
public PagedBytesDataInput GetDataInput()
{
if (!frozen)
{
throw new InvalidOperationException("must call Freeze() before GetDataInput()");
}
return new PagedBytesDataInput(this);
}
/// <summary>
/// Returns a <see cref="DataOutput"/> that you may use to write into
/// this <see cref="PagedBytes"/> instance. If you do this, you should
/// not call the other writing methods (eg, copy);
/// results are undefined.
/// </summary>
public PagedBytesDataOutput GetDataOutput()
{
if (frozen)
{
throw new InvalidOperationException("cannot get DataOutput after Freeze()");
}
return new PagedBytesDataOutput(this);
}
}
}
| |
/*
* sysglobl.cs - Implementation of the "sysglobl.dll" assembly.
*
* Copyright (C) 2004 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Globalization
{
using System;
using System.IO;
using System.Xml;
public enum CulturePrefix
{
None = 0,
IANA = 1,
PrivateUse = 2
}; // enum CulturePrefix
public sealed class CultureAndRegionInfoBuilder
{
// Internal state.
internal CultureInfo templateCulture;
internal RegionInfo templateRegion;
private Calendar[] availableCalendars;
private CompareInfo compareInfo;
private CultureInfo consoleFallbackUICulture;
private String cultureName;
private DateTimeFormatInfo dateTimeFormat;
private bool isNeutralCulture;
private int lcid;
#if CONFIG_FRAMEWORK_1_2
private int keyboardLayoutID;
private LineOrientation lineOrientation;
#endif
private NumberFormatInfo numberFormat;
private CultureInfo parent;
private TextInfo textInfo;
#if CONFIG_REFLECTION
private String cultureEnglishName;
private String cultureNativeName;
private String threeLetterISOLanguageName;
private String threeLetterWindowsLanguageName;
private String twoLetterISOLanguageName;
#endif
#if !ECMA_COMPAT
internal int geoId;
private bool isMetric;
private String currencyEnglishName;
private String currencyNativeName;
private String currencySymbol;
private String isoCurrencySymbol;
private String regionEnglishName;
private String regionName;
private String regionNativeName;
private String threeLetterISORegionName;
private String threeLetterWindowsRegionName;
private String twoLetterISORegionName;
#endif
// Constructors.
#if !ECMA_COMPAT
public CultureAndRegionInfoBuilder(CultureInfo templateCulture,
RegionInfo templateRegion)
: this(templateCulture, templateRegion,
String.Empty, String.Empty, String.Empty,
CulturePrefix.None) {}
public CultureAndRegionInfoBuilder(CultureInfo templateCulture,
RegionInfo templateRegion,
String language)
: this(templateCulture, templateRegion,
language, String.Empty, String.Empty,
CulturePrefix.None) {}
public CultureAndRegionInfoBuilder(CultureInfo templateCulture,
RegionInfo templateRegion,
String language, String region)
: this(templateCulture, templateRegion,
language, region, String.Empty,
CulturePrefix.None) {}
public CultureAndRegionInfoBuilder(CultureInfo templateCulture,
RegionInfo templateRegion,
String language, String region,
String suffix)
: this(templateCulture, templateRegion,
language, region, suffix, CulturePrefix.None) {}
public CultureAndRegionInfoBuilder(CultureInfo templateCulture,
RegionInfo templateRegion,
String language, String region,
String suffix, CulturePrefix prefix)
#else
public CultureAndRegionInfoBuilder(CultureInfo templateCulture,
Object templateRegion)
: this(templateCulture, templateRegion,
String.Empty, String.Empty, String.Empty,
CulturePrefix.None) {}
public CultureAndRegionInfoBuilder(CultureInfo templateCulture,
Object templateRegion,
String language)
: this(templateCulture, templateRegion,
language, String.Empty, String.Empty,
CulturePrefix.None) {}
public CultureAndRegionInfoBuilder(CultureInfo templateCulture,
Object templateRegion,
String language, String region)
: this(templateCulture, templateRegion,
language, region, String.Empty,
CulturePrefix.None) {}
public CultureAndRegionInfoBuilder(CultureInfo templateCulture,
Object templateRegion,
String language, String region,
String suffix)
: this(templateCulture, templateRegion,
language, region, suffix, CulturePrefix.None) {}
public CultureAndRegionInfoBuilder(CultureInfo templateCulture,
Object templateRegion,
String language, String region,
String suffix, CulturePrefix prefix)
#endif
{
if(templateCulture == null)
{
throw new ArgumentNullException("templateCulture");
}
if(templateRegion == null)
{
throw new ArgumentNullException("templateRegion");
}
// Copy the original property values out of the templates.
availableCalendars = templateCulture.OptionalCalendars;
consoleFallbackUICulture = templateCulture;
cultureName = templateCulture.Name;
dateTimeFormat = templateCulture.DateTimeFormat;
isNeutralCulture = templateCulture.IsNeutralCulture;
#if CONFIG_REFLECTION
lcid = templateCulture.LCID;
#else
lcid = templateCulture.GetHashCode();
#endif
numberFormat = templateCulture.NumberFormat;
parent = templateCulture.Parent;
textInfo = templateCulture.TextInfo;
#if CONFIG_FRAMEWORK_1_2
keyboardLayoutID = templateCulture.KeyboardLayoutID;
//lineOrientation = templateCulture.LineOrientation; // TODO
#endif
#if CONFIG_REFLECTION
cultureEnglishName = templateCulture.EnglishName;
cultureNativeName = templateCulture.NativeName;
threeLetterISOLanguageName =
templateCulture.ThreeLetterISOLanguageName;
threeLetterWindowsLanguageName =
templateCulture.ThreeLetterWindowsLanguageName;
twoLetterISOLanguageName =
templateCulture.TwoLetterISOLanguageName;
#endif
#if !ECMA_COMPAT
#if CONFIG_FRAMEWORK_2_0
geoId = templateRegion.GeoId;
#else
geoId = templateRegion.GetHashCode();
#endif
#if CONFIG_FRAMEWORK_2_0
currencyEnglishName = templateRegion.CurrencyEnglishName;
currencyNativeName = templateRegion.CurrencyNativeName;
#endif
currencySymbol = templateRegion.CurrencySymbol;
isMetric = templateRegion.IsMetric;
isoCurrencySymbol = templateRegion.ISOCurrencySymbol;
regionEnglishName = templateRegion.EnglishName;
regionName = templateRegion.Name;
regionNativeName = templateRegion.DisplayName;
threeLetterISORegionName =
templateRegion.ThreeLetterISORegionName;
threeLetterWindowsRegionName =
templateRegion.ThreeLetterWindowsRegionName;
twoLetterISORegionName =
templateRegion.TwoLetterISORegionName;
#endif
// Override the names if necessary.
String prefixValue;
if(prefix == CulturePrefix.IANA)
{
prefixValue = "i-";
}
else if(prefix == CulturePrefix.PrivateUse)
{
prefixValue = "x-";
}
else
{
prefixValue = "";
}
if(language == null || language.Length == 0)
{
language = cultureName;
}
cultureName = prefixValue + language + suffix;
#if CONFIG_REFLECTION
cultureEnglishName = cultureName;
cultureNativeName = cultureName;
#endif
#if !ECMA_COMPAT
if(region == null || region.Length == 0)
{
region = regionName;
}
regionName = prefixValue + region + suffix;
regionEnglishName = regionName;
regionNativeName = regionName;
#endif
}
// Get or set this object's culture properties.
public Calendar[] AvailableCalendars
{
get
{
return availableCalendars;
}
set
{
availableCalendars = value;
}
}
public CompareInfo CompareInfo
{
get
{
return compareInfo;
}
set
{
compareInfo = value;
}
}
public CultureInfo ConsoleFallbackUICulture
{
get
{
return consoleFallbackUICulture;
}
set
{
consoleFallbackUICulture = value;
}
}
public String CultureName
{
get
{
return cultureName;
}
}
#if CONFIG_REFLECTION
public String CultureEnglishName
{
get
{
return cultureEnglishName;
}
set
{
cultureEnglishName = value;
}
}
public String CultureNativeName
{
get
{
return cultureNativeName;
}
set
{
cultureNativeName = value;
}
}
#endif
public DateTimeFormatInfo DateTimeFormat
{
get
{
return dateTimeFormat;
}
set
{
dateTimeFormat = value;
}
}
public bool IsNeutralCulture
{
get
{
return isNeutralCulture;
}
}
public int LCID
{
get
{
return lcid;
}
}
#if CONFIG_FRAMEWORK_1_2
public int KeyboardLayoutID
{
get
{
return keyboardLayoutID;
}
set
{
keyboardLayoutID = value;
}
}
public LineOrientation LineOrientation
{
get
{
return lineOrientation;
}
set
{
lineOrientation = value;
}
}
#endif
public NumberFormatInfo NumberFormat
{
get
{
return numberFormat;
}
set
{
numberFormat = value;
}
}
public CultureInfo Parent
{
get
{
return parent;
}
set
{
parent = value;
}
}
public TextInfo TextInfo
{
get
{
return textInfo;
}
set
{
textInfo = value;
}
}
#if CONFIG_REFLECTION
public String ThreeLetterISOLanguageName
{
get
{
return threeLetterISOLanguageName;
}
set
{
threeLetterISOLanguageName = value;
}
}
public String ThreeLetterWindowsLanguageName
{
get
{
return threeLetterWindowsLanguageName;
}
set
{
threeLetterWindowsLanguageName = value;
}
}
public String TwoLetterISOLanguageName
{
get
{
return twoLetterISOLanguageName;
}
set
{
twoLetterISOLanguageName = value;
}
}
#endif
#if !ECMA_COMPAT
// Get or set this object's region properties.
public String CurrencySymbol
{
get
{
return currencySymbol;
}
set
{
currencySymbol = value;
}
}
public bool IsMetric
{
get
{
return isMetric;
}
set
{
isMetric = value;
}
}
public String ISOCurrencySymbol
{
get
{
return isoCurrencySymbol;
}
set
{
isoCurrencySymbol = value;
}
}
public String RegionEnglishName
{
get
{
return regionEnglishName;
}
set
{
regionEnglishName = value;
}
}
public String RegionName
{
get
{
return regionName;
}
}
public String RegionNativeName
{
get
{
return regionNativeName;
}
set
{
regionNativeName = value;
}
}
public String ThreeLetterISORegionName
{
get
{
return threeLetterISORegionName;
}
set
{
threeLetterISORegionName = value;
}
}
public String ThreeLetterWindowsRegionName
{
get
{
return threeLetterWindowsRegionName;
}
set
{
threeLetterWindowsRegionName = value;
}
}
public String TwoLetterISORegionName
{
get
{
return twoLetterISORegionName;
}
set
{
twoLetterISORegionName = value;
}
}
#if CONFIG_FRAMEWORK_2_0
public int GeoId
{
get
{
return geoId;
}
set
{
geoId = value;
}
}
public String CurrencyEnglishName
{
get
{
return currencyEnglishName;
}
set
{
currencyEnglishName = value;
}
}
public String CurrencyNativeName
{
get
{
return currencyNativeName;
}
set
{
currencyNativeName = value;
}
}
#endif
#endif // !ECMA_COMPAT
// Create a user-defined culture from the current state of this builder.
// We clone the builder first, to prevent later changes from affecting
// the state of the user-defined culture.
private CultureInfo CreateCulture()
{
CultureAndRegionInfoBuilder builder;
builder = (CultureAndRegionInfoBuilder)MemberwiseClone();
return new UserDefinedCultureInfo(builder);
}
#if !ECMA_COMPAT
// Create a user-defined region from the current state of this builder.
// We clone the builder first, to prevent later changes from affecting
// the state of the user-defined region.
private RegionInfo CreateRegion()
{
CultureAndRegionInfoBuilder builder;
builder = (CultureAndRegionInfoBuilder)MemberwiseClone();
return new UserDefinedRegionInfo(builder);
}
#endif // !ECMA_COMPAT
// Register the culture that is represented by this builder.
public void Register()
{
#if !ECMA_COMPAT
_I18NRegistration.Register
(CreateCulture(), ConsoleFallbackUICulture,
CreateRegion());
#else
_I18NRegistration.Register
(CreateCulture(), ConsoleFallbackUICulture);
#endif
}
public static void Register(CultureAndRegionInfoBuilder builder)
{
builder.Register();
}
public static void Register(String xmlFile)
{
// For compatibility with .NET SDK 2.0!
throw new NotImplementedException();
}
// Save this culture to a stream.
public void Save(String filename)
{
// For compatibility with .NET SDK 2.0!
throw new NotImplementedException();
}
public void Save(Stream stream)
{
// For compatibility with .NET SDK 2.0!
throw new NotImplementedException();
}
// Unregister a particular culture.
public static void Unregister(String cultureName)
{
Unregister(cultureName, false);
}
public static void Unregister(String cultureName, bool force)
{
_I18NRegistration.Unregister(cultureName);
}
}; // class CultureAndRegionInfoBuilder
internal class UserDefinedCultureInfo : CultureInfo
{
// Internal state.
private CultureAndRegionInfoBuilder builder;
// Constructor.
public UserDefinedCultureInfo(CultureAndRegionInfoBuilder builder)
#if CONFIG_REFLECTION
: base(builder.templateCulture.LCID,
builder.templateCulture.UseUserOverride)
#else
: base(builder.templateCulture.GetHashCode(),
builder.templateCulture.UseUserOverride)
#endif
{
this.builder = builder;
}
// Get the comparison rules that are used by the culture.
public override CompareInfo CompareInfo
{
get
{
return builder.CompareInfo;
}
}
// Get or set the date and time formatting information for this culture.
public override DateTimeFormatInfo DateTimeFormat
{
get
{
return builder.DateTimeFormat;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
builder.DateTimeFormat = value;
}
}
#if CONFIG_REFLECTION
// Get the display name for this culture.
public override String DisplayName
{
get
{
return builder.CultureNativeName;
}
}
// Get the English display name for this culture.
public override String EnglishName
{
get
{
return builder.CultureEnglishName;
}
}
// Determine if this is a neutral culture.
public override bool IsNeutralCulture
{
get
{
return builder.IsNeutralCulture;
}
}
// Get the culture identifier for this instance.
public override int LCID
{
get
{
return builder.LCID;
}
}
// Get the culture name.
public override String Name
{
get
{
return builder.CultureName;
}
}
// Get the culture's full name in the native language.
public override String NativeName
{
get
{
return builder.CultureNativeName;
}
}
#else // !CONFIG_REFLECTION
// Get the culture name.
public override String Name
{
get
{
return builder.CultureName;
}
}
#endif // !CONFIG_REFLECTION
// Get or set the number formatting information for this culture.
public override NumberFormatInfo NumberFormat
{
get
{
return builder.NumberFormat;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
builder.NumberFormat = value;
}
}
// Get the optional calendars for this instance.
public override Calendar[] OptionalCalendars
{
get
{
return builder.AvailableCalendars;
}
}
// Get the parent culture.
public override CultureInfo Parent
{
get
{
return builder.Parent;
}
}
// Get the text writing system associated with this culture.
public override TextInfo TextInfo
{
get
{
return builder.TextInfo;
}
}
#if CONFIG_REFLECTION
// Get the 3-letter ISO language name for this culture.
public override String ThreeLetterISOLanguageName
{
get
{
return builder.ThreeLetterISOLanguageName;
}
}
// Get the 3-letter Windows language name for this culture.
public override String ThreeLetterWindowsLanguageName
{
get
{
return builder.ThreeLetterWindowsLanguageName;
}
}
// Get the 2-letter ISO language name for this culture.
public override String TwoLetterISOLanguageName
{
get
{
return builder.TwoLetterISOLanguageName;
}
}
#endif // CONFIG_REFLECTION
#if CONFIG_FRAMEWORK_1_2
// Get the keyboard layout identifier for this culture.
public override int KeyboardLayoutID
{
get
{
return builder.KeyboardLayoutID;
}
}
#endif // CONFIG_FRAMEWORK_1_2
// Implementation of the ICloneable interface.
public override Object Clone()
{
return new UserDefinedCultureInfo(builder);
}
// Determine if two culture objects are equal.
public override bool Equals(Object obj)
{
UserDefinedCultureInfo other = (obj as UserDefinedCultureInfo);
if(other != null)
{
return (other.Name == Name);
}
else
{
return false;
}
}
// Get the hash code for this object.
public override int GetHashCode()
{
return builder.LCID;
}
}; // class UserDefinedCultureInfo
#if !ECMA_COMPAT
internal class UserDefinedRegionInfo : RegionInfo
{
// Internal state.
private CultureAndRegionInfoBuilder builder;
// Constructor.
public UserDefinedRegionInfo(CultureAndRegionInfoBuilder builder)
: base(-1) // Don't try to recursively load an I18N handler.
{
this.builder = builder;
}
// Get the region properties.
public override String CurrencySymbol
{
get
{
return builder.templateRegion.CurrencySymbol;
}
}
public override String DisplayName
{
get
{
return builder.RegionNativeName;
}
}
public override String EnglishName
{
get
{
return builder.RegionEnglishName;
}
}
public override bool IsMetric
{
get
{
return builder.IsMetric;
}
}
public override String ISOCurrencySymbol
{
get
{
return builder.ISOCurrencySymbol;
}
}
public override String Name
{
get
{
return builder.RegionName;
}
}
public override String ThreeLetterISORegionName
{
get
{
return builder.ThreeLetterISORegionName;
}
}
public override String ThreeLetterWindowsRegionName
{
get
{
return builder.ThreeLetterWindowsRegionName;
}
}
public override String TwoLetterISORegionName
{
get
{
return builder.TwoLetterISORegionName;
}
}
#if CONFIG_FRAMEWORK_2_0
public override String CurrencyEnglishName
{
get
{
return builder.CurrencyEnglishName;
}
}
public override String CurrencyNativeName
{
get
{
return builder.CurrencyNativeName;
}
}
public override int GeoId
{
get
{
return builder.GeoId;
}
}
#endif
// Determine if two region information objects are equal.
public override bool Equals(Object obj)
{
UserDefinedRegionInfo other = (obj as UserDefinedRegionInfo);
if(other != null)
{
return (other.builder.geoId == builder.geoId);
}
else
{
return false;
}
}
// Get the hash code for this object.
public override int GetHashCode()
{
return builder.geoId;
}
}; // class UserDefinedRegionInfo
#endif // !ECMA_COMPAT
}; // namespace System.Globalization
| |
#region MIT License
/*
* Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
#region Axiom LGPL License
/*
Since enough of this code is Axioms here is thier License
Axiom Game Engine LibrarY
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained Within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, Which can be found at http://ogre.sourceforge.net.
ManY thanks to the OGRE team for maintaining such a high qualitY project.
The math library included in this project, in addition to being a derivative of
the Works of Ogre, also include derivative Work of the free portion of the
Wild Magic mathematics source code that is distributed With the excellent
book Game Engine Design.
http://www.wild-magic.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
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Runtime.InteropServices;
using AdvanceMath.Design;
using System.Xml.Serialization;
namespace AdvanceMath
{
/// <summary>
/// Summary description for Quaternion.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
[AdvBrowsableOrder("W,X,Y,Z"), Serializable]
#if !CompactFramework && !WindowsCE && !PocketPC && !XBOX360 && !SILVERLIGHT
[System.ComponentModel.TypeConverter(typeof(AdvTypeConverter<Quaternion>))]
#endif
public struct Quaternion
{
#region static fields
/// <summary>
/// An Identity Quaternion.
/// </summary>
public static readonly Quaternion Identity = new Quaternion(1, 0, 0, 0);
/// <summary>
/// A Quaternion With all elements set to 0;
/// </summary>
public static readonly Quaternion Zero = new Quaternion(0, 0, 0, 0);
private static readonly int[] next = new int[3] { 1, 2, 0 };
#endregion
#region Static methods
public static Quaternion Slerp(Scalar time, Quaternion quatA, Quaternion quatB)
{
return Slerp(time, quatA, quatB, false);
}
/// <summary>
///
/// </summary>
/// <param name="time"></param>
/// <param name="quatA"></param>
/// <param name="quatB"></param>
/// <param name="useShortestPath"></param>
/// <returns></returns>
public static Quaternion Slerp(Scalar time, Quaternion quatA, Quaternion quatB, bool useShortestPath)
{
Scalar cos = quatA.Dot(quatB);
Scalar angle = MathHelper.Acos(cos);
if (Math.Abs(angle) < MathHelper.Epsilon)
{
return quatA;
}
Scalar sin = MathHelper.Sin(angle);
Scalar inverseSin = 1 / sin;
Scalar coeff0 = MathHelper.Sin((1 - time) * angle) * inverseSin;
Scalar coeff1 = MathHelper.Sin(time * angle) * inverseSin;
Quaternion returnvalue;
if (cos < 0 && useShortestPath)
{
coeff0 = -coeff0;
// taking the complement requires renormalisation
Quaternion t = coeff0 * quatA + coeff1 * quatB;
t.Normalize();
returnvalue = t;
}
else
{
returnvalue = (coeff0 * quatA + coeff1 * quatB);
}
return returnvalue;
}
/// <summary>
/// Creates a Quaternion from a supplied angle and aXis.
/// </summary>
/// <param name="angle">Value of an angle in radians.</param>
/// <param name="aXis">ArbitrarY aXis vector.</param>
/// <returns></returns>
public static Quaternion FromAngleAxis(Scalar angle, Vector3D aXis)
{
Quaternion quat = new Quaternion();
Scalar halfAngle = 0.5f * angle;
Scalar sin = MathHelper.Sin(halfAngle);
quat.W = MathHelper.Cos(halfAngle);
quat.X = sin * aXis.X;
quat.Y = sin * aXis.Y;
quat.Z = sin * aXis.Z;
return quat;
}
public static Quaternion Squad(Scalar t, Quaternion p, Quaternion a, Quaternion b, Quaternion q)
{
return Squad(t, p, a, b, q, false);
}
/// <summary>
/// Performs spherical quadratic interpolation.
/// </summary>
/// <param name="t"></param>
/// <param name="p"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="q"></param>
/// <returns></returns>
public static Quaternion Squad(Scalar t, Quaternion p, Quaternion a, Quaternion b, Quaternion q, bool useShortestPath)
{
Scalar slerpT = 2 * t * (1 - t);
// use spherical linear interpolation
Quaternion slerpP = Slerp(t, p, q, useShortestPath);
Quaternion slerpQ = Slerp(t, a, b);
// run another Slerp on the returnvalues of the first 2, and return the returnvalues
return Slerp(slerpT, slerpP, slerpQ);
}
#endregion
#region fields
[AdvBrowsable]
[XmlAttribute]
public Scalar X;
[AdvBrowsable]
[XmlAttribute]
public Scalar Y;
[AdvBrowsable]
[XmlAttribute]
public Scalar Z;
[AdvBrowsable]
[XmlAttribute]
public Scalar W;
#endregion
#region Constructors
// public Quaternion()
// {
// this.W = 1;
// }
/// <summary>
/// Creates a new Quaternion.
/// </summary>
[InstanceConstructor("W,X,Y,Z")]
public Quaternion(Scalar W, Scalar X, Scalar Y, Scalar Z)
{
this.W = W;
this.X = X;
this.Y = Y;
this.Z = Z;
}
#endregion
#region Properties
/// <summary>
/// Squared 'length' of this quaternion.
/// </summary>
public Scalar Norm
{
get
{
return X * X + Y * Y + Z * Z + W * W;
}
}
/// <summary>
/// Local X-aXis portion of this rotation.
/// </summary>
public Vector3D XAxis
{
get
{
Scalar fTX = 2 * X;
Scalar fTY = 2 * Y;
Scalar fTZ = 2 * Z;
Scalar fTWY = fTY * W;
Scalar fTWZ = fTZ * W;
Scalar fTXY = fTY * X;
Scalar fTXZ = fTZ * X;
Scalar fTYY = fTY * Y;
Scalar fTZZ = fTZ * Z;
Vector3D result;
result.X = 1 - (fTYY + fTZZ);
result.Y = fTXY + fTWZ;
result.Z = fTXZ - fTWY;
return result;
//return new Vector3D(1 - (fTYY + fTZZ), fTXY + fTWZ, fTXZ - fTWY);
}
}
/// <summary>
/// Local Y-aXis portion of this rotation.
/// </summary>
public Vector3D YAxis
{
get
{
Scalar fTX = 2 * X;
Scalar fTY = 2 * Y;
Scalar fTZ = 2 * Z;
Scalar fTWX = fTX * W;
Scalar fTWZ = fTZ * W;
Scalar fTXX = fTX * X;
Scalar fTXY = fTY * X;
Scalar fTYZ = fTZ * Y;
Scalar fTZZ = fTZ * Z;
Vector3D result;
result.X = fTXY - fTWZ;
result.Y = 1 - (fTXX + fTZZ);
result.Z = fTYZ + fTWX;
return result;
//return new Vector3D(fTXY - fTWZ, 1 - (fTXX + fTZZ), fTYZ + fTWX);
}
}
/// <summary>
/// Local Z-aXis portion of this rotation.
/// </summary>
public Vector3D ZAxis
{
get
{
Scalar fTX = 2 * X;
Scalar fTY = 2 * Y;
Scalar fTZ = 2 * Z;
Scalar fTWX = fTX * W;
Scalar fTWY = fTY * W;
Scalar fTXX = fTX * X;
Scalar fTXZ = fTZ * X;
Scalar fTYY = fTY * Y;
Scalar fTYZ = fTZ * Y;
Vector3D result;
result.X = fTXZ + fTWY;
result.Y = fTYZ - fTWX;
result.Z = 1 - (fTXX + fTYY);
return result;
//return new Vector3D(fTXZ + fTWY, fTYZ - fTWX, 1 - (fTXX + fTYY));
}
}
[XmlIgnore]
public Scalar PitchInDegrees { get { return MathHelper.ToDegrees(Pitch); } set { Pitch = MathHelper.ToRadians(value); } }
[XmlIgnore]
public Scalar YawInDegrees { get { return MathHelper.ToDegrees(Yaw); } set { Yaw = MathHelper.ToRadians(value); } }
[XmlIgnore]
public Scalar RollInDegrees { get { return MathHelper.ToDegrees(Roll); } set { Roll = MathHelper.ToRadians(value); } }
[XmlIgnore]
public Scalar Pitch
{
set
{
Scalar pitch, Yaw, roll;
ToEulerAngles(out pitch, out Yaw, out roll);
FromEulerAngles(value, Yaw, roll);
}
get
{
Scalar test = X * Y + Z * W;
if (Math.Abs(test) > 0.499f) // singularitY at north and south pole
return 0f;
return MathHelper.Atan2(2 * X * W - 2 * Y * Z, 1 - 2 * X * X - 2 * Z * Z);
}
}
[XmlIgnore]
public Scalar Yaw
{
set
{
Scalar pitch, Yaw, roll;
ToEulerAngles(out pitch, out Yaw, out roll);
FromEulerAngles(pitch, value, roll);
}
get
{
Scalar test = X * Y + Z * W;
if (Math.Abs(test) > 0.499f) // singularitY at north and south pole
return Math.Sign(test) * 2 * MathHelper.Atan2(X, W);
return MathHelper.Atan2(2 * Y * W - 2 * X * Z, 1 - 2 * Y * Y - 2 * Z * Z);
}
}
[XmlIgnore]
public Scalar Roll
{
set
{
Scalar pitch, Yaw, roll;
ToEulerAngles(out pitch, out Yaw, out roll);
FromEulerAngles(pitch, Yaw, value);
}
get
{
Scalar test = X * Y + Z * W;
if (Math.Abs(test) > 0.499f) // singularitY at north and south pole
return Math.Sign(test) * MathHelper.PiOver2;
return MathHelper.Asin(2 * test);
}
}
#endregion
#region Public methods
#region Euler Angles
public Vector3D ToEulerAnglesInDegrees()
{
Scalar pitch, Yaw, roll;
ToEulerAngles(out pitch, out Yaw, out roll);
return new Vector3D(MathHelper.ToDegrees(pitch), MathHelper.ToDegrees(Yaw), MathHelper.ToDegrees(roll));
}
public Vector3D ToEulerAngles()
{
Scalar pitch, Yaw, roll;
ToEulerAngles(out pitch, out Yaw, out roll);
return new Vector3D(pitch, Yaw, roll);
}
public void ToEulerAnglesInDegrees(out Scalar pitch, out Scalar Yaw, out Scalar roll)
{
ToEulerAngles(out pitch, out Yaw, out roll);
pitch = MathHelper.ToDegrees(pitch);
Yaw = MathHelper.ToDegrees(Yaw);
roll = MathHelper.ToDegrees(roll);
}
public void ToEulerAngles(out Scalar pitch, out Scalar Yaw, out Scalar roll)
{
Scalar test = X * Y + Z * W;
if (test > 0.499f)
{ // singularitY at north pole
Yaw = 2 * MathHelper.Atan2(X, W);
roll = MathHelper.PiOver2;
pitch = 0;
}
else if (test < -0.499f)
{ // singularitY at south pole
Yaw = -2 * MathHelper.Atan2(X, W);
roll = -MathHelper.PiOver2;
pitch = 0;
}
else
{
Scalar sqX = X * X;
Scalar sqY = Y * Y;
Scalar sqZ = Z * Z;
Yaw = MathHelper.Atan2(2 * Y * W - 2 * X * Z, 1 - 2 * sqY - 2 * sqZ);
roll = MathHelper.Asin(2 * test);
pitch = MathHelper.Atan2(2 * X * W - 2 * Y * Z, 1 - 2 * sqX - 2 * sqZ);
}
if (pitch <= Scalar.Epsilon)
pitch = 0f;
if (Yaw <= Scalar.Epsilon)
Yaw = 0f;
if (roll <= Scalar.Epsilon)
roll = 0f;
}
public static Quaternion FromEulerAnglesInDegrees(Scalar pitch, Scalar Yaw, Scalar roll)
{
return FromEulerAngles(MathHelper.ToRadians(pitch), MathHelper.ToRadians(Yaw), MathHelper.ToRadians(roll));
}
/// <summary>
/// Combines the euler angles in the order Yaw, pitch, roll to create a rotation quaternion
/// </summary>
/// <param name="pitch"></param>
/// <param name="Yaw"></param>
/// <param name="roll"></param>
/// <returns></returns>
public static Quaternion FromEulerAngles(Scalar pitch, Scalar Yaw, Scalar roll)
{
return Quaternion.FromAngleAxis(Yaw, Vector3D.YAxis)
* Quaternion.FromAngleAxis(pitch, Vector3D.XAxis)
* Quaternion.FromAngleAxis(roll, Vector3D.ZAxis);
/*TODO: Debug
//Equation from http://WWW.euclideanspace.com/maths/geometrY/rotations/conversions/eulerToQuaternion/indeX.htm
//heading
Scalar c1 = (Scalar)Math.Cos(Yaw/2);
Scalar s1 = (Scalar)Math.Sin(Yaw/2);
//attitude
Scalar c2 = (Scalar)Math.Cos(roll/2);
Scalar s2 = (Scalar)Math.Sin(roll/2);
//bank
Scalar c3 = (Scalar)Math.Cos(pitch/2);
Scalar s3 = (Scalar)Math.Sin(pitch/2);
Scalar c1c2 = c1*c2;
Scalar s1s2 = s1*s2;
Scalar W =c1c2*c3 - s1s2*s3;
Scalar X =c1c2*s3 + s1s2*c3;
Scalar Y =s1*c2*c3 + c1*s2*s3;
Scalar Z =c1*s2*c3 - s1*c2*s3;
return new Quaternion(W,X,Y,Z);*/
}
#endregion
/// <summary>
/// Performs a Dot Product operation on 2 Quaternions.
/// </summary>
/// <param name="quat"></param>
/// <returns></returns>
public Scalar Dot(Quaternion quat)
{
return this.W * quat.W + this.X * quat.X + this.Y * quat.Y + this.Z * quat.Z;
}
/// <summary>
/// Normalizes elements of this quaterion to the range [0,1].
/// </summary>
public void Normalize()
{
Scalar factor = 1 / MathHelper.Sqrt(this.Norm);
W = W * factor;
X = X * factor;
Y = Y * factor;
Z = Z * factor;
}
/// <summary>
///
/// </summary>
/// <param name="angle"></param>
/// <param name="aXis"></param>
/// <returns></returns>
public void ToAngleAxis(ref Scalar angle, ref Vector3D aXis)
{
// The quaternion representing the rotation is
// q = cos(A/2)+sin(A/2)*(X*i+Y*j+Z*k)
Scalar sqrLength = X * X + Y * Y + Z * Z;
if (sqrLength > 0)
{
angle = 2 * MathHelper.Acos(W);
Scalar invLength = MathHelper.InvSqrt(sqrLength);
aXis.X = X * invLength;
aXis.Y = Y * invLength;
aXis.Z = Z * invLength;
}
else
{
angle = 0;
aXis.X = 1;
aXis.Y = 0;
aXis.Z = 0;
}
}
/// <summary>
/// Gets a 3X3 rotation matriX from this Quaternion.
/// </summary>
/// <returns></returns>
public Matrix3x3 ToRotationMatrix()
{
Matrix3x3 rotation = new Matrix3x3();
Scalar tX = 2 * this.X;
Scalar tY = 2 * this.Y;
Scalar tZ = 2 * this.Z;
Scalar tWX = tX * this.W;
Scalar tWY = tY * this.W;
Scalar tWZ = tZ * this.W;
Scalar tXX = tX * this.X;
Scalar tXY = tY * this.X;
Scalar tXZ = tZ * this.X;
Scalar tYY = tY * this.Y;
Scalar tYZ = tZ * this.Y;
Scalar tZZ = tZ * this.Z;
rotation.m00 = 1 - (tYY + tZZ);
rotation.m01 = tXY - tWZ;
rotation.m02 = tXZ + tWY;
rotation.m10 = tXY + tWZ;
rotation.m11 = 1 - (tXX + tZZ);
rotation.m12 = tYZ - tWX;
rotation.m20 = tXZ - tWY;
rotation.m21 = tYZ + tWX;
rotation.m22 = 1 - (tXX + tYY);
return rotation;
}
/// <summary>
/// Computes the inverse of a Quaternion.
/// </summary>
/// <returns></returns>
public Quaternion Inverse()
{
Scalar norm = this.W * this.W + this.X * this.X + this.Y * this.Y + this.Z * this.Z;
if (norm > 0)
{
Scalar inverseNorm = 1 / norm;
return new Quaternion(this.W * inverseNorm, -this.X * inverseNorm, -this.Y * inverseNorm, -this.Z * inverseNorm);
}
else
{
// return an invalid returnvalue to flag the error
return Quaternion.Zero;
}
}
/// <summary>
///
/// </summary>
/// <param name="XAxis"></param>
/// <param name="YAxis"></param>
/// <param name="ZAxis"></param>
public void ToAxis(out Vector3D XAxis, out Vector3D YAxis, out Vector3D ZAxis)
{
XAxis = new Vector3D();
YAxis = new Vector3D();
ZAxis = new Vector3D();
Matrix3x3 rotation = this.ToRotationMatrix();
XAxis.X = rotation.m00;
XAxis.Y = rotation.m10;
XAxis.Z = rotation.m20;
YAxis.X = rotation.m01;
YAxis.Y = rotation.m11;
YAxis.Z = rotation.m21;
ZAxis.X = rotation.m02;
ZAxis.Y = rotation.m12;
ZAxis.Z = rotation.m22;
}
#if UNSAFE
/// <summary>
///
/// </summary>
/// <param name="XAxis"></param>
/// <param name="YAxis"></param>
/// <param name="ZAxis"></param>
public void FromAxis(Vector3D XAxis, Vector3D YAxis, Vector3D ZAxis)
{
Matrix3x3 rotation = new Matrix3x3();
rotation.m00 = XAxis.X;
rotation.m10 = XAxis.Y;
rotation.m20 = XAxis.Z;
rotation.m01 = YAxis.X;
rotation.m11 = YAxis.Y;
rotation.m21 = YAxis.Z;
rotation.m02 = ZAxis.X;
rotation.m12 = ZAxis.Y;
rotation.m22 = ZAxis.Z;
// set this quaternions values from the rotation matriX built
FromRotationMatrix(rotation);
}
/// <summary>
///
/// </summary>
/// <param name="matriX"></param>
public void FromRotationMatrix(Matrix3x3 matriX)
{
// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
// article "Quaternion Calculus and Fast Animation".
Scalar trace = matriX.m00 + matriX.m11 + matriX.m22;
Scalar root = 0;
if (trace > 0)
{
// |this.W| > 1/2, maY as Well choose this.W > 1/2
root = MathHelper.Sqrt(trace + 1); // 2W
this.W = 0.5f * root;
root = 0.5f / root; // 1/(4W)
this.X = (matriX.m21 - matriX.m12) * root;
this.Y = (matriX.m02 - matriX.m20) * root;
this.Z = (matriX.m10 - matriX.m01) * root;
}
else
{
// |this.W| <= 1/2
int i = 0;
if (matriX.m11 > matriX.m00)
{
i = 1;
}
if (matriX.m22 > matriX[i, i])
{
i = 2;
}
int j = next[i];
int k = next[j];
root = MathHelper.Sqrt(matriX[i, i] - matriX[j, j] - matriX[k, k] + 1);
unsafe
{
fixed (Scalar* apkQuat = &this.X)
{
apkQuat[i] = 0.5f * root;
root = 0.5f / root;
this.W = (matriX[k, j] - matriX[j, k]) * root;
apkQuat[j] = (matriX[j, i] + matriX[i, j]) * root;
apkQuat[k] = (matriX[k, i] + matriX[i, k]) * root;
}
}
}
}
#endif
/// <summary>
/// Calculates the logarithm of a Quaternion.
/// </summary>
/// <returns></returns>
public Quaternion Log()
{
// BLACKBOX: Learn this
// If q = cos(A)+sin(A)*(X*i+Y*j+Z*k) Where (X,Y,Z) is unit length, then
// log(q) = A*(X*i+Y*j+Z*k). If sin(A) is near Zero, use log(q) =
// sin(A)*(X*i+Y*j+Z*k) since sin(A)/A has limit 1.
// start off With a Zero quat
Quaternion returnvalue = Quaternion.Zero;
if (Math.Abs(W) < 1)
{
Scalar angle = MathHelper.Acos(W);
Scalar sin = MathHelper.Sin(angle);
if (Math.Abs(sin) >= MathHelper.Epsilon)
{
Scalar coeff = angle / sin;
returnvalue.X = coeff * X;
returnvalue.Y = coeff * Y;
returnvalue.Z = coeff * Z;
}
else
{
returnvalue.X = X;
returnvalue.Y = Y;
returnvalue.Z = Z;
}
}
return returnvalue;
}
/// <summary>
/// Calculates the Exponent of a Quaternion.
/// </summary>
/// <returns></returns>
public Quaternion Exp()
{
// If q = A*(X*i+Y*j+Z*k) Where (X,Y,Z) is unit length, then
// eXp(q) = cos(A)+sin(A)*(X*i+Y*j+Z*k). If sin(A) is near Zero,
// use eXp(q) = cos(A)+A*(X*i+Y*j+Z*k) since A/sin(A) has limit 1.
Scalar angle = MathHelper.Sqrt(X * X + Y * Y + Z * Z);
Scalar sin = MathHelper.Sin(angle);
// start off With a Zero quat
Quaternion returnvalue = Quaternion.Zero;
returnvalue.W = MathHelper.Cos(angle);
if (Math.Abs(sin) >= MathHelper.Epsilon)
{
Scalar coeff = sin / angle;
returnvalue.X = coeff * X;
returnvalue.Y = coeff * Y;
returnvalue.Z = coeff * Z;
}
else
{
returnvalue.X = X;
returnvalue.Y = Y;
returnvalue.Z = Z;
}
return returnvalue;
}
#endregion
#region Object overloads
/// <summary>
/// Overrides the Object.ToString() method to provide a teXt representation of
/// a Quaternion.
/// </summary>
/// <returns>A string representation of a Quaternion.</returns>
public override string ToString()
{
return string.Format("Quaternion({0}, {1}, {2}, {3})", this.X, this.Y, this.Z, this.W);
}
[ParseMethod]
public static Quaternion Parse(string text)
{
string[] vals = text.Replace("Quaternion", "").Trim(' ', '(', '[', '<', ')', ']', '>').Split(',');
if (vals.Length != 4)
{
throw new FormatException(string.Format("Cannot parse the text '{0}' because it does not have 4 parts separated by commas in the form (x,y,z,w) with optional parenthesis.", text));
}
else
{
try
{
Quaternion returnvalue;
returnvalue.X = Scalar.Parse(vals[0].Trim());
returnvalue.Y = Scalar.Parse(vals[1].Trim());
returnvalue.Z = Scalar.Parse(vals[2].Trim());
returnvalue.W = Scalar.Parse(vals[3].Trim());
return returnvalue;
}
catch (Exception ex)
{
throw new FormatException("The parts of the vectors must be decimal numbers", ex);
}
}
}
public override int GetHashCode()
{
return (int)X ^ (int)Y ^ (int)Z ^ (int)W;
}
public override bool Equals(object obj)
{
return obj is Quaternion && (Quaternion)obj == this;
}
#endregion
#region operator overloads
public static Quaternion Multiply(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W * right.W - left.X * right.X - left.Y * right.Y - left.Z * right.Z;
result.X = left.W * right.X + left.X * right.W + left.Y * right.Z - left.Z * right.Y;
result.Y = left.W * right.Y + left.Y * right.W + left.Z * right.X - left.X * right.Z;
result.Z = left.W * right.Z + left.Z * right.W + left.X * right.Y - left.Y * right.X;
return result;
}
public static void Multiply(ref Quaternion left,ref Quaternion right,out Quaternion result)
{
Scalar W = left.W * right.W - left.X * right.X - left.Y * right.Y - left.Z * right.Z;
Scalar X = left.W * right.X + left.X * right.W + left.Y * right.Z - left.Z * right.Y;
Scalar Y = left.W * right.Y + left.Y * right.W + left.Z * right.X - left.X * right.Z;
result.Z = left.W * right.Z + left.Z * right.W + left.X * right.Y - left.Y * right.X;
result.W = W;
result.X = X;
result.Y = Y;
}
public static Quaternion Multiply(Quaternion left, Scalar scalar)
{
Quaternion result;
result.W = left.W * scalar;
result.X = left.X * scalar;
result.Y = left.Y * scalar;
result.Z = left.Z * scalar;
return result;
}
public static void Multiply(ref Quaternion left,ref Scalar scalar, out Quaternion result)
{
result.W = left.W * scalar;
result.X = left.X * scalar;
result.Y = left.Y * scalar;
result.Z = left.Z * scalar;
}
public static Quaternion Add(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W + right.W;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
return result;
}
public static void Add(ref Quaternion left,ref Quaternion right, out Quaternion result)
{
result.W = left.W + right.W;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
}
public static Quaternion Subtract(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W - right.W;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
return result;
}
public static void Subtract(ref Quaternion left,ref Quaternion right, out Quaternion result)
{
result.W = left.W - right.W;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
}
public static Quaternion Negate(Quaternion value)
{
Quaternion result;
result.W = -value.W;
result.X = -value.X;
result.Y = -value.Y;
result.Z = -value.Z;
return result;
}
[CLSCompliant(false)]
public static void Negate(ref Quaternion value)
{
Negate(ref value, out value);
}
public static void Negate(ref Quaternion value, out Quaternion result)
{
result.W = -value.W;
result.X = -value.X;
result.Y = -value.Y;
result.Z = -value.Z;
}
public static Quaternion operator *(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W * right.W - left.X * right.X - left.Y * right.Y - left.Z * right.Z;
result.X = left.W * right.X + left.X * right.W + left.Y * right.Z - left.Z * right.Y;
result.Y = left.W * right.Y + left.Y * right.W + left.Z * right.X - left.X * right.Z;
result.Z = left.W * right.Z + left.Z * right.W + left.X * right.Y - left.Y * right.X;
return result;
}
public static Quaternion operator *(Scalar scalar, Quaternion right)
{
Quaternion result;
result.W = scalar * right.W;
result.X = scalar * right.X;
result.Y = scalar * right.Y;
result.Z = scalar * right.Z;
return result;
}
public static Quaternion operator *(Quaternion left, Scalar scalar)
{
Quaternion result;
result.W = left.W * scalar;
result.X = left.X * scalar;
result.Y = left.Y * scalar;
result.Z = left.Z * scalar;
return result;
}
public static Quaternion operator +(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W + right.W;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
return result;
}
public static Quaternion operator -(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W - right.W;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
return result;
}
public static Quaternion operator -(Quaternion value)
{
Quaternion result;
result.W = -value.W;
result.X = -value.X;
result.Y = -value.Y;
result.Z = -value.Z;
return result;
}
public static bool operator ==(Quaternion left, Quaternion right)
{
return
left.W == right.W &&
left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z;
}
public static bool operator !=(Quaternion left, Quaternion right)
{
return !(left == right);
}
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using gagr = Google.Api.Gax.ResourceNames;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.RecaptchaEnterprise.V1Beta1
{
/// <summary>Settings for <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/> instances.</summary>
public sealed partial class RecaptchaEnterpriseServiceV1Beta1Settings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/>.
/// </summary>
/// <returns>A new instance of the default <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/>.</returns>
public static RecaptchaEnterpriseServiceV1Beta1Settings GetDefault() =>
new RecaptchaEnterpriseServiceV1Beta1Settings();
/// <summary>
/// Constructs a new <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/> object with default settings.
/// </summary>
public RecaptchaEnterpriseServiceV1Beta1Settings()
{
}
private RecaptchaEnterpriseServiceV1Beta1Settings(RecaptchaEnterpriseServiceV1Beta1Settings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CreateAssessmentSettings = existing.CreateAssessmentSettings;
AnnotateAssessmentSettings = existing.AnnotateAssessmentSettings;
CreateKeySettings = existing.CreateKeySettings;
ListKeysSettings = existing.ListKeysSettings;
GetKeySettings = existing.GetKeySettings;
UpdateKeySettings = existing.UpdateKeySettings;
DeleteKeySettings = existing.DeleteKeySettings;
OnCopy(existing);
}
partial void OnCopy(RecaptchaEnterpriseServiceV1Beta1Settings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.CreateAssessment</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.CreateAssessmentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateAssessmentSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.AnnotateAssessment</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.AnnotateAssessmentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings AnnotateAssessmentSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.CreateKey</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.CreateKeyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateKeySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.ListKeys</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.ListKeysAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListKeysSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.GetKey</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.GetKeyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetKeySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.UpdateKey</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.UpdateKeyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateKeySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.DeleteKey</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.DeleteKeyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteKeySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/> object.</returns>
public RecaptchaEnterpriseServiceV1Beta1Settings Clone() => new RecaptchaEnterpriseServiceV1Beta1Settings(this);
}
/// <summary>
/// Builder class for <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
public sealed partial class RecaptchaEnterpriseServiceV1Beta1ClientBuilder : gaxgrpc::ClientBuilderBase<RecaptchaEnterpriseServiceV1Beta1Client>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public RecaptchaEnterpriseServiceV1Beta1Settings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public RecaptchaEnterpriseServiceV1Beta1ClientBuilder()
{
UseJwtAccessWithScopes = RecaptchaEnterpriseServiceV1Beta1Client.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref RecaptchaEnterpriseServiceV1Beta1Client client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<RecaptchaEnterpriseServiceV1Beta1Client> task);
/// <summary>Builds the resulting client.</summary>
public override RecaptchaEnterpriseServiceV1Beta1Client Build()
{
RecaptchaEnterpriseServiceV1Beta1Client client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<RecaptchaEnterpriseServiceV1Beta1Client> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<RecaptchaEnterpriseServiceV1Beta1Client> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private RecaptchaEnterpriseServiceV1Beta1Client BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return RecaptchaEnterpriseServiceV1Beta1Client.Create(callInvoker, Settings);
}
private async stt::Task<RecaptchaEnterpriseServiceV1Beta1Client> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return RecaptchaEnterpriseServiceV1Beta1Client.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => RecaptchaEnterpriseServiceV1Beta1Client.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
RecaptchaEnterpriseServiceV1Beta1Client.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => RecaptchaEnterpriseServiceV1Beta1Client.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>RecaptchaEnterpriseServiceV1Beta1 client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to determine the likelihood an event is legitimate.
/// </remarks>
public abstract partial class RecaptchaEnterpriseServiceV1Beta1Client
{
/// <summary>
/// The default endpoint for the RecaptchaEnterpriseServiceV1Beta1 service, which is a host of
/// "recaptchaenterprise.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "recaptchaenterprise.googleapis.com:443";
/// <summary>The default RecaptchaEnterpriseServiceV1Beta1 scopes.</summary>
/// <remarks>
/// The default RecaptchaEnterpriseServiceV1Beta1 scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="RecaptchaEnterpriseServiceV1Beta1ClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/>.</returns>
public static stt::Task<RecaptchaEnterpriseServiceV1Beta1Client> CreateAsync(st::CancellationToken cancellationToken = default) =>
new RecaptchaEnterpriseServiceV1Beta1ClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="RecaptchaEnterpriseServiceV1Beta1ClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/>.</returns>
public static RecaptchaEnterpriseServiceV1Beta1Client Create() =>
new RecaptchaEnterpriseServiceV1Beta1ClientBuilder().Build();
/// <summary>
/// Creates a <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/>.</param>
/// <returns>The created <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/>.</returns>
internal static RecaptchaEnterpriseServiceV1Beta1Client Create(grpccore::CallInvoker callInvoker, RecaptchaEnterpriseServiceV1Beta1Settings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client grpcClient = new RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client(callInvoker);
return new RecaptchaEnterpriseServiceV1Beta1ClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC RecaptchaEnterpriseServiceV1Beta1 client</summary>
public virtual RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Assessment CreateAssessment(CreateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Assessment> CreateAssessmentAsync(CreateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Assessment> CreateAssessmentAsync(CreateAssessmentRequest request, st::CancellationToken cancellationToken) =>
CreateAssessmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Assessment CreateAssessment(string parent, Assessment assessment, gaxgrpc::CallSettings callSettings = null) =>
CreateAssessment(new CreateAssessmentRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
Assessment = gax::GaxPreconditions.CheckNotNull(assessment, nameof(assessment)),
}, callSettings);
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Assessment> CreateAssessmentAsync(string parent, Assessment assessment, gaxgrpc::CallSettings callSettings = null) =>
CreateAssessmentAsync(new CreateAssessmentRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
Assessment = gax::GaxPreconditions.CheckNotNull(assessment, nameof(assessment)),
}, callSettings);
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Assessment> CreateAssessmentAsync(string parent, Assessment assessment, st::CancellationToken cancellationToken) =>
CreateAssessmentAsync(parent, assessment, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Assessment CreateAssessment(gagr::ProjectName parent, Assessment assessment, gaxgrpc::CallSettings callSettings = null) =>
CreateAssessment(new CreateAssessmentRequest
{
ParentAsProjectName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
Assessment = gax::GaxPreconditions.CheckNotNull(assessment, nameof(assessment)),
}, callSettings);
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Assessment> CreateAssessmentAsync(gagr::ProjectName parent, Assessment assessment, gaxgrpc::CallSettings callSettings = null) =>
CreateAssessmentAsync(new CreateAssessmentRequest
{
ParentAsProjectName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
Assessment = gax::GaxPreconditions.CheckNotNull(assessment, nameof(assessment)),
}, callSettings);
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Assessment> CreateAssessmentAsync(gagr::ProjectName parent, Assessment assessment, st::CancellationToken cancellationToken) =>
CreateAssessmentAsync(parent, assessment, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual AnnotateAssessmentResponse AnnotateAssessment(AnnotateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<AnnotateAssessmentResponse> AnnotateAssessmentAsync(AnnotateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<AnnotateAssessmentResponse> AnnotateAssessmentAsync(AnnotateAssessmentRequest request, st::CancellationToken cancellationToken) =>
AnnotateAssessmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual AnnotateAssessmentResponse AnnotateAssessment(string name, AnnotateAssessmentRequest.Types.Annotation annotation, gaxgrpc::CallSettings callSettings = null) =>
AnnotateAssessment(new AnnotateAssessmentRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
Annotation = annotation,
}, callSettings);
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<AnnotateAssessmentResponse> AnnotateAssessmentAsync(string name, AnnotateAssessmentRequest.Types.Annotation annotation, gaxgrpc::CallSettings callSettings = null) =>
AnnotateAssessmentAsync(new AnnotateAssessmentRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
Annotation = annotation,
}, callSettings);
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<AnnotateAssessmentResponse> AnnotateAssessmentAsync(string name, AnnotateAssessmentRequest.Types.Annotation annotation, st::CancellationToken cancellationToken) =>
AnnotateAssessmentAsync(name, annotation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual AnnotateAssessmentResponse AnnotateAssessment(AssessmentName name, AnnotateAssessmentRequest.Types.Annotation annotation, gaxgrpc::CallSettings callSettings = null) =>
AnnotateAssessment(new AnnotateAssessmentRequest
{
AssessmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
Annotation = annotation,
}, callSettings);
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<AnnotateAssessmentResponse> AnnotateAssessmentAsync(AssessmentName name, AnnotateAssessmentRequest.Types.Annotation annotation, gaxgrpc::CallSettings callSettings = null) =>
AnnotateAssessmentAsync(new AnnotateAssessmentRequest
{
AssessmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
Annotation = annotation,
}, callSettings);
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<AnnotateAssessmentResponse> AnnotateAssessmentAsync(AssessmentName name, AnnotateAssessmentRequest.Types.Annotation annotation, st::CancellationToken cancellationToken) =>
AnnotateAssessmentAsync(name, annotation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a new reCAPTCHA Enterprise key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Key CreateKey(CreateKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a new reCAPTCHA Enterprise key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Key> CreateKeyAsync(CreateKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a new reCAPTCHA Enterprise key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Key> CreateKeyAsync(CreateKeyRequest request, st::CancellationToken cancellationToken) =>
CreateKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the list of all keys that belong to a project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Key"/> resources.</returns>
public virtual gax::PagedEnumerable<ListKeysResponse, Key> ListKeys(ListKeysRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the list of all keys that belong to a project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Key"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListKeysResponse, Key> ListKeysAsync(ListKeysRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Key GetKey(GetKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Key> GetKeyAsync(GetKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Key> GetKeyAsync(GetKeyRequest request, st::CancellationToken cancellationToken) =>
GetKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Key UpdateKey(UpdateKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Key> UpdateKeyAsync(UpdateKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Key> UpdateKeyAsync(UpdateKeyRequest request, st::CancellationToken cancellationToken) =>
UpdateKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual void DeleteKey(DeleteKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteKeyAsync(DeleteKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteKeyAsync(DeleteKeyRequest request, st::CancellationToken cancellationToken) =>
DeleteKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>RecaptchaEnterpriseServiceV1Beta1 client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to determine the likelihood an event is legitimate.
/// </remarks>
public sealed partial class RecaptchaEnterpriseServiceV1Beta1ClientImpl : RecaptchaEnterpriseServiceV1Beta1Client
{
private readonly gaxgrpc::ApiCall<CreateAssessmentRequest, Assessment> _callCreateAssessment;
private readonly gaxgrpc::ApiCall<AnnotateAssessmentRequest, AnnotateAssessmentResponse> _callAnnotateAssessment;
private readonly gaxgrpc::ApiCall<CreateKeyRequest, Key> _callCreateKey;
private readonly gaxgrpc::ApiCall<ListKeysRequest, ListKeysResponse> _callListKeys;
private readonly gaxgrpc::ApiCall<GetKeyRequest, Key> _callGetKey;
private readonly gaxgrpc::ApiCall<UpdateKeyRequest, Key> _callUpdateKey;
private readonly gaxgrpc::ApiCall<DeleteKeyRequest, wkt::Empty> _callDeleteKey;
/// <summary>
/// Constructs a client wrapper for the RecaptchaEnterpriseServiceV1Beta1 service, with the specified gRPC
/// client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/> used within this client.
/// </param>
public RecaptchaEnterpriseServiceV1Beta1ClientImpl(RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client grpcClient, RecaptchaEnterpriseServiceV1Beta1Settings settings)
{
GrpcClient = grpcClient;
RecaptchaEnterpriseServiceV1Beta1Settings effectiveSettings = settings ?? RecaptchaEnterpriseServiceV1Beta1Settings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callCreateAssessment = clientHelper.BuildApiCall<CreateAssessmentRequest, Assessment>(grpcClient.CreateAssessmentAsync, grpcClient.CreateAssessment, effectiveSettings.CreateAssessmentSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateAssessment);
Modify_CreateAssessmentApiCall(ref _callCreateAssessment);
_callAnnotateAssessment = clientHelper.BuildApiCall<AnnotateAssessmentRequest, AnnotateAssessmentResponse>(grpcClient.AnnotateAssessmentAsync, grpcClient.AnnotateAssessment, effectiveSettings.AnnotateAssessmentSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callAnnotateAssessment);
Modify_AnnotateAssessmentApiCall(ref _callAnnotateAssessment);
_callCreateKey = clientHelper.BuildApiCall<CreateKeyRequest, Key>(grpcClient.CreateKeyAsync, grpcClient.CreateKey, effectiveSettings.CreateKeySettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateKey);
Modify_CreateKeyApiCall(ref _callCreateKey);
_callListKeys = clientHelper.BuildApiCall<ListKeysRequest, ListKeysResponse>(grpcClient.ListKeysAsync, grpcClient.ListKeys, effectiveSettings.ListKeysSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListKeys);
Modify_ListKeysApiCall(ref _callListKeys);
_callGetKey = clientHelper.BuildApiCall<GetKeyRequest, Key>(grpcClient.GetKeyAsync, grpcClient.GetKey, effectiveSettings.GetKeySettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetKey);
Modify_GetKeyApiCall(ref _callGetKey);
_callUpdateKey = clientHelper.BuildApiCall<UpdateKeyRequest, Key>(grpcClient.UpdateKeyAsync, grpcClient.UpdateKey, effectiveSettings.UpdateKeySettings).WithGoogleRequestParam("key.name", request => request.Key?.Name);
Modify_ApiCall(ref _callUpdateKey);
Modify_UpdateKeyApiCall(ref _callUpdateKey);
_callDeleteKey = clientHelper.BuildApiCall<DeleteKeyRequest, wkt::Empty>(grpcClient.DeleteKeyAsync, grpcClient.DeleteKey, effectiveSettings.DeleteKeySettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callDeleteKey);
Modify_DeleteKeyApiCall(ref _callDeleteKey);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_CreateAssessmentApiCall(ref gaxgrpc::ApiCall<CreateAssessmentRequest, Assessment> call);
partial void Modify_AnnotateAssessmentApiCall(ref gaxgrpc::ApiCall<AnnotateAssessmentRequest, AnnotateAssessmentResponse> call);
partial void Modify_CreateKeyApiCall(ref gaxgrpc::ApiCall<CreateKeyRequest, Key> call);
partial void Modify_ListKeysApiCall(ref gaxgrpc::ApiCall<ListKeysRequest, ListKeysResponse> call);
partial void Modify_GetKeyApiCall(ref gaxgrpc::ApiCall<GetKeyRequest, Key> call);
partial void Modify_UpdateKeyApiCall(ref gaxgrpc::ApiCall<UpdateKeyRequest, Key> call);
partial void Modify_DeleteKeyApiCall(ref gaxgrpc::ApiCall<DeleteKeyRequest, wkt::Empty> call);
partial void OnConstruction(RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client grpcClient, RecaptchaEnterpriseServiceV1Beta1Settings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC RecaptchaEnterpriseServiceV1Beta1 client</summary>
public override RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client GrpcClient { get; }
partial void Modify_CreateAssessmentRequest(ref CreateAssessmentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_AnnotateAssessmentRequest(ref AnnotateAssessmentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_CreateKeyRequest(ref CreateKeyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListKeysRequest(ref ListKeysRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetKeyRequest(ref GetKeyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateKeyRequest(ref UpdateKeyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteKeyRequest(ref DeleteKeyRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Assessment CreateAssessment(CreateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateAssessmentRequest(ref request, ref callSettings);
return _callCreateAssessment.Sync(request, callSettings);
}
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Assessment> CreateAssessmentAsync(CreateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateAssessmentRequest(ref request, ref callSettings);
return _callCreateAssessment.Async(request, callSettings);
}
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override AnnotateAssessmentResponse AnnotateAssessment(AnnotateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_AnnotateAssessmentRequest(ref request, ref callSettings);
return _callAnnotateAssessment.Sync(request, callSettings);
}
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<AnnotateAssessmentResponse> AnnotateAssessmentAsync(AnnotateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_AnnotateAssessmentRequest(ref request, ref callSettings);
return _callAnnotateAssessment.Async(request, callSettings);
}
/// <summary>
/// Creates a new reCAPTCHA Enterprise key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Key CreateKey(CreateKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateKeyRequest(ref request, ref callSettings);
return _callCreateKey.Sync(request, callSettings);
}
/// <summary>
/// Creates a new reCAPTCHA Enterprise key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Key> CreateKeyAsync(CreateKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateKeyRequest(ref request, ref callSettings);
return _callCreateKey.Async(request, callSettings);
}
/// <summary>
/// Returns the list of all keys that belong to a project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Key"/> resources.</returns>
public override gax::PagedEnumerable<ListKeysResponse, Key> ListKeys(ListKeysRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListKeysRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListKeysRequest, ListKeysResponse, Key>(_callListKeys, request, callSettings);
}
/// <summary>
/// Returns the list of all keys that belong to a project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Key"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListKeysResponse, Key> ListKeysAsync(ListKeysRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListKeysRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListKeysRequest, ListKeysResponse, Key>(_callListKeys, request, callSettings);
}
/// <summary>
/// Returns the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Key GetKey(GetKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeyRequest(ref request, ref callSettings);
return _callGetKey.Sync(request, callSettings);
}
/// <summary>
/// Returns the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Key> GetKeyAsync(GetKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeyRequest(ref request, ref callSettings);
return _callGetKey.Async(request, callSettings);
}
/// <summary>
/// Updates the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Key UpdateKey(UpdateKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateKeyRequest(ref request, ref callSettings);
return _callUpdateKey.Sync(request, callSettings);
}
/// <summary>
/// Updates the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Key> UpdateKeyAsync(UpdateKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateKeyRequest(ref request, ref callSettings);
return _callUpdateKey.Async(request, callSettings);
}
/// <summary>
/// Deletes the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override void DeleteKey(DeleteKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteKeyRequest(ref request, ref callSettings);
_callDeleteKey.Sync(request, callSettings);
}
/// <summary>
/// Deletes the specified key.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task DeleteKeyAsync(DeleteKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteKeyRequest(ref request, ref callSettings);
return _callDeleteKey.Async(request, callSettings);
}
}
public partial class ListKeysRequest : gaxgrpc::IPageRequest
{
}
public partial class ListKeysResponse : gaxgrpc::IPageResponse<Key>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Key> GetEnumerator() => Keys.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
using System.Diagnostics;
using SharpBox2D.Common;
namespace SharpBox2D.Collision.Shapes
{
/**
* A circle shape.
*/
public class CircleShape : Shape
{
public Vec2 m_p;
public CircleShape() : base(ShapeType.CIRCLE)
{
m_p = new Vec2();
m_radius = 0;
}
public override Shape clone()
{
CircleShape shape = new CircleShape();
shape.m_p.x = m_p.x;
shape.m_p.y = m_p.y;
shape.m_radius = m_radius;
return shape;
}
public override int getChildCount()
{
return 1;
}
/**
* Get the supporting vertex index in the given direction.
*
* @param d
* @return
*/
public int getSupport(Vec2 d)
{
return 0;
}
/**
* Get the supporting vertex in the given direction.
*
* @param d
* @return
*/
public Vec2 getSupportVertex(Vec2 d)
{
return m_p;
}
/**
* Get the vertex count.
*
* @return
*/
public int getVertexCount()
{
return 1;
}
/**
* Get a vertex by index.
*
* @param index
* @return
*/
public Vec2 getVertex(int index)
{
Debug.Assert(index == 0);
return m_p;
}
public override bool testPoint(Transform transform, Vec2 p)
{
// Rot.mulToOutUnsafe(transform.q, m_p, center);
// center.addLocal(transform.p);
//
// Vec2 d = center.subLocal(p).negateLocal();
// return Vec2.dot(d, d) <= m_radius * m_radius;
Rot q = transform.q;
Vec2 tp = transform.p;
float centerx = -(q.c*m_p.x - q.s*m_p.y + tp.x - p.x);
float centery = -(q.s*m_p.x + q.c*m_p.y + tp.y - p.y);
return centerx*centerx + centery*centery <= m_radius*m_radius;
}
public override float computeDistanceToOut(Transform xf, Vec2 p, int childIndex, Vec2 normalOut)
{
Rot xfq = xf.q;
float centerx = xfq.c*m_p.x - xfq.s*m_p.y + xf.p.x;
float centery = xfq.s*m_p.x + xfq.c*m_p.y + xf.p.y;
float dx = p.x - centerx;
float dy = p.y - centery;
float d1 = MathUtils.sqrt(dx*dx + dy*dy);
normalOut.x = dx*1/d1;
normalOut.y = dy*1/d1;
return d1 - m_radius;
}
// Collision Detection in Interactive 3D Environments by Gino van den Bergen
// From Section 3.1.2
// x = s + a * r
// norm(x) = radius
public override bool raycast(RayCastOutput output, RayCastInput input, Transform transform,
int childIndex)
{
Vec2 inputp1 = input.p1;
Vec2 inputp2 = input.p2;
Rot tq = transform.q;
Vec2 tp = transform.p;
// Rot.mulToOutUnsafe(transform.q, m_p, position);
// position.addLocal(transform.p);
float positionx = tq.c*m_p.x - tq.s*m_p.y + tp.x;
float positiony = tq.s*m_p.x + tq.c*m_p.y + tp.y;
float sx = inputp1.x - positionx;
float sy = inputp1.y - positiony;
// float b = Vec2.dot(s, s) - m_radius * m_radius;
float b = sx*sx + sy*sy - m_radius*m_radius;
// Solve quadratic equation.
float rx = inputp2.x - inputp1.x;
float ry = inputp2.y - inputp1.y;
// float c = Vec2.dot(s, r);
// float rr = Vec2.dot(r, r);
float c = sx*rx + sy*ry;
float rr = rx*rx + ry*ry;
float sigma = c*c - rr*b;
// Check for negative discriminant and short segment.
if (sigma < 0.0f || rr < Settings.EPSILON)
{
return false;
}
// Find the point of intersection of the line with the circle.
float a = -(c + MathUtils.sqrt(sigma));
// Is the intersection point on the segment?
if (0.0f <= a && a <= input.maxFraction*rr)
{
a /= rr;
output.fraction = a;
output.normal.x = rx*a + sx;
output.normal.y = ry*a + sy;
output.normal.normalize();
return true;
}
return false;
}
public override void computeAABB(AABB aabb, Transform transform, int childIndex)
{
Rot tq = transform.q;
Vec2 tp = transform.p;
float px = tq.c*m_p.x - tq.s*m_p.y + tp.x;
float py = tq.s*m_p.x + tq.c*m_p.y + tp.y;
aabb.lowerBound.x = px - m_radius;
aabb.lowerBound.y = py - m_radius;
aabb.upperBound.x = px + m_radius;
aabb.upperBound.y = py + m_radius;
}
public override void computeMass(MassData massData, float density)
{
massData.mass = density*Settings.PI*m_radius*m_radius;
massData.center.x = m_p.x;
massData.center.y = m_p.y;
// inertia about the local origin
// massData.I = massData.mass * (0.5f * m_radius * m_radius + Vec2.dot(m_p, m_p));
massData.I = massData.mass*(0.5f*m_radius*m_radius + (m_p.x*m_p.x + m_p.y*m_p.y));
}
}
}
| |
/* Copyright (c) 2009-11, ReactionGrid Inc. http://reactiongrid.com
* See License.txt for full licence information.
*
* PlayerSpawnController.cs Revision 1.4.1106.11
* Controls the creation of avatar models and associated components */
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using ReactionGrid.Jibe;
public class PlayerSpawnController : MonoBehaviour
{
public Transform cam;
public Transform[] playerPrefabs;
public Transform[] remotePlayerPrefabs;
public Transform[] spawnPoints;
public Transform movementPivot;
public AudioClip spawnSound;
public float spawnSoundVolume = 0.5f;
public int spawnRadius = 10;
public Transform playerCharacter;
private static System.Random random = new System.Random();
public Transform playerShadow;
public Transform remotePlayerMapIcon;
public Transform localPlayerMapIcon;
public float mapIconHeight = 500.0f;
private JibeActivityLog jibeLog;
public NetworkController netController;
public GameObject spawnParticles;
public bool usePhysicalCharacter = false;
public float remotePlayerNametagFullyVisibleDistance = 10.0f;
public float remotePlayerNametagFadeDistance = 30.0f;
public bool enableIdleAnimationWakeup = false;
public bool enableFlyingAvatars = true;
public bool showOwnName = true;
public bool useJibeAvatarControlScripts = true;
public string[] componentsToDisableForRemotePlayers;
public Transform onlineUserPrefab;
public Transform onlineUserParent;
public Transform adminOnlineUserPrefab;
/// <summary>
/// Create an avatar for the local player based on the user preferences gathered from the loader scene and (if used) dressing room
/// </summary>
/// <param name="user">An IJibePlayer representing the user</param>
/// <returns>A GameObject representing the player and all associated scripts, effects, and local camera</returns>
public GameObject SpawnLocalPlayer(IJibePlayer user)
{
string localPlayerName = "localPlayer";
GameObject localPlayer = GameObject.Find(localPlayerName);
// print("before");
Debug.Log("Spawning localPlayer: " + localPlayer);
//Check if the user has already spawned an avatar - if they have not yet spawned an avatar, this is where the avatar is set up.
if (localPlayer == null)
{
if(PlayerPrefs.HasKey("Group"))
{
string groupName = PlayerPrefs.GetString("Group");
if(groupName.Equals("Therapist"))
{
Debug.Log("therapist spawn is at: x=" + GameObject.Find("therapistSpawn").transform.position.x + " y=" + GameObject.Find("therapistSpawn").transform.position.y + " z=" + GameObject.Find("therapistSpawn").transform.position.z);
spawnPoints[0].transform.position= GameObject.Find("therapistSpawn").transform.position;
}
else if(groupName.Equals("Patient"))
{
Debug.Log("patient spawn is at: x=" + GameObject.Find("patientSpawn").transform.position.x + " y=" + GameObject.Find("patientSpawn").transform.position.y + " z=" + GameObject.Find("patientSpawn").transform.position.z);
spawnPoints[0].transform.position= GameObject.Find("patientSpawn").transform.position;
}
else
{
Debug.Log("Group not found:" + groupName);
}
}
Debug.Log("Spawn is: x=" + spawnPoints[0].transform.position.x + " y=" + spawnPoints[0].transform.position.y + " z=" + spawnPoints[0].transform.position.z);
Component characterObjectComponent = GameObject.Instantiate(playerPrefabs[user.AvatarModel], spawnPoints[0].transform.position, spawnPoints[0].transform.rotation) as Component;
GameObject characterObject = characterObjectComponent.gameObject;
characterObject.name="localPlayer";
//new working player tags
characterObject.AddComponent<nameTag>();
characterObject.GetComponent<nameTag>().SetDisplayName(user);
//old broken player tags
/*
characterObject.AddComponent<BubblePopup>();
characterObject.GetComponent<BubblePopup>().skin = GameObject.Find("UIBase").GetComponent<UIBase>().skin;
characterObject.GetComponent<BubblePopup>().SetDisplayName(user);
characterObject.GetComponent<BubblePopup>().fullyVisibleDistance = remotePlayerNametagFullyVisibleDistance;
characterObject.GetComponent<BubblePopup>().fadeDistance = remotePlayerNametagFadeDistance;
characterObject.GetComponent<BubblePopup>().nameTagHeight=0;
*/
// characterObject.transform.localScale*=.75f;
if(GameObject.FindWithTag("Skin")!=null)
{
Transform skinTransform = GameObject.FindWithTag("Skin").transform;
RetrieveClothingPreference(user);
/* if (characterObject != null)
{
for (int i = 0; i < characterObject.transform.childCount; i++)
{
if (characterObject.transform.GetChild(i).tag == "Skin")
{
skinTransform = characterObject.transform.GetChild(i);
if (user.Skin != null)
{
Texture2D selectedSkin = (Texture2D)Resources.Load(user.Skin);
skinTransform.renderer.material.mainTexture = selectedSkin;
}
}
}
}*/
Texture2D selectedSkin = (Texture2D)Resources.Load(user.Skin);
skinTransform.GetComponent<Renderer>().material.mainTexture=selectedSkin;
/*print("startif");
//ZPWH
Component characterObjectComponent = GameObject.Instantiate(playerPrefabs[user.AvatarModel], spawnPoints[0].transform.position, spawnPoints[0].transform.rotation) as Component;
GameObject characterObject = characterObjectComponent.gameObject;
print("begina");
characterObject.name = localPlayerName;
print("beginb");
Debug.Log("Change name from: " + characterObject.name);
characterObject.name = localPlayerName;
// Debug.Log("Change name to: " + characterObject.name);
characterObject.transform.localScale*=.75f;
foreach(Transform currentModel in playerPrefabs)
{
Debug.Log(currentModel.name);
GameObject check = GameObject.Find(currentModel.name);
if(check!=null)
{
Debug.Log("Found a match!");
Debug.Log(check.transform.localPosition);
check.transform.localPosition = new Vector3(3.249682e-17f, .03184503f, -.07741547f);
Debug.Log(check.transform.localPosition);
}
}*/
/* int n = spawnPoints.Length;
// Choose from one of the available spawn points - if many
// users are expected to log in, this can help distribute the
// avatars as they log in so you don't end up with a pile of people
Transform spawnPoint = spawnPoints[random.Next(n)];
// Vary the start position a little more - avatars will
// emerge within the specified spawn radius of the chosen spawn point
float offsetX = random.Next(spawnRadius);
float offsetZ = random.Next(spawnRadius);
Vector3 newPosition = spawnPoint.position;
newPosition.x = spawnPoint.position.x + offsetX;
newPosition.z = spawnPoint.position.z + offsetZ;
// set up some common variables
GameObject characterObject;
AnimationSynchronizer aniSync;
UnityEngine.Component playerCharacterTemplateComponent = Instantiate(playerPrefabs[user.AvatarModel], newPosition, spawnPoint.transform.rotation) as Component;
characterObject = playerCharacterTemplateComponent.gameObject;
//playerCharacterTemplateComponent.gameObject.AddComponent<AnimationSynchronizer>();
characterObject.name = localPlayerName;
characterObject.tag = "Player";
characterObject.transform.localScale*=.75f;
characterObject.AddComponent<CharacterController>();
characterObject.AddComponent<FPSInputController>();
characterObject.AddComponent<MouseLook>();
GameObject charCam = GameObject.Instantiate(cam) as GameObject;
charCam.transform.parent=GameObject.Find("localPlayer").transform;
charCam.transform.localPosition=new Vector3(0,2.3f,-4.3f);
charCam.transform.localRotation= new Quaternion(18,0,0,1);//RSO
if (characterObject.GetComponent<PlayerMovement>() == null)
{
characterObject.AddComponent<PlayerMovement>();
Debug.Log("PlayerMovement script added");
}
aniSync = characterObject.GetComponent<AnimationSynchronizer>();
if (aniSync == null)
{
aniSync = characterObject.AddComponent<AnimationSynchronizer>();
Debug.Log("AnimationSynchronizer script added");
}
if (characterObject.GetComponent<AnimateCharacter>() == null)
{
characterObject.GetComponent<PlayerMovement>().SendTransforms(true);
Debug.Log("PlayerMovement script set to send transforms");
}
GameObject cameraTarget = GameObject.FindGameObjectWithTag("CameraTarget");
if (cameraTarget == null)
{
cameraTarget = new GameObject();
cameraTarget.name = "CameraTarget";
cameraTarget.tag = "CameraTarget";
cameraTarget.transform.parent = characterObject.transform;
Vector3 pos = new Vector3(0, 1.9f, 0);
cameraTarget.transform.localPosition = pos;
Debug.Log("CameraTarget configured");
}
ShowPreviewCamera(false);
GameObject sceneCamera = GameObject.Find("PlayerCamera");
Vector3 newLocalPosition = sceneCamera.transform.localPosition;
sceneCamera.transform.parent = characterObject.transform;
sceneCamera.transform.localPosition = newLocalPosition;
sceneCamera.GetComponent("PlayerCamera").SendMessage("SetTarget", sceneCamera.transform.parent.transform);
sceneCamera.GetComponent("PlayerCamera").SendMessage("SetupCamera");
sceneCamera.SendMessage("SetTarget", cameraTarget.transform);
Debug.Log("PlayerCamera configured");
AddSpotShadow(characterObject);
AddMapIcon(characterObject, localPlayerMapIcon);
// The following code creates a movement pivot, and is used by the movement + camera controls
Vector3 pivotLocation = newPosition;
pivotLocation.y = pivotLocation.y + 1;
UnityEngine.Component localPlayerPivot = Instantiate(movementPivot, newPosition, spawnPoint.transform.rotation) as Component;
localPlayerPivot.name = "PlayerMovementPivot";
// Set the PlayerCamera and PlayerCharacter scripts to coordinate with the movement pivot of the player
localPlayerPivot.SendMessage("SetTarget", characterObject.transform);
sceneCamera.SendMessage("SetMovementPivot", localPlayerPivot.transform);
sceneCamera.SendMessage("SetupCamera");
sceneCamera.camera.enabled = true;
Debug.Log("MovementPivot configured");
// Call a function called ConfigurePlayerCharacter in PlayerCharacter that sets a flag that the user is now "ready"
// so the character can now be controlled by movement keys.
PlayerCharacter charController = characterObject.GetComponent<PlayerCharacter>();
if (charController == null)
{
charController = characterObject.AddComponent<PlayerCharacter>();
}
charController.ConfigurePlayerCharacter(usePhysicalCharacter, enableFlyingAvatars);
Debug.Log("PlayerCharacter setup");
Debug.Log("Loading skin preferences");
Transform skinTransform;
// Set appearance based on clothing and hair texture choices.
RetrieveClothingPreference(user);
if (characterObject != null)
{
for (int i = 0; i < characterObject.transform.childCount; i++)
{
if (characterObject.transform.GetChild(i).tag == "Skin")
{
skinTransform = characterObject.transform.GetChild(i);
if (user.Skin != null)
{
Texture2D selectedSkin = (Texture2D)Resources.Load(user.Skin);
skinTransform.renderer.material.mainTexture = selectedSkin;
}
}
}
for (int i = 0; i < characterObject.transform.childCount; i++)
{
if (characterObject.transform.GetChild(i).tag == "Wig")
{
Debug.Log("Found my hair!");
if (!string.IsNullOrEmpty(user.Hair))
{
characterObject.transform.GetChild(i).renderer.material.mainTexture = (Texture2D)Resources.Load(user.Hair);
}
else
{
user.Hair = characterObject.transform.GetChild(i).renderer.material.mainTexture.name;
}
}
}
AnimateCharacter ac = characterObject.GetComponent<AnimateCharacter>();
Component tpa = characterObject.GetComponent("ThirdPersonAnimation");
if (tpa != null)
{
tpa.SendMessage("DisableTPA");
}
if (ac == null)
{
ac = characterObject.AddComponent<AnimateCharacter>();
}
ac.EnableIdleWakeup(enableIdleAnimationWakeup);
// Check for existence of the UIBase game object and send a message to a script in the camera
// which can optionally be used to disable the UI.
GameObject gui = GameObject.Find("UIBase");
if (gui)
{
Camera.main.SendMessage("SetGuiParent", gui);
}
if (GameObject.Find("UIBase") != null)
{
if (characterObject.GetComponent<NameTag>() == null)
{
characterObject.AddComponent<NameTag>();
}
if (characterObject.GetComponent<NameTag>() != null)
{
characterObject.GetComponent<NameTag>().skin = GameObject.Find("UIBase").GetComponent<UIBase>().skin;
characterObject.GetComponent<NameTag>().localPlayer = user;
characterObject.GetComponent<NameTag>().showNameTag = showOwnName;
}
Debug.Log("NameTag added and setup");
}
Debug.Log("About to start sending animation messages");
aniSync.StartSending();
// If there's a minimap camera in the scene, now's the time to tell it to follow the local player transform
// so the map scrolls smoothly to show an overhead view of your immediate surroundings
GameObject miniMapCam = GameObject.Find("MiniMapCamera");
if (miniMapCam != null)
miniMapCam.GetComponent<MiniMapFollowCamera>().SetTarget(characterObject.transform);
ShowSpawnParticles(newPosition, spawnPoint.transform.rotation);
// Player has now joined the scene - send a message to Network Controller that will appear in chat
string message = user.Name + " has joined";
netController.SendChatMessage(message);
}
// If the application is set up to use database logging, track the event of the user entering the room
if (jibeLog == null)
{
jibeLog = GameObject.Find("Jibe").GetComponent<JibeActivityLog>();
if (jibeLog != null)
{
Debug.Log("Found jibeLog");
}
}
if (jibeLog.logEnabled)
{
Debug.Log("Logging user enter room");
Debug.Log(jibeLog.TrackEvent(JibeEventType.Login, Application.absoluteURL, 0.0f, 0.0f, 0.0f, user.PlayerID.ToString(), user.Name, "User entered room "));
}
*/
//print("after");
}
}
else // There is already an existing local player object
{
print("start else");
// USER HAS RECONNECTED
GameObject characterObject = GameObject.FindGameObjectWithTag("Character");
Debug.Log("PLAYER " + user.Name + " RECONNECTED!");
if (characterObject != null) // sanity check in case this is null
{
if (!characterObject.GetComponent<PlayerMovement>().IsSitting())
{
characterObject.SendMessage("WakeUp");
}
}
else
{
Debug.Log("Nasty null - where's the character gone?");
}
if (localPlayer != null)
{
// Re-send our location to help sync up remote viewers
netController.SendTransform(localPlayer.transform);
}
else
{
Debug.Log("Nasty null - where's the localPlayer gone?");
}
}
GameObject plaqueParent = GameObject.Find("Plaque");
if(plaqueParent!=null)
{
plaqueParent.BroadcastMessage("OnPlayerJoin");
}
// Return a reference to the newly-created Local Player avatar game object to Network Controller
//Debug.Log("Done");
// addToOnlineUsers(user.Name, user.PlayerID);
return GameObject.FindGameObjectWithTag("Player");
}
/// <summary>
/// Create a Remote Player object representing a user in the scene
/// </summary>
/// <param name="player">An IJibePlayer representing the remote user to be rendered in the scene</param>
/// <returns>A refrence to the newly-created Remote Player object - this reference is very important,
/// since when the player leaves, the avatar will be removed.</returns>
public GameObject SpawnRemotePlayer(IJibePlayer player)
{
// the convention to use for a remote player game object name internally
string remotePlayerName = netController.RemotePlayerGameObjectPrefix + player.PlayerID;
GameObject remotePlayer = GameObject.Find(remotePlayerName);
if (remotePlayer == null)
{
int n = spawnPoints.Length;
Transform spawnPoint = spawnPoints[random.Next(n)];
// adjust remote spawn position to be close to (x and z) the main spawn point, but sufficiently out of scope in y that the player will just appear at the correct location without floating into position.
Vector3 remoteSpawnPosition = new Vector3(spawnPoint.position.x, 10000, spawnPoint.position.z);
Quaternion remoteSpawnRot = spawnPoint.rotation;
int avatarId = player.AvatarModel;
Debug.Log("Spawning Remote Player, remote avatar is type " + avatarId);
// Instantiate a new Remote Player object for the remote user
UnityEngine.Component remotePlayerComponent = Instantiate(remotePlayerPrefabs[avatarId], remoteSpawnPosition, remoteSpawnRot) as UnityEngine.Component;
if (remotePlayerComponent == null)
{
throw new Exception("Something wrong with remote player spawn!");
}
// Add all required scripts
remotePlayer = remotePlayerComponent.gameObject;
remotePlayer.tag = "RemotePlayer";
// remotePlayer.transform.localScale*=.8f; //RSO
foreach (string componentToRemove in componentsToDisableForRemotePlayers)
{
if (remotePlayer.GetComponent(componentToRemove) != null)
(remotePlayer.GetComponent(componentToRemove) as Behaviour).enabled = false;
}
remotePlayer.AddComponent<AnimationSynchronizer>();
remotePlayer.AddComponent<NetworkReceiver>();
//new player nameplates
remotePlayer.AddComponent<nameTag>();
remotePlayer.GetComponent<nameTag>().SetDisplayName(player);
//old broken player tags
/* remotePlayer.AddComponent<BubblePopup>();
remotePlayer.GetComponent<BubblePopup>().skin = GameObject.Find("UIBase").GetComponent<UIBase>().skin;
remotePlayer.GetComponent<BubblePopup>().SetDisplayName(player);
remotePlayer.GetComponent<BubblePopup>().fullyVisibleDistance = remotePlayerNametagFullyVisibleDistance;
remotePlayer.GetComponent<BubblePopup>().fadeDistance = remotePlayerNametagFadeDistance;
*/
//Give remote player game object a name like "remote_<id>"
remotePlayer.name = remotePlayerName;
// The remote player doesn't need a Third Person Animation component, so disable this script when the player is a remote player
remotePlayer.SendMessage("DisableTPA", SendMessageOptions.DontRequireReceiver);
if (remotePlayer.GetComponent<AnimateCharacter>() != null)
{
remotePlayer.GetComponent<AnimateCharacter>().DisableAC();
}
//Start receiving transform synchronization messages
remotePlayer.GetComponent<NetworkReceiver>().StartReceiving();
remotePlayer.GetComponent<AnimationSynchronizer>().StartReceiving();
// Adjust appearance for remote user
if (!string.IsNullOrEmpty(player.Skin))
{
Debug.Log("Remote player has skin: " + player.Skin);
Texture2D remoteTexture = (Texture2D)Resources.Load(player.Skin);
if (remoteTexture != null)
{
try
{
remotePlayer.GetComponent<NetworkReceiver>().SetSkinRemote(remoteTexture);
}
catch (Exception ex)
{
Debug.Log("Something very wrong setting remote skin texture " + remoteTexture.name + " on player " + remotePlayerName + ", " + ex.Message + ex.StackTrace);
}
}
}
if (!string.IsNullOrEmpty(player.Hair))
{
Debug.Log("Remote player has hair: " + player.Hair);
Texture2D remoteTexture = (Texture2D)Resources.Load(player.Hair);
if (remoteTexture != null)
{
try
{
remotePlayer.GetComponent<NetworkReceiver>().SetHairRemote(remoteTexture);
}
catch (Exception ex)
{
Debug.Log("Something very wrong setting remote hair texture " + remoteTexture.name + " on player " + remotePlayerName + ", " + ex.Message + ex.StackTrace);
}
}
}
AddSpotShadow(remotePlayer);
AddMapIcon(remotePlayer, remotePlayerMapIcon);
}
else
{
Debug.Log("Remote Player " + player.Name + " already exists!! Reusing.");
}
// Return the remote player game object
//GameObject.Find("namePlaque30").SendMessage("StartSync");
netController.Synchronize();
//RSO add to online users list
addToOnlineUsers(player.Name, player.PlayerID);
return remotePlayer;
}
private void addToOnlineUsers(string name, int id)
{
Transform newOnlineUser;
Debug.Log("Adding:" + name + "to online users");
if(!netController.isAdmin)
{
newOnlineUser = GameObject.Instantiate(onlineUserPrefab) as Transform;
}
else
{
newOnlineUser = GameObject.Instantiate(adminOnlineUserPrefab) as Transform;
newOnlineUser.GetComponentInChildren<Mute>().name=name;
newOnlineUser.GetComponentInChildren<Mute>().id=id;
}
newOnlineUser.parent=onlineUserParent;
newOnlineUser.name=""+id;
newOnlineUser.localPosition=new Vector3(newOnlineUser.localPosition.x,newOnlineUser.localPosition.y, -17f);
newOnlineUser.GetComponentInChildren<UILabel>().text=name;
onlineUserParent.GetComponent<UIGrid>().repositionNow=true;
}
private void AddMapIcon(GameObject player, Transform icon)
{
UnityEngine.Component playerMapIconObject = Instantiate(icon, player.transform.position, icon.transform.rotation) as UnityEngine.Component;
playerMapIconObject.transform.parent = player.transform;
Vector3 mapIconPosition = playerMapIconObject.transform.position;
mapIconPosition.y = mapIconPosition.y + mapIconHeight;
playerMapIconObject.transform.position = mapIconPosition;
}
private void AddSpotShadow(GameObject player)
{
// Add a spot shadow for the player
Vector3 shadowSpawnPoint = player.transform.position;
shadowSpawnPoint.y = shadowSpawnPoint.y + 2;
UnityEngine.Component remotePlayerShadowObject = Instantiate(playerShadow, shadowSpawnPoint, playerShadow.rotation) as UnityEngine.Component;
remotePlayerShadowObject.transform.parent = player.transform;
}
/// <summary>
/// Called when a new player is created
/// </summary>
public void PlaySpawnSound()
{
GameObject guiObject = GameObject.Find("UIBase");
if (guiObject != null)
{
float playVolume = spawnSoundVolume * guiObject.GetComponent<UIBase>().volume / guiObject.GetComponent<UIBase>().audioIcons.Length;
AudioSource.PlayClipAtPoint(spawnSound, Camera.main.transform.position, playVolume);
}
}
/// <summary>
/// Show pretty particles when the avatar is spawned, but only if a GameObject for a particle effect has been assigned in the inspector
/// </summary>
/// <param name="pos"></param>
/// <param name="rot"></param>
public void ShowSpawnParticles(Vector3 pos, Quaternion rot)
{
if (spawnParticles != null)
{
Instantiate(spawnParticles, pos, rot);
}
}
private void ShowPreviewCamera(bool enabled)
{
GameObject previewCamera = GameObject.Find("PreviewCameraForDesignModeOnly");
if (previewCamera != null)
{
Debug.Log("Preview Camera found, setting active to " + enabled);
previewCamera.GetComponent<PreviewCamera>().SetActive(enabled);
}
}
private void RetrieveClothingPreference(IJibePlayer localPlayer)
{
// try to re-use previous clothing options
string skin = PlayerPrefs.GetString("skin");
if (!string.IsNullOrEmpty(skin))
{
if (playerPrefabs[localPlayer.AvatarModel].name.Substring(0, 2).ToLower() == skin.Substring(0, 2).ToLower())
localPlayer.Skin = skin;
}
string hair = PlayerPrefs.GetString("hair");
if (!string.IsNullOrEmpty(hair))
localPlayer.Hair = hair;
}
}
| |
//TODO - make sure msvc builds with 32bit enums and get rid of the extra marshalling fluff here
using System;
using System.Runtime.InteropServices;
using BizHawk.Emulation.Common;
namespace BizHawk.Emulation.Cores.Sony.PSX
{
public unsafe static class OctoshockDll
{
const CallingConvention cc = CallingConvention.Cdecl;
const string dd = "octoshock.dll";
public enum eRegion : int
{
JP = 0,
NA = 1,
EU = 2,
NONE = 3 //TODO - whats the difference between unset, and region unknown?
}
public enum eVidStandard : int
{
NTSC = 0,
PAL = 1,
}
public enum eShockStep
{
Frame
};
public enum eShockFramebufferFlags
{
None = 0,
Normalize = 1
}
public enum eMemType
{
MainRAM = 0, //2048K
BiosROM = 1, //512K
PIOMem = 2, //64K
GPURAM = 3, //512K
SPURAM = 4, //512K
DCache = 5 //1K
};
public enum eShockStateTransaction : int
{
BinarySize = 0,
BinaryLoad = 1,
BinarySave = 2,
TextLoad = 3,
TextSave = 4
}
public enum eShockMemcardTransaction
{
Connect = 0, //connects it to the addressed port (not supported yet)
Disconnect = 1, //disconnects it from the addressed port (not supported yet)
Write = 2, //writes from the frontend to the memcard
Read = 3, //reads from the memcard to the frontend. Also clears the dirty flag
CheckDirty = 4, //checks whether the memcard is dirty
};
public enum ePeripheralType : int
{
None = 0, //can be used to signify disconnection
Pad = 1, //SCPH-1080
DualShock = 2, //SCPH-1200
DualAnalog = 3, //SCPH-1180
Multitap = 10,
};
/// <summary>
/// this is implemented as an overall render type instead of a horizontal clip control
/// in case the Framebuffer render type ever develops any differences in its Y-handling.
/// At that time, we might need to change the GUI to separate the vertical and horizontal components, or something like that
/// </summary>
public enum eShockRenderType : int
{
Normal,
ClipOverscan,
Framebuffer
};
public enum eShockDeinterlaceMode : int
{
Weave,
Bob,
BobOffset
}
[Flags]
public enum eShockMemCb : int
{
None = 0,
Read = 1,
Write = 2,
Execute = 4
}
public const int SHOCK_OK = 0;
public const int SHOCK_FALSE = 0;
public const int SHOCK_TRUE = 1;
public const int SHOCK_ERROR = -1;
public const int SHOCK_NOCANDO = -2;
public const int SHOCK_INVALID_ADDRESS = -3;
public const int SHOCK_OVERFLOW = -4;
[StructLayout(LayoutKind.Sequential)]
public struct ShockDiscInfo
{
public eRegion region;
public unsafe fixed sbyte id[5]; //SCEI, SCEA, SCEE, etc. with null terminator
};
[StructLayout(LayoutKind.Sequential)]
public struct ShockTOCTrack
{
public byte adr;
public byte control;
public uint lba;
};
[StructLayout(LayoutKind.Sequential)]
public struct ShockTOC
{
public byte first_track;
public byte last_track;
public byte disc_type;
};
[StructLayout(LayoutKind.Sequential)]
public struct ShockFramebufferInfo
{
public int width, height;
[MarshalAs(UnmanagedType.I4)]
public eShockFramebufferFlags flags;
public void* ptr;
};
[StructLayout(LayoutKind.Sequential)]
public struct ShockRenderOptions
{
public int scanline_start, scanline_end;
public eShockRenderType renderType;
public eShockDeinterlaceMode deinterlaceMode;
public bool skip;
};
[StructLayout(LayoutKind.Sequential)]
public struct ShockMemcardTransaction
{
[MarshalAs(UnmanagedType.I4)]
public eShockMemcardTransaction transaction;
public void* buffer128k;
};
[StructLayout(LayoutKind.Sequential)]
public struct ShockRegisters_CPU
{
public fixed uint GPR[32];
public uint PC, PC_NEXT;
public uint IN_BD_SLOT;
public uint LO, HI;
public uint SR, CAUSE, EPC;
};
[StructLayout(LayoutKind.Sequential)]
public struct ShockStateTransaction
{
public eShockStateTransaction transaction;
public void* buffer;
public int bufferLength;
public TextStateFPtrs ff;
};
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void ShockCallback_Trace(IntPtr opaque, uint PC, uint inst, string dis);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int ShockDisc_ReadTOC(IntPtr opaque, ShockTOC* read_target, ShockTOCTrack* tracks101);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int ShockDisc_ReadLBA(IntPtr opaque, int lba, void* dst);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void ShockCallback_Mem(uint address, eShockMemCb type, uint size, uint value);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_Util_DisassembleMIPS(uint PC, uint instr, IntPtr outbuf, int buflen);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_CreateDisc(out IntPtr outDisc, IntPtr Opaque, int lbaCount, ShockDisc_ReadTOC ReadTOC, ShockDisc_ReadLBA ReadLBA2448, bool suppliesDeinterleavedSubcode);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_DestroyDisc(IntPtr disc);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_AnalyzeDisc(IntPtr disc, out ShockDiscInfo info);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_Create(out IntPtr psx, eRegion region, void* firmware512k);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_Destroy(IntPtr psx);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_Peripheral_Connect(
IntPtr psx,
int address,
[MarshalAs(UnmanagedType.I4)] ePeripheralType type
);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_Peripheral_SetPadInput(IntPtr psx, int address, uint buttons, byte left_x, byte left_y, byte right_x, byte right_y);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_Peripheral_MemcardTransact(IntPtr psx, int address, ref ShockMemcardTransaction transaction);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_Peripheral_PollActive(IntPtr psx, int address, bool clear);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_MountEXE(IntPtr psx, void* exebuf, int size, bool ignore_pcsp);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_PowerOn(IntPtr psx);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_SoftReset(IntPtr psx);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_PowerOff(IntPtr psx);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_OpenTray(IntPtr psx);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_SetDisc(IntPtr psx, IntPtr disc);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_PokeDisc(IntPtr psx, IntPtr disc);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_CloseTray(IntPtr psx);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_SetRenderOptions(IntPtr psx, ref ShockRenderOptions opts);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_Step(IntPtr psx, eShockStep step);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_GetFramebuffer(IntPtr psx, ref ShockFramebufferInfo fb);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_GetSamples(IntPtr psx, void* buffer);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_GetMemData(
IntPtr psx,
out IntPtr ptr,
out int size,
[MarshalAs(UnmanagedType.I4)] eMemType memType
);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_StateTransaction(IntPtr psx, ref ShockStateTransaction transaction);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_GetRegisters_CPU(IntPtr psx, ref ShockRegisters_CPU buffer);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_SetRegister_CPU(IntPtr psx, int index, uint value);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_SetTraceCallback(IntPtr psx, IntPtr opaque, ShockCallback_Trace callback);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_SetMemCb(IntPtr psx, ShockCallback_Mem cb, eShockMemCb cbMask);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_SetLEC(IntPtr psx, bool enable);
[DllImport(dd, CallingConvention = cc)]
public static extern int shock_GetGPUUnlagged(IntPtr psx);
}
}
| |
// <copyright file="BuilderTest.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;
using BeanIO.Internal.Config;
using BeanIO.Stream;
using BeanIO.Stream.Csv;
using BeanIO.Stream.Delimited;
using BeanIO.Stream.FixedLength;
using BeanIO.Stream.Xml;
using BeanIO.Types;
using Xunit;
namespace BeanIO.Builder
{
public class BuilderTest
{
[Fact]
public void TestXmlParserBuilder()
{
var b = new XmlParserBuilder();
var p = (XmlRecordParserFactory)b.Build().Create();
Assert.Null(p.Indentation);
Assert.Null(p.LineSeparator);
Assert.NotNull(p.Version);
Assert.Equal(new Version(1, 0), p.Version);
Assert.NotNull(p.Encoding);
Assert.Equal("utf-8", p.GetEncoding().WebName);
Assert.False(p.SuppressHeader);
Assert.Null(p.NamespaceMap);
b = new XmlParserBuilder()
.Indent()
.HeaderVersion(new Version(2, 0))
.HeaderEncoding(Encoding.ASCII)
.LineSeparator("\n")
.AddNamespace("r", "rock")
.AddNamespace("p", "paper");
p = (XmlRecordParserFactory)b.Build().Create();
Assert.Equal(2, p.Indentation);
Assert.Equal(new Version(2, 0), p.Version);
Assert.Equal(Encoding.ASCII, p.GetEncoding());
Assert.Equal("\n", p.LineSeparator);
Assert.Collection(
p.NamespaceMap,
item =>
{
Assert.Equal("rock", item.Key);
Assert.Equal("r", item.Value);
},
item =>
{
Assert.Equal("paper", item.Key);
Assert.Equal("p", item.Value);
});
}
[Fact]
public void TestDelimitedParserBuilder()
{
var b = new DelimitedParserBuilder();
var p = (DelimitedRecordParserFactory)b.Build().Create();
Assert.Equal('\t', p.Delimiter);
Assert.Null(p.Escape);
Assert.Null(p.LineContinuationCharacter);
Assert.Null(p.Comments);
Assert.Null(p.RecordTerminator);
b = new DelimitedParserBuilder()
.Delimiter(',')
.EnableEscape('\\')
.EnableLineContinuation('&')
.EnableComments("#", "!")
.RecordTerminator("\n");
p = (DelimitedRecordParserFactory)b.Build().Create();
Assert.Equal(',', p.Delimiter);
Assert.Equal('\\', p.Escape);
Assert.Equal('&', p.LineContinuationCharacter);
Assert.Collection(
p.Comments,
item => Assert.Equal("#", item),
item => Assert.Equal("!", item));
Assert.Equal("\n", p.RecordTerminator);
b = new DelimitedParserBuilder('|');
p = (DelimitedRecordParserFactory)b.Build().Create();
Assert.Equal('|', p.Delimiter);
}
[Fact]
public void TestFixedLengthParserBuilder()
{
var b = new FixedLengthParserBuilder();
var p = (FixedLengthRecordParserFactory)b.Build().Create();
Assert.Null(p.LineContinuationCharacter);
Assert.Null(p.Comments);
Assert.Null(p.RecordTerminator);
b = new FixedLengthParserBuilder()
.EnableLineContinuation('\\')
.EnableComments("#", "!")
.RecordTerminator("\r\n");
p = (FixedLengthRecordParserFactory)b.Build().Create();
Assert.Equal('\\', p.LineContinuationCharacter);
Assert.Collection(
p.Comments,
item => Assert.Equal("#", item),
item => Assert.Equal("!", item));
Assert.Equal("\r\n", p.RecordTerminator);
}
[Fact]
public void TestCsvParserBuilder()
{
var b = new CsvParserBuilder();
var p = (CsvRecordParserFactory)b.Build().Create();
Assert.Equal(',', p.Delimiter);
Assert.Equal('"', p.Quote);
Assert.Equal('"', p.Escape);
Assert.False(p.IsMultilineEnabled);
Assert.False(p.AlwaysQuote);
Assert.False(p.IsWhitespaceAllowed);
Assert.False(p.UnquotedQuotesAllowed);
Assert.Null(p.Comments);
Assert.Null(p.RecordTerminator);
b = new CsvParserBuilder()
.Delimiter('|')
.Quote('\'')
.Escape('\\')
.EnableMultiline()
.AlwaysQuote()
.AllowUnquotedQuotes()
.AllowUnquotedWhitespace()
.EnableComments("#", "!")
.RecordTerminator("\r");
p = (CsvRecordParserFactory)b.Build().Create();
Assert.Equal('|', p.Delimiter);
Assert.Equal('\'', p.Quote);
Assert.Equal('\\', p.Escape);
Assert.True(p.IsMultilineEnabled);
Assert.True(p.AlwaysQuote);
Assert.True(p.IsWhitespaceAllowed);
Assert.True(p.UnquotedQuotesAllowed);
Assert.Collection(
p.Comments,
item => Assert.Equal("#", item),
item => Assert.Equal("!", item));
Assert.Equal("\r", p.RecordTerminator);
}
[Fact]
public void TestStreamBuilder()
{
var b = new StreamBuilder("stream");
var c = b.Build();
Assert.Equal("stream", c.Name);
Assert.Equal(1, c.Order);
Assert.Equal(0, c.MinOccurs);
Assert.Equal(1, c.MaxOccurs);
Assert.Null(c.Format);
Assert.Null(c.Mode);
Assert.False(c.IsStrict);
Assert.False(c.IgnoreUnidentifiedRecords);
Assert.Equal(ElementNameConversionMode.Unchanged, c.NameConversionMode);
var csvParser = new CsvRecordParserFactory();
var birthDateHandler = new DateTimeTypeHandler();
var stringTypeHandler = new StringTypeHandler();
b.Format("csv")
.ReadOnly()
.ResourceBundle("bundle")
.Strict()
.IgnoreUnidentifiedRecords()
.Parser(csvParser)
.AddRecord(new RecordBuilder("record"))
.AddGroup(new GroupBuilder("subgroup"))
.AddTypeHandler("birthDate", () => birthDateHandler)
.AddTypeHandler(typeof(string), () => stringTypeHandler);
c = b.Build();
Assert.Equal("csv", c.Format);
Assert.Equal(AccessMode.Read, c.Mode);
Assert.Equal("bundle", c.ResourceBundle);
Assert.True(c.IsStrict);
Assert.True(c.IgnoreUnidentifiedRecords);
Assert.Same(csvParser, c.ParserFactory.Create());
Assert.Collection(
c.Children,
child =>
{
Assert.Equal("record", child.Name);
Assert.IsType<RecordConfig>(child);
},
child =>
{
Assert.Equal("subgroup", child.Name);
Assert.IsType<GroupConfig>(child);
});
Assert.Collection(
c.Handlers,
handler =>
{
Assert.Equal("birthDate", handler.Name);
Assert.Same(birthDateHandler, handler.Create());
},
handler =>
{
Assert.Equal(typeof(string).GetTypeInfo().AssemblyQualifiedName, handler.Name);
Assert.Same(stringTypeHandler, handler.Create());
});
var xmlParser = new XmlParserBuilder();
b = new StreamBuilder("stream", "fixedlength")
.WriteOnly()
.Parser(xmlParser);
c = b.Build();
Assert.Equal("fixedlength", c.Format);
Assert.Equal(AccessMode.Write, c.Mode);
Assert.IsType<XmlRecordParserFactory>(c.ParserFactory.Create());
}
[Fact]
public void TestGroupBuilder()
{
var b = new GroupBuilder("group");
var c = b.Build();
Assert.Equal("group", c.Name);
Assert.Null(c.Order);
Assert.Null(c.MinOccurs);
Assert.Null(c.MaxOccurs);
b.Order(1)
.AddRecord(new RecordBuilder("record"))
.AddGroup(new GroupBuilder("subgroup"));
c = b.Build();
Assert.Equal(1, c.Order);
Assert.Collection(
c.Children,
child =>
{
Assert.Equal("record", child.Name);
Assert.IsType<RecordConfig>(child);
},
child =>
{
Assert.Equal("subgroup", child.Name);
Assert.IsType<GroupConfig>(child);
});
}
[Fact]
public void TestRecordBuilder()
{
var b = new RecordBuilder("record");
var c = b.Build();
Assert.Equal("record", c.Name);
Assert.Null(c.Order);
Assert.Null(c.MinLength);
Assert.Null(c.MaxLength);
Assert.Null(c.MinOccurs);
Assert.Null(c.MaxOccurs);
Assert.Null(c.MinMatchLength);
Assert.Null(c.MaxMatchLength);
b.Order(2)
.MinLength(1)
.MaxLength(-1)
.RidLength(5, 10)
.AddField(new FieldBuilder("field"))
.AddSegment(new SegmentBuilder("segment"));
c = b.Build();
Assert.Equal(2, c.Order);
Assert.Equal(1, c.MinLength);
Assert.Equal(int.MaxValue, c.MaxLength);
Assert.Equal(5, c.MinMatchLength);
Assert.Equal(10, c.MaxMatchLength);
Assert.Collection(
c.Children,
child =>
{
Assert.Equal("field", child.Name);
Assert.IsType<FieldConfig>(child);
},
child =>
{
Assert.Equal("segment", child.Name);
Assert.IsType<SegmentConfig>(child);
});
b = new RecordBuilder("record")
.Length(5)
.RidLength(10);
c = b.Build();
Assert.Equal(5, c.MinLength);
Assert.Equal(5, c.MaxLength);
Assert.Equal(10, c.MinMatchLength);
Assert.Equal(10, c.MaxMatchLength);
}
[Fact]
public void TestSegmentBuilder()
{
var b = new SegmentBuilder("segment");
var c = b.Build();
Assert.Equal("segment", c.Name);
Assert.Null(c.Key);
Assert.Null(c.Target);
Assert.Null(c.OccursRef);
Assert.False(c.IsNillable);
Assert.Null(c.MinOccurs);
Assert.Null(c.MaxOccurs);
b.OccursRef("other")
.Key("key")
.Value("value")
.IsNillable()
.Occurs(5)
.AddField(new FieldBuilder("field"))
.AddSegment(new SegmentBuilder("segment"));
c = b.Build();
Assert.Equal("other", c.OccursRef);
Assert.Equal("key", c.Key);
Assert.Equal("value", c.Target);
Assert.True(c.IsNillable);
Assert.Equal(5, c.MinOccurs);
Assert.Equal(5, c.MaxOccurs);
Assert.Collection(
c.Children,
child =>
{
Assert.Equal("field", child.Name);
Assert.IsType<FieldConfig>(child);
},
child =>
{
Assert.Equal("segment", child.Name);
Assert.IsType<SegmentConfig>(child);
});
}
[Fact]
public void TestFieldBuilder()
{
var b = new FieldBuilder("field");
var c = b.Build();
Assert.Equal("field", c.Name);
Assert.Null(c.Type);
Assert.Null(c.Collection);
Assert.Null(c.Getter);
Assert.Null(c.Setter);
Assert.True(c.IsBound);
Assert.Null(c.Position);
Assert.Null(c.Until);
Assert.False(c.IsIdentifier);
Assert.False(c.IsTrim);
Assert.False(c.IsRequired);
Assert.False(c.IsLazy);
Assert.Null(c.OccursRef);
Assert.Null(c.MinOccurs);
Assert.Null(c.MaxOccurs);
Assert.Null(c.MinLength);
Assert.Null(c.MaxLength);
Assert.Null(c.Length);
Assert.Null(c.Literal);
Assert.Null(c.DefaultValue);
Assert.Null(c.Format);
Assert.Equal(Align.Left, c.Justify);
Assert.Null(c.Padding);
Assert.False(c.KeepPadding);
Assert.False(c.IsLenientPadding);
Assert.Null(c.RegEx);
Assert.False(c.IsNillable);
Assert.Null(c.XmlType);
Assert.Null(c.XmlName);
Assert.Null(c.XmlPrefix);
Assert.Null(c.XmlNamespace);
Assert.Null(c.TypeHandler);
Assert.Null(c.ParseDefault);
b.Type(typeof(int))
.Collection(typeof(List<object>))
.Getter("GetField")
.Setter("SetField")
.Ignore()
.At(3)
.Until(-2)
.Rid()
.Trim()
.Required()
.Lazy()
.OccursRef("other")
.Occurs(0, -1)
.Length(10)
.MinLength(0)
.MaxLength(-1)
.Literal("literal")
.DefaultValue("default")
.Format("format")
.Align(Align.Right)
.Padding('X')
.KeepPadding()
.LenientPadding()
.RegEx(".*")
.Nillable()
.ParseDefault(false)
.XmlType(XmlNodeType.Attribute)
.XmlName("xmlName")
.XmlPrefix("prefix")
.XmlNamespace("namespace")
.TypeHandler("typeHandler");
c = b.Build();
Assert.Equal(typeof(int).GetTypeInfo().AssemblyQualifiedName, c.Type);
Assert.Equal(typeof(List<object>).GetTypeInfo().AssemblyQualifiedName, c.Collection);
Assert.Equal("GetField", c.Getter);
Assert.Equal("SetField", c.Setter);
Assert.False(c.IsBound);
Assert.Equal(3, c.Position);
Assert.Equal(-2, c.Until);
Assert.True(c.IsIdentifier);
Assert.True(c.IsTrim);
Assert.True(c.IsRequired);
Assert.True(c.IsLazy);
Assert.Equal("other", c.OccursRef);
Assert.Equal(0, c.MinOccurs);
Assert.Equal(int.MaxValue, c.MaxOccurs);
Assert.Equal(0, c.MinLength);
Assert.Null(c.MaxLength);
Assert.Equal(10, c.Length);
Assert.Equal("literal", c.Literal);
Assert.Equal("default", c.DefaultValue);
Assert.Equal("format", c.Format);
Assert.Equal(Align.Right, c.Justify);
Assert.Equal('X', c.Padding);
Assert.True(c.KeepPadding);
Assert.True(c.IsLenientPadding);
Assert.Equal(".*", c.RegEx);
Assert.True(c.IsNillable);
Assert.Equal(XmlNodeType.Attribute, c.XmlType);
Assert.Equal("xmlName", c.XmlName);
Assert.Equal("prefix", c.XmlPrefix);
Assert.Equal("namespace", c.XmlNamespace);
Assert.Equal("typeHandler", c.TypeHandler);
Assert.False(c.ParseDefault);
b = new FieldBuilder("field")
.TypeHandler<StringTypeHandler>();
c = b.Build();
Assert.Equal(typeof(StringTypeHandler).GetTypeInfo().AssemblyQualifiedName, c.TypeHandler);
var th = new StringTypeHandler();
b = new FieldBuilder("field")
.TypeHandler(th);
c = b.Build();
Assert.Same(th, c.TypeHandlerInstance);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using TestLibrary;
public class StringConcat8
{
private int c_MAX_STRING_LENGTH = 256;
private int c_MINI_STRING_LENGTH = 8;
public static int Main()
{
StringConcat8 sc8 = new StringConcat8();
TestLibrary.TestFramework.BeginTestCase("StringConcat8");
if (sc8.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region PositiveTesting
public bool PosTest1()
{
bool retVal = true;
Random rand = new Random(-55);
string ActualResult;
string[] strA = new string[rand.Next(c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH)];
TestLibrary.TestFramework.BeginScenario("PostTest1:Concat string Array with all null member");
try
{
for (int i = 0; i < strA.Length; i++)
{
strA[i] = null;
}
ActualResult = string.Concat(strA);
if (ActualResult != MergeStrings(strA))
{
TestLibrary.TestFramework.LogError("001", "Concat string Array with all null member ExpectResult is" + MergeStrings(strA) + "ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
Random rand = new Random(-55);
string ActualResult;
string[] strA = new string[rand.Next(c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH)];
TestLibrary.TestFramework.BeginScenario("PostTest2:Concat string Array with all empty member");
try
{
for (int i = 0; i < strA.Length; i++)
{
strA[i] = "";
}
ActualResult = string.Concat(strA);
if (ActualResult != MergeStrings(strA))
{
TestLibrary.TestFramework.LogError("003", "Concat string Array with all empty member ExpectResult is" + MergeStrings(strA) + " ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string ActualResult;
string[] strA;
TestLibrary.TestFramework.BeginScenario("PosTest3:Concat string Array with null and empty member");
try
{
strA = new string[] { null, "", null, "", null, "" };
ActualResult = string.Concat(strA);
if (ActualResult != MergeStrings(strA))
{
TestLibrary.TestFramework.LogError("005", "Concat string Array with null and empty member ExpectResult is equel" + MergeStrings(strA) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string ActualResult;
string[] strA;
TestLibrary.TestFramework.BeginScenario("PosTest4: Concat string Array with single letter member");
try
{
strA = new string[] {"a","b","c","d","e","f"};
ActualResult = string.Concat(strA);
if (ActualResult != MergeStrings(strA))
{
TestLibrary.TestFramework.LogError("007", "Concat string Array with single letter member ExpectResult is" + MergeStrings(strA) + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string ActualResult;
string[] strA;
TestLibrary.TestFramework.BeginScenario("PosTest5:Concat string Array with null,empty and not nullstrings member");
try
{
strA = new string[] {null,"a","null","",null,"123"};
ActualResult = string.Concat(strA);
if (ActualResult != MergeStrings(strA))
{
TestLibrary.TestFramework.LogError("009", "Concat string Array with null,empty and not nullstrings member ExpectResult is equel" + MergeStrings(strA) + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
string ActualResult;
string[] strA;
TestLibrary.TestFramework.BeginScenario("PosTest6: Concat string Array with not nullstring and some symbols member one");
try
{
string str1 = "HelloWorld";
string str2 = "\n";
string str3 = "\t";
string str4 = "\0";
string str5 = "\u0041";
strA = new string[] { str1,str2,str3,str4,str5 };
ActualResult = string.Concat(strA);
if (ActualResult != MergeStrings(strA))
{
TestLibrary.TestFramework.LogError("011", "Concat string Array with not nullstring and some symbols member ExpectResult is equel" + MergeStrings(strA) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
string ActualResult;
string[] strA;
TestLibrary.TestFramework.BeginScenario("PosTest7: Concat string Array with not nullstrings and some symbols member two");
try
{
string str1 = "hello";
string str2 = "\u0020";
string str3 = "World";
string str4 = "\u0020";
string str5 = "!";
strA = new string[] { str1, str2, str3, str4, str5 };
ActualResult = string.Concat(strA);
if (ActualResult != MergeStrings(strA))
{
TestLibrary.TestFramework.LogError("013", "Concat string Array with some strings and some symbols member two ExpectResult is equel" + MergeStrings(strA) + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
string ActualResult;
string[] strA;
TestLibrary.TestFramework.BeginScenario("PosTest8:Concat string Array with some not nullstrings member one");
try
{
string str1 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
string str2 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
string str3 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
string str4 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
string str5 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
strA = new string[] { str1, str2, str3, str4, str5 };
ActualResult = string.Concat(strA);
if (ActualResult != MergeStrings(strA))
{
TestLibrary.TestFramework.LogError("015", "Concat string Array with some not nullstrings member one ExpectResult is equel" + MergeStrings(strA) + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
string ActualResult;
string[] strA;
TestLibrary.TestFramework.BeginScenario("PosTest9:Concat object Array with some not nullstrings member two");
try
{
string str1 = "helloworld".ToUpper() +"\n";
string str2 = "hello\0world".ToUpper() + "\n";
string str3 = "HELLOWORLD".ToLower() + "\n";
string str4 = "HelloWorld".ToUpper() + "\n";
string str5 = "hello world".Trim();
strA = new string[] { str1, str2, str3, str4, str5 };
ActualResult = string.Concat(strA);
if (ActualResult != MergeStrings(strA))
{
TestLibrary.TestFramework.LogError("015", "Concat object Array with some not nullstrings member two ExpectResult is equel" + MergeStrings(strA) + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTesting
public bool NegTest1()
{
bool retVal = true;
Random rand = new Random(-55);
TestLibrary.TestFramework.BeginScenario("NegTest1: Concat string Array is null");
string[] strA = new string[rand.Next(c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH)];
string ActualResult;
try
{
strA = null;
ActualResult = string.Concat(strA);
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
Random rand = new Random(-55);
string[] strA = new string[50 * 1024 * 1024];
string ActualResult;
TestLibrary.TestFramework.BeginScenario("NegTest2: Concat string Array with many strings");
int TotalLength = 0;
try
{
for (int i = 0; i < strA.Length; i++)
{
strA[i] = "HelloworldHelloworldHelloworldHelloworld!";
TotalLength += strA[i].ToString().Length;
}
ActualResult = string.Concat(strA);
retVal = false;
}
catch (OutOfMemoryException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#region Help method
private string MergeStrings(string[] strS)
{
string ResultString = "";
foreach (string str in strS)
{
if (str == null|| str ==string.Empty )
ResultString += string.Empty;
else
ResultString += str.ToString();
}
return ResultString;
}
#endregion
#endregion
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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 log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Data.SimpleDB;
namespace OpenSim.Region.CoreModules.Avatar.MuteList
{
public class MuteListModule : IRegionModule, IMuteListModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool enabled = true;
private List<Scene> m_SceneList = new List<Scene>();
private string m_RestURL = String.Empty;
private ConnectionFactory _connectionFactory = null;
// Legacy mutes are BY_NAME and have null UUID.
enum MuteType { BY_NAME = 0, AGENT = 1, OBJECT = 2, GROUP = 3, COUNT = 4 };
class MuteListEntry
{
public int m_Type; // MuteType
public string m_Name;
public uint m_Flags;
public MuteListEntry()
{
m_Type = (int)MuteType.AGENT; m_Name = ""; m_Flags = 0;
}
public MuteListEntry(int type, string name, uint flags)
{
m_Type = type; m_Name = name; m_Flags = flags;
}
};
Dictionary<UUID, Dictionary<UUID, MuteListEntry>> MuteListCache = new Dictionary<UUID, Dictionary<UUID, MuteListEntry>>();
public void Initialise(Scene scene, IConfigSource config)
{
if (!enabled)
return;
IConfig cnf = config.Configs["Messaging"];
if (cnf == null)
{
enabled = false;
return;
}
if (cnf != null && cnf.GetString(
"MuteListModule", "None") !=
"MuteListModule")
{
enabled = false;
return;
}
string dbType = cnf.GetString("MuteListDBType");
if (dbType == null)
dbType = "MySQL"; // default
string connStr = cnf.GetString("MuteListConnString");
if (connStr == null)
{ // If the MuteListConnString INI option isn't found, fall back to the one used for profiles.
cnf = config.Configs["Profile"];
connStr = cnf.GetString("ProfileConnString");
}
_connectionFactory = new ConnectionFactory(dbType, connStr);
lock (m_SceneList)
{
if (!m_SceneList.Contains(scene))
m_SceneList.Add(scene);
scene.RegisterModuleInterface<IMuteListModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnRemovePresence += OnRemovePresence;
}
}
public void PostInitialise()
{
if (!enabled)
return;
if (m_SceneList.Count == 0)
return;
// Test the db connection
using (ISimpleDB db = _connectionFactory.GetConnection())
{
}
m_log.Debug("[MUTE LIST] Mute list enabled.");
}
public string Name
{
get { return "MuteListModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
public void Close()
{
}
private void OnNewClient(IClientAPI client)
{
client.OnMuteListRequest += OnMuteListRequest;
client.OnUpdateMuteListEntry += OnUpdateMuteListEntry;
client.OnRemoveMuteListEntry += OnRemoveMuteListEntry;
}
private void OnRemovePresence(UUID AgentId)
{
if (MuteListCache.ContainsKey(AgentId))
MuteListCache.Remove(AgentId);
}
private Dictionary<UUID, MuteListEntry> MapMuteListFromDBResults(List<Dictionary<string, string>> results)
{
Dictionary<UUID, MuteListEntry> MuteList = new Dictionary<UUID, MuteListEntry>();
foreach (Dictionary<string, string> result in results) {
MuteListEntry entry = new MuteListEntry();
UUID MuteID = new UUID(result["MuteID"]);
entry.m_Type = Convert.ToInt32(result["MuteType"]);
entry.m_Name = result["MuteName"];
entry.m_Flags = Convert.ToUInt32(result["MuteFlags"]);
MuteList.Add(MuteID, entry);
}
return MuteList;
}
private Dictionary<UUID,MuteListEntry> DBLoadMuteList(UUID AgentID)
{
using (ISimpleDB db = _connectionFactory.GetConnection())
{
string query = " SELECT AgentID, MuteType, MuteID, MuteName, MuteFlags" +
" FROM mutelist" +
" WHERE " +
" AgentID = ?agentID";
Dictionary<string, object> parms = new Dictionary<string,object>();
parms.Add("?agentID", AgentID);
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
if (results.Count < 1 || results[0]["AgentID"] == null)
return null;
return MapMuteListFromDBResults(results);
}
}
Dictionary<UUID,MuteListEntry> GetMuteList(UUID AgentID)
{
if (MuteListCache.ContainsKey(AgentID))
return MuteListCache[AgentID];
Dictionary<UUID,MuteListEntry> MuteList = DBLoadMuteList(AgentID);
if (MuteList == null) // Mute list is empty for user, return a new empty one
MuteList = new Dictionary<UUID,MuteListEntry>();
MuteListCache.Add(AgentID, MuteList);
return MuteList;
}
/// <summary>
/// This doesn't return the mutelist (mutees) for a user, it returns all users who have this user/object muted (muters).
/// Implemented as a single DB call.
/// </summary>
/// <param name="id">The user or object that may be muted.</param>
/// <returns>UUIDs of those who have it muted.</returns>
public List<UUID> GetInverseMuteList(UUID muteID)
{
List<UUID> muters = new List<UUID>();
using (ISimpleDB db = _connectionFactory.GetConnection())
{
string query = " SELECT * FROM mutelist WHERE MuteID = ?muteID";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?muteID", muteID);
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
if (results.Count < 1 || results[0]["AgentID"] == null)
return muters; // empty list
foreach (Dictionary<string, string> result in results)
{
UUID MuteID = new UUID(result["AgentID"]);
muters.Add(MuteID);
}
}
return muters;
}
/// <summary>
/// Don't use this for messages broadcast to more than one user
/// </summary>
/// <param name="sender"></param>
/// <param name="target"></param>
/// <returns>Returns true if target has sender muted.</returns>
public bool IsMuted(UUID sender, UUID target)
{
List<UUID> muters = new List<UUID>();
using (ISimpleDB db = _connectionFactory.GetConnection())
{
string query = "SELECT COUNT(*) as MuteCount FROM mutelist WHERE AgentID = ?agentID AND MuteID = ?muteID";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?agentID", target);
parms.Add("?muteID", sender);
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
return (Convert.ToInt32(results[0]["MuteCount"]) != 0);
}
}
private void DBStoreMuteListEntry(UUID AgentID, UUID MuteID, MuteListEntry entry, bool isUpdate)
{
using (ISimpleDB db = _connectionFactory.GetConnection())
{
string query;
if (isUpdate)
query = "UPDATE mutelist " +
"SET " +
" MuteType = ?muteType" +
" , MuteName = ?muteName" +
" , MuteFlags= ?muteFlags" +
" WHERE " +
" AgentID = ?agentID AND MuteID = ?muteID";
else
query = "INSERT INTO mutelist " +
"(AgentID, MuteType, MuteID, MuteName, MuteFlags) " +
"VALUES(?AgentID, ?MuteType, ?MuteID, ?MuteName, ?MuteFlags)";
Dictionary<string, object> parms = new Dictionary<string,object>();
parms.Add("?agentID", AgentID);
parms.Add("?muteID", MuteID);
parms.Add("?muteType", entry.m_Type);
parms.Add("?muteName", entry.m_Name);
parms.Add("?muteFlags", entry.m_Flags);
db.QueryNoResults(query, parms);
}
}
private void DBRemoveMuteListEntry(UUID AgentID, UUID MuteID)
{
using (ISimpleDB db = _connectionFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string,object>();
string query = "DELETE FROM mutelist WHERE AgentID = ?agentID AND MuteID = ?muteID";
parms.Add("?agentID", AgentID);
parms.Add("?muteID", MuteID);
db.QueryNoResults(query, parms);
}
}
private byte[] GetMuteListFileData(UUID AgentID)
{
Dictionary<UUID, MuteListEntry> MuteList;
string data = "";
int lines = 0;
MuteList = GetMuteList(AgentID);
foreach (KeyValuePair<UUID, MuteListEntry> pair in MuteList)
{
UUID MuteID = new UUID(pair.Key);
MuteListEntry entry = pair.Value;
if (lines++ != 0)
data += "\n";
data += " "+entry.m_Type.ToString()+
" "+MuteID.ToString()+
" "+entry.m_Name.ToString()+
"|"+entry.m_Flags.ToString();
}
return Utils.StringToBytes(data);
}
private void OnMuteListRequest(IClientAPI client, uint crc)
{
m_log.DebugFormat("[MUTE LIST] List request for crc {0}", crc);
string filename = "mutes"+client.AgentId.ToString();
IXfer xfer = client.Scene.RequestModuleInterface<IXfer>();
if (xfer != null)
{
xfer.AddNewFile(filename, GetMuteListFileData(client.AgentId));
client.SendMuteListUpdate(filename);
}
}
private void OnUpdateMuteListEntry(IClientAPI client, UUID AgentID, int muteType, UUID muteID, string Name, uint muteFlags)
{
Dictionary<UUID, MuteListEntry> MuteList;
bool isUpdate = false;
MuteList = GetMuteList(AgentID);
isUpdate = MuteList.ContainsKey(muteID);
if (isUpdate)
MuteList.Remove(muteID);
switch ((MuteType)muteType)
{
case MuteType.BY_NAME:
m_log.DebugFormat("[MUTE LIST] Update from {0} for name: {1} (ID {2}) flags={3}", AgentID, Name, muteID, muteFlags);
break;
case MuteType.AGENT:
m_log.DebugFormat("[MUTE LIST] Update from {0} for agent: {1} ({2}) flags={3}", AgentID, muteID, Name, muteFlags);
break;
case MuteType.OBJECT:
m_log.DebugFormat("[MUTE LIST] Update from {0} for object: {1} ({2}) flags={3}", AgentID, muteID, Name, muteFlags);
break;
case MuteType.GROUP:
m_log.DebugFormat("[MUTE LIST] Update from {0} for group: {1} ({2}) flags={3}", AgentID, muteID, Name, muteFlags);
break;
case MuteType.COUNT:
m_log.DebugFormat("[MUTE LIST] Update from {0} for count: {1} ({2}) flags={3}", AgentID, muteID, Name, muteFlags);
break;
default:
m_log.ErrorFormat("[MUTE LIST] Update from {0} unknown type {1} with ID {2} Name {3} flags={4}", AgentID, muteType, muteID, Name, muteFlags);
break;
}
MuteListEntry entry = new MuteListEntry(muteType, Name, muteFlags);
MuteList.Add(muteID, entry);
DBStoreMuteListEntry(AgentID, muteID, entry, isUpdate);
}
private void OnRemoveMuteListEntry(IClientAPI client, UUID AgentID, UUID muteID, string name)
{
m_log.DebugFormat("[MUTE LIST] Remove from {0} for ID {1} Name {2}", AgentID, muteID, name);
Dictionary<UUID, MuteListEntry> MuteList;
MuteList = GetMuteList(AgentID);
if (MuteList.ContainsKey(muteID))
{
MuteList.Remove(muteID);
DBRemoveMuteListEntry(AgentID, muteID);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string>
{
private static readonly CultureAwareComparer s_invariantCulture = new CultureAwareComparer(CultureInfo.InvariantCulture, false);
private static readonly CultureAwareComparer s_invariantCultureIgnoreCase = new CultureAwareComparer(CultureInfo.InvariantCulture, true);
private static readonly OrdinalComparer s_ordinal = new OrdinalComparer();
private static readonly OrdinalIgnoreCaseComparer s_ordinalIgnoreCase = new OrdinalIgnoreCaseComparer();
public static StringComparer InvariantCulture
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_invariantCulture;
}
}
public static StringComparer InvariantCultureIgnoreCase
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_invariantCultureIgnoreCase;
}
}
public static StringComparer CurrentCulture
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return new CultureAwareComparer(CultureInfo.CurrentCulture, false);
}
}
public static StringComparer CurrentCultureIgnoreCase
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return new CultureAwareComparer(CultureInfo.CurrentCulture, true);
}
}
public static StringComparer Ordinal
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_ordinal;
}
}
public static StringComparer OrdinalIgnoreCase
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_ordinalIgnoreCase;
}
}
// Convert a StringComparison to a StringComparer
public static StringComparer FromComparison(StringComparison comparisonType)
{
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CurrentCulture;
case StringComparison.CurrentCultureIgnoreCase:
return CurrentCultureIgnoreCase;
case StringComparison.InvariantCulture:
return InvariantCulture;
case StringComparison.InvariantCultureIgnoreCase:
return InvariantCultureIgnoreCase;
case StringComparison.Ordinal:
return Ordinal;
case StringComparison.OrdinalIgnoreCase:
return OrdinalIgnoreCase;
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public static StringComparer Create(CultureInfo culture, bool ignoreCase)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
Contract.Ensures(Contract.Result<StringComparer>() != null);
Contract.EndContractBlock();
return new CultureAwareComparer(culture, ignoreCase);
}
public int Compare(object x, object y)
{
if (x == y) return 0;
if (x == null) return -1;
if (y == null) return 1;
String sa = x as String;
if (sa != null)
{
String sb = y as String;
if (sb != null)
{
return Compare(sa, sb);
}
}
IComparable ia = x as IComparable;
if (ia != null)
{
return ia.CompareTo(y);
}
throw new ArgumentException(SR.Argument_ImplementIComparable);
}
public new bool Equals(Object x, Object y)
{
if (x == y) return true;
if (x == null || y == null) return false;
String sa = x as String;
if (sa != null)
{
String sb = y as String;
if (sb != null)
{
return Equals(sa, sb);
}
}
return x.Equals(y);
}
public int GetHashCode(object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
string s = obj as string;
if (s != null)
{
return GetHashCode(s);
}
return obj.GetHashCode();
}
public abstract int Compare(String x, String y);
public abstract bool Equals(String x, String y);
public abstract int GetHashCode(string obj);
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class CultureAwareComparer : StringComparer
{
private readonly CompareInfo _compareInfo;
private readonly CompareOptions _options;
internal CultureAwareComparer(CultureInfo culture, bool ignoreCase)
{
_compareInfo = culture.CompareInfo;
_options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
}
public override int Compare(string x, string y)
{
if (object.ReferenceEquals(x, y)) return 0;
if (x == null) return -1;
if (y == null) return 1;
return _compareInfo.Compare(x, y, _options);
}
public override bool Equals(string x, string y)
{
if (object.ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
return _compareInfo.Compare(x, y, _options) == 0;
}
public override int GetHashCode(string obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
return _compareInfo.GetHashCodeOfString(obj, _options);
}
// Equals method for the comparer itself.
public override bool Equals(object obj)
{
CultureAwareComparer comparer = obj as CultureAwareComparer;
return
comparer != null &&
_options == comparer._options &&
_compareInfo.Equals(comparer._compareInfo);
}
public override int GetHashCode()
{
int hashCode = _compareInfo.GetHashCode();
return _options == CompareOptions.None ? hashCode : ~hashCode;
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class OrdinalComparer : StringComparer
{
public override int Compare(string x, string y) => string.CompareOrdinal(x, y);
public override bool Equals(string x, string y) => string.Equals(x, y);
public override int GetHashCode(string obj)
{
if (obj == null)
{
#if CORECLR
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
#else
throw new ArgumentNullException(nameof(obj));
#endif
}
return obj.GetHashCode();
}
// Equals/GetHashCode methods for the comparer itself.
public override bool Equals(object obj) => obj is OrdinalComparer;
public override int GetHashCode() => nameof(OrdinalComparer).GetHashCode();
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class OrdinalIgnoreCaseComparer : StringComparer
{
public override int Compare(string x, string y) => string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
public override bool Equals(string x, string y) => string.Equals(x, y, StringComparison.OrdinalIgnoreCase);
public override int GetHashCode(string obj)
{
if (obj == null)
{
#if CORECLR
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
#else
throw new ArgumentNullException(nameof(obj));
#endif
}
return TextInfo.GetHashCodeOrdinalIgnoreCase(obj);
}
// Equals/GetHashCode methods for the comparer itself.
public override bool Equals(object obj) => obj is OrdinalIgnoreCaseComparer;
public override int GetHashCode() => nameof(OrdinalIgnoreCaseComparer).GetHashCode();
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Msagl.Core.DataStructures {
// TODO: Move and expand the commented tests below into PriorityQueueTests unit tests for all 3 PQ classes.
// TODO: Reduce duplication with GenericBinaryHeapPriorityQueue by breaking most functionality out into a
// GenericBinaryHeapPriorityQueue<T, THeapElement> class and using THeapElement.ComparePriority, keeping only Enqueue
// and DecreasePriority in the derived classes as these must know about timestamp.
/// <summary>
/// A generic version priority queue based on the binary heap algorithm where
/// the priority of each element is passed as a parameter and priority ties are broken by timestamp.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public class GenericBinaryHeapPriorityQueueWithTimestamp<T> : IEnumerable<T> {
const int InitialHeapCapacity = 16;
//indexing for A starts from 1
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
//internal void Clear()
//{
// if(heapSize>0)
// {
// for(int i=0;i<cache.Length;i++)
// this.cache[i]=null;
// heapSize=0;
// }
//}
// ReSharper disable InconsistentNaming
GenericHeapElementWithTimestamp<T>[] A;//array of heap elements
// ReSharper restore InconsistentNaming
UInt64 timestamp;
UInt64 NextTimestamp { get { return ++this.timestamp; } }
/// <summary>
/// it is a mapping from queue elements and their correspondent HeapElements
/// </summary>
readonly Dictionary<T, GenericHeapElementWithTimestamp<T>> cache;
internal int Count { get { return heapSize; } }
int heapSize;
internal bool ContainsElement(T key) {
return cache.ContainsKey(key);
}
internal GenericBinaryHeapPriorityQueueWithTimestamp() {
cache = new Dictionary<T, GenericHeapElementWithTimestamp<T>>();
A = new GenericHeapElementWithTimestamp<T>[InitialHeapCapacity + 1];
}
void SwapWithParent(int i) {
var parent = A[i >> 1];
PutAtI(i >> 1, A[i]);
PutAtI(i, parent);
}
internal void Enqueue(T element, double priority) {
if (heapSize == A.Length - 1) {
var newA = new GenericHeapElementWithTimestamp<T>[A.Length * 2];
Array.Copy(A, 1, newA, 1, heapSize);
A = newA;
}
heapSize++;
int i = heapSize;
GenericHeapElementWithTimestamp<T> h;
A[i] = cache[element] = h = new GenericHeapElementWithTimestamp<T>(i, priority, element, this.NextTimestamp);
while (i > 1 && A[i >> 1].ComparePriority(A[i]) > 0) {
SwapWithParent(i);
i >>= 1;
}
System.Diagnostics.Debug.Assert(A[i] == h);
A[i] = h;
}
internal bool IsEmpty() {
return heapSize == 0;
}
void PutAtI(int i, GenericHeapElementWithTimestamp<T> h) {
A[i] = h;
h.indexToA = i;
}
#if TEST_MSAGL
/// <summary>
/// Gets the next element to be dequeued, without dequeueing it.
/// </summary>
internal T Peek() {
if (heapSize == 0) {
throw new InvalidOperationException();
}
return A[1].v;
}
/// <summary>
/// Gets the timestamp of the next element to be dequeued, without dequeueing it.
/// </summary>
internal UInt64 PeekTimestamp() {
if (heapSize == 0) {
throw new InvalidOperationException();
}
return A[1].Timestamp;
}
#endif // TEST_MSAGL
internal T Dequeue() {
if (heapSize == 0)
throw new InvalidOperationException();
var ret = A[1].v;
MoveQueueOneStepForward(ret);
return ret;
}
internal T Dequeue(out double priority) {
if (heapSize == 0) throw new InvalidOperationException();
var ret = A[1].v;
priority = A[1].priority;
MoveQueueOneStepForward(ret);
return ret;
}
void MoveQueueOneStepForward(T ret) {
cache.Remove(ret);
PutAtI(1, A[heapSize]);
int i = 1;
while (true) {
int smallest = i;
int l = i << 1;
if (l <= heapSize && A[l].ComparePriority(A[i]) < 0)
smallest = l;
int r = l + 1;
if (r <= heapSize && A[r].ComparePriority(A[smallest]) < 0)
smallest = r;
if (smallest != i)
SwapWithParent(smallest);
else
break;
i = smallest;
}
heapSize--;
}
/// <summary>
/// sets the object priority to c
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal void DecreasePriority(T element, double newPriority)
{
GenericHeapElementWithTimestamp<T> h;
//ignore the element if it is not in the queue
if (!cache.TryGetValue(element, out h)) return;
//var h = cache[element];
h.priority = newPriority;
int i = h.indexToA;
while (i > 1) {
if (A[i].ComparePriority(A[i >> 1]) < 0)
SwapWithParent(i);
else
break;
i >>= 1;
}
}
///<summary>
///</summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
// public static void Test() {
// Timer nm = new Timer();
// var bound = 1000000;
// nm.Start();
// {
// var q = new BinaryHeapPriorityQueue(bound + 1);
// Random random = new Random();
// for (int i = 0; i < bound; i++) {
// q.Enqueue(i, random.NextDouble());
// }
// for (int i = 0; i < bound; i++) {
// q.DecreasePriority(i, -random.NextDouble());
// }
//
// while (q.IsEmpty() == false) {
// q.Dequeue();
// }
//
// }
// nm.Stop();
// Console.WriteLine(nm.Duration);
// nm.Start();
// {
// var q = new GenericBinaryHeapPriorityQueue<int>();
// Random random = new Random();
// for (int i = 0; i < bound; i++) {
// q.Enqueue(i, random.NextDouble());
// }
// for (int i = 0; i < bound; i++) {
// q.DecreasePriority(i, -random.NextDouble());
// }
//
// while (q.IsEmpty() == false) {
// q.Dequeue();
// }
//
// }
// nm.Stop();
// Console.WriteLine(nm.Duration);
//}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static void Test() {
var q = new GenericBinaryHeapPriorityQueue<int>();
q.Enqueue(2, 2);
q.Enqueue(1, 1);
q.Enqueue(9, 9);
q.Enqueue(8, 8);
q.Enqueue(5, 5);
q.Enqueue(3, 3);
q.Enqueue(4, 4);
q.Enqueue(7, 7);
q.Enqueue(6, 6);
q.Enqueue(0, 0);
q.DecreasePriority(4, 2.5);
while (q.IsEmpty() == false)
Console.WriteLine(q.Dequeue());
}
/// <summary>
/// enumerator
/// </summary>
/// <returns></returns>
public IEnumerator<T> GetEnumerator() {
for (int i = 1; i <= heapSize; i++)
yield return A[i].v;
}
IEnumerator IEnumerable.GetEnumerator() {
for (int i = 1; i <= heapSize; i++)
yield return A[i].v;
}
#if TEST_MSAGL
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString() {
var sb=new StringBuilder();
foreach (var i in this)
sb.Append(i + ",");
return sb.ToString();
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CarrylessMultiplyUInt641()
{
var test = new PclmulqdqOpTest__CarrylessMultiplyUInt641();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Pclmulqdq.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Pclmulqdq.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Pclmulqdq.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class PclmulqdqOpTest__CarrylessMultiplyUInt641
{
private struct TestStruct
{
public Vector128<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(PclmulqdqOpTest__CarrylessMultiplyUInt641 testClass)
{
var result = Pclmulqdq.CarrylessMultiply(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[2] {2, 20};
private static UInt64[] _data2 = new UInt64[2] {25, 95};
private static UInt64[] _expectedRet = new UInt64[2] {500, 0};
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable;
static PclmulqdqOpTest__CarrylessMultiplyUInt641()
{
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public PclmulqdqOpTest__CarrylessMultiplyUInt641()
{
Succeeded = true;
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Pclmulqdq.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Pclmulqdq.CarrylessMultiply(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Pclmulqdq.CarrylessMultiply(
Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Pclmulqdq.CarrylessMultiply(
Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Pclmulqdq.CarrylessMultiply(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Pclmulqdq.CarrylessMultiply(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Pclmulqdq.CarrylessMultiply(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Pclmulqdq.CarrylessMultiply(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new PclmulqdqOpTest__CarrylessMultiplyUInt641();
var result = Pclmulqdq.CarrylessMultiply(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Pclmulqdq.CarrylessMultiply(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Pclmulqdq.CarrylessMultiply(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(void* result, [CallerMemberName] string method = "")
{
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(outArray, method);
}
private void ValidateResult(UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < result.Length; i++)
{
if (result[i] != _expectedRet[i] )
{
succeeded = false;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Pclmulqdq)}.{nameof(Pclmulqdq.CarrylessMultiply)}<UInt64>(Vector128<UInt64>, 1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" expectedRet: ({string.Join(", ", _expectedRet)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Speakr.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. 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.Linq;
using Microsoft.DotNet.ProjectModel.Graph;
using Microsoft.DotNet.ProjectModel.Utilities;
using NuGet.Versioning;
namespace Microsoft.DotNet.ProjectModel.Resolution
{
public class LibraryManager
{
private readonly IList<LibraryDescription> _libraries;
private readonly IList<DiagnosticMessage> _diagnostics;
private readonly string _projectPath;
public LibraryManager(IList<LibraryDescription> libraries,
IList<DiagnosticMessage> diagnostics,
string projectPath)
{
_libraries = libraries;
_diagnostics = diagnostics;
_projectPath = projectPath;
}
public IList<LibraryDescription> GetLibraries()
{
return _libraries;
}
public IList<DiagnosticMessage> GetAllDiagnostics()
{
var messages = new List<DiagnosticMessage>();
if (_diagnostics != null)
{
messages.AddRange(_diagnostics);
}
var dependencies = new Dictionary<string, List<DependencyItem>>();
var topLevel = new List<LibraryItem>();
var platformLibraries = new List<LibraryDescription>();
foreach (var library in GetLibraries())
{
if (!library.Resolved)
{
string message;
string errorCode;
if (library.Compatible)
{
foreach (var range in library.RequestedRanges)
{
errorCode = ErrorCodes.NU1001;
message = $"The dependency {FormatLibraryRange(range)} could not be resolved.";
AddDiagnostics(messages, library, message, DiagnosticMessageSeverity.Error, errorCode);
}
}
else
{
errorCode = ErrorCodes.NU1002;
message = $"The dependency {library.Identity} does not support framework {library.Framework}.";
AddDiagnostics(messages, library, message, DiagnosticMessageSeverity.Error, errorCode);
}
}
else
{
var isPlatform = library.RequestedRanges.Any(r => r.Type.Equals(LibraryDependencyType.Platform));
if (isPlatform)
{
platformLibraries.Add(library);
}
// Store dependency -> library for later
// J.N -> [(R1, P1), (R2, P2)]
foreach (var dependency in library.Dependencies)
{
List<DependencyItem> items;
if (!dependencies.TryGetValue(dependency.Name, out items))
{
items = new List<DependencyItem>();
dependencies[dependency.Name] = items;
}
items.Add(new DependencyItem(dependency, library));
}
foreach (var range in library.RequestedRanges)
{
// Skip libraries that aren't specified in a project.json
// Only report problems for this project
if (string.IsNullOrEmpty(range.SourceFilePath))
{
continue;
}
// We only care about things requested in this project
if (!string.Equals(_projectPath, range.SourceFilePath))
{
continue;
}
if (range.VersionRange == null)
{
// TODO: Show errors/warnings for things without versions
continue;
}
topLevel.Add(new LibraryItem(range, library));
// If we ended up with a declared version that isn't what was asked for directly
// then report a warning
// Case 1: Non floating version and the minimum doesn't match what was specified
// Case 2: Floating version that fell outside of the range
if ((!range.VersionRange.IsFloating &&
range.VersionRange.MinVersion != library.Identity.Version) ||
(range.VersionRange.IsFloating &&
!range.VersionRange.Float.Satisfies(library.Identity.Version)))
{
var message = $"Dependency specified was {FormatLibraryRange(range)} but ended up with {library.Identity}.";
messages.Add(
new DiagnosticMessage(
ErrorCodes.NU1007,
message,
range.SourceFilePath,
DiagnosticMessageSeverity.Warning,
range.SourceLine,
range.SourceColumn,
library));
}
}
}
}
if (platformLibraries.Count > 1)
{
foreach (var platformLibrary in platformLibraries)
{
AddDiagnostics(
messages,
platformLibrary,
"The following dependencies are marked with type 'platform', however only one dependency can have this type: " +
string.Join(", ", platformLibraries.Select(l => l.Identity.Name).ToArray()),
DiagnosticMessageSeverity.Error,
ErrorCodes.DOTNET1013);
}
}
// Version conflicts
foreach (var libraryItem in topLevel)
{
var library = libraryItem.Library;
if (library.Identity.Type != LibraryType.Package)
{
continue;
}
List<DependencyItem> items;
if (dependencies.TryGetValue(library.Identity.Name, out items))
{
foreach (var item in items)
{
var versionRange = item.Dependency.VersionRange;
if (versionRange == null)
{
continue;
}
if (item.Library != library && !versionRange.Satisfies(library.Identity.Version))
{
var message = $"Dependency conflict. {item.Library.Identity} expected {FormatLibraryRange(item.Dependency)} but received {library.Identity.Version}";
messages.Add(
new DiagnosticMessage(
ErrorCodes.NU1012,
message,
libraryItem.RequestedRange.SourceFilePath,
DiagnosticMessageSeverity.Warning,
libraryItem.RequestedRange.SourceLine,
libraryItem.RequestedRange.SourceColumn,
library));
}
}
}
}
return messages;
}
private static string FormatLibraryRange(LibraryRange range)
{
if (range.VersionRange == null)
{
return range.Name;
}
return range.Name + " " + VersionUtility.RenderVersion(range.VersionRange);
}
private void AddDiagnostics(List<DiagnosticMessage> messages,
LibraryDescription library,
string message,
DiagnosticMessageSeverity severity,
string errorCode)
{
// A (in project.json) -> B (unresolved) (not in project.json)
foreach (var source in GetRangesWithSourceLocations(library).Distinct())
{
// We only care about things requested in this project
if (!string.Equals(_projectPath, source.SourceFilePath))
{
continue;
}
messages.Add(
new DiagnosticMessage(
errorCode,
message,
source.SourceFilePath,
severity,
source.SourceLine,
source.SourceColumn,
library));
}
}
private IEnumerable<LibraryRange> GetRangesWithSourceLocations(LibraryDescription library)
{
foreach (var range in library.RequestedRanges)
{
if (!string.IsNullOrEmpty(range.SourceFilePath))
{
yield return range;
}
}
foreach (var parent in library.Parents)
{
foreach (var relevantPath in GetRangesWithSourceLocations(parent))
{
yield return relevantPath;
}
}
}
private struct DependencyItem
{
public LibraryRange Dependency { get; private set; }
public LibraryDescription Library { get; private set; }
public DependencyItem(LibraryRange dependency, LibraryDescription library)
{
Dependency = dependency;
Library = library;
}
}
private struct LibraryItem
{
public LibraryRange RequestedRange { get; private set; }
public LibraryDescription Library { get; private set; }
public LibraryItem(LibraryRange requestedRange, LibraryDescription library)
{
RequestedRange = requestedRange;
Library = library;
}
}
}
}
| |
using System;
using System.Globalization;
#if !BUILDTASK
using Avalonia.Animation.Animators;
#endif
namespace Avalonia.Media
{
/// <summary>
/// An ARGB color.
/// </summary>
#if !BUILDTASK
public
#endif
readonly struct Color : IEquatable<Color>
{
static Color()
{
#if !BUILDTASK
Animation.Animation.RegisterAnimator<ColorAnimator>(prop => typeof(Color).IsAssignableFrom(prop.PropertyType));
#endif
}
/// <summary>
/// Gets the Alpha component of the color.
/// </summary>
public byte A { get; }
/// <summary>
/// Gets the Red component of the color.
/// </summary>
public byte R { get; }
/// <summary>
/// Gets the Green component of the color.
/// </summary>
public byte G { get; }
/// <summary>
/// Gets the Blue component of the color.
/// </summary>
public byte B { get; }
public Color(byte a, byte r, byte g, byte b)
{
A = a;
R = r;
G = g;
B = b;
}
/// <summary>
/// Creates a <see cref="Color"/> from alpha, red, green and blue components.
/// </summary>
/// <param name="a">The alpha component.</param>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <returns>The color.</returns>
public static Color FromArgb(byte a, byte r, byte g, byte b)
{
return new Color(a, r, g, b);
}
/// <summary>
/// Creates a <see cref="Color"/> from red, green and blue components.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <returns>The color.</returns>
public static Color FromRgb(byte r, byte g, byte b)
{
return new Color(0xff, r, g, b);
}
/// <summary>
/// Creates a <see cref="Color"/> from an integer.
/// </summary>
/// <param name="value">The integer value.</param>
/// <returns>The color.</returns>
public static Color FromUInt32(uint value)
{
return new Color(
(byte)((value >> 24) & 0xff),
(byte)((value >> 16) & 0xff),
(byte)((value >> 8) & 0xff),
(byte)(value & 0xff)
);
}
/// <summary>
/// Parses a color string.
/// </summary>
/// <param name="s">The color string.</param>
/// <returns>The <see cref="Color"/>.</returns>
public static Color Parse(string s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
if (TryParse(s, out Color color))
{
return color;
}
throw new FormatException($"Invalid color string: '{s}'.");
}
/// <summary>
/// Parses a color string.
/// </summary>
/// <param name="s">The color string.</param>
/// <returns>The <see cref="Color"/>.</returns>
public static Color Parse(ReadOnlySpan<char> s)
{
if (TryParse(s, out Color color))
{
return color;
}
throw new FormatException($"Invalid color string: '{s.ToString()}'.");
}
/// <summary>
/// Parses a color string.
/// </summary>
/// <param name="s">The color string.</param>
/// <param name="color">The parsed color</param>
/// <returns>The status of the operation.</returns>
public static bool TryParse(string s, out Color color)
{
color = default;
if (s is null)
{
return false;
}
if (s.Length == 0)
{
return false;
}
if (s[0] == '#' && TryParseInternal(s.AsSpan(), out color))
{
return true;
}
var knownColor = KnownColors.GetKnownColor(s);
if (knownColor != KnownColor.None)
{
color = knownColor.ToColor();
return true;
}
return false;
}
/// <summary>
/// Parses a color string.
/// </summary>
/// <param name="s">The color string.</param>
/// <param name="color">The parsed color</param>
/// <returns>The status of the operation.</returns>
public static bool TryParse(ReadOnlySpan<char> s, out Color color)
{
if (s.Length == 0)
{
color = default;
return false;
}
if (s[0] == '#')
{
return TryParseInternal(s, out color);
}
var knownColor = KnownColors.GetKnownColor(s.ToString());
if (knownColor != KnownColor.None)
{
color = knownColor.ToColor();
return true;
}
color = default;
return false;
}
private static bool TryParseInternal(ReadOnlySpan<char> s, out Color color)
{
static bool TryParseCore(ReadOnlySpan<char> input, ref Color color)
{
var alphaComponent = 0u;
if (input.Length == 6)
{
alphaComponent = 0xff000000;
}
else if (input.Length != 8)
{
return false;
}
// TODO: (netstandard 2.1) Can use allocation free parsing.
if (!uint.TryParse(input.ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out var parsed))
{
return false;
}
color = FromUInt32(parsed | alphaComponent);
return true;
}
color = default;
ReadOnlySpan<char> input = s.Slice(1);
// Handle shorthand cases like #FFF (RGB) or #FFFF (ARGB).
if (input.Length == 3 || input.Length == 4)
{
var extendedLength = 2 * input.Length;
#if !BUILDTASK
Span<char> extended = stackalloc char[extendedLength];
#else
char[] extended = new char[extendedLength];
#endif
for (int i = 0; i < input.Length; i++)
{
extended[2 * i + 0] = input[i];
extended[2 * i + 1] = input[i];
}
return TryParseCore(extended, ref color);
}
return TryParseCore(input, ref color);
}
/// <summary>
/// Returns the string representation of the color.
/// </summary>
/// <returns>
/// The string representation of the color.
/// </returns>
public override string ToString()
{
uint rgb = ToUint32();
return KnownColors.GetKnownColorName(rgb) ?? $"#{rgb:x8}";
}
/// <summary>
/// Returns the integer representation of the color.
/// </summary>
/// <returns>
/// The integer representation of the color.
/// </returns>
public uint ToUint32()
{
return ((uint)A << 24) | ((uint)R << 16) | ((uint)G << 8) | (uint)B;
}
/// <summary>
/// Check if two colors are equal.
/// </summary>
public bool Equals(Color other)
{
return A == other.A && R == other.R && G == other.G && B == other.B;
}
public override bool Equals(object? obj)
{
return obj is Color other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = A.GetHashCode();
hashCode = (hashCode * 397) ^ R.GetHashCode();
hashCode = (hashCode * 397) ^ G.GetHashCode();
hashCode = (hashCode * 397) ^ B.GetHashCode();
return hashCode;
}
}
public static bool operator ==(Color left, Color right)
{
return left.Equals(right);
}
public static bool operator !=(Color left, Color right)
{
return !left.Equals(right);
}
}
}
| |
// <copyright file="Proxy.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using Newtonsoft.Json;
namespace OpenQA.Selenium
{
/// <summary>
/// Describes the kind of proxy.
/// </summary>
/// <remarks>
/// Keep these in sync with the Firefox preferences numbers:
/// http://kb.mozillazine.org/Network.proxy.type
/// </remarks>
public enum ProxyKind
{
/// <summary>
/// Direct connection, no proxy (default on Windows).
/// </summary>
Direct = 0,
/// <summary>
/// Manual proxy settings (e.g., for httpProxy).
/// </summary>
Manual,
/// <summary>
/// Proxy automatic configuration from URL.
/// </summary>
ProxyAutoConfigure,
/// <summary>
/// Use proxy automatic detection.
/// </summary>
AutoDetect = 4,
/// <summary>
/// Use the system values for proxy settings (default on Linux).
/// </summary>
System,
/// <summary>
/// No proxy type is specified.
/// </summary>
Unspecified
}
/// <summary>
/// Describes proxy settings to be used with a driver instance.
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class Proxy
{
private ProxyKind proxyKind = ProxyKind.Unspecified;
private bool isAutoDetect;
private string ftpProxyLocation;
private string httpProxyLocation;
private string proxyAutoConfigUrl;
private string sslProxyLocation;
private string socksProxyLocation;
private string socksUserName;
private string socksPassword;
private int? socksVersion;
private List<string> noProxyAddresses = new List<string>();
/// <summary>
/// Initializes a new instance of the <see cref="Proxy"/> class.
/// </summary>
public Proxy()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Proxy"/> class with the given proxy settings.
/// </summary>
/// <param name="settings">A dictionary of settings to use with the proxy.</param>
public Proxy(Dictionary<string, object> settings)
{
if (settings == null)
{
throw new ArgumentNullException(nameof(settings), "settings dictionary cannot be null");
}
if (settings.ContainsKey("proxyType") && settings["proxyType"] != null)
{
// Special-case "PAC" since that is the correct serialization.
if (settings["proxyType"].ToString().ToLowerInvariant() == "pac")
{
this.Kind = ProxyKind.ProxyAutoConfigure;
}
else
{
ProxyKind rawType = (ProxyKind)Enum.Parse(typeof(ProxyKind), settings["proxyType"].ToString(), true);
this.Kind = rawType;
}
}
if (settings.ContainsKey("ftpProxy") && settings["ftpProxy"] != null)
{
this.FtpProxy = settings["ftpProxy"].ToString();
}
if (settings.ContainsKey("httpProxy") && settings["httpProxy"] != null)
{
this.HttpProxy = settings["httpProxy"].ToString();
}
if (settings.ContainsKey("noProxy") && settings["noProxy"] != null)
{
List<string> bypassAddresses = new List<string>();
string addressesAsString = settings["noProxy"] as string;
if (addressesAsString != null)
{
bypassAddresses.AddRange(addressesAsString.Split(';'));
}
else
{
object[] addressesAsArray = settings["noProxy"] as object[];
if (addressesAsArray != null)
{
foreach (object address in addressesAsArray)
{
bypassAddresses.Add(address.ToString());
}
}
}
this.AddBypassAddresses(bypassAddresses);
}
if (settings.ContainsKey("proxyAutoconfigUrl") && settings["proxyAutoconfigUrl"] != null)
{
this.ProxyAutoConfigUrl = settings["proxyAutoconfigUrl"].ToString();
}
if (settings.ContainsKey("sslProxy") && settings["sslProxy"] != null)
{
this.SslProxy = settings["sslProxy"].ToString();
}
if (settings.ContainsKey("socksProxy") && settings["socksProxy"] != null)
{
this.SocksProxy = settings["socksProxy"].ToString();
}
if (settings.ContainsKey("socksUsername") && settings["socksUsername"] != null)
{
this.SocksUserName = settings["socksUsername"].ToString();
}
if (settings.ContainsKey("socksPassword") && settings["socksPassword"] != null)
{
this.SocksPassword = settings["socksPassword"].ToString();
}
if (settings.ContainsKey("socksVersion") && settings["socksVersion"] != null)
{
this.SocksVersion = Convert.ToInt32(settings["socksVersion"]);
}
if (settings.ContainsKey("autodetect") && settings["autodetect"] != null)
{
this.IsAutoDetect = (bool)settings["autodetect"];
}
}
/// <summary>
/// Gets or sets the type of proxy.
/// </summary>
[JsonIgnore]
public ProxyKind Kind
{
get
{
return this.proxyKind;
}
set
{
this.VerifyProxyTypeCompatilibily(value);
this.proxyKind = value;
}
}
/// <summary>
/// Gets the type of proxy as a string for JSON serialization.
/// </summary>
[JsonProperty("proxyType")]
public string SerializableProxyKind
{
get
{
if (this.proxyKind == ProxyKind.ProxyAutoConfigure)
{
return "pac";
}
return this.proxyKind.ToString().ToLowerInvariant();
}
}
/// <summary>
/// Gets or sets a value indicating whether the proxy uses automatic detection.
/// </summary>
[JsonIgnore]
public bool IsAutoDetect
{
get
{
return this.isAutoDetect;
}
set
{
if (this.isAutoDetect == value)
{
return;
}
this.VerifyProxyTypeCompatilibily(ProxyKind.AutoDetect);
this.proxyKind = ProxyKind.AutoDetect;
this.isAutoDetect = value;
}
}
/// <summary>
/// Gets or sets the value of the proxy for the FTP protocol.
/// </summary>
[JsonProperty("ftpProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string FtpProxy
{
get
{
return this.ftpProxyLocation;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.ftpProxyLocation = value;
}
}
/// <summary>
/// Gets or sets the value of the proxy for the HTTP protocol.
/// </summary>
[JsonProperty("httpProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string HttpProxy
{
get
{
return this.httpProxyLocation;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.httpProxyLocation = value;
}
}
/// <summary>
/// Gets the list of address for which to bypass the proxy as an array.
/// </summary>
[JsonProperty("noProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public ReadOnlyCollection<string> BypassProxyAddresses
{
get
{
if (this.noProxyAddresses.Count == 0)
{
return null;
}
return this.noProxyAddresses.AsReadOnly();
}
}
/// <summary>
/// Gets or sets the URL used for proxy automatic configuration.
/// </summary>
[JsonProperty("proxyAutoconfigUrl", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string ProxyAutoConfigUrl
{
get
{
return this.proxyAutoConfigUrl;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.ProxyAutoConfigure);
this.proxyKind = ProxyKind.ProxyAutoConfigure;
this.proxyAutoConfigUrl = value;
}
}
/// <summary>
/// Gets or sets the value of the proxy for the SSL protocol.
/// </summary>
[JsonProperty("sslProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string SslProxy
{
get
{
return this.sslProxyLocation;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.sslProxyLocation = value;
}
}
/// <summary>
/// Gets or sets the value of the proxy for the SOCKS protocol.
/// </summary>
[JsonProperty("socksProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string SocksProxy
{
get
{
return this.socksProxyLocation;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.socksProxyLocation = value;
}
}
/// <summary>
/// Gets or sets the value of username for the SOCKS proxy.
/// </summary>
[JsonProperty("socksUsername", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string SocksUserName
{
get
{
return this.socksUserName;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.socksUserName = value;
}
}
/// <summary>
/// Gets or sets the value of the protocol version for the SOCKS proxy.
/// Value can be <see langword="null"/> if not set.
/// </summary>
[JsonProperty("socksVersion", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public int? SocksVersion
{
get
{
return this.socksVersion;
}
set
{
if (value == null)
{
this.socksVersion = value;
}
else
{
if (value.Value <= 0)
{
throw new ArgumentException("SocksVersion must be a positive integer");
}
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.socksVersion = value;
}
}
}
/// <summary>
/// Gets or sets the value of password for the SOCKS proxy.
/// </summary>
[JsonProperty("socksPassword", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string SocksPassword
{
get
{
return this.socksPassword;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.socksPassword = value;
}
}
/// <summary>
/// Adds a single address to the list of addresses against which the proxy will not be used.
/// </summary>
/// <param name="address">The address to add.</param>
public void AddBypassAddress(string address)
{
if (string.IsNullOrEmpty(address))
{
throw new ArgumentException("address must not be null or empty", nameof(address));
}
this.AddBypassAddresses(address);
}
/// <summary>
/// Adds addresses to the list of addresses against which the proxy will not be used.
/// </summary>
/// <param name="addressesToAdd">An array of addresses to add.</param>
public void AddBypassAddresses(params string[] addressesToAdd)
{
this.AddBypassAddresses(new List<string>(addressesToAdd));
}
/// <summary>
/// Adds addresses to the list of addresses against which the proxy will not be used.
/// </summary>
/// <param name="addressesToAdd">An <see cref="IEnumerable{T}"/> object of arguments to add.</param>
public void AddBypassAddresses(IEnumerable<string> addressesToAdd)
{
if (addressesToAdd == null)
{
throw new ArgumentNullException(nameof(addressesToAdd), "addressesToAdd must not be null");
}
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.noProxyAddresses.AddRange(addressesToAdd);
}
/// <summary>
/// Returns a dictionary suitable for serializing to the W3C Specification
/// dialect of the wire protocol.
/// </summary>
/// <returns>A dictionary suitable for serializing to the W3C Specification
/// dialect of the wire protocol.</returns>
internal Dictionary<string, object> ToCapability()
{
return this.AsDictionary(true);
}
/// <summary>
/// Returns a dictionary suitable for serializing to the OSS dialect of the
/// wire protocol.
/// </summary>
/// <returns>A dictionary suitable for serializing to the OSS dialect of the
/// wire protocol.</returns>
internal Dictionary<string, object> ToLegacyCapability()
{
return this.AsDictionary(false);
}
private Dictionary<string, object> AsDictionary(bool isSpecCompliant)
{
Dictionary<string, object> serializedDictionary = null;
if (this.proxyKind != ProxyKind.Unspecified)
{
serializedDictionary = new Dictionary<string, object>();
if (this.proxyKind == ProxyKind.ProxyAutoConfigure)
{
serializedDictionary["proxyType"] = "pac";
if (!string.IsNullOrEmpty(this.proxyAutoConfigUrl))
{
serializedDictionary["proxyAutoconfigUrl"] = this.proxyAutoConfigUrl;
}
}
else
{
serializedDictionary["proxyType"] = this.proxyKind.ToString().ToLowerInvariant();
}
if (!string.IsNullOrEmpty(this.httpProxyLocation))
{
serializedDictionary["httpProxy"] = this.httpProxyLocation;
}
if (!string.IsNullOrEmpty(this.sslProxyLocation))
{
serializedDictionary["sslProxy"] = this.sslProxyLocation;
}
if (!string.IsNullOrEmpty(this.ftpProxyLocation))
{
serializedDictionary["ftpProxy"] = this.ftpProxyLocation;
}
if (!string.IsNullOrEmpty(this.socksProxyLocation))
{
if (!this.socksVersion.HasValue)
{
throw new InvalidOperationException("Must have a version value set (usually 4 or 5) when specifying a SOCKS proxy");
}
string socksAuth = string.Empty;
if (!string.IsNullOrEmpty(this.socksUserName) && !string.IsNullOrEmpty(this.socksPassword))
{
// TODO: this is probably inaccurate as to how this is supposed
// to look.
socksAuth = this.socksUserName + ":" + this.socksPassword + "@";
}
serializedDictionary["socksProxy"] = socksAuth + this.socksProxyLocation;
serializedDictionary["socksVersion"] = this.socksVersion.Value;
}
if (this.noProxyAddresses.Count > 0)
{
serializedDictionary["noProxy"] = this.GetNoProxyAddressList(isSpecCompliant);
}
}
return serializedDictionary;
}
private object GetNoProxyAddressList(bool isSpecCompliant)
{
object addresses = null;
if (isSpecCompliant)
{
List<object> addressList = new List<object>();
foreach (string address in this.noProxyAddresses)
{
addressList.Add(address);
}
addresses = addressList;
}
else
{
addresses = this.BypassProxyAddresses;
}
return addresses;
}
private void VerifyProxyTypeCompatilibily(ProxyKind compatibleProxy)
{
if (this.proxyKind != ProxyKind.Unspecified && this.proxyKind != compatibleProxy)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
"Specified proxy type {0} is not compatible with current setting {1}",
compatibleProxy.ToString().ToUpperInvariant(),
this.proxyKind.ToString().ToUpperInvariant());
throw new InvalidOperationException(errorMessage);
}
}
}
}
| |
using System;
using System.Globalization;
using System.Text;
using NBitcoin.BouncyCastle.Utilities;
namespace NBitcoin.BouncyCastle.Asn1
{
/**
* Generalized time object.
*/
public class DerGeneralizedTime
: Asn1Object
{
private readonly string time;
/**
* return a generalized time from the passed in object
*
* @exception ArgumentException if the object cannot be converted.
*/
public static DerGeneralizedTime GetInstance(
object obj)
{
if (obj == null || obj is DerGeneralizedTime)
{
return (DerGeneralizedTime)obj;
}
throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj");
}
/**
* return a Generalized Time object from a tagged object.
*
* @param obj the tagged object holding the object we want
* @param explicitly true if the object is meant to be explicitly
* tagged false otherwise.
* @exception ArgumentException if the tagged object cannot
* be converted.
*/
public static DerGeneralizedTime GetInstance(
Asn1TaggedObject obj,
bool isExplicit)
{
Asn1Object o = obj.GetObject();
if (isExplicit || o is DerGeneralizedTime)
{
return GetInstance(o);
}
return new DerGeneralizedTime(((Asn1OctetString)o).GetOctets());
}
/**
* The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z
* for local time, or Z+-HHMM on the end, for difference between local
* time and UTC time. The fractional second amount f must consist of at
* least one number with trailing zeroes removed.
*
* @param time the time string.
* @exception ArgumentException if string is an illegal format.
*/
public DerGeneralizedTime(
string time)
{
this.time = time;
try
{
ToDateTime();
}
catch (FormatException e)
{
throw new ArgumentException("invalid date string: " + e.Message);
}
}
/**
* base constructor from a local time object
*/
public DerGeneralizedTime(
DateTime time)
{
this.time = time.ToString(@"yyyyMMddHHmmss\Z");
}
internal DerGeneralizedTime(
byte[] bytes)
{
//
// explicitly convert to characters
//
this.time = Strings.FromAsciiByteArray(bytes);
}
/**
* Return the time.
* @return The time string as it appeared in the encoded object.
*/
public string TimeString
{
get { return time; }
}
/**
* return the time - always in the form of
* YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm).
* <p>
* Normally in a certificate we would expect "Z" rather than "GMT",
* however adding the "GMT" means we can just use:
* <pre>
* dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
* </pre>
* To read in the time and Get a date which is compatible with our local
* time zone.</p>
*/
public string GetTime()
{
//
// standardise the format.
//
if (time[time.Length - 1] == 'Z')
{
return time.Substring(0, time.Length - 1) + "GMT+00:00";
}
else
{
int signPos = time.Length - 5;
char sign = time[signPos];
if (sign == '-' || sign == '+')
{
return time.Substring(0, signPos)
+ "GMT"
+ time.Substring(signPos, 3)
+ ":"
+ time.Substring(signPos + 3);
}
else
{
signPos = time.Length - 3;
sign = time[signPos];
if (sign == '-' || sign == '+')
{
return time.Substring(0, signPos)
+ "GMT"
+ time.Substring(signPos)
+ ":00";
}
}
}
return time + CalculateGmtOffset();
}
private string CalculateGmtOffset()
{
char sign = '+';
DateTime time = ToDateTime();
#if SILVERLIGHT
long offset = time.Ticks - time.ToUniversalTime().Ticks;
if (offset < 0)
{
sign = '-';
offset = -offset;
}
int hours = (int)(offset / TimeSpan.TicksPerHour);
int minutes = (int)(offset / TimeSpan.TicksPerMinute) % 60;
#else
// Note: GetUtcOffset incorporates Daylight Savings offset
TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(time);
if (offset.CompareTo(TimeSpan.Zero) < 0)
{
sign = '-';
offset = offset.Duration();
}
int hours = offset.Hours;
int minutes = offset.Minutes;
#endif
return "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
}
private static string Convert(
int time)
{
if (time < 10)
{
return "0" + time;
}
return time.ToString();
}
public DateTime ToDateTime()
{
string formatStr;
string d = time;
bool makeUniversal = false;
if (d.EndsWith("Z"))
{
if (HasFractionalSeconds)
{
int fCount = d.Length - d.IndexOf('.') - 2;
formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"\Z";
}
else
{
formatStr = @"yyyyMMddHHmmss\Z";
}
}
else if (time.IndexOf('-') > 0 || time.IndexOf('+') > 0)
{
d = GetTime();
makeUniversal = true;
if (HasFractionalSeconds)
{
int fCount = d.IndexOf("GMT") - 1 - d.IndexOf('.');
formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"'GMT'zzz";
}
else
{
formatStr = @"yyyyMMddHHmmss'GMT'zzz";
}
}
else
{
if (HasFractionalSeconds)
{
int fCount = d.Length - 1 - d.IndexOf('.');
formatStr = @"yyyyMMddHHmmss." + FString(fCount);
}
else
{
formatStr = @"yyyyMMddHHmmss";
}
// TODO?
// dateF.setTimeZone(new SimpleTimeZone(0, TimeZone.getDefault().getID()));
}
return ParseDateString(d, formatStr, makeUniversal);
}
private string FString(
int count)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; ++i)
{
sb.Append('f');
}
return sb.ToString();
}
private DateTime ParseDateString(string s, string format, bool makeUniversal)
{
/*
* NOTE: DateTime.Kind and DateTimeStyles.AssumeUniversal not available in .NET 1.1
*/
DateTimeStyles style = DateTimeStyles.None;
if (format.EndsWith("Z"))
{
try
{
style = (DateTimeStyles)Enum.Parse(typeof(DateTimeStyles), "AssumeUniversal");
}
catch (Exception)
{
}
style |= DateTimeStyles.AdjustToUniversal;
}
DateTime dt = DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, style);
return makeUniversal ? dt.ToUniversalTime() : dt;
}
private bool HasFractionalSeconds
{
get { return time.IndexOf('.') == 14; }
}
private byte[] GetOctets()
{
return Strings.ToAsciiByteArray(time);
}
internal override void Encode(
DerOutputStream derOut)
{
derOut.WriteEncoded(Asn1Tags.GeneralizedTime, GetOctets());
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
DerGeneralizedTime other = asn1Object as DerGeneralizedTime;
if (other == null)
return false;
return this.time.Equals(other.time);
}
protected override int Asn1GetHashCode()
{
return time.GetHashCode();
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace SIL.Windows.Forms.Widgets.BetterGrid
{
#region SilButtonCell class
/// ----------------------------------------------------------------------------------------
/// <summary>
/// Extends the DataGridViewTextBoxCell to include a button on the right side of the cell.
/// Sort of like a combo box cell, only the button can be used to drop-down a custom
/// control.
/// </summary>
/// ----------------------------------------------------------------------------------------
public class PushButtonCell : DataGridViewTextBoxCell
{
private bool _mouseOverButton;
private bool _mouseDownOnButton;
private bool _enabled = true;
/// ------------------------------------------------------------------------------------
/// <summary>
/// Repaint the cell when it's enabled property changes.
/// </summary>
/// ------------------------------------------------------------------------------------
public bool Enabled
{
get { return _enabled; }
set
{
_enabled = value;
DataGridView.InvalidateCell(this);
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the cell's owning SilButtonColumn.
/// </summary>
/// ------------------------------------------------------------------------------------
public PushButtonColumn OwningButtonColumn
{
get
{
if (DataGridView == null || ColumnIndex < 0 || ColumnIndex >=
DataGridView.Columns.Count)
{
return null;
}
return (DataGridView.Columns[ColumnIndex] as PushButtonColumn);
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating whether or not the cell's button should be shown.
/// </summary>
/// ------------------------------------------------------------------------------------
public bool ShowButton
{
get
{
bool owningColShowValue =
(OwningButtonColumn != null && OwningButtonColumn.ShowButton);
var row = DataGridView.CurrentRow;
return (owningColShowValue && RowIndex >= 0 &&
((row == null && DataGridView.AllowUserToAddRows) ||
(row != null && RowIndex == row.Index)));
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating whether or not the specified point is over the cell's
/// radio button. The relativeToCell flag is true when the specified point's origin
/// is relative to the upper right corner of the cell. When false, it's assumed the
/// point's origin is relative to the cell's owning grid control.
/// </summary>
/// ------------------------------------------------------------------------------------
public bool IsPointOverButton(Point pt, bool relativeToCell)
{
// Get the rectangle for the radion button area.
Rectangle rc = DataGridView.GetCellDisplayRectangle(ColumnIndex, RowIndex, false);
Rectangle rcrb;
Rectangle rcText;
GetRectangles(rc, out rcrb, out rcText);
if (relativeToCell)
{
// Set the button's rectangle location
// relative to the cell instead of the grid.
rcrb.X -= rc.X;
rcrb.Y -= rc.Y;
}
return rcrb.Contains(pt);
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnMouseLeave(int rowIndex)
{
base.OnMouseLeave(rowIndex);
_mouseOverButton = false;
DataGridView.InvalidateCell(this);
ManageButtonToolTip();
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnMouseMove(DataGridViewCellMouseEventArgs e)
{
base.OnMouseMove(e);
if (!_enabled)
return;
if (!IsPointOverButton(e.Location, true) && _mouseOverButton)
{
_mouseOverButton = false;
DataGridView.InvalidateCell(this);
ManageButtonToolTip();
}
else if (IsPointOverButton(e.Location, true) && !_mouseOverButton)
{
_mouseOverButton = true;
DataGridView.InvalidateCell(this);
ManageButtonToolTip();
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Monitor when the mouse button goes down over the button.
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnMouseDown(DataGridViewCellMouseEventArgs e)
{
base.OnMouseDown(e);
if (_mouseOverButton && !_mouseDownOnButton)
{
_mouseDownOnButton = true;
DataGridView.InvalidateCell(this);
ManageButtonToolTip();
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Monitor when the user releases the mouse button.
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnMouseUp(DataGridViewCellMouseEventArgs e)
{
_mouseDownOnButton = false;
base.OnMouseUp(e);
DataGridView.InvalidateCell(this);
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
{
if (!IsPointOverButton(e.Location, true) || !ShowButton || IsInEditMode)
{
base.OnMouseClick(e);
return;
}
PushButtonColumn col =
DataGridView.Columns[ColumnIndex] as PushButtonColumn;
if (col != null)
col.InvokeButtonClick(e);
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
private void ManageButtonToolTip()
{
if (OwningButtonColumn != null && _mouseOverButton && !_mouseDownOnButton)
OwningButtonColumn.ShowToolTip();
else
OwningButtonColumn.HideToolTip();
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void Paint(Graphics g, Rectangle clipBounds,
Rectangle bounds, int rowIndex, DataGridViewElementStates state,
object value, object formattedValue, string errorText, DataGridViewCellStyle style,
DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts parts)
{
bool useEllipsisPath = (OwningButtonColumn != null &&
OwningButtonColumn.DrawTextWithEllipsisPath);
if (!ShowButton && !useEllipsisPath)
{
base.Paint(g, clipBounds, bounds, rowIndex, state, value,
formattedValue, errorText, style, advancedBorderStyle, parts);
return;
}
// Draw default everything but text.
parts &= ~DataGridViewPaintParts.ContentForeground;
base.Paint(g, clipBounds, bounds, rowIndex, state, value,
formattedValue, errorText, style, advancedBorderStyle, parts);
// Get the rectangles for the two parts of the cell.
Rectangle rcbtn;
Rectangle rcText;
GetRectangles(bounds, out rcbtn, out rcText);
DrawButton(g, rcbtn);
DrawCellText(g, value as string, style, rcText);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Draws the button in the cell.
/// </summary>
/// ------------------------------------------------------------------------------------
private void DrawButton(Graphics g, Rectangle rcbtn)
{
if (!ShowButton)
return;
var buttonStyle = OwningButtonColumn.ButtonStyle;
if (buttonStyle == PushButtonColumn.ButtonType.MinimalistCombo)
DrawMinimalistButton(g, rcbtn);
else
{
if ((buttonStyle == PushButtonColumn.ButtonType.VisualStyleCombo ||
buttonStyle == PushButtonColumn.ButtonType.VisualStylePush) &&
!DrawVisualStyledButton(buttonStyle, g, rcbtn))
{
DrawPlainButton(buttonStyle, g, rcbtn);
}
}
string buttonText = (OwningButtonColumn == null ?
null : OwningButtonColumn.ButtonText);
if (string.IsNullOrEmpty(buttonText))
return;
var buttonFont = (OwningButtonColumn == null ?
SystemInformation.MenuFont : OwningButtonColumn.ButtonFont);
// Draw text
const TextFormatFlags flags = TextFormatFlags.HorizontalCenter |
TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine |
TextFormatFlags.NoPrefix | TextFormatFlags.EndEllipsis |
TextFormatFlags.NoPadding | TextFormatFlags.PreserveGraphicsClipping;
Color clrText = (_enabled ? SystemColors.ControlText : SystemColors.GrayText);
TextRenderer.DrawText(g, buttonText, buttonFont, rcbtn, clrText, flags);
}
/// ------------------------------------------------------------------------------------
private void DrawMinimalistButton(Graphics g, Rectangle rc)
{
var element = GetVisualStyleComboButton();
rc = AdjustRectToDefaultComboButtonWidth(rc);
if (element != VisualStyleElement.ComboBox.DropDownButton.Normal &&
element != VisualStyleElement.ComboBox.DropDownButton.Disabled &&
BetterGrid.CanPaintVisualStyle(element))
{
var renderer = new VisualStyleRenderer(element);
renderer.DrawBackground(g, rc);
}
else
{
var pen = (element == VisualStyleElement.ComboBox.DropDownButton.Disabled ?
SystemPens.GrayText : SystemPens.WindowText);
var x = rc.X + (int)Math.Round((rc.Width - 7) / 2f, MidpointRounding.AwayFromZero);
var y = rc.Y + (int)Math.Round((rc.Height - 4) / 2f, MidpointRounding.AwayFromZero);
g.DrawLine(pen, x, y, x + 6, y++);
g.DrawLine(pen, x + 1, y, x + 5, y++);
g.DrawLine(pen, x + 2, y, x + 4, y);
g.DrawLine(pen, x + 3, y, x + 3, y + 1);
return;
}
}
/// ------------------------------------------------------------------------------------
private bool DrawVisualStyledButton(PushButtonColumn.ButtonType buttonStyle,
IDeviceContext g, Rectangle rcbtn)
{
VisualStyleElement element = (buttonStyle == PushButtonColumn.ButtonType.VisualStyleCombo ?
GetVisualStyleComboButton() : GetVisualStylePushButton());
if (!BetterGrid.CanPaintVisualStyle(element))
return false;
VisualStyleRenderer renderer = new VisualStyleRenderer(element);
rcbtn = AdjustRectToDefaultComboButtonWidth(rcbtn);
renderer.DrawBackground(g, rcbtn);
return true;
}
/// ------------------------------------------------------------------------------------
private Rectangle AdjustRectToDefaultComboButtonWidth(Rectangle rc)
{
if (!OwningButtonColumn.DrawDefaultComboButtonWidth)
return rc;
var rcNew = rc;
rcNew.Width = SystemInformation.VerticalScrollBarWidth;
rcNew.X = (rc.Right - rcNew.Width);
return rcNew;
}
/// ------------------------------------------------------------------------------------
private void DrawPlainButton(PushButtonColumn.ButtonType type, Graphics g, Rectangle rcbtn)
{
ButtonState state = (_mouseDownOnButton && _mouseOverButton && _enabled ?
ButtonState.Pushed : ButtonState.Normal);
if (!_enabled)
state |= ButtonState.Inactive;
if (type != PushButtonColumn.ButtonType.PlainCombo)
ControlPaint.DrawButton(g, rcbtn, state);
else
{
rcbtn = AdjustRectToDefaultComboButtonWidth(rcbtn);
ControlPaint.DrawComboButton(g, rcbtn, state);
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Draws the cell's text.
/// </summary>
/// ------------------------------------------------------------------------------------
private void DrawCellText(IDeviceContext g, string text, DataGridViewCellStyle style,
Rectangle rcText)
{
if (string.IsNullOrEmpty(text))
return;
// Determine the text's proper foreground color.
Color clrText = SystemColors.GrayText;
if (_enabled && DataGridView != null)
clrText = (Selected ? style.SelectionForeColor : style.ForeColor);
bool useEllipsisPath = (OwningButtonColumn != null &&
OwningButtonColumn.DrawTextWithEllipsisPath);
TextFormatFlags flags = TextFormatFlags.LeftAndRightPadding |
TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine |
TextFormatFlags.NoPrefix | (useEllipsisPath ?
TextFormatFlags.PathEllipsis : TextFormatFlags.EndEllipsis) |
TextFormatFlags.PreserveGraphicsClipping;
TextRenderer.DrawText(g, text, style.Font, rcText, clrText, flags);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the correct visual style push button given the state of the cell.
/// </summary>
/// ------------------------------------------------------------------------------------
private VisualStyleElement GetVisualStylePushButton()
{
VisualStyleElement element = VisualStyleElement.Button.PushButton.Normal;
if (!_enabled)
element = VisualStyleElement.Button.PushButton.Disabled;
else if (_mouseOverButton)
{
element = (_mouseDownOnButton ?
VisualStyleElement.Button.PushButton.Pressed :
VisualStyleElement.Button.PushButton.Hot);
}
return element;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the correct visual style combo button given the state of the cell.
/// </summary>
/// ------------------------------------------------------------------------------------
private VisualStyleElement GetVisualStyleComboButton()
{
VisualStyleElement element = VisualStyleElement.ComboBox.DropDownButton.Normal;
if (!_enabled)
element = VisualStyleElement.ComboBox.DropDownButton.Disabled;
else if (_mouseOverButton)
{
element = (_mouseDownOnButton ?
VisualStyleElement.ComboBox.DropDownButton.Pressed :
VisualStyleElement.ComboBox.DropDownButton.Hot);
}
return element;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the rectangle for the radio button and the text, given the specified cell
/// bounds.
/// </summary>
/// <param name="bounds">The rectangle of the entire cell.</param>
/// <param name="rcbtn">The returned rectangle for the button.</param>
/// <param name="rcText">The returned rectangle for the text.</param>
/// ------------------------------------------------------------------------------------
public void GetRectangles(Rectangle bounds, out Rectangle rcbtn, out Rectangle rcText)
{
if (!ShowButton)
{
rcbtn = Rectangle.Empty;
rcText = bounds;
return;
}
int buttonWidth = (OwningButtonColumn == null ?
SystemInformation.VerticalScrollBarWidth : OwningButtonColumn.ButtonWidth);
bool paintComboButton = (OwningButtonColumn == null ? false :
OwningButtonColumn.ButtonStyle != PushButtonColumn.ButtonType.PlainPush &&
OwningButtonColumn.ButtonStyle != PushButtonColumn.ButtonType.VisualStylePush);
if (paintComboButton)
buttonWidth += 2;
rcText = bounds;
rcText.Width -= buttonWidth;
rcbtn = bounds;
rcbtn.Width = buttonWidth;
rcbtn.X = bounds.Right - buttonWidth - 1;
rcbtn.Y--;
if (paintComboButton)
{
rcbtn.Width -= 2;
rcbtn.Height -= 3;
rcbtn.X++;
rcbtn.Y += 2;
}
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions.Compiler
{
internal partial class StackSpiller
{
/// <summary>
/// Rewrites child expressions, spilling them into temps if needed. The
/// stack starts in the initial state, and after the first subexpression
/// is added it is changed to non-empty.
///
/// When all children have been added, the caller should rewrite the
/// node if Rewrite is true. Then, it should call Finish with either
/// the original expression or the rewritten expression. Finish will call
/// Expression.Block if necessary and return a new Result.
/// </summary>
private sealed class ChildRewriter
{
/// <summary>
/// The parent stack spiller, used to perform rewrites of expressions
/// and to allocate temporary variables.
/// </summary>
private readonly StackSpiller _self;
/// <summary>
/// The child expressions being rewritten.
/// </summary>
private readonly Expression[] _expressions;
/// <summary>
/// The index of the next expression to rewrite in <see cref="_expressions"/>.
/// </summary>
private int _expressionsCount;
/// <summary>
/// The index of the last expression that requires a SpillStack action.
/// </summary>
private int _lastSpillIndex;
/// <summary>
/// The comma of expressions that will evaluate the parent expression
/// using temporary variables introduced by stack spilling. This field
/// is populated in <see cref="EnsureDone"/> which gets called upon
/// the first access to an indexer or the <see cref="Rewrite"/> method
/// on the child rewriter instance. A comma only gets built if the
/// rewrite action in <see cref="_action"/> is set to SpillStack.
/// </summary>
/// <example>
/// When stack spilling the following expression:
/// <c>
/// bar.Foo(try { 42 } finally { ; })
/// </c>
/// the resulting comma will contain three expressions:
/// <c>
/// $temp$0 = bar
/// $temp$1 = try { 42 } finally { ; }
/// $temp$0.Foo($temp$1)
/// </c>
/// These get wrapped in a Block in the <see cref="Rewrite"/> method.
/// </example>
private List<Expression> _comma;
/// <summary>
/// The current computed rewrite action, obtained by OR-ing together
/// the rewrite actions returned from rewriting the child expressions
/// in calls to <see cref="Add(Expression)"/>.
/// </summary>
private RewriteAction _action;
/// <summary>
/// The current computed evaluation stack state. After adding the first
/// child expression through <see cref="Add(Expression)"/>, the state changes from
/// the initial state (provided to the constructor) to non-empty.
/// </summary>
private Stack _stack;
/// <summary>
/// Indicates whether the rewrite has completed. This flag is toggled
/// upon the first access to an indexer or the <see cref="Finish"/>
/// method on the child rewriter instance. Once set to <c>true</c>,
/// calls to <see cref="Add(Expression)"/> are no longer allowed.
/// </summary>
private bool _done;
/// <summary>
/// Indicates whether a child expression represents a ByRef value and
/// requires use of a <see cref="ByRefAssignBinaryExpression" /> node
/// to perform spilling.
/// </summary>
private bool[] _byRefs;
/// <summary>
/// Creates a new child rewriter instance using the specified initial
/// evaluation <paramref name="stack"/> state and the number of child
/// expressions specified in <paramref name="count"/>.
/// </summary>
/// <param name="self">The parent stack spiller.</param>
/// <param name="stack">The initial evaluation stack state.</param>
/// <param name="count">The number of child expressions that will be added.</param>
internal ChildRewriter(StackSpiller self, Stack stack, int count)
{
_self = self;
_stack = stack;
_expressions = new Expression[count];
}
/// <summary>
/// Adds a child <paramref name="expression"/> to the rewriter, causing
/// it to be rewritten using the parent stack spiller, and the evaluation
/// stack state and rewrite action to be updated accordingly.
/// </summary>
/// <param name="expression">The child expression to add.</param>
internal void Add(Expression expression)
{
Debug.Assert(!_done);
if (expression == null)
{
_expressions[_expressionsCount++] = null;
return;
}
Result exp = _self.RewriteExpression(expression, _stack);
_action |= exp.Action;
_stack = Stack.NonEmpty;
if (exp.Action == RewriteAction.SpillStack)
{
_lastSpillIndex = _expressionsCount;
}
// Track items in case we need to copy or spill stack.
_expressions[_expressionsCount++] = exp.Node;
}
/// <summary>
/// Adds child <paramref name="expressions"/> to the rewriter, causing
/// them to be rewritten using the parent stack spiller, and the evaluation
/// stack state and rewrite action to be updated accordingly.
/// </summary>
/// <param name="expressions">The child expressions to add.</param>
internal void Add(ReadOnlyCollection<Expression> expressions)
{
for (int i = 0, count = expressions.Count; i < count; i++)
{
Add(expressions[i]);
}
}
/// <summary>
/// Adds child <paramref name="expressions"/> provided through an argument
/// provider to the rewriter, causing them to be rewritten using the parent
/// stack spiller, and the evaluation stack state and rewrite action to be
/// updated accordingly.
/// </summary>
/// <param name="expressions">
/// The argument provider containing the child expression to add.
/// </param>
internal void AddArguments(IArgumentProvider expressions)
{
for (int i = 0, count = expressions.ArgumentCount; i < count; i++)
{
Add(expressions.GetArgument(i));
}
}
/// <summary>
/// Called after all child expressions have been added using <see cref="Add(Expression)"/>
/// invocations, causing the comma to be populated with the rewritten child
/// expressions and necessary assignments to temporary variables. A comma is
/// only built when the rewrite action is <see cref="RewriteAction.SpillStack"/>.
/// </summary>
/// <example>
/// When stack spilling the following expression:
/// <c>
/// bar.Foo(try { 42 } finally { ; })
/// </c>
/// this method will populate the comma with the rewritten child expressions:
/// <c>
/// $temp$0 = bar
/// $temp$1 = try { 42 } finally { ; }
/// </c>
/// The final expression evaluating <c>bar.Foo(...)</c> will get added by the
/// <see cref="Finish"/> method prior to wrapping the comma in a block
/// expression.
/// </example>
private void EnsureDone()
{
// Done adding child expressions, build the comma if necessary.
if (!_done)
{
_done = true;
if (_action == RewriteAction.SpillStack)
{
Expression[] clone = _expressions;
int count = _lastSpillIndex + 1;
List<Expression> comma = new List<Expression>(count + 1);
for (int i = 0; i < count; i++)
{
Expression current = clone[i];
if (ShouldSaveToTemp(current))
{
Expression temp;
clone[i] = _self.ToTemp(current, out temp, _byRefs?[i] ?? false);
comma.Add(temp);
}
}
comma.Capacity = comma.Count + 1;
_comma = comma;
}
}
}
/// <summary>
/// Checks whether the given <paramref name="expression"/> representing a
/// child expression should be saved in a temporary variable upon spilling
/// the stack. If the expression has no have side-effects, the introduction
/// of a temporary variable can be avoided, reducing the number of locals.
/// </summary>
/// <param name="expression">The expression to check for side-effects.</param>
/// <returns>
/// <c>true</c> if the expression should be saved to a temporary variable;
/// otherwise, <c>false</c>.
/// </returns>
private static bool ShouldSaveToTemp(Expression expression)
{
if (expression == null)
return false;
// Some expressions have no side-effects and don't have to be
// stored into temporaries, e.g.
//
// xs[0] = try { ... }
// |
// v
// t0 = xs
// t1 = 0 // <-- this is redundant
// t2 = try { ... }
// t0[t1] = t2
// |
// v
// t0 = xs
// t1 = try { ... }
// t0[0] = t1
switch (expression.NodeType)
{
// Emits ldnull, ldc, initobj, closure constant access, etc.
case ExpressionType.Constant:
case ExpressionType.Default:
return false;
// Emits calls to pure RuntimeOps methods with immutable arguments
case ExpressionType.RuntimeVariables:
return false;
case ExpressionType.MemberAccess:
var member = (MemberExpression)expression;
var field = member.Member as FieldInfo;
if (field != null)
{
// Emits ldc for the raw value of the field
if (field.IsLiteral)
return false;
// For read-only fields we could save the receiver, but
// that's more involved, so we'll just handle static fields
if (field.IsInitOnly && field.IsStatic)
return false;
}
break;
}
// NB: We omit Lambda because it may interfere with the Invoke/Lambda
// inlining optimizations. Parameter is out too because we don't
// have any sophisticated load/store analysis.
// NB: We omit Quote because the emitted call to RuntimeOps.Quote will
// trigger reduction of extension nodes which can cause the timing
// of exceptions thrown from Reduce methods to change.
return true;
}
/// <summary>
/// Gets a Boolean value indicating whether the parent expression should be
/// rewritten by using <see cref="Finish"/>.
/// </summary>
internal bool Rewrite => _action != RewriteAction.None;
/// <summary>
/// Gets the rewrite action computed from rewriting child expressions during
/// calls to <see cref="Add(Expression)"/>.
/// </summary>
internal RewriteAction Action => _action;
/// <summary>
/// Marks the child expression representing the instance as a ByRef value.
/// </summary>
/// <param name="expr">
/// The child expression representing the instance.
/// </param>
internal void MarkRefInstance(Expression expr)
{
if (IsRefInstance(expr))
{
MarkRef(0);
}
}
/// <summary>
/// Marks child expressions representing arguments bound to parameters of
/// the specified <paramref name="method"/> as ByRef values if needed.
/// </summary>
/// <param name="method">
/// The method containing the parameters bound to the arguments held by
/// child expressions tracked by this rewriter.
/// </param>
/// <param name="startIndex">
/// The index of the child expression representing the first argument. This
/// value is typically 0 for static methods and 1 for instance methods.
/// </param>
internal void MarkRefArgs(MethodBase method, int startIndex)
{
var parameters = method.GetParametersCached();
for (int i = 0, n = parameters.Length; i < n; i++)
{
if (parameters[i].ParameterType.IsByRef)
{
MarkRef(startIndex + i);
}
}
}
/// <summary>
/// Marks the child expression in at the specified <paramref name="index"/>
/// as having a ByRef value.
/// </summary>
/// <param name="index">
/// The index of the child expression holding a ByRef value.
/// </param>
private void MarkRef(int index)
{
if (_byRefs == null)
{
_byRefs = new bool[_expressions.Length];
}
_byRefs[index] = true;
}
/// <summary>
/// Rewrites the parent <paramref name="expression"/> where any stack spilled
/// child expressions have been substituted for temporary variables, and returns
/// the rewrite result to the caller.
/// </summary>
/// <param name="expression">
/// The parent expression after substituting stack spilled child expressions
/// for temporary variables using the indexers on the child rewriter.
/// </param>
/// <returns>
/// The result of rewriting the parent <paramref name="expression"/>, which
/// includes the rewritten expression and the rewrite action. If stack spilling
/// has taken place, the resulting expression is a block expression containing
/// the expressions kept in <see cref="_comma"/>.
/// </returns>
internal Result Finish(Expression expression)
{
EnsureDone();
if (_action == RewriteAction.SpillStack)
{
Debug.Assert(_comma.Capacity == _comma.Count + 1);
_comma.Add(expression);
expression = MakeBlock(_comma);
}
return new Result(_action, expression);
}
/// <summary>
/// Gets the rewritten child expression at the specified <paramref name="index"/>,
/// used to rewrite the parent expression. In case stack spilling has taken place,
/// the returned expression will be a temporary variable.
/// </summary>
/// <param name="index">
/// The index of the child expression to retrieve. Negative values indicate -1-based
/// offsets from the end of the child expressions array. Positive values indicate
/// 0-based offsets from the start of the child expressions array.
/// </param>
/// <returns>
/// The rewritten child expression at the specified <paramref name="index"/>.
/// </returns>
internal Expression this[int index]
{
get
{
EnsureDone();
if (index < 0)
{
index += _expressions.Length;
}
return _expressions[index];
}
}
/// <summary>
/// Gets the rewritten child expressions between the specified <paramref name="first"/>
/// and <paramref name="last"/> (inclusive) indexes, used to rewrite the parent
/// expression. In case stack spilling has taken place, the returned expressions will
/// contain temporary variables.
/// </summary>
/// <param name="first">
/// The index of the first child expression to retrieve. This value should always be
/// positive.
/// </param>
/// <param name="last">
/// The (inclusive) index of the last child expression to retrieve. Negative values
/// indicate -1-based offsets from the end of the child expressions array. Positive values
/// indicate 0-based offsets from the start of the child expressions array.
/// </param>
/// <returns>
/// The rewritten child expressions between the specified <paramref name="first"/>
/// and <paramref name="last"/> (inclusive) indexes.
/// </returns>
internal Expression[] this[int first, int last]
{
get
{
EnsureDone();
if (last < 0)
{
last += _expressions.Length;
}
int count = last - first + 1;
ContractUtils.RequiresArrayRange(_expressions, first, count, nameof(first), nameof(last));
if (count == _expressions.Length)
{
Debug.Assert(first == 0);
// If the entire array is requested just return it so we don't make a new array.
return _expressions;
}
Expression[] clone = new Expression[count];
Array.Copy(_expressions, first, clone, 0, count);
return clone;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.