context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Binary
{
using System;
using System.Collections;
/// <summary>
/// Writer for binary objects.
/// </summary>
public interface IBinaryWriter
{
/// <summary>
/// Write named byte value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte value.</param>
void WriteByte(string fieldName, byte val);
/// <summary>
/// Write named byte array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte array.</param>
void WriteByteArray(string fieldName, byte[] val);
/// <summary>
/// Write named char value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char value.</param>
void WriteChar(string fieldName, char val);
/// <summary>
/// Write named char array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char array.</param>
void WriteCharArray(string fieldName, char[] val);
/// <summary>
/// Write named short value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short value.</param>
void WriteShort(string fieldName, short val);
/// <summary>
/// Write named short array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short array.</param>
void WriteShortArray(string fieldName, short[] val);
/// <summary>
/// Write named int value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int value.</param>
void WriteInt(string fieldName, int val);
/// <summary>
/// Write named int array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int array.</param>
void WriteIntArray(string fieldName, int[] val);
/// <summary>
/// Write named long value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long value.</param>
void WriteLong(string fieldName, long val);
/// <summary>
/// Write named long array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long array.</param>
void WriteLongArray(string fieldName, long[] val);
/// <summary>
/// Write named boolean value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean value.</param>
void WriteBoolean(string fieldName, bool val);
/// <summary>
/// Write named boolean array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean array.</param>
void WriteBooleanArray(string fieldName, bool[] val);
/// <summary>
/// Write named float value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float value.</param>
void WriteFloat(string fieldName, float val);
/// <summary>
/// Write named float array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float array.</param>
void WriteFloatArray(string fieldName, float[] val);
/// <summary>
/// Write named double value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double value.</param>
void WriteDouble(string fieldName, double val);
/// <summary>
/// Write named double array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double array.</param>
void WriteDoubleArray(string fieldName, double[] val);
/// <summary>
/// Write named decimal value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal value.</param>
void WriteDecimal(string fieldName, decimal? val);
/// <summary>
/// Write named decimal array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal array.</param>
void WriteDecimalArray(string fieldName, decimal?[] val);
/// <summary>
/// Write named date value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date value.</param>
void WriteTimestamp(string fieldName, DateTime? val);
/// <summary>
/// Write named date array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date array.</param>
void WriteTimestampArray(string fieldName, DateTime?[] val);
/// <summary>
/// Write named string value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String value.</param>
void WriteString(string fieldName, string val);
/// <summary>
/// Write named string array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String array.</param>
void WriteStringArray(string fieldName, string[] val);
/// <summary>
/// Write named GUID value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID value.</param>
void WriteGuid(string fieldName, Guid? val);
/// <summary>
/// Write named GUID array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID array.</param>
void WriteGuidArray(string fieldName, Guid?[] val);
/// <summary>
/// Write named enum value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum value.</param>
void WriteEnum<T>(string fieldName, T val);
/// <summary>
/// Write named enum array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum array.</param>
void WriteEnumArray<T>(string fieldName, T[] val);
/// <summary>
/// Write named object value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object value.</param>
void WriteObject<T>(string fieldName, T val);
/// <summary>
/// Write named object array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object array.</param>
void WriteArray<T>(string fieldName, T[] val);
/// <summary>
/// Writes a named collection in interoperable form.
///
/// Use this method to communicate with other platforms
/// or with nodes that need to read collection elements in binary form.
///
/// When there is no need for binarization or interoperability, please use <see cref="WriteObject{T}" />,
/// which will properly preserve generic collection type.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Collection.</param>
void WriteCollection(string fieldName, ICollection val);
/// <summary>
/// Writes a named dictionary in interoperable form.
///
/// Use this method to communicate with other platforms
/// or with nodes that need to read dictionary elements in binary form.
///
/// When there is no need for binarization or interoperability, please use <see cref="WriteObject{T}" />,
/// which will properly preserve generic dictionary type.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Dictionary.</param>
void WriteDictionary(string fieldName, IDictionary val);
/// <summary>
/// Get raw writer.
/// </summary>
/// <returns>Raw writer.</returns>
IBinaryRawWriter GetRawWriter();
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Globalization;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.PythonTools.Django {
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute"]' />
/// <devdoc>
/// This attribute associates a file extension to a given editor factory.
/// The editor factory may be specified as either a GUID or a type and
/// is placed on a package.
///
/// This differs from the normal one in that more than one extension can be supplied and
/// a linked editor GUID can be supplied.
/// </devdoc>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
internal sealed class ProvideEditorExtension2Attribute : RegistrationAttribute {
private Guid _factory;
private string _extension;
private int _priority;
private Guid _project;
private string _templateDir;
private int _resId;
private bool _editorFactoryNotify;
private string _editorName;
private Guid _linkedEditorGuid;
private readonly string[] _extensions;
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.ProvideEditorExtensionAttribute"]' />
/// <devdoc>
/// Creates a new attribute.
/// </devdoc>
public ProvideEditorExtension2Attribute(object factoryType, string extension, int priority, params string[] extensions) {
// figure out what type of object they passed in and get the GUID from it
if (factoryType is string)
this._factory = new Guid((string)factoryType);
else if (factoryType is Type)
this._factory = ((Type)factoryType).GUID;
else if (factoryType is Guid)
this._factory = (Guid)factoryType;
else
throw new ArgumentException(string.Format(Resources.Culture, "invalid factory type: {0}", factoryType));
_extension = extension;
_priority = priority;
_project = Guid.Empty;
_templateDir = "";
_resId = 0;
_editorFactoryNotify = false;
_extensions = extensions;
}
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.Extension"]' />
/// <devdoc>
/// The file extension of the file.
/// </devdoc>
public string Extension {
get {
return _extension;
}
}
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.Factory"]' />
/// <devdoc>
/// The editor factory guid.
/// </devdoc>
public Guid Factory {
get {
return _factory;
}
}
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.Priority"]' />
/// <devdoc>
/// The priority of this extension registration.
/// </devdoc>
public int Priority {
get {
return _priority;
}
}
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.ProjectGuid"]/*' />
public string ProjectGuid {
set { _project = new System.Guid(value); }
get { return _project.ToString(); }
}
public string LinkedEditorGuid {
get { return _linkedEditorGuid.ToString(); }
set { _linkedEditorGuid = new System.Guid(value); }
}
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.EditorFactoryNotify"]/*' />
public bool EditorFactoryNotify {
get { return this._editorFactoryNotify; }
set { this._editorFactoryNotify = value; }
}
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.TemplateDir"]/*' />
public string TemplateDir {
get { return _templateDir; }
set { _templateDir = value; }
}
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.NameResourceID"]/*' />
public int NameResourceID {
get { return _resId; }
set { _resId = value; }
}
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.DefaultName"]/*' />
public string DefaultName {
get { return _editorName; }
set { _editorName = value; }
}
/// <summary>
/// The reg key name of this extension.
/// </summary>
private string RegKeyName {
get {
return string.Format(CultureInfo.InvariantCulture, "Editors\\{0}", Factory.ToString("B"));
}
}
/// <summary>
/// The reg key name of the project.
/// </summary>
private string ProjectRegKeyName(RegistrationContext context) {
return string.Format(CultureInfo.InvariantCulture,
"Projects\\{0}\\AddItemTemplates\\TemplateDirs\\{1}",
_project.ToString("B"),
context.ComponentType.GUID.ToString("B"));
}
private string EditorFactoryNotifyKey {
get {
return string.Format(CultureInfo.InvariantCulture, "Projects\\{0}\\FileExtensions\\{1}",
_project.ToString("B"),
Extension);
}
}
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="Register"]' />
/// <devdoc>
/// Called to register this attribute with the given context. The context
/// contains the location where the registration inforomation should be placed.
/// it also contains such as the type being registered, and path information.
///
/// This method is called both for registration and unregistration. The difference is
/// that unregistering just uses a hive that reverses the changes applied to it.
/// </devdoc>
public override void Register(RegistrationContext context) {
using (Key editorKey = context.CreateKey(RegKeyName)) {
if (!string.IsNullOrEmpty(DefaultName)) {
editorKey.SetValue(null, DefaultName);
}
if (0 != _resId)
editorKey.SetValue("DisplayName", "#" + _resId.ToString(CultureInfo.InvariantCulture));
if (_linkedEditorGuid != Guid.Empty) {
editorKey.SetValue("LinkedEditorGuid", _linkedEditorGuid.ToString("B"));
}
editorKey.SetValue("Package", context.ComponentType.GUID.ToString("B"));
}
using (Key extensionKey = context.CreateKey(RegKeyName + "\\Extensions")) {
extensionKey.SetValue(Extension.Substring(1), Priority);
if (_extensions != null && _extensions.Length > 0) {
foreach (var extension in _extensions) {
var extensionAndPri = extension.Split(':');
int pri;
if (extensionAndPri.Length != 2 || !Int32.TryParse(extensionAndPri[1], out pri)) {
throw new InvalidOperationException("Expected extension:priority");
}
extensionKey.SetValue(extensionAndPri[0], pri);
}
}
}
// Build the path of the registry key for the "Add file to project" entry
if (_project != Guid.Empty) {
string prjRegKey = ProjectRegKeyName(context) + "\\/1";
using (Key projectKey = context.CreateKey(prjRegKey)) {
if (0 != _resId)
projectKey.SetValue("", "#" + _resId.ToString(CultureInfo.InvariantCulture));
if (_templateDir.Length != 0) {
Uri url = new Uri(context.ComponentType.Assembly.CodeBase);
string templates = url.LocalPath;
templates = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(templates), _templateDir);
templates = context.EscapePath(System.IO.Path.GetFullPath(templates));
projectKey.SetValue("TemplatesDir", templates);
}
projectKey.SetValue("SortPriority", Priority);
}
}
// Register the EditorFactoryNotify
if (EditorFactoryNotify) {
// The IVsEditorFactoryNotify interface is called by the project system, so it doesn't make sense to
// register it if there is no project associated to this editor.
if (_project == Guid.Empty)
throw new ArgumentException("project");
// Create the registry key
using (Key edtFactoryNotifyKey = context.CreateKey(EditorFactoryNotifyKey)) {
edtFactoryNotifyKey.SetValue("EditorFactoryNotify", Factory.ToString("B"));
}
}
}
/// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="Unregister"]' />
/// <devdoc>
/// Unregister this editor.
/// </devdoc>
/// <param name="context"></param>
public override void Unregister(RegistrationContext context) {
context.RemoveKey(RegKeyName);
if (_project != Guid.Empty) {
context.RemoveKey(ProjectRegKeyName(context));
if (EditorFactoryNotify)
context.RemoveKey(EditorFactoryNotifyKey);
}
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
#nullable disable
using System;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Numerics;
using System.Text;
using Scriban.Functions;
using Scriban.Helpers;
using Scriban.Parsing;
using Scriban.Runtime;
namespace Scriban.Syntax
{
[ScriptSyntax("binary expression", "<expression> operator <expression>")]
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
partial class ScriptBinaryExpression : ScriptExpression
{
private ScriptExpression _left;
private ScriptToken _operatorToken;
private ScriptExpression _right;
public ScriptExpression Left
{
get => _left;
set => ParentToThis(ref _left, value);
}
public ScriptBinaryOperator Operator { get; set; }
public ScriptToken OperatorToken
{
get => _operatorToken;
set => ParentToThis(ref _operatorToken, value);
}
public string OperatorAsText => OperatorToken?.Value ?? Operator.ToText();
public ScriptExpression Right
{
get => _right;
set => ParentToThis(ref _right, value);
}
public override object Evaluate(TemplateContext context)
{
// If we are in scientific mode and we have a function which takes arguments, and is not an explicit call (e.g sin(x) rather then sin * x)
// Then we need to rewrite the call to a proper expression.
if (context.UseScientific)
{
var newExpression = ScientificFunctionCallRewriter.Rewrite(context, this);
if (!ReferenceEquals(newExpression, this))
{
return context.Evaluate(newExpression);
}
}
var leftValue = context.Evaluate(Left);
switch (Operator)
{
case ScriptBinaryOperator.And:
{
var leftBoolValue = context.ToBool(Left.Span, leftValue);
if (!leftBoolValue) return false;
var rightValue = context.Evaluate(Right);
var rightBoolValue = context.ToBool(Right.Span, rightValue);
return leftBoolValue && rightBoolValue;
}
case ScriptBinaryOperator.Or:
{
var leftBoolValue = context.ToBool(Left.Span, leftValue);
if (leftBoolValue) return true;
var rightValue = context.Evaluate(Right);
return context.ToBool(Right.Span, rightValue);
}
default:
{
var rightValue = context.Evaluate(Right);
return Evaluate(context, OperatorToken?.Span ?? Span , Operator, Left.Span, leftValue, Right.Span, rightValue);
}
}
}
public override void PrintTo(ScriptPrinter printer)
{
printer.Write(Left);
// Because a-b is a variable name, we need to transform binary op a-b to a - b
if (Operator == ScriptBinaryOperator.Substract && !printer.PreviousHasSpace)
{
printer.ExpectSpace();
}
if (OperatorToken != null)
{
printer.Write(OperatorToken);
}
else
{
printer.ExpectSpace();
}
if (Operator == ScriptBinaryOperator.Substract)
{
printer.ExpectSpace();
}
printer.Write(Right);
}
public override bool CanHaveLeadingTrivia()
{
return false;
}
public static object Evaluate(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, object leftValue, object rightValue)
{
return Evaluate(context, span, op, span, leftValue, span, rightValue);
}
public static object Evaluate(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, SourceSpan leftSpan, object leftValue, SourceSpan rightSpan, object rightValue)
{
if (op == ScriptBinaryOperator.EmptyCoalescing)
{
return leftValue ?? rightValue;
}
switch (op)
{
case ScriptBinaryOperator.LiquidHasKey:
{
var leftDict = leftValue as IDictionary<string, object>;
if (leftDict != null)
{
return ObjectFunctions.HasKey(leftDict, context.ObjectToString(rightValue));
}
}
break;
case ScriptBinaryOperator.LiquidHasValue:
{
var leftDict = leftValue as IDictionary<string, object>;
if (leftDict != null)
{
return ObjectFunctions.HasValue(leftDict, context.ObjectToString(rightValue));
}
}
break;
case ScriptBinaryOperator.CompareEqual:
case ScriptBinaryOperator.CompareNotEqual:
case ScriptBinaryOperator.CompareGreater:
case ScriptBinaryOperator.CompareLess:
case ScriptBinaryOperator.CompareGreaterOrEqual:
case ScriptBinaryOperator.CompareLessOrEqual:
case ScriptBinaryOperator.Add:
case ScriptBinaryOperator.Substract:
case ScriptBinaryOperator.Multiply:
case ScriptBinaryOperator.Divide:
case ScriptBinaryOperator.DivideRound:
case ScriptBinaryOperator.Modulus:
case ScriptBinaryOperator.Power:
case ScriptBinaryOperator.BinaryAnd:
case ScriptBinaryOperator.BinaryOr:
case ScriptBinaryOperator.ShiftLeft:
case ScriptBinaryOperator.ShiftRight:
case ScriptBinaryOperator.RangeInclude:
case ScriptBinaryOperator.RangeExclude:
case ScriptBinaryOperator.LiquidContains:
case ScriptBinaryOperator.LiquidStartsWith:
case ScriptBinaryOperator.LiquidEndsWith:
try
{
if (leftValue is string || rightValue is string || leftValue is char || rightValue is char)
{
if (leftValue is char leftChar) leftValue = leftChar.ToString(context.CurrentCulture);
if (rightValue is char rightChar) rightValue = rightChar.ToString(CultureInfo.InvariantCulture);
return CalculateToString(context, span, op, leftSpan, leftValue, rightSpan, rightValue);
}
else if (leftValue == EmptyScriptObject.Default || rightValue == EmptyScriptObject.Default)
{
return CalculateEmpty(context, span, op, leftSpan, leftValue, rightSpan, rightValue);
}
// Allow custom binary operation
else if (leftValue is IScriptCustomBinaryOperation leftBinaryOp)
{
if (leftBinaryOp.TryEvaluate(context, span, op, leftSpan, leftValue, rightSpan, rightValue, out var result))
{
return result;
}
break;
}
else if (rightValue is IScriptCustomBinaryOperation rightBinaryOp)
{
if (rightBinaryOp.TryEvaluate(context, span, op, leftSpan, leftValue, rightSpan, rightValue, out var result))
{
return result;
}
break;
}
else
{
return CalculateOthers(context, span, op, leftSpan, leftValue, rightSpan, rightValue);
}
}
catch (Exception ex) when(!(ex is ScriptRuntimeException))
{
throw new ScriptRuntimeException(span, ex.Message);
}
}
throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not supported between `{leftValue}` and `{rightValue}`");
}
private static object CalculateEmpty(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, SourceSpan leftSpan, object leftValue, SourceSpan rightSpan, object rightValue)
{
var leftIsEmptyObject = leftValue == EmptyScriptObject.Default;
var rightIsEmptyObject = rightValue == EmptyScriptObject.Default;
// If both are empty, we return false or empty
if (leftIsEmptyObject && rightIsEmptyObject)
{
switch (op)
{
case ScriptBinaryOperator.CompareEqual:
case ScriptBinaryOperator.CompareGreaterOrEqual:
case ScriptBinaryOperator.CompareLessOrEqual:
return true;
case ScriptBinaryOperator.CompareNotEqual:
case ScriptBinaryOperator.CompareGreater:
case ScriptBinaryOperator.CompareLess:
case ScriptBinaryOperator.LiquidContains:
case ScriptBinaryOperator.LiquidStartsWith:
case ScriptBinaryOperator.LiquidEndsWith:
return false;
}
return EmptyScriptObject.Default;
}
var against = leftIsEmptyObject ? rightValue : leftValue;
var againstEmpty = context.IsEmpty(span, against);
switch (op)
{
case ScriptBinaryOperator.CompareEqual:
return againstEmpty;
case ScriptBinaryOperator.CompareNotEqual:
return againstEmpty is bool ? !(bool)againstEmpty : againstEmpty;
case ScriptBinaryOperator.CompareGreater:
case ScriptBinaryOperator.CompareLess:
return false;
case ScriptBinaryOperator.CompareGreaterOrEqual:
case ScriptBinaryOperator.CompareLessOrEqual:
return againstEmpty;
case ScriptBinaryOperator.Add:
case ScriptBinaryOperator.Substract:
case ScriptBinaryOperator.Multiply:
case ScriptBinaryOperator.Power:
case ScriptBinaryOperator.BinaryOr:
case ScriptBinaryOperator.BinaryAnd:
case ScriptBinaryOperator.Divide:
case ScriptBinaryOperator.DivideRound:
case ScriptBinaryOperator.Modulus:
case ScriptBinaryOperator.RangeInclude:
case ScriptBinaryOperator.RangeExclude:
return EmptyScriptObject.Default;
case ScriptBinaryOperator.LiquidContains:
case ScriptBinaryOperator.LiquidStartsWith:
case ScriptBinaryOperator.LiquidEndsWith:
return false;
}
throw new ScriptRuntimeException(span, $"Operator `{op.ToText()}` is not implemented for `{(leftIsEmptyObject ? "empty" : leftValue)}` / `{(rightIsEmptyObject ? "empty" : rightValue)}`");
}
private static object CalculateToString(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, SourceSpan leftSpan, object left, SourceSpan rightSpan, object right)
{
switch (op)
{
case ScriptBinaryOperator.Add:
return context.ObjectToString(left) + context.ObjectToString(right);
case ScriptBinaryOperator.Multiply:
var spanMultiplier = rightSpan;
if (right is string)
{
var temp = left;
left = right;
right = temp;
spanMultiplier = leftSpan;
}
// Don't fail when converting
int value;
try
{
value = context.ToInt(span, right);
}
catch
{
throw new ScriptRuntimeException(spanMultiplier, $"Expecting an integer. The operator `{op.ToText()}` is not supported for the expression. Only working on string x int or int x string"); // unit test: 112-binary-string-error1
}
var leftText = context.ObjectToString(left);
var builder = new StringBuilder();
for (int i = 0; i < value; i++)
{
builder.Append(leftText);
}
return builder.ToString();
case ScriptBinaryOperator.CompareEqual:
return context.ObjectToString(left) == context.ObjectToString(right);
case ScriptBinaryOperator.CompareNotEqual:
return context.ObjectToString(left) != context.ObjectToString(right);
case ScriptBinaryOperator.CompareGreater:
return context.ObjectToString(left).CompareTo(context.ObjectToString(right)) > 0;
case ScriptBinaryOperator.CompareLess:
return context.ObjectToString(left).CompareTo(context.ObjectToString(right)) < 0;
case ScriptBinaryOperator.CompareGreaterOrEqual:
return context.ObjectToString(left).CompareTo(context.ObjectToString(right)) >= 0;
case ScriptBinaryOperator.CompareLessOrEqual:
return context.ObjectToString(left).CompareTo(context.ObjectToString(right)) <= 0;
case ScriptBinaryOperator.LiquidContains:
return context.ObjectToString(left).Contains(context.ObjectToString(right));
case ScriptBinaryOperator.LiquidStartsWith:
return context.ObjectToString(left).StartsWith(context.ObjectToString(right));
case ScriptBinaryOperator.LiquidEndsWith:
return context.ObjectToString(left).EndsWith(context.ObjectToString(right));
default:
break;
}
// unit test: 150-range-expression-error1.out.txt
throw new ScriptRuntimeException(span, $"Operator `{op.ToText()}` is not supported on string objects"); // unit test: 112-binary-string-error2.txt
}
private static IEnumerable<object> RangeInclude(long left, long right)
{
// unit test: 150-range-expression.txt
if (left < right)
{
for (var i = left; i <= right; i++)
{
yield return FitToBestInteger(i);
}
}
else
{
for (var i = left; i >= right; i--)
{
yield return FitToBestInteger(i);
}
}
}
private static IEnumerable<object> RangeExclude(long left, long right)
{
// unit test: 150-range-expression.txt
if (left < right)
{
for (var i = left; i < right; i++)
{
yield return FitToBestInteger(i);
}
}
else
{
for (var i = left; i > right; i--)
{
yield return FitToBestInteger(i);
}
}
}
private static IEnumerable<object> RangeInclude(BigInteger left, BigInteger right)
{
// unit test: 150-range-expression.txt
if (left < right)
{
for (var i = left; i <= right; i++)
{
yield return FitToBestInteger(i);
}
}
else
{
for (var i = left; i >= right; i--)
{
yield return FitToBestInteger(i);
}
}
}
private static IEnumerable<object> RangeExclude(BigInteger left, BigInteger right)
{
// unit test: 150-range-expression.txt
if (left < right)
{
for (var i = left; i < right; i++)
{
yield return FitToBestInteger(i);
}
}
else
{
for (var i = left; i > right; i--)
{
yield return FitToBestInteger(i);
}
}
}
private static object CalculateOthers(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, SourceSpan leftSpan, object leftValue, SourceSpan rightSpan, object rightValue)
{
// Both values are null, applies the relevant binary ops
if (leftValue == null && rightValue == null)
{
switch (op)
{
case ScriptBinaryOperator.CompareEqual:
return true;
case ScriptBinaryOperator.CompareNotEqual:
return false;
case ScriptBinaryOperator.CompareGreater:
case ScriptBinaryOperator.CompareLess:
case ScriptBinaryOperator.CompareGreaterOrEqual:
case ScriptBinaryOperator.CompareLessOrEqual:
if (context.UseScientific) throw new ScriptRuntimeException(span, $"Both left and right expressions are null. Cannot perform this operation on null values.");
return false;
case ScriptBinaryOperator.Add:
case ScriptBinaryOperator.Substract:
case ScriptBinaryOperator.Multiply:
case ScriptBinaryOperator.Divide:
case ScriptBinaryOperator.Power:
case ScriptBinaryOperator.BinaryOr:
case ScriptBinaryOperator.BinaryAnd:
case ScriptBinaryOperator.ShiftLeft:
case ScriptBinaryOperator.ShiftRight:
case ScriptBinaryOperator.DivideRound:
case ScriptBinaryOperator.Modulus:
case ScriptBinaryOperator.RangeInclude:
case ScriptBinaryOperator.RangeExclude:
if (context.UseScientific) throw new ScriptRuntimeException(span, $"Both left and right expressions are null. Cannot perform this operation on null values.");
return null;
case ScriptBinaryOperator.LiquidContains:
case ScriptBinaryOperator.LiquidStartsWith:
case ScriptBinaryOperator.LiquidEndsWith:
return false;
}
return null;
}
// One value is null
if (leftValue == null || rightValue == null)
{
switch (op)
{
case ScriptBinaryOperator.CompareEqual:
return false;
case ScriptBinaryOperator.CompareNotEqual:
return true;
case ScriptBinaryOperator.CompareGreater:
case ScriptBinaryOperator.CompareLess:
case ScriptBinaryOperator.CompareGreaterOrEqual:
case ScriptBinaryOperator.CompareLessOrEqual:
case ScriptBinaryOperator.LiquidContains:
case ScriptBinaryOperator.LiquidStartsWith:
case ScriptBinaryOperator.LiquidEndsWith:
if (context.UseScientific) throw new ScriptRuntimeException(span, $"The {(leftValue == null ? "left" : "right")} expression is null. Cannot perform this operation on a null value.");
return false;
case ScriptBinaryOperator.Add:
case ScriptBinaryOperator.Substract:
case ScriptBinaryOperator.Multiply:
case ScriptBinaryOperator.Divide:
case ScriptBinaryOperator.DivideRound:
case ScriptBinaryOperator.Power:
case ScriptBinaryOperator.BinaryOr:
case ScriptBinaryOperator.BinaryAnd:
case ScriptBinaryOperator.ShiftLeft:
case ScriptBinaryOperator.ShiftRight:
case ScriptBinaryOperator.Modulus:
case ScriptBinaryOperator.RangeInclude:
case ScriptBinaryOperator.RangeExclude:
if (context.UseScientific) throw new ScriptRuntimeException(span, $"The {(leftValue == null ? "left" : "right")} expression is null. Cannot perform this operation on a null value.");
return null;
}
return null;
}
var leftType = leftValue.GetType();
var rightType = rightValue.GetType();
// The order matters: decimal, double, float, long, int
if (leftType == typeof(decimal))
{
var rightDecimal = (decimal)context.ToObject(span, rightValue, typeof(decimal));
return CalculateDecimal(op, span, (decimal)leftValue, rightDecimal);
}
if (rightType == typeof(decimal))
{
var leftDecimal = (decimal)context.ToObject(span, leftValue, typeof(decimal));
return CalculateDecimal(op, span, leftDecimal, (decimal)rightValue);
}
if (leftType == typeof(double))
{
var rightDouble = (double)context.ToObject(span, rightValue, typeof(double));
return CalculateDouble(op, span, (double)leftValue, rightDouble);
}
if (rightType == typeof(double))
{
var leftDouble = (double)context.ToObject(span, leftValue, typeof(double));
return CalculateDouble(op, span, leftDouble, (double)rightValue);
}
if (leftType == typeof(float))
{
var rightFloat = (float)context.ToObject(span, rightValue, typeof(float));
return CalculateFloat(op, span, (float)leftValue, rightFloat);
}
if (rightType == typeof(float))
{
var leftFloat = (float)context.ToObject(span, leftValue, typeof(float));
return CalculateFloat(op, span, leftFloat, (float)rightValue);
}
if (leftType == typeof(BigInteger))
{
var rightBig = (BigInteger)context.ToObject(span, rightValue, typeof(BigInteger));
return CalculateBigInteger(op, span, (BigInteger)leftValue, rightBig);
}
if (rightType == typeof(BigInteger))
{
var leftBig = (BigInteger)context.ToObject(span, leftValue, typeof(BigInteger));
return CalculateBigInteger(op, span, leftBig, (BigInteger)rightValue);
}
if (leftType == typeof(long))
{
var rightLong = (long)context.ToObject(span, rightValue, typeof(long));
return CalculateLong(op, span, (long)leftValue, rightLong);
}
if (rightType == typeof(long))
{
var leftLong = (long)context.ToObject(span, leftValue, typeof(long));
return CalculateLong(op, span, leftLong, (long)rightValue);
}
if (leftType == typeof(long))
{
var rightLong = (long)context.ToObject(span, rightValue, typeof(long));
return CalculateLong(op, span, (long)leftValue, rightLong);
}
if (rightType == typeof(long))
{
var leftLong = (long)context.ToObject(span, leftValue, typeof(long));
return CalculateLong(op, span, leftLong, (long)rightValue);
}
if (leftType == typeof(int) || (leftType != null && leftType.IsEnum))
{
var rightInt = (int)context.ToObject(span, rightValue, typeof(int));
return CalculateInt(op, span, (int)leftValue, rightInt);
}
if (rightType == typeof(int) || (rightType != null && rightType.IsEnum))
{
var leftInt = (int)context.ToObject(span, leftValue, typeof(int));
return CalculateInt(op, span, leftInt, (int)rightValue);
}
if (leftType == typeof(bool))
{
var rightBool = (bool)context.ToObject(span, rightValue, typeof(bool));
return CalculateBool(op, span, (bool)leftValue, rightBool);
}
if (rightType == typeof(bool))
{
var leftBool = (bool)context.ToObject(span, leftValue, typeof(bool));
return CalculateBool(op, span, leftBool, (bool)rightValue);
}
if (leftType == typeof(DateTime) && rightType == typeof(DateTime))
{
return CalculateDateTime(op, span, (DateTime)leftValue, (DateTime)rightValue);
}
if (leftType == typeof(DateTime) && rightType == typeof(TimeSpan))
{
return CalculateDateTime(op, span, (DateTime)leftValue, (TimeSpan)rightValue);
}
//allows to check equality for objects with not only primitive types
if (op == ScriptBinaryOperator.CompareEqual)
{
return leftValue.Equals(rightValue);
}
throw new ScriptRuntimeException(span, $"Unsupported types `{leftValue}/{context.GetTypeName(leftValue)}` {op.ToText()} `{rightValue}/{context.GetTypeName(rightValue)}` for binary operation");
}
private static object CalculateInt(ScriptBinaryOperator op, SourceSpan span, int left, int right)
{
return FitToBestInteger(CalculateLongWithInt(op, span, left, right));
}
private static object FitToBestInteger(object value)
{
if (value is int) return value;
if (value is long longValue)
{
return FitToBestInteger(longValue);
}
if (value is BigInteger bigInt)
{
return FitToBestInteger(bigInt);
}
return value;
}
private static object FitToBestInteger(long longValue)
{
if (longValue >= int.MinValue && longValue <= int.MaxValue) return (int)longValue;
return longValue;
}
private static object FitToBestInteger(BigInteger bigInt)
{
if (bigInt >= int.MinValue && bigInt <= int.MaxValue) return (int)bigInt;
if (bigInt >= long.MinValue && bigInt <= long.MaxValue) return (long)bigInt;
return bigInt;
}
/// <summary>
/// Use this value as a maximum integer
/// </summary>
private static readonly BigInteger MaxBigInteger = BigInteger.One << 1024 * 1024;
private static object CalculateLongWithInt(ScriptBinaryOperator op, SourceSpan span, int leftInt, int rightInt)
{
long left = leftInt;
long right = rightInt;
switch (op)
{
case ScriptBinaryOperator.Add:
return left + right;
case ScriptBinaryOperator.Substract:
return left - right;
case ScriptBinaryOperator.Multiply:
return left * right;
case ScriptBinaryOperator.Divide:
return (double)left / (double)right;
case ScriptBinaryOperator.DivideRound:
return left / right;
case ScriptBinaryOperator.ShiftLeft:
return (BigInteger)left << (int)right;
case ScriptBinaryOperator.ShiftRight:
return (BigInteger)left >> (int)right;
case ScriptBinaryOperator.Power:
if (right < 0)
{
return Math.Pow(left, right);
}
else
{
return BigInteger.ModPow(left, right, MaxBigInteger);
}
case ScriptBinaryOperator.BinaryOr:
return left | right;
case ScriptBinaryOperator.BinaryAnd:
return left & right;
case ScriptBinaryOperator.Modulus:
return left % right;
case ScriptBinaryOperator.CompareEqual:
return left == right;
case ScriptBinaryOperator.CompareNotEqual:
return left != right;
case ScriptBinaryOperator.CompareGreater:
return left > right;
case ScriptBinaryOperator.CompareLess:
return left < right;
case ScriptBinaryOperator.CompareGreaterOrEqual:
return left >= right;
case ScriptBinaryOperator.CompareLessOrEqual:
return left <= right;
case ScriptBinaryOperator.RangeInclude:
return new ScriptRange(RangeInclude(left, right));
case ScriptBinaryOperator.RangeExclude:
return new ScriptRange(RangeExclude(left, right));
}
throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not implemented for long<->long");
}
private static object CalculateLong(ScriptBinaryOperator op, SourceSpan span, long left, long right)
{
return CalculateBigInteger(op, span, new BigInteger(left), new BigInteger(right));
}
private static object CalculateBigInteger(ScriptBinaryOperator op, SourceSpan span, BigInteger left, BigInteger right)
{
return FitToBestInteger(CalculateBigIntegerNoFit(op, span, left, right));
}
private static object CalculateBigIntegerNoFit(ScriptBinaryOperator op, SourceSpan span, BigInteger left, BigInteger right)
{
switch (op)
{
case ScriptBinaryOperator.Add:
return left + right;
case ScriptBinaryOperator.Substract:
return left - right;
case ScriptBinaryOperator.Multiply:
return left * right;
case ScriptBinaryOperator.Divide:
return (double)left / (double)right;
case ScriptBinaryOperator.DivideRound:
return left / right;
case ScriptBinaryOperator.ShiftLeft:
return left << (int)right;
case ScriptBinaryOperator.ShiftRight:
return left >> (int)right;
case ScriptBinaryOperator.Power:
if (right < 0)
{
return Math.Pow((double)left, (double)right);
}
else
{
return BigInteger.ModPow(left, right, MaxBigInteger);
}
case ScriptBinaryOperator.BinaryOr:
return left | right;
case ScriptBinaryOperator.BinaryAnd:
return left & right;
case ScriptBinaryOperator.Modulus:
return left % right;
case ScriptBinaryOperator.CompareEqual:
return left == right;
case ScriptBinaryOperator.CompareNotEqual:
return left != right;
case ScriptBinaryOperator.CompareGreater:
return left > right;
case ScriptBinaryOperator.CompareLess:
return left < right;
case ScriptBinaryOperator.CompareGreaterOrEqual:
return left >= right;
case ScriptBinaryOperator.CompareLessOrEqual:
return left <= right;
case ScriptBinaryOperator.RangeInclude:
return new ScriptRange(RangeInclude(left, right));
case ScriptBinaryOperator.RangeExclude:
return new ScriptRange(RangeExclude(left, right));
}
throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not implemented for long<->long");
}
private static object CalculateDouble(ScriptBinaryOperator op, SourceSpan span, double left, double right)
{
switch (op)
{
case ScriptBinaryOperator.Add:
return left + right;
case ScriptBinaryOperator.Substract:
return left - right;
case ScriptBinaryOperator.Multiply:
return left * right;
case ScriptBinaryOperator.Divide:
return left / right;
case ScriptBinaryOperator.DivideRound:
return Math.Round(left / right);
case ScriptBinaryOperator.ShiftLeft:
return left * Math.Pow(2, right);
case ScriptBinaryOperator.ShiftRight:
return left / Math.Pow(2, right);
case ScriptBinaryOperator.Power:
return Math.Pow(left, right);
case ScriptBinaryOperator.Modulus:
return left % right;
case ScriptBinaryOperator.CompareEqual:
return left == right;
case ScriptBinaryOperator.CompareNotEqual:
return left != right;
case ScriptBinaryOperator.CompareGreater:
return left > right;
case ScriptBinaryOperator.CompareLess:
return left < right;
case ScriptBinaryOperator.CompareGreaterOrEqual:
return left >= right;
case ScriptBinaryOperator.CompareLessOrEqual:
return left <= right;
}
throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not implemented for double<->double");
}
private static object CalculateDecimal(ScriptBinaryOperator op, SourceSpan span, decimal left, decimal right)
{
switch (op)
{
case ScriptBinaryOperator.Add:
return left + right;
case ScriptBinaryOperator.Substract:
return left - right;
case ScriptBinaryOperator.Multiply:
return left * right;
case ScriptBinaryOperator.Divide:
return left / right;
case ScriptBinaryOperator.DivideRound:
return Math.Round(left / right);
case ScriptBinaryOperator.ShiftLeft:
return left * (decimal) Math.Pow(2, (double) right);
case ScriptBinaryOperator.ShiftRight:
return left / (decimal) Math.Pow(2, (double) right);
case ScriptBinaryOperator.Power:
return (decimal)Math.Pow((double)left, (double)right);
case ScriptBinaryOperator.Modulus:
return left % right;
case ScriptBinaryOperator.CompareEqual:
return left == right;
case ScriptBinaryOperator.CompareNotEqual:
return left != right;
case ScriptBinaryOperator.CompareGreater:
return left > right;
case ScriptBinaryOperator.CompareLess:
return left < right;
case ScriptBinaryOperator.CompareGreaterOrEqual:
return left >= right;
case ScriptBinaryOperator.CompareLessOrEqual:
return left <= right;
}
throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not implemented for decimal<->decimal");
}
private static object CalculateFloat(ScriptBinaryOperator op, SourceSpan span, float left, float right)
{
switch (op)
{
case ScriptBinaryOperator.Add:
return left + right;
case ScriptBinaryOperator.Substract:
return left - right;
case ScriptBinaryOperator.Multiply:
return left * right;
case ScriptBinaryOperator.Divide:
return (float)left / right;
case ScriptBinaryOperator.DivideRound:
return (float)(int)(left / right);
#if NETSTANDARD2_1
case ScriptBinaryOperator.Power:
return MathF.Pow(left, right);
#else
case ScriptBinaryOperator.Power:
return (float)Math.Pow(left, right);
#endif
#if NETSTANDARD2_1
case ScriptBinaryOperator.ShiftLeft:
return left * (float)MathF.Pow(2.0f, right);
case ScriptBinaryOperator.ShiftRight:
return left / (float)MathF.Pow(2.0f, right);
#else
case ScriptBinaryOperator.ShiftLeft:
return left * (float)Math.Pow(2, right);
case ScriptBinaryOperator.ShiftRight:
return left / (float)Math.Pow(2, right);
#endif
case ScriptBinaryOperator.Modulus:
return left % right;
case ScriptBinaryOperator.CompareEqual:
return left == right;
case ScriptBinaryOperator.CompareNotEqual:
return left != right;
case ScriptBinaryOperator.CompareGreater:
return left > right;
case ScriptBinaryOperator.CompareLess:
return left < right;
case ScriptBinaryOperator.CompareGreaterOrEqual:
return left >= right;
case ScriptBinaryOperator.CompareLessOrEqual:
return left <= right;
}
throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not implemented for float<->float");
}
private static object CalculateDateTime(ScriptBinaryOperator op, SourceSpan span, DateTime left, DateTime right)
{
switch (op)
{
case ScriptBinaryOperator.Substract:
return left - right;
case ScriptBinaryOperator.CompareEqual:
return left == right;
case ScriptBinaryOperator.CompareNotEqual:
return left != right;
case ScriptBinaryOperator.CompareLess:
return left < right;
case ScriptBinaryOperator.CompareLessOrEqual:
return left <= right;
case ScriptBinaryOperator.CompareGreater:
return left > right;
case ScriptBinaryOperator.CompareGreaterOrEqual:
return left >= right;
}
throw new ScriptRuntimeException(span, $"The operator `{op}` is not supported for DateTime");
}
private static object CalculateDateTime(ScriptBinaryOperator op, SourceSpan span, DateTime left, TimeSpan right)
{
switch (op)
{
case ScriptBinaryOperator.Add:
return left + right;
}
throw new ScriptRuntimeException(span, $"The operator `{op}` is not supported for between <DateTime> and <TimeSpan>");
}
private static object CalculateBool(ScriptBinaryOperator op, SourceSpan span, bool left, bool right)
{
switch (op)
{
case ScriptBinaryOperator.CompareEqual:
return left == right;
case ScriptBinaryOperator.CompareNotEqual:
return left != right;
}
throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not valid for bool<->bool");
}
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
/*
* AvaTax API Client Library
*
* (c) 2004-2018 Avalara, Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Ted Spence
* @author Zhenya Frolov
* @author Greg Hester
*/
namespace Avalara.AvaTax.RestClient
{
/// <summary>
/// Filing Returns Model
/// </summary>
public class FilingReturnModelBasic
{
/// <summary>
/// The unique ID number of the company filing return.
/// </summary>
public Int64? companyId { get; set; }
/// <summary>
/// The unique ID number of this filing return.
/// </summary>
public Int64? id { get; set; }
/// <summary>
/// The filing id that this return belongs too
/// </summary>
public Int64? filingId { get; set; }
/// <summary>
/// The resourceFileId of the return
/// </summary>
public Int64? resourceFileId { get; set; }
/// <summary>
/// The region id that this return belongs too
/// </summary>
public Int64? filingRegionId { get; set; }
/// <summary>
/// The unique ID number of the filing calendar associated with this return.
/// </summary>
public Int64? filingCalendarId { get; set; }
/// <summary>
/// The country of the form.
/// </summary>
public String country { get; set; }
/// <summary>
/// The region of the form.
/// </summary>
public String region { get; set; }
/// <summary>
/// The month of the filing period for this tax filing.
/// The filing period represents the year and month of the last day of taxes being reported on this filing.
/// For example, an annual tax filing for Jan-Dec 2015 would have a filing period of Dec 2015.
/// </summary>
public Int32? endPeriodMonth { get; set; }
/// <summary>
/// The year of the filing period for this tax filing.
/// The filing period represents the year and month of the last day of taxes being reported on this filing.
/// For example, an annual tax filing for Jan-Dec 2015 would have a filing period of Dec 2015.
/// </summary>
public Int16? endPeriodYear { get; set; }
/// <summary>
/// The current status of the filing return.
/// </summary>
public FilingStatusId? status { get; set; }
/// <summary>
/// The filing frequency of the return.
/// </summary>
public FilingFrequencyId? filingFrequency { get; set; }
/// <summary>
/// The date the return was filed by Avalara.
/// </summary>
public DateTime? filedDate { get; set; }
/// <summary>
/// The sales amount.
/// </summary>
public Decimal? salesAmount { get; set; }
/// <summary>
/// The filing type of the return.
/// </summary>
public FilingTypeId? filingType { get; set; }
/// <summary>
/// The name of the form.
/// </summary>
public String formName { get; set; }
/// <summary>
/// The remittance amount of the return.
/// </summary>
public Decimal? remitAmount { get; set; }
/// <summary>
/// The unique code of the form.
/// </summary>
public String formCode { get; set; }
/// <summary>
/// A description for the return.
/// </summary>
public String description { get; set; }
/// <summary>
/// The taxable amount.
/// </summary>
public Decimal? taxableAmount { get; set; }
/// <summary>
/// The tax amount.
/// </summary>
public Decimal? taxAmount { get; set; }
/// <summary>
/// The amount collected by avalara for this return
/// </summary>
public Decimal? collectAmount { get; set; }
/// <summary>
/// The tax due amount.
/// </summary>
public Decimal? taxDueAmount { get; set; }
/// <summary>
/// The non-taxable amount.
/// </summary>
public Decimal? nonTaxableAmount { get; set; }
/// <summary>
/// The non-taxable due amount.
/// </summary>
public Decimal? nonTaxableDueAmount { get; set; }
/// <summary>
/// Consumer use tax liability.
/// </summary>
public Decimal? consumerUseTaxAmount { get; set; }
/// <summary>
/// Consumer use non-taxable amount.
/// </summary>
public Decimal? consumerUseNonTaxableAmount { get; set; }
/// <summary>
/// Consumer use taxable amount.
/// </summary>
public Decimal? consumerUseTaxableAmount { get; set; }
/// <summary>
/// The amount of sales excluded from the liability calculation
/// </summary>
public Decimal? excludedSalesAmount { get; set; }
/// <summary>
/// The amount of non-taxable sales excluded from the liability calculation
/// </summary>
public Decimal? excludedNonTaxableAmount { get; set; }
/// <summary>
/// The amount of tax excluded from the liability calculation
/// </summary>
public Decimal? excludedTaxAmount { get; set; }
/// <summary>
/// Accrual type of the return
/// </summary>
public AccrualType? accrualType { get; set; }
/// <summary>
/// The attachments for this return.
/// </summary>
public List<FilingAttachmentModel> attachments { get; set; }
/// <summary>
/// The date when this record was created.
/// </summary>
public DateTime? createdDate { get; set; }
/// <summary>
/// The User ID of the user who created this record.
/// </summary>
public Int32? createdUserId { get; set; }
/// <summary>
/// The date/time when this record was last modified.
/// </summary>
public DateTime? modifiedDate { get; set; }
/// <summary>
/// Convert this object to a JSON string of itself
/// </summary>
/// <returns>A JSON string of this object</returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
}
}
}
| |
// 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.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Xml;
using MSS = Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Server;
namespace System.Data.SqlClient
{
using Res = System.SR;
internal abstract class DataFeed
{
}
internal class StreamDataFeed : DataFeed
{
internal Stream _source;
internal StreamDataFeed(Stream source)
{
_source = source;
}
}
internal class TextDataFeed : DataFeed
{
internal TextReader _source;
internal TextDataFeed(TextReader source)
{
_source = source;
}
}
internal class XmlDataFeed : DataFeed
{
internal XmlReader _source;
internal XmlDataFeed(XmlReader source)
{
_source = source;
}
}
public sealed partial class SqlParameter : DbParameter
{
private MetaType _metaType;
private SqlCollation _collation;
private string _xmlSchemaCollectionDatabase;
private string _xmlSchemaCollectionOwningSchema;
private string _xmlSchemaCollectionName;
private string _typeName;
private string _parameterName;
private byte _precision;
private byte _scale;
private bool _hasScale; // V1.0 compat, ignore _hasScale
private MetaType _internalMetaType;
private SqlBuffer _sqlBufferReturnValue;
private INullable _valueAsINullable;
private bool _isSqlParameterSqlType;
private bool _isNull = true;
private bool _coercedValueIsSqlType;
private bool _coercedValueIsDataFeed;
private int _actualSize = -1;
public SqlParameter() : base()
{
}
public SqlParameter(string parameterName, SqlDbType dbType) : this()
{
this.ParameterName = parameterName;
this.SqlDbType = dbType;
}
public SqlParameter(string parameterName, object value) : this()
{
Debug.Assert(!(value is SqlDbType), "use SqlParameter(string, SqlDbType)");
this.ParameterName = parameterName;
this.Value = value;
}
public SqlParameter(string parameterName, SqlDbType dbType, int size) : this()
{
this.ParameterName = parameterName;
this.SqlDbType = dbType;
this.Size = size;
}
public SqlParameter(string parameterName, SqlDbType dbType, int size, string sourceColumn) : this()
{
this.ParameterName = parameterName;
this.SqlDbType = dbType;
this.Size = size;
this.SourceColumn = sourceColumn;
}
//
// currently the user can't set this value. it gets set by the returnvalue from tds
//
internal SqlCollation Collation
{
get
{
return _collation;
}
set
{
_collation = value;
}
}
public SqlCompareOptions CompareInfo
{
// Bits 21 through 25 represent the CompareInfo
get
{
SqlCollation collation = _collation;
if (null != collation)
{
return collation.SqlCompareOptions;
}
return SqlCompareOptions.None;
}
set
{
SqlCollation collation = _collation;
if (null == collation)
{
_collation = collation = new SqlCollation();
}
if ((value & SqlString.x_iValidSqlCompareOptionMask) != value)
{
throw ADP.ArgumentOutOfRange("CompareInfo");
}
collation.SqlCompareOptions = value;
}
}
public string XmlSchemaCollectionDatabase
{
get
{
string xmlSchemaCollectionDatabase = _xmlSchemaCollectionDatabase;
return ((xmlSchemaCollectionDatabase != null) ? xmlSchemaCollectionDatabase : ADP.StrEmpty);
}
set
{
_xmlSchemaCollectionDatabase = value;
}
}
public string XmlSchemaCollectionOwningSchema
{
get
{
string xmlSchemaCollectionOwningSchema = _xmlSchemaCollectionOwningSchema;
return ((xmlSchemaCollectionOwningSchema != null) ? xmlSchemaCollectionOwningSchema : ADP.StrEmpty);
}
set
{
_xmlSchemaCollectionOwningSchema = value;
}
}
public string XmlSchemaCollectionName
{
get
{
string xmlSchemaCollectionName = _xmlSchemaCollectionName;
return ((xmlSchemaCollectionName != null) ? xmlSchemaCollectionName : ADP.StrEmpty);
}
set
{
_xmlSchemaCollectionName = value;
}
}
override public DbType DbType
{
get
{
return GetMetaTypeOnly().DbType;
}
set
{
MetaType metatype = _metaType;
if ((null == metatype) || (metatype.DbType != value) ||
// Two special datetime cases for backward compat
// DbType.Date and DbType.Time should always be treated as setting DbType.DateTime instead
value == DbType.Date ||
value == DbType.Time)
{
PropertyTypeChanging();
_metaType = MetaType.GetMetaTypeFromDbType(value);
}
}
}
public override void ResetDbType()
{
ResetSqlDbType();
}
internal MetaType InternalMetaType
{
get
{
Debug.Assert(null != _internalMetaType, "null InternalMetaType");
return _internalMetaType;
}
set { _internalMetaType = value; }
}
public int LocaleId
{
// Lowest 20 bits represent LocaleId
get
{
SqlCollation collation = _collation;
if (null != collation)
{
return collation.LCID;
}
return 0;
}
set
{
SqlCollation collation = _collation;
if (null == collation)
{
_collation = collation = new SqlCollation();
}
if (value != (SqlCollation.MaskLcid & value))
{
throw ADP.ArgumentOutOfRange("LocaleId");
}
collation.LCID = value;
}
}
internal bool SizeInferred
{
get
{
return 0 == _size;
}
}
internal MSS.SmiParameterMetaData MetaDataForSmi(out ParameterPeekAheadValue peekAhead)
{
peekAhead = null;
MetaType mt = ValidateTypeLengths();
long actualLen = GetActualSize();
long maxLen = this.Size;
// GetActualSize returns bytes length, but smi expects char length for
// character types, so adjust
if (!mt.IsLong)
{
if (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)
{
actualLen = actualLen / sizeof(char);
}
if (actualLen > maxLen)
{
maxLen = actualLen;
}
}
// Determine maxLength for types that ValidateTypeLengths won't figure out
if (0 == maxLen)
{
if (SqlDbType.Binary == mt.SqlDbType || SqlDbType.VarBinary == mt.SqlDbType)
{
maxLen = MSS.SmiMetaData.MaxBinaryLength;
}
else if (SqlDbType.Char == mt.SqlDbType || SqlDbType.VarChar == mt.SqlDbType)
{
maxLen = MSS.SmiMetaData.MaxANSICharacters;
}
else if (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)
{
maxLen = MSS.SmiMetaData.MaxUnicodeCharacters;
}
}
else if ((maxLen > MSS.SmiMetaData.MaxBinaryLength && (SqlDbType.Binary == mt.SqlDbType || SqlDbType.VarBinary == mt.SqlDbType))
|| (maxLen > MSS.SmiMetaData.MaxANSICharacters && (SqlDbType.Char == mt.SqlDbType || SqlDbType.VarChar == mt.SqlDbType))
|| (maxLen > MSS.SmiMetaData.MaxUnicodeCharacters && (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)))
{
maxLen = -1;
}
int localeId = LocaleId;
if (0 == localeId && mt.IsCharType)
{
object value = GetCoercedValue();
if (value is SqlString && !((SqlString)value).IsNull)
{
localeId = ((SqlString)value).LCID;
}
else
{
localeId = Locale.GetCurrentCultureLcid();
}
}
SqlCompareOptions compareOpts = CompareInfo;
if (0 == compareOpts && mt.IsCharType)
{
object value = GetCoercedValue();
if (value is SqlString && !((SqlString)value).IsNull)
{
compareOpts = ((SqlString)value).SqlCompareOptions;
}
else
{
compareOpts = MSS.SmiMetaData.GetDefaultForType(mt.SqlDbType).CompareOptions;
}
}
string typeSpecificNamePart1 = null;
string typeSpecificNamePart2 = null;
string typeSpecificNamePart3 = null;
if (SqlDbType.Xml == mt.SqlDbType)
{
typeSpecificNamePart1 = this.XmlSchemaCollectionDatabase;
typeSpecificNamePart2 = this.XmlSchemaCollectionOwningSchema;
typeSpecificNamePart3 = this.XmlSchemaCollectionName;
}
else if (SqlDbType.Udt == mt.SqlDbType || (SqlDbType.Structured == mt.SqlDbType && !ADP.IsEmpty(this.TypeName)))
{
// Split the input name. The type name is specified as single 3 part name.
// NOTE: ParseTypeName throws if format is incorrect
String[] names;
if (SqlDbType.Udt == mt.SqlDbType)
{
throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString());
}
else
{
names = ParseTypeName(this.TypeName);
}
if (1 == names.Length)
{
typeSpecificNamePart3 = names[0];
}
else if (2 == names.Length)
{
typeSpecificNamePart2 = names[0];
typeSpecificNamePart3 = names[1];
}
else if (3 == names.Length)
{
typeSpecificNamePart1 = names[0];
typeSpecificNamePart2 = names[1];
typeSpecificNamePart3 = names[2];
}
else
{
throw ADP.ArgumentOutOfRange("names");
}
if ((!ADP.IsEmpty(typeSpecificNamePart1) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart1.Length)
|| (!ADP.IsEmpty(typeSpecificNamePart2) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart2.Length)
|| (!ADP.IsEmpty(typeSpecificNamePart3) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart3.Length))
{
throw ADP.ArgumentOutOfRange("names");
}
}
byte precision = GetActualPrecision();
byte scale = GetActualScale();
// precision for decimal types may still need adjustment.
if (SqlDbType.Decimal == mt.SqlDbType)
{
if (0 == precision)
{
precision = TdsEnums.DEFAULT_NUMERIC_PRECISION;
}
}
// Sub-field determination
List<SmiExtendedMetaData> fields = null;
MSS.SmiMetaDataPropertyCollection extendedProperties = null;
if (SqlDbType.Structured == mt.SqlDbType)
{
GetActualFieldsAndProperties(out fields, out extendedProperties, out peekAhead);
}
return new MSS.SmiParameterMetaData(mt.SqlDbType,
maxLen,
precision,
scale,
localeId,
compareOpts,
SqlDbType.Structured == mt.SqlDbType,
fields,
extendedProperties,
this.ParameterNameFixed,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3,
this.Direction);
}
internal bool ParamaterIsSqlType
{
get
{
return _isSqlParameterSqlType;
}
set
{
_isSqlParameterSqlType = value;
}
}
override public string ParameterName
{
get
{
string parameterName = _parameterName;
return ((null != parameterName) ? parameterName : ADP.StrEmpty);
}
set
{
if (ADP.IsEmpty(value) || (value.Length < TdsEnums.MAX_PARAMETER_NAME_LENGTH)
|| (('@' == value[0]) && (value.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH)))
{
if (_parameterName != value)
{
PropertyChanging();
_parameterName = value;
}
}
else
{
throw SQL.InvalidParameterNameLength(value);
}
}
}
internal string ParameterNameFixed
{
get
{
string parameterName = ParameterName;
if ((0 < parameterName.Length) && ('@' != parameterName[0]))
{
parameterName = "@" + parameterName;
}
Debug.Assert(parameterName.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH, "parameter name too long");
return parameterName;
}
}
public override Byte Precision
{
get
{
return PrecisionInternal;
}
set
{
PrecisionInternal = value;
}
}
internal byte PrecisionInternal
{
get
{
byte precision = _precision;
SqlDbType dbtype = GetMetaSqlDbTypeOnly();
if ((0 == precision) && (SqlDbType.Decimal == dbtype))
{
precision = ValuePrecision(SqlValue);
}
return precision;
}
set
{
SqlDbType sqlDbType = SqlDbType;
if (sqlDbType == SqlDbType.Decimal && value > TdsEnums.MAX_NUMERIC_PRECISION)
{
throw SQL.PrecisionValueOutOfRange(value);
}
if (_precision != value)
{
PropertyChanging();
_precision = value;
}
}
}
private bool ShouldSerializePrecision()
{
return (0 != _precision);
}
public override Byte Scale
{
get
{
return ScaleInternal;
}
set
{
ScaleInternal = value;
}
}
internal byte ScaleInternal
{
get
{
byte scale = _scale;
SqlDbType dbtype = GetMetaSqlDbTypeOnly();
if ((0 == scale) && (SqlDbType.Decimal == dbtype))
{
scale = ValueScale(SqlValue);
}
return scale;
}
set
{
if (_scale != value || !_hasScale)
{
PropertyChanging();
_scale = value;
_hasScale = true;
_actualSize = -1; // Invalidate actual size such that it is re-calculated
}
}
}
private bool ShouldSerializeScale()
{
return (0 != _scale); // V1.0 compat, ignore _hasScale
}
public SqlDbType SqlDbType
{
get
{
return GetMetaTypeOnly().SqlDbType;
}
set
{
MetaType metatype = _metaType;
// HACK!!!
// We didn't want to expose SmallVarBinary on SqlDbType so we
// stuck it at the end of SqlDbType in v1.0, except that now
// we have new data types after that and it's smack dab in the
// middle of the valid range. To prevent folks from setting
// this invalid value we have to have this code here until we
// can take the time to fix it later.
if ((SqlDbType)TdsEnums.SmallVarBinary == value)
{
throw SQL.InvalidSqlDbType(value);
}
if ((null == metatype) || (metatype.SqlDbType != value))
{
PropertyTypeChanging();
_metaType = MetaType.GetMetaTypeFromSqlDbType(value, value == SqlDbType.Structured);
}
}
}
private bool ShouldSerializeSqlDbType()
{
return (null != _metaType);
}
public void ResetSqlDbType()
{
if (null != _metaType)
{
PropertyTypeChanging();
_metaType = null;
}
}
public object SqlValue
{
get
{
if (_value != null)
{
if (_value == DBNull.Value)
{
return MetaType.GetNullSqlValue(GetMetaTypeOnly().SqlType);
}
if (_value is INullable)
{
return _value;
}
// For Date and DateTime2, return the CLR object directly without converting it to a SqlValue
// GetMetaTypeOnly() will convert _value to a string in the case of char or char[], so only check
// the SqlDbType for DateTime.
if (_value is DateTime)
{
SqlDbType sqlDbType = GetMetaTypeOnly().SqlDbType;
if (sqlDbType == SqlDbType.Date || sqlDbType == SqlDbType.DateTime2)
{
return _value;
}
}
return (MetaType.GetSqlValueFromComVariant(_value));
}
else if (_sqlBufferReturnValue != null)
{
return _sqlBufferReturnValue.SqlValue;
}
return null;
}
set
{
Value = value;
}
}
public String TypeName
{
get
{
string typeName = _typeName;
return ((null != typeName) ? typeName : ADP.StrEmpty);
}
set
{
_typeName = value;
}
}
override public object Value
{ // V1.2.3300, XXXParameter V1.0.3300
get
{
if (_value != null)
{
return _value;
}
else if (_sqlBufferReturnValue != null)
{
if (ParamaterIsSqlType)
{
return _sqlBufferReturnValue.SqlValue;
}
return _sqlBufferReturnValue.Value;
}
return null;
}
set
{
_value = value;
_sqlBufferReturnValue = null;
_coercedValue = null;
_valueAsINullable = _value as INullable;
_isSqlParameterSqlType = (_valueAsINullable != null);
_isNull = ((_value == null) || (_value == DBNull.Value) || ((_isSqlParameterSqlType) && (_valueAsINullable.IsNull)));
_actualSize = -1;
}
}
internal INullable ValueAsINullable
{
get
{
return _valueAsINullable;
}
}
internal bool IsNull
{
get
{
// NOTE: Udts can change their value any time
if (_internalMetaType.SqlDbType == Data.SqlDbType.Udt)
{
_isNull = ((_value == null) || (_value == DBNull.Value) || ((_isSqlParameterSqlType) && (_valueAsINullable.IsNull)));
}
return _isNull;
}
}
//
// always returns data in bytes - except for non-unicode chars, which will be in number of chars
//
internal int GetActualSize()
{
MetaType mt = InternalMetaType;
SqlDbType actualType = mt.SqlDbType;
// NOTE: Users can change the Udt at any time, so we may need to recalculate
if ((_actualSize == -1) || (actualType == Data.SqlDbType.Udt))
{
_actualSize = 0;
object val = GetCoercedValue();
bool isSqlVariant = false;
if (IsNull && !mt.IsVarTime)
{
return 0;
}
// if this is a backend SQLVariant type, then infer the TDS type from the SQLVariant type
if (actualType == SqlDbType.Variant)
{
mt = MetaType.GetMetaTypeFromValue(val, streamAllowed: false);
actualType = MetaType.GetSqlDataType(mt.TDSType, 0 /*no user type*/, 0 /*non-nullable type*/).SqlDbType;
isSqlVariant = true;
}
if (mt.IsFixed)
{
_actualSize = mt.FixedLength;
}
else
{
// @hack: until we have ForceOffset behavior we have the following semantics:
// @hack: if the user supplies a Size through the Size propeprty or constructor,
// @hack: we only send a MAX of Size bytes over. If the actualSize is < Size, then
// @hack: we send over actualSize
int coercedSize = 0;
// get the actual length of the data, in bytes
switch (actualType)
{
case SqlDbType.NChar:
case SqlDbType.NVarChar:
case SqlDbType.NText:
case SqlDbType.Xml:
{
coercedSize = ((!_isNull) && (!_coercedValueIsDataFeed)) ? (StringSize(val, _coercedValueIsSqlType)) : 0;
_actualSize = (ShouldSerializeSize() ? Size : 0);
_actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
if (_actualSize == -1)
_actualSize = coercedSize;
_actualSize <<= 1;
}
break;
case SqlDbType.Char:
case SqlDbType.VarChar:
case SqlDbType.Text:
{
// for these types, ActualSize is the num of chars, not actual bytes - since non-unicode chars are not always uniform size
coercedSize = ((!_isNull) && (!_coercedValueIsDataFeed)) ? (StringSize(val, _coercedValueIsSqlType)) : 0;
_actualSize = (ShouldSerializeSize() ? Size : 0);
_actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
if (_actualSize == -1)
_actualSize = coercedSize;
}
break;
case SqlDbType.Binary:
case SqlDbType.VarBinary:
case SqlDbType.Image:
case SqlDbType.Timestamp:
coercedSize = ((!_isNull) && (!_coercedValueIsDataFeed)) ? (BinarySize(val, _coercedValueIsSqlType)) : 0;
_actualSize = (ShouldSerializeSize() ? Size : 0);
_actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
if (_actualSize == -1)
_actualSize = coercedSize;
break;
case SqlDbType.Udt:
throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString());
case SqlDbType.Structured:
coercedSize = -1;
break;
case SqlDbType.Time:
_actualSize = (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
break;
case SqlDbType.DateTime2:
// Date in number of days (3 bytes) + time
_actualSize = 3 + (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
break;
case SqlDbType.DateTimeOffset:
// Date in days (3 bytes) + offset in minutes (2 bytes) + time
_actualSize = 5 + (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
break;
default:
Debug.Assert(false, "Unknown variable length type!");
break;
} // switch
// don't even send big values over to the variant
if (isSqlVariant && (coercedSize > TdsEnums.TYPE_SIZE_LIMIT))
throw SQL.ParameterInvalidVariant(this.ParameterName);
}
}
return _actualSize;
}
// Coerced Value is also used in SqlBulkCopy.ConvertValue(object value, _SqlMetaData metadata)
internal static object CoerceValue(object value, MetaType destinationType, out bool coercedToDataFeed, out bool typeChanged, bool allowStreaming = true)
{
Debug.Assert(!(value is DataFeed), "Value provided should not already be a data feed");
Debug.Assert(!ADP.IsNull(value), "Value provided should not be null");
Debug.Assert(null != destinationType, "null destinationType");
coercedToDataFeed = false;
typeChanged = false;
Type currentType = value.GetType();
if ((typeof(object) != destinationType.ClassType) &&
(currentType != destinationType.ClassType) &&
((currentType != destinationType.SqlType) || (SqlDbType.Xml == destinationType.SqlDbType)))
{ // Special case for Xml types (since we need to convert SqlXml into a string)
try
{
// Assume that the type changed
typeChanged = true;
if ((typeof(string) == destinationType.ClassType))
{
// For Xml data, destination Type is always string
if (typeof(SqlXml) == currentType)
{
value = MetaType.GetStringFromXml((XmlReader)(((SqlXml)value).CreateReader()));
}
else if (typeof(SqlString) == currentType)
{
typeChanged = false; // Do nothing
}
else if (typeof(XmlReader).IsAssignableFrom(currentType))
{
if (allowStreaming)
{
coercedToDataFeed = true;
value = new XmlDataFeed((XmlReader)value);
}
else
{
value = MetaType.GetStringFromXml((XmlReader)value);
}
}
else if (typeof(char[]) == currentType)
{
value = new string((char[])value);
}
else if (typeof(SqlChars) == currentType)
{
value = new string(((SqlChars)value).Value);
}
else if (value is TextReader && allowStreaming)
{
coercedToDataFeed = true;
value = new TextDataFeed((TextReader)value);
}
else
{
value = Convert.ChangeType(value, destinationType.ClassType, (IFormatProvider)null);
}
}
else if ((DbType.Currency == destinationType.DbType) && (typeof(string) == currentType))
{
value = Decimal.Parse((string)value, NumberStyles.Currency, (IFormatProvider)null); // WebData 99376
}
else if ((typeof(SqlBytes) == currentType) && (typeof(byte[]) == destinationType.ClassType))
{
typeChanged = false; // Do nothing
}
else if ((typeof(string) == currentType) && (SqlDbType.Time == destinationType.SqlDbType))
{
value = TimeSpan.Parse((string)value);
}
else if ((typeof(string) == currentType) && (SqlDbType.DateTimeOffset == destinationType.SqlDbType))
{
value = DateTimeOffset.Parse((string)value, (IFormatProvider)null);
}
else if ((typeof(DateTime) == currentType) && (SqlDbType.DateTimeOffset == destinationType.SqlDbType))
{
value = new DateTimeOffset((DateTime)value);
}
else if (TdsEnums.SQLTABLE == destinationType.TDSType && (
value is DbDataReader ||
value is System.Collections.Generic.IEnumerable<SqlDataRecord>))
{
// no conversion for TVPs.
typeChanged = false;
}
else if (destinationType.ClassType == typeof(byte[]) && value is Stream && allowStreaming)
{
coercedToDataFeed = true;
value = new StreamDataFeed((Stream)value);
}
else
{
value = Convert.ChangeType(value, destinationType.ClassType, (IFormatProvider)null);
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
throw ADP.ParameterConversionFailed(value, destinationType.ClassType, e); // WebData 75433
}
}
Debug.Assert(allowStreaming || !coercedToDataFeed, "Streaming is not allowed, but type was coerced into a data feed");
Debug.Assert(value.GetType() == currentType ^ typeChanged, "Incorrect value for typeChanged");
return value;
}
internal void FixStreamDataForNonPLP()
{
object value = GetCoercedValue();
AssertCachedPropertiesAreValid();
if (!_coercedValueIsDataFeed)
{
return;
}
_coercedValueIsDataFeed = false;
if (value is TextDataFeed)
{
if (Size > 0)
{
char[] buffer = new char[Size];
int nRead = ((TextDataFeed)value)._source.ReadBlock(buffer, 0, Size);
CoercedValue = new string(buffer, 0, nRead);
}
else
{
CoercedValue = ((TextDataFeed)value)._source.ReadToEnd();
}
return;
}
if (value is StreamDataFeed)
{
if (Size > 0)
{
byte[] buffer = new byte[Size];
int totalRead = 0;
Stream sourceStream = ((StreamDataFeed)value)._source;
while (totalRead < Size)
{
int nRead = sourceStream.Read(buffer, totalRead, Size - totalRead);
if (nRead == 0)
{
break;
}
totalRead += nRead;
}
if (totalRead < Size)
{
Array.Resize(ref buffer, totalRead);
}
CoercedValue = buffer;
}
else
{
MemoryStream ms = new MemoryStream();
((StreamDataFeed)value)._source.CopyTo(ms);
CoercedValue = ms.ToArray();
}
return;
}
if (value is XmlDataFeed)
{
CoercedValue = MetaType.GetStringFromXml(((XmlDataFeed)value)._source);
return;
}
// We should have returned before reaching here
Debug.Assert(false, "_coercedValueIsDataFeed was true, but the value was not a known DataFeed type");
}
internal byte GetActualPrecision()
{
return ShouldSerializePrecision() ? PrecisionInternal : ValuePrecision(CoercedValue);
}
internal byte GetActualScale()
{
if (ShouldSerializeScale())
{
return ScaleInternal;
}
// issue: how could a user specify 0 as the actual scale?
if (GetMetaTypeOnly().IsVarTime)
{
return TdsEnums.DEFAULT_VARTIME_SCALE;
}
return ValueScale(CoercedValue);
}
internal int GetParameterSize()
{
return ShouldSerializeSize() ? Size : ValueSize(CoercedValue);
}
private void GetActualFieldsAndProperties(out List<MSS.SmiExtendedMetaData> fields, out SmiMetaDataPropertyCollection props, out ParameterPeekAheadValue peekAhead)
{
fields = null;
props = null;
peekAhead = null;
object value = GetCoercedValue();
if (value is SqlDataReader)
{
fields = new List<MSS.SmiExtendedMetaData>(((SqlDataReader)value).GetInternalSmiMetaData());
if (fields.Count <= 0)
{
throw SQL.NotEnoughColumnsInStructuredType();
}
bool[] keyCols = new bool[fields.Count];
bool hasKey = false;
for (int i = 0; i < fields.Count; i++)
{
MSS.SmiQueryMetaData qmd = fields[i] as MSS.SmiQueryMetaData;
if (null != qmd && !qmd.IsKey.IsNull && qmd.IsKey.Value)
{
keyCols[i] = true;
hasKey = true;
}
}
// Add unique key property, if any found.
if (hasKey)
{
props = new SmiMetaDataPropertyCollection();
props[MSS.SmiPropertySelector.UniqueKey] = new MSS.SmiUniqueKeyProperty(new List<bool>(keyCols));
}
}
else if (value is IEnumerable<SqlDataRecord>)
{
// must grab the first record of the enumerator to get the metadata
IEnumerator<MSS.SqlDataRecord> enumerator = ((IEnumerable<MSS.SqlDataRecord>)value).GetEnumerator();
MSS.SqlDataRecord firstRecord = null;
try
{
// no need for fields if there's no rows or no columns -- we'll be sending a null instance anyway.
if (enumerator.MoveNext())
{
firstRecord = enumerator.Current;
int fieldCount = firstRecord.FieldCount;
if (0 < fieldCount)
{
// It's valid! Grab those fields.
bool[] keyCols = new bool[fieldCount];
bool[] defaultFields = new bool[fieldCount];
bool[] sortOrdinalSpecified = new bool[fieldCount];
int maxSortOrdinal = -1; // largest sort ordinal seen, used to optimize locating holes in the list
bool hasKey = false;
bool hasDefault = false;
int sortCount = 0;
SmiOrderProperty.SmiColumnOrder[] sort = new SmiOrderProperty.SmiColumnOrder[fieldCount];
fields = new List<MSS.SmiExtendedMetaData>(fieldCount);
for (int i = 0; i < fieldCount; i++)
{
SqlMetaData colMeta = firstRecord.GetSqlMetaData(i);
fields.Add(MSS.MetaDataUtilsSmi.SqlMetaDataToSmiExtendedMetaData(colMeta));
if (colMeta.IsUniqueKey)
{
keyCols[i] = true;
hasKey = true;
}
if (colMeta.UseServerDefault)
{
defaultFields[i] = true;
hasDefault = true;
}
sort[i].Order = colMeta.SortOrder;
if (SortOrder.Unspecified != colMeta.SortOrder)
{
// SqlMetaData takes care of checking for negative sort ordinals with specified sort order
// bail early if there's no way sort order could be monotonically increasing
if (fieldCount <= colMeta.SortOrdinal)
{
throw SQL.SortOrdinalGreaterThanFieldCount(i, colMeta.SortOrdinal);
}
// Check to make sure we haven't seen this ordinal before
if (sortOrdinalSpecified[colMeta.SortOrdinal])
{
throw SQL.DuplicateSortOrdinal(colMeta.SortOrdinal);
}
sort[i].SortOrdinal = colMeta.SortOrdinal;
sortOrdinalSpecified[colMeta.SortOrdinal] = true;
if (colMeta.SortOrdinal > maxSortOrdinal)
{
maxSortOrdinal = colMeta.SortOrdinal;
}
sortCount++;
}
}
if (hasKey)
{
props = new SmiMetaDataPropertyCollection();
props[MSS.SmiPropertySelector.UniqueKey] = new MSS.SmiUniqueKeyProperty(new List<bool>(keyCols));
}
if (hasDefault)
{
// May have already created props list in unique key handling
if (null == props)
{
props = new SmiMetaDataPropertyCollection();
}
props[MSS.SmiPropertySelector.DefaultFields] = new MSS.SmiDefaultFieldsProperty(new List<bool>(defaultFields));
}
if (0 < sortCount)
{
// validate monotonically increasing sort order.
// Since we already checked for duplicates, we just need
// to watch for values outside of the sortCount range.
if (maxSortOrdinal >= sortCount)
{
// there is at least one hole, find the first one
int i;
for (i = 0; i < sortCount; i++)
{
if (!sortOrdinalSpecified[i])
{
break;
}
}
Debug.Assert(i < sortCount, "SqlParameter.GetActualFieldsAndProperties: SortOrdinal hole-finding algorithm failed!");
throw SQL.MissingSortOrdinal(i);
}
// May have already created props list
if (null == props)
{
props = new SmiMetaDataPropertyCollection();
}
props[MSS.SmiPropertySelector.SortOrder] = new MSS.SmiOrderProperty(
new List<SmiOrderProperty.SmiColumnOrder>(sort));
}
// pack it up so we don't have to rewind to send the first value
peekAhead = new ParameterPeekAheadValue();
peekAhead.Enumerator = enumerator;
peekAhead.FirstRecord = firstRecord;
// now that it's all packaged, make sure we don't dispose it.
enumerator = null;
}
else
{
throw SQL.NotEnoughColumnsInStructuredType();
}
}
else
{
throw SQL.IEnumerableOfSqlDataRecordHasNoRows();
}
}
finally
{
if (enumerator != null)
{
enumerator.Dispose();
}
}
}
else if (value is DbDataReader)
{
// For ProjectK\CoreCLR, DbDataReader no longer supports GetSchema
// So instead we will attempt to generate the metadata from the Field Type alone
var reader = (DbDataReader)value;
if (reader.FieldCount <= 0)
{
throw SQL.NotEnoughColumnsInStructuredType();
}
fields = new List<MSS.SmiExtendedMetaData>(reader.FieldCount);
for (int i = 0; i < reader.FieldCount; i++)
{
fields.Add(MSS.MetaDataUtilsSmi.SmiMetaDataFromType(reader.GetName(i), reader.GetFieldType(i)));
}
}
}
internal object GetCoercedValue()
{
// NOTE: User can change the Udt at any time
if ((null == _coercedValue) || (_internalMetaType.SqlDbType == Data.SqlDbType.Udt))
{ // will also be set during parameter Validation
bool isDataFeed = Value is DataFeed;
if ((IsNull) || (isDataFeed))
{
// No coercion is done for DataFeeds and Nulls
_coercedValue = Value;
_coercedValueIsSqlType = (_coercedValue == null) ? false : _isSqlParameterSqlType; // set to null for output parameters that keeps _isSqlParameterSqlType
_coercedValueIsDataFeed = isDataFeed;
_actualSize = IsNull ? 0 : -1;
}
else
{
bool typeChanged;
_coercedValue = CoerceValue(Value, _internalMetaType, out _coercedValueIsDataFeed, out typeChanged);
_coercedValueIsSqlType = ((_isSqlParameterSqlType) && (!typeChanged)); // Type changed always results in a CLR type
_actualSize = -1;
}
}
AssertCachedPropertiesAreValid();
return _coercedValue;
}
internal bool CoercedValueIsSqlType
{
get
{
if (null == _coercedValue)
{
GetCoercedValue();
}
AssertCachedPropertiesAreValid();
return _coercedValueIsSqlType;
}
}
internal bool CoercedValueIsDataFeed
{
get
{
if (null == _coercedValue)
{
GetCoercedValue();
}
AssertCachedPropertiesAreValid();
return _coercedValueIsDataFeed;
}
}
[Conditional("DEBUG")]
internal void AssertCachedPropertiesAreValid()
{
AssertPropertiesAreValid(_coercedValue, _coercedValueIsSqlType, _coercedValueIsDataFeed, IsNull);
}
[Conditional("DEBUG")]
internal void AssertPropertiesAreValid(object value, bool? isSqlType = null, bool? isDataFeed = null, bool? isNull = null)
{
Debug.Assert(!isSqlType.HasValue || (isSqlType.Value == (value is INullable)), "isSqlType is incorrect");
Debug.Assert(!isDataFeed.HasValue || (isDataFeed.Value == (value is DataFeed)), "isDataFeed is incorrect");
Debug.Assert(!isNull.HasValue || (isNull.Value == ADP.IsNull(value)), "isNull is incorrect");
}
private SqlDbType GetMetaSqlDbTypeOnly()
{
MetaType metaType = _metaType;
if (null == metaType)
{ // infer the type from the value
metaType = MetaType.GetDefaultMetaType();
}
return metaType.SqlDbType;
}
// This may not be a good thing to do in case someone overloads the parameter type but I
// don't want to go from SqlDbType -> metaType -> TDSType
private MetaType GetMetaTypeOnly()
{
if (null != _metaType)
{
return _metaType;
}
if (null != _value && DBNull.Value != _value)
{
// We have a value set by the user then just use that value
// char and char[] are not directly supported so we convert those values to string
if (_value is char)
{
_value = _value.ToString();
}
else if (Value is char[])
{
_value = new string((char[])_value);
}
return MetaType.GetMetaTypeFromValue(_value, inferLen: false);
}
else if (null != _sqlBufferReturnValue)
{ // value came back from the server
Type valueType = _sqlBufferReturnValue.GetTypeFromStorageType(_isSqlParameterSqlType);
if (null != valueType)
{
return MetaType.GetMetaTypeFromType(valueType);
}
}
return MetaType.GetDefaultMetaType();
}
internal void Prepare(SqlCommand cmd)
{
if (null == _metaType)
{
throw ADP.PrepareParameterType(cmd);
}
else if (!ShouldSerializeSize() && !_metaType.IsFixed)
{
throw ADP.PrepareParameterSize(cmd);
}
else if ((!ShouldSerializePrecision() && !ShouldSerializeScale()) && (_metaType.SqlDbType == SqlDbType.Decimal))
{
throw ADP.PrepareParameterScale(cmd, SqlDbType.ToString());
}
}
private void PropertyChanging()
{
_internalMetaType = null;
}
private void PropertyTypeChanging()
{
PropertyChanging();
CoercedValue = null;
}
internal void SetSqlBuffer(SqlBuffer buff)
{
_sqlBufferReturnValue = buff;
_value = null;
_coercedValue = null;
_isNull = _sqlBufferReturnValue.IsNull;
_coercedValueIsDataFeed = false;
_coercedValueIsSqlType = false;
_actualSize = -1;
}
internal void Validate(int index, bool isCommandProc)
{
MetaType metaType = GetMetaTypeOnly();
_internalMetaType = metaType;
// NOTE: (General Criteria): SqlParameter does a Size Validation check and would fail if the size is 0.
// This condition filters all scenarios where we view a valid size 0.
if (ADP.IsDirection(this, ParameterDirection.Output) &&
!ADP.IsDirection(this, ParameterDirection.ReturnValue) &&
(!metaType.IsFixed) &&
!ShouldSerializeSize() &&
((null == _value) || (_value == DBNull.Value)) &&
(SqlDbType != SqlDbType.Timestamp) &&
(SqlDbType != SqlDbType.Udt) &&
// Output parameter with size 0 throws for XML, TEXT, NTEXT, IMAGE.
(SqlDbType != SqlDbType.Xml) &&
!metaType.IsVarTime)
{
throw ADP.UninitializedParameterSize(index, metaType.ClassType);
}
if (metaType.SqlDbType != SqlDbType.Udt && Direction != ParameterDirection.Output)
{
GetCoercedValue();
}
// Validate structured-type-specific details.
if (metaType.SqlDbType == SqlDbType.Structured)
{
if (!isCommandProc && ADP.IsEmpty(TypeName))
throw SQL.MustSetTypeNameForParam(metaType.TypeName, this.ParameterName);
if (ParameterDirection.Input != this.Direction)
{
throw SQL.UnsupportedTVPOutputParameter(this.Direction, this.ParameterName);
}
if (DBNull.Value == GetCoercedValue())
{
throw SQL.DBNullNotSupportedForTVPValues(this.ParameterName);
}
}
else if (!ADP.IsEmpty(TypeName))
{
throw SQL.UnexpectedTypeNameForNonStructParams(this.ParameterName);
}
}
// func will change type to that with a 4 byte length if the type has a two
// byte length and a parameter length > than that expressable in 2 bytes
internal MetaType ValidateTypeLengths()
{
MetaType mt = InternalMetaType;
// Since the server will automatically reject any
// char, varchar, binary, varbinary, nchar, or nvarchar parameter that has a
// byte sizeInCharacters > 8000 bytes, we promote the parameter to image, text, or ntext. This
// allows the user to specify a parameter type using a COM+ datatype and be able to
// use that parameter against a BLOB column.
if ((SqlDbType.Udt != mt.SqlDbType) && (false == mt.IsFixed) && (false == mt.IsLong))
{ // if type has 2 byte length
long actualSizeInBytes = this.GetActualSize();
long sizeInCharacters = this.Size;
// 'actualSizeInBytes' is the size of value passed;
// 'sizeInCharacters' is the parameter size;
// 'actualSizeInBytes' is in bytes;
// 'this.Size' is in charaters;
// 'sizeInCharacters' is in characters;
// 'TdsEnums.TYPE_SIZE_LIMIT' is in bytes;
// For Non-NCharType and for non-Yukon or greater variables, size should be maintained;
// Modifed variable names from 'size' to 'sizeInCharacters', 'actualSize' to 'actualSizeInBytes', and
// 'maxSize' to 'maxSizeInBytes'
// The idea is to
// Keeping these goals in mind - the following are the changes we are making
long maxSizeInBytes = 0;
if (mt.IsNCharType)
maxSizeInBytes = ((sizeInCharacters * sizeof(char)) > actualSizeInBytes) ? sizeInCharacters * sizeof(char) : actualSizeInBytes;
else
{
// Notes:
// Elevation from (n)(var)char (4001+) to (n)text succeeds without failure only with Yukon and greater.
// it fails in sql server 2000
maxSizeInBytes = (sizeInCharacters > actualSizeInBytes) ? sizeInCharacters : actualSizeInBytes;
}
if ((maxSizeInBytes > TdsEnums.TYPE_SIZE_LIMIT) || (_coercedValueIsDataFeed) ||
(sizeInCharacters == -1) || (actualSizeInBytes == -1))
{ // is size > size able to be described by 2 bytes
// Convert the parameter to its max type
mt = MetaType.GetMaxMetaTypeFromMetaType(mt);
_metaType = mt;
InternalMetaType = mt;
if (!mt.IsPlp)
{
if (mt.SqlDbType == SqlDbType.Xml)
{
throw ADP.InvalidMetaDataValue(); //Xml should always have IsPartialLength = true
}
if (mt.SqlDbType == SqlDbType.NVarChar
|| mt.SqlDbType == SqlDbType.VarChar
|| mt.SqlDbType == SqlDbType.VarBinary)
{
Size = (int)(SmiMetaData.UnlimitedMaxLengthIndicator);
}
}
}
}
return mt;
}
private byte ValuePrecision(object value)
{
if (value is SqlDecimal)
{
if (((SqlDecimal)value).IsNull)
return 0;
return ((SqlDecimal)value).Precision;
}
return ValuePrecisionCore(value);
}
private byte ValueScale(object value)
{
if (value is SqlDecimal)
{
if (((SqlDecimal)value).IsNull)
return 0;
return ((SqlDecimal)value).Scale;
}
return ValueScaleCore(value);
}
private static int StringSize(object value, bool isSqlType)
{
if (isSqlType)
{
Debug.Assert(!((INullable)value).IsNull, "Should not call StringSize on null values");
if (value is SqlString)
{
return ((SqlString)value).Value.Length;
}
if (value is SqlChars)
{
return ((SqlChars)value).Value.Length;
}
}
else
{
string svalue = (value as string);
if (null != svalue)
{
return svalue.Length;
}
char[] cvalue = (value as char[]);
if (null != cvalue)
{
return cvalue.Length;
}
if (value is char)
{
return 1;
}
}
// Didn't match, unknown size
return 0;
}
private static int BinarySize(object value, bool isSqlType)
{
if (isSqlType)
{
Debug.Assert(!((INullable)value).IsNull, "Should not call StringSize on null values");
if (value is SqlBinary)
{
return ((SqlBinary)value).Length;
}
if (value is SqlBytes)
{
return ((SqlBytes)value).Value.Length;
}
}
else
{
byte[] bvalue = (value as byte[]);
if (null != bvalue)
{
return bvalue.Length;
}
if (value is byte)
{
return 1;
}
}
// Didn't match, unknown size
return 0;
}
private int ValueSize(object value)
{
if (value is SqlString)
{
if (((SqlString)value).IsNull)
return 0;
return ((SqlString)value).Value.Length;
}
if (value is SqlChars)
{
if (((SqlChars)value).IsNull)
return 0;
return ((SqlChars)value).Value.Length;
}
if (value is SqlBinary)
{
if (((SqlBinary)value).IsNull)
return 0;
return ((SqlBinary)value).Length;
}
if (value is SqlBytes)
{
if (((SqlBytes)value).IsNull)
return 0;
return (int)(((SqlBytes)value).Length);
}
if (value is DataFeed)
{
// Unknown length
return 0;
}
return ValueSizeCore(value);
}
// parse an string of the form db.schema.name where any of the three components
// might have "[" "]" and dots within it.
// returns:
// [0] dbname (or null)
// [1] schema (or null)
// [2] name
// NOTE: if perf/space implications of Regex is not a problem, we can get rid
// of this and use a simple regex to do the parsing
internal static string[] ParseTypeName(string typeName)
{
Debug.Assert(null != typeName, "null typename passed to ParseTypeName");
try
{
string errorMsg;
{
errorMsg = Res.SQL_TypeName;
}
return MultipartIdentifier.ParseMultipartIdentifier(typeName, "[\"", "]\"", '.', 3, true, errorMsg, true);
}
catch (ArgumentException)
{
{
throw SQL.InvalidParameterTypeNameFormat();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WebApiHelpPage.Models;
using WebApiHelpPage.ModelDescriptions;
namespace WebApiHelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
internal static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
**
** Purpose: Class to represent all synchronization objects in the runtime (that allow multiple wait)
**
**
=============================================================================*/
using System.Threading;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
using System.IO;
namespace System.Threading
{
public abstract class WaitHandle : IDisposable
{
public const int WaitTimeout = LowLevelThread.WAIT_TIMEOUT;
protected static readonly IntPtr InvalidHandle = Interop.InvalidHandleValue;
internal SafeWaitHandle waitHandle;
internal enum OpenExistingResult
{
Success,
NameNotFound,
PathNotFound,
NameInvalid
}
protected WaitHandle()
{
}
public SafeWaitHandle SafeWaitHandle
{
[System.Security.SecurityCritical]
get
{
if (waitHandle == null)
{
waitHandle = new SafeWaitHandle(InvalidHandle, false);
}
return waitHandle;
}
[System.Security.SecurityCritical]
set
{ waitHandle = value; }
}
public virtual bool WaitOne(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException("millisecondsTimeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
return WaitOne((long)millisecondsTimeout);
}
public virtual bool WaitOne(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long)Int32.MaxValue < tm)
{
throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return WaitOne(tm);
}
public virtual bool WaitOne()
{
//Infinite Timeout
return WaitOne(-1);
}
[System.Security.SecuritySafeCritical] // auto-generated
private bool WaitOne(long timeout)
{
return InternalWaitOne(waitHandle, timeout);
}
[System.Security.SecurityCritical] // auto-generated
internal static bool InternalWaitOne(SafeWaitHandle waitableSafeHandle, long millisecondsTimeout)
{
if (waitableSafeHandle == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
Contract.EndContractBlock();
int ret = WaitOneNative(waitableSafeHandle, millisecondsTimeout);
#if FEATURE_LEGACYNETCFFAS
if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
#endif // FEATURE_LEGACYNETCFFAS
if (ret == LowLevelThread.WAIT_ABANDONED)
{
ThrowAbandonedMutexException();
}
return (ret != WaitTimeout);
}
#if FEATURE_LEGACYNETCFFAS
[System.Security.SecurityCritical]
internal bool WaitOneWithoutFAS()
{
// version of waitone without fast application switch (FAS) support
// This is required to support the Wait which FAS needs (otherwise recursive dependency comes in)
if (safeWaitHandle == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
Contract.EndContractBlock();
long timeout = -1;
int ret = WaitOneNative(safeWaitHandle, (uint)timeout, false);
if (ret == WAIT_ABANDONED)
{
ThrowAbandonedMutexException();
}
return (ret != WaitTimeout);
}
#endif // FEATURE_LEGACYNETCFFAS
internal static int WaitOneNative(SafeWaitHandle waitableSafeHandle, long millisecondsTimeout)
{
Contract.Assert(millisecondsTimeout >= -1 && millisecondsTimeout <= int.MaxValue);
waitableSafeHandle.DangerousAddRef();
try
{
return LowLevelThread.WaitForSingleObject(waitableSafeHandle.DangerousGetHandle(), (int)millisecondsTimeout);
}
finally
{
waitableSafeHandle.DangerousRelease();
}
}
/*========================================================================
** Waits for signal from all the objects.
** timeout indicates how long to wait before the method returns.
** This method will return either when all the object have been pulsed
** or timeout milliseonds have elapsed.
========================================================================*/
private static int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool WaitAll)
{
IntPtr[] handles = new IntPtr[waitHandles.Length];
for (int i = 0; i < handles.Length; i++)
{
waitHandles[i].waitHandle.DangerousAddRef();
handles[i] = waitHandles[i].waitHandle.DangerousGetHandle();
}
try
{
return LowLevelThread.WaitForMultipleObjects(handles, WaitAll, millisecondsTimeout);
}
finally
{
for (int i = 0; i < handles.Length; i++)
{
waitHandles[i].waitHandle.DangerousRelease();
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout)
{
if (waitHandles == null)
{
throw new ArgumentNullException(SR.ArgumentNull_Waithandles);
}
if (waitHandles.Length == 0)
{
//
// Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct.
// Somehow, in 2.0, this became ArgumentNullException. This was not fixed until Silverlight 2,
// which went back to ArgumentException.
//
// Now we're in a bit of a bind. Backward-compatibility requires us to keep throwing ArgumentException
// in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking
// user code.
//
throw new ArgumentNullException(SR.Argument_EmptyWaithandleArray);
}
if (waitHandles.Length > LowLevelThread.MAX_WAITHANDLES)
{
throw new NotSupportedException(SR.NotSupported_MaxWaitHandles);
}
if (-1 > millisecondsTimeout)
{
throw new ArgumentOutOfRangeException("millisecondsTimeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length];
for (int i = 0; i < waitHandles.Length; i++)
{
WaitHandle waitHandle = waitHandles[i];
if (waitHandle == null)
throw new ArgumentNullException(SR.ArgumentNull_ArrayElement);
internalWaitHandles[i] = waitHandle;
}
#if DEBUG
// make sure we do not use waitHandles any more.
waitHandles = null;
#endif
int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, true /* waitall*/ );
#if FEATURE_LEGACYNETCFFAS
if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
#endif // FEATURE_LEGACYNETCFFAS
if ((LowLevelThread.WAIT_ABANDONED <= ret) && (LowLevelThread.WAIT_ABANDONED + internalWaitHandles.Length > ret))
{
//In the case of WaitAll the OS will only provide the
// information that mutex was abandoned.
// It won't tell us which one. So we can't set the Index or provide access to the Mutex
ThrowAbandonedMutexException();
}
GC.KeepAlive(internalWaitHandles);
return (ret != WaitTimeout);
}
public static bool WaitAll(
WaitHandle[] waitHandles,
TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long)Int32.MaxValue < tm)
{
throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return WaitAll(waitHandles, (int)tm);
}
public static bool WaitAll(WaitHandle[] waitHandles)
{
return WaitAll(waitHandles, Timeout.Infinite);
}
/*========================================================================
** Waits for notification from any of the objects.
** timeout indicates how long to wait before the method returns.
** This method will return either when either one of the object have been
** signalled or timeout milliseonds have elapsed.
========================================================================*/
[System.Security.SecuritySafeCritical] // auto-generated
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout)
{
if (waitHandles == null)
{
throw new ArgumentNullException(SR.ArgumentNull_Waithandles);
}
if (waitHandles.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyWaithandleArray);
}
if (LowLevelThread.MAX_WAITHANDLES < waitHandles.Length)
{
throw new NotSupportedException(SR.NotSupported_MaxWaitHandles);
}
if (-1 > millisecondsTimeout)
{
throw new ArgumentOutOfRangeException("millisecondsTimeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length];
for (int i = 0; i < waitHandles.Length; i++)
{
WaitHandle waitHandle = waitHandles[i];
if (waitHandle == null)
throw new ArgumentNullException(SR.ArgumentNull_ArrayElement);
internalWaitHandles[i] = waitHandle;
}
#if DEBUG
// make sure we do not use waitHandles any more.
waitHandles = null;
#endif
int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, false /* waitany*/ );
#if FEATURE_LEGACYNETCFFAS
if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
#endif // FEATURE_LEGACYNETCFFAS
if ((LowLevelThread.WAIT_ABANDONED <= ret) && (LowLevelThread.WAIT_ABANDONED + internalWaitHandles.Length > ret))
{
int mutexIndex = ret - LowLevelThread.WAIT_ABANDONED;
if (0 <= mutexIndex && mutexIndex < internalWaitHandles.Length)
{
ThrowAbandonedMutexException(mutexIndex, internalWaitHandles[mutexIndex]);
}
else
{
ThrowAbandonedMutexException();
}
}
GC.KeepAlive(internalWaitHandles);
return ret;
}
public static int WaitAny(
WaitHandle[] waitHandles,
TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long)Int32.MaxValue < tm)
{
throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return WaitAny(waitHandles, (int)tm);
}
public static int WaitAny(WaitHandle[] waitHandles)
{
return WaitAny(waitHandles, Timeout.Infinite);
}
private static void ThrowAbandonedMutexException()
{
throw new AbandonedMutexException();
}
private static void ThrowAbandonedMutexException(int location, WaitHandle handle)
{
throw new AbandonedMutexException(location, handle);
}
[System.Security.SecuritySafeCritical] // auto-generated
protected virtual void Dispose(bool explicitDisposing)
{
if (waitHandle != null)
{
waitHandle.Close();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
internal static Exception ExceptionFromCreationError(int errorCode, string path)
{
switch (errorCode)
{
case Interop.mincore.Errors.ERROR_PATH_NOT_FOUND:
return new IOException(SR.Format(SR.IO_PathNotFound_Path, path));
case Interop.mincore.Errors.ERROR_ACCESS_DENIED:
return new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, path));
case Interop.mincore.Errors.ERROR_ALREADY_EXISTS:
return new IOException(SR.Format(SR.IO_AlreadyExists_Name, path));
case Interop.mincore.Errors.ERROR_FILENAME_EXCED_RANGE:
return new PathTooLongException();
default:
return new IOException(SR.Arg_IOException, errorCode);
}
}
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using Belikov.GenuineChannels.Connection;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Messaging;
using Belikov.GenuineChannels.Parameters;
using Belikov.GenuineChannels.Receiving;
using Belikov.GenuineChannels.Security;
using Belikov.GenuineChannels.TransportContext;
namespace Belikov.GenuineChannels.GenuineTcp
{
/// <summary>
/// Incapsulates information about a socket connection.
/// </summary>
internal class TcpSocketInfo : Stream
{
/// <summary>
/// Constructs an instance of the TcpSocketInfo class.
/// </summary>
/// <param name="socket">The socket.</param>
/// <param name="iTransportContext">Transport Context.</param>
/// <param name="connectionName">The name of the connection.</param>
/// <param name="typeOfSocket">The type of the socket used for debugging.</param>
internal TcpSocketInfo(Socket socket, ITransportContext iTransportContext, string connectionName
#if DEBUG
,string typeOfSocket
#endif
)
{
this.Socket = socket;
this.ITransportContext = iTransportContext;
this.ConnectionName = connectionName == null ? "~" + Guid.NewGuid().ToString("N") : connectionName;
this.MaxSendSize = (int) this.ITransportContext.IParameterProvider[GenuineParameter.TcpMaxSendSize];
#if DEBUG
this._typeOfSocket = typeOfSocket;
this._connectionNumber = Interlocked.Increment(ref _dbg_ConnectionCounter);
#endif
}
/// <summary>
/// To guarantee atomic access to local members.
/// </summary>
private object _accessToLocalMembers = new object();
#region -- Debug information ---------------------------------------------------------------
#if DEBUG
private static int _dbg_ConnectionCounter = 0;
private int _connectionNumber = 0;
private string _typeOfSocket;
/// <summary>
/// Returns a String that represents the current Object.
/// </summary>
/// <returns>A String that represents the current Object.</returns>
public override string ToString()
{
return string.Format("(No: {0}. Type: {1}. Valid: {2}. Type: {3}. Name: {4}. Identifier: {5}.)",
this._connectionNumber, this._typeOfSocket, this.IsValid,
Enum.Format(typeof(GenuineConnectionType), this.GenuineConnectionType, "g"),
this.ConnectionName, this.DbgConnectionId);
}
#endif
/// <summary>
/// Gets the identifier of the connection.
/// </summary>
public int DbgConnectionId
{
get
{
return this._connectionId;
}
}
private int _connectionId = ConnectionManager.GetUniqueConnectionId();
#endregion
#region -- Connection information ----------------------------------------------------------
/// <summary>
/// The socket.
/// </summary>
public Socket Socket;
/// <summary>
/// The name of this connection.
/// </summary>
public string ConnectionName;
/// <summary>
/// The host the connection is directed to.
/// </summary>
public HostInformation Remote;
/// <summary>
/// Gets the URL of the remote host if it's a server or the URI of the remote host if it's a client.
/// </summary>
public string PrimaryRemoteUri
{
get
{
// if we're server => return remote's uri
return this.IsServer ? this.Remote.Uri : this.Remote.Url;
}
}
/// <summary>
/// Transport Context.
/// </summary>
public ITransportContext ITransportContext;
/// <summary>
/// Indicates whether this connection is capable of sending or receiving messages.
/// </summary>
public bool IsValid = true;
/// <summary>
/// The type of the connection.
/// </summary>
public GenuineConnectionType GenuineConnectionType;
/// <summary>
/// Connection-level Security Session.
/// </summary>
public SecuritySession ConnectionLevelSecurity;
/// <summary>
/// The message being sent asynchronously.
/// </summary>
public Message Message;
/// <summary>
/// Maximum size of the chunk being sent through the socket.
/// </summary>
public int MaxSendSize;
/// <summary>
/// The message registrator to prevent processing the same request twice after connection
/// reestablishing.
/// </summary>
public IMessageRegistrator _iMessageRegistrator = new MessageRegistratorWithLimitedTime();
#endregion
#region -- Persistent or Named connection --------------------------------------------------
/// <summary>
/// Gets or sets an indication whether this socket is available for sending.
/// </summary>
public bool LockForSending = false;
/// <summary>
/// A queue of the messages arranged to be sent through this connection.
/// </summary>
public MessageContainer MessageContainer;
/// <summary>
/// The most recent moment the message was sent to the remote host.
/// To manage the ping sending.
/// </summary>
public int LastTimeContentWasSent
{
get
{
lock (_lastTimeContentWasSentLock)
return _lastTimeContentWasSent;
}
set
{
lock (_lastTimeContentWasSentLock)
_lastTimeContentWasSent = value;
}
}
private int _lastTimeContentWasSent = GenuineUtility.TickCount;
private object _lastTimeContentWasSentLock = new object();
#endregion
#region -- Invocation or One-Way connection ------------------------------------------------
/// <summary>
/// The message to receive a response for.
/// </summary>
public Message InitialMessage;
/// <summary>
/// The time span to close invocation connection after this period of inactivity.
/// </summary>
public int CloseConnectionAfterInactivity;
/// <summary>
/// The time after which the socket will be shut down automatically.
/// </summary>
public int ShutdownTime
{
get
{
lock (this._accessToLocalMembers)
return this._shutdownTime;
}
}
private int _shutdownTime = GenuineUtility.FurthestFuture;
/// <summary>
/// Renews socket activity for the CloseConnectionAfterInactivity value.
/// </summary>
public void Renew()
{
lock (this._accessToLocalMembers)
this._shutdownTime = GenuineUtility.GetTimeout(this.CloseConnectionAfterInactivity);
this.Remote.Renew(this.CloseConnectionAfterInactivity, false);
}
/// <summary>
/// Indicates whether the connection was opened by the remote host.
/// </summary>
public bool IsServer;
/// <summary>
/// Indicates the current state of the connection.
/// </summary>
public TcpInvocationFiniteAutomatonState TcpInvocationFiniteAutomatonState;
#endregion
#region -- Synchronous sending -------------------------------------------------------------
private int _syncWritingTimeout;
internal byte[] _sendBuffer;
internal MessageList MessagesSentSynchronously = new MessageList(1);
/// <summary>
/// Sets up the synchronous reading from the socket.
/// </summary>
/// <param name="operationTimeout">Operation timeout.</param>
public void SetupWriting(int operationTimeout)
{
if (this._sendBuffer == null)
this._sendBuffer = new byte[this.MaxSendSize];
this._syncWritingTimeout = operationTimeout;
}
/// <summary>
/// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
public override void Write(byte[] buffer, int offset, int count)
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
int milliseconds = GenuineUtility.GetMillisecondsLeft(this._syncWritingTimeout);
if (milliseconds <= 0)
throw GenuineExceptions.Get_Send_Timeout();
try
{
this.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, milliseconds);
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Transport] > 0 )
{
binaryLogWriter.WriteTransportContentEvent(LogCategory.Transport, "TcpSocketInfo.Write",
LogMessageType.SynchronousSendingStarted, null, null, this.Remote == null ? null : this.Remote,
binaryLogWriter[LogCategory.Transport] > 1 ? new MemoryStream(GenuineUtility.CutOutBuffer(buffer, offset, count)) : null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
this.DbgConnectionId, count, this.Remote == null || this.Remote.PhysicalAddress == null ? null : this.Remote.PhysicalAddress.ToString(),
null, null,
"The content is being sent synchronously. Size: {0}.", count);
}
for ( ; ; )
{
int bytesSent = 0;
try
{
bytesSent = this.Socket.Send(buffer, offset, count, SocketFlags.None);
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 )
{
binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "TcpSocketInfo.Write",
LogMessageType.LowLevelTransport_SyncSendingCompleted, null, null, this.Remote,
binaryLogWriter[LogCategory.LowLevelTransport] > 1 ? new MemoryStream(GenuineUtility.CutOutBuffer(buffer, offset, bytesSent)) : null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
this.DbgConnectionId, bytesSent, this.Socket.RemoteEndPoint.ToString(),
null, null,
"Socket.Send(). Size: {0}. Sent: {1}.", count, bytesSent);
}
}
catch (Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 )
{
binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "TcpSocketInfo.Write",
LogMessageType.LowLevelTransport_SyncSendingCompleted, ex, null, this.Remote == null ? null : this.Remote,
binaryLogWriter[LogCategory.LowLevelTransport] > 1 ? new MemoryStream(GenuineUtility.CutOutBuffer(buffer, offset, bytesSent)) : null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
this.DbgConnectionId, bytesSent, this.Socket.RemoteEndPoint.ToString(),
null, null,
"Socket.Send() failed. Size: {0}. Sent: {1}.", count, bytesSent);
}
}
if (bytesSent == 0)
throw GenuineExceptions.Get_Send_TransportProblem();
offset += bytesSent;
count -= bytesSent;
if (count <= 0)
break;
}
}
catch(Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Transport] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Transport, "TcpSocketInfo.Write",
LogMessageType.SynchronousSendingStarted, ex, null, this.Remote == null ? null : this.Remote,
binaryLogWriter[LogCategory.Transport] > 1 ? new MemoryStream(GenuineUtility.CutOutBuffer(buffer, offset, count)) : null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, this.DbgConnectionId, 0, 0, 0, count.ToString(), null, null, null,
"An exception is raised during synchronous sending.");
}
throw GenuineExceptions.Get_Send_TransportProblem();
}
}
#endregion
#region -- Asynchronous sending ------------------------------------------------------------
// WARNING: the stream is taken directly from the message
/// <summary>
/// The data being sent to the socket asynchronously.
/// </summary>
public byte[] AsyncSendBuffer;
/// <summary>
/// Size of the valid content being contained in SendingBuffer.
/// </summary>
public int AsyncSendBufferSizeOfValidContent;
/// <summary>
/// Current position in SendingBuffer.
/// </summary>
public int AsyncSendBufferCurrentPosition;
/// <summary>
/// Indicates whether the stream was read and last packet flag was sent.
/// </summary>
public bool AsyncSendBufferIsLastPacket;
/// <summary>
/// The stream containing the data being sent to the remote host.
/// </summary>
public Stream AsyncSendStream;
#endregion
#region -- Asynchronous receiving ----------------------------------------------------------
/// <summary>
/// The header.
/// </summary>
public byte[] ReceivingHeaderBuffer;
// /// <summary>
// /// The data being received from the socket asynchronously.
// /// </summary>
// public byte[] ReceivingBuffer;
/// <summary>
/// The size of the content being read to ReceivingBuffer.
/// </summary>
public int ReceivingBufferExpectedSize;
/// <summary>
/// The current position in ReceivingBuffer.
/// </summary>
public int ReceivingBufferCurrentPosition;
/// <summary>
/// True if a header is being currently received.
/// </summary>
public bool IsHeaderIsBeingReceived;
// /// <summary>
// /// Indicates whether the current packet being receivied is a last one.
// /// </summary>
// public bool IsLastPacket;
// /// <summary>
// /// The received content.
// /// </summary>
// public GenuineChunkedStream ReceivingMessageStream;
#endregion
#region -- Insignificant stream members ----------------------------------------------------
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>The total number of bytes read into the buffer.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
public override bool CanRead
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
public override bool CanSeek
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
public override bool CanWrite
{
get
{
return true;
}
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
public override long Length
{
get
{
throw new NotSupportedException();
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// Always fires NotSupportedException exception.
/// </summary>
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
/// <summary>
/// Begins an asynchronous read operation.
/// </summary>
/// <param name="buffer">The buffer to read the data into.</param>
/// <param name="offset">The byte offset in buffer at which to begin writing data read from the stream.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <param name="callback">An optional asynchronous callback, to be called when the read is complete.</param>
/// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param>
/// <returns>An IAsyncResult that represents the asynchronous read, which could still be pending.</returns>
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
/// <summary>
/// Begins an asynchronous write operation.
/// </summary>
/// <param name="buffer">The buffer to write data from.</param>
/// <param name="offset">The byte offset in buffer from which to begin writing.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <param name="callback">An optional asynchronous callback, to be called when the write is complete.</param>
/// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
/// <returns>An IAsyncResult that represents the asynchronous write, which could still be pending.</returns>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
/// <summary>
/// Waits for the pending asynchronous read to complete.
/// </summary>
/// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param>
/// <returns>The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams only return zero (0) at the end of the stream, otherwise, they should block until at least one byte is available.</returns>
public override int EndRead(IAsyncResult asyncResult)
{
throw new NotSupportedException();
}
/// <summary>
/// Ends an asynchronous write operation.
/// </summary>
/// <param name="asyncResult">A reference to the outstanding asynchronous I/O request.</param>
public override void EndWrite(IAsyncResult asyncResult)
{
throw new NotSupportedException();
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
public override void Flush()
{
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Sets the length of the current stream.
/// </summary>
/// <param name="val">The desired length of the current stream in bytes.</param>
public override void SetLength(long val)
{
throw new NotSupportedException();
}
#endregion
#region -- Connection state ----------------------------------------------------------------
/// <summary>
/// The state controller.
/// </summary>
private ConnectionStateSignaller _connectionStateSignaller;
/// <summary>
/// The state controller lock.
/// </summary>
private object _connectionStateSignallerLock = new object();
/// <summary>
/// Sets the state of the connection.
/// </summary>
/// <param name="genuineEventType">The state of the connection.</param>
/// <param name="reason">The exception.</param>
/// <param name="additionalInfo">The additional info.</param>
public void SignalState(GenuineEventType genuineEventType, Exception reason, object additionalInfo)
{
lock (this._connectionStateSignallerLock)
{
if (this._connectionStateSignaller == null)
this._connectionStateSignaller = new ConnectionStateSignaller(this.Remote, this.ITransportContext.IGenuineEventProvider);
this._connectionStateSignaller.SetState(genuineEventType, reason, additionalInfo);
}
}
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Securities;
using QuantConnect.ToolBox;
using QuantConnect.Util;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Market;
namespace QuantConnect.Tests.ToolBox
{
[TestFixture, Parallelizable(ParallelScope.Fixtures)]
public class LeanDataReaderTests
{
string _dataDirectory = "../../../Data/";
DateTime _fromDate = new DateTime(2013, 10, 7);
DateTime _toDate = new DateTime(2013, 10, 11);
[Test, Parallelizable(ParallelScope.Self)]
public void LoadsEquity_Daily_SingleEntryZip()
{
var dataPath = LeanData.GenerateZipFilePath(Globals.DataFolder, Symbols.AAPL, DateTime.UtcNow, Resolution.Daily, TickType.Trade);
var leanDataReader = new LeanDataReader(dataPath);
var data = leanDataReader.Parse().ToList();
Assert.AreEqual(5849, data.Count);
Assert.IsTrue(data.All(baseData => baseData.Symbol == Symbols.AAPL && baseData is TradeBar));
}
#region futures
[Test, Parallelizable(ParallelScope.Self)]
public void ReadsEntireZipFileEntries_OpenInterest()
{
var baseFuture = Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, SecurityIdentifier.DefaultDate);
var filePath = LeanData.GenerateZipFilePath(Globals.DataFolder, baseFuture, new DateTime(2013, 10, 06), Resolution.Minute, TickType.OpenInterest);
var leanDataReader = new LeanDataReader(filePath);
var data = leanDataReader.Parse()
.ToList()
.GroupBy(baseData => baseData.Symbol)
.Select(grp => grp.ToList())
.OrderBy(list => list[0].Symbol)
.ToList();
Assert.AreEqual(5, data.Count);
Assert.IsTrue(data.All(kvp => kvp.Count == 1));
foreach (var dataForSymbol in data)
{
Assert.IsTrue(dataForSymbol[0] is OpenInterest);
Assert.IsFalse(dataForSymbol[0].Symbol.IsCanonical());
Assert.AreEqual(Futures.Indices.SP500EMini, dataForSymbol[0].Symbol.ID.Symbol);
Assert.AreNotEqual(0, dataForSymbol[0]);
}
}
[Test, Parallelizable(ParallelScope.Self)]
public void ReadsEntireZipFileEntries_Trade()
{
var baseFuture = Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, SecurityIdentifier.DefaultDate);
var filePath = LeanData.GenerateZipFilePath(Globals.DataFolder, baseFuture, new DateTime(2013, 10, 06), Resolution.Minute, TickType.Trade);
var leanDataReader = new LeanDataReader(filePath);
var data = leanDataReader.Parse()
.ToList()
.GroupBy(baseData => baseData.Symbol)
.Select(grp => grp.ToList())
.OrderBy(list => list[0].Symbol)
.ToList();
Assert.AreEqual(2, data.Count);
foreach (var dataForSymbol in data)
{
Assert.IsTrue(dataForSymbol[0] is TradeBar);
Assert.IsFalse(dataForSymbol[0].Symbol.IsCanonical());
Assert.AreEqual(Futures.Indices.SP500EMini, dataForSymbol[0].Symbol.ID.Symbol);
}
Assert.AreEqual(118, data[0].Count);
Assert.AreEqual(10, data[1].Count);
}
[Test, Parallelizable(ParallelScope.Self)]
public void ReadsEntireZipFileEntries_Quote()
{
var baseFuture = Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, SecurityIdentifier.DefaultDate);
var filePath = LeanData.GenerateZipFilePath(Globals.DataFolder, baseFuture, new DateTime(2013, 10, 06), Resolution.Minute, TickType.Quote);
var leanDataReader = new LeanDataReader(filePath);
var data = leanDataReader.Parse()
.ToList()
.GroupBy(baseData => baseData.Symbol)
.Select(grp => grp.ToList())
.OrderBy(list => list[0].Symbol)
.ToList();
Assert.AreEqual(5, data.Count);
foreach (var dataForSymbol in data)
{
Assert.IsTrue(dataForSymbol[0] is QuoteBar);
Assert.IsFalse(dataForSymbol[0].Symbol.IsCanonical());
Assert.AreEqual(Futures.Indices.SP500EMini, dataForSymbol[0].Symbol.ID.Symbol);
}
Assert.AreEqual(10, data[0].Count);
Assert.AreEqual(13, data[1].Count);
Assert.AreEqual(52, data[2].Count);
Assert.AreEqual(155, data[3].Count);
Assert.AreEqual(100, data[4].Count);
}
[Test]
public void ReadFutureChainData()
{
var canonicalFutures = new Dictionary<Symbol, string>()
{
{ Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME),
"ES20Z13|ES21H14|ES20M14|ES19U14|ES19Z14" },
{Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX),
"GC29V13|GC26X13|GC27Z13|GC26G14|GC28J14|GC26M14|GC27Q14|GC29V14|GC29Z14|GC25G15|GC28J15|GC26M15|GC27Q15|GC29Z15|GC28M16|GC28Z16|GC28M17|GC27Z17|GC27M18|GC27Z18|GC26M19"},
};
var tickTypes = new[] { TickType.Trade, TickType.Quote, TickType.OpenInterest };
var resolutions = new[] { Resolution.Minute };
foreach (var canonical in canonicalFutures)
{
foreach (var res in resolutions)
{
foreach (var tickType in tickTypes)
{
var futures = LoadFutureChain(canonical.Key, _fromDate, tickType, res);
string chain = string.Join("|", futures.Select(f => f.Value));
if (tickType == TickType.Quote) //only quotes have the full chain!
Assert.AreEqual(canonical.Value, chain);
foreach (var future in futures)
{
string csv = LoadFutureData(future, tickType, res);
Assert.IsTrue(!string.IsNullOrEmpty(csv));
}
}
}
}
}
private List<Symbol> LoadFutureChain(Symbol baseFuture, DateTime date, TickType tickType, Resolution res)
{
var filePath = LeanData.GenerateZipFilePath(_dataDirectory, baseFuture, date, res, tickType);
//load future chain first
var config = new SubscriptionDataConfig(typeof(ZipEntryName), baseFuture, res,
TimeZones.NewYork, TimeZones.NewYork, false, false, false, false, tickType);
var factory = new ZipEntryNameSubscriptionDataSourceReader(TestGlobals.DataProvider, config, date, false);
var result = factory.Read(new SubscriptionDataSource(filePath, SubscriptionTransportMedium.LocalFile, FileFormat.ZipEntryName))
.Select(s => s.Symbol).ToList();
return result;
}
private string LoadFutureData(Symbol future, TickType tickType, Resolution res)
{
var dataType = LeanData.GetDataType(res, tickType);
var config = new SubscriptionDataConfig(dataType, future, res,
TimeZones.NewYork, TimeZones.NewYork, false, false, false, false, tickType);
var date = _fromDate;
var sb = new StringBuilder();
while (date <= _toDate)
{
var leanDataReader = new LeanDataReader(config, future, res, date, _dataDirectory);
foreach (var bar in leanDataReader.Parse())
{
//write base data type back to string
sb.AppendLine(LeanData.GenerateLine(bar, SecurityType.Future, res));
}
date = date.AddDays(1);
}
var csv = sb.ToString();
return csv;
}
[Test]
public void GenerateDailyAndHourlyFutureDataFromMinutes()
{
var tickTypes = new[] { TickType.Trade, TickType.Quote, TickType.OpenInterest };
var futures = new[] { Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME),
Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX)};
var resolutions = new[] { Resolution.Hour, Resolution.Daily };
foreach (var future in futures)
foreach (var res in resolutions)
foreach (var tickType in tickTypes)
ConvertMinuteFuturesData(future, tickType, res);
}
private void ConvertMinuteFuturesData(Symbol canonical, TickType tickType, Resolution outputResolution, Resolution inputResolution = Resolution.Minute)
{
var timeSpans = new Dictionary<Resolution, TimeSpan>()
{
{ Resolution.Daily, TimeSpan.FromHours(24)},
{ Resolution.Hour, TimeSpan.FromHours(1)},
};
var timeSpan = timeSpans[outputResolution];
var tickTypeConsolidatorMap = new Dictionary<TickType, Func<IDataConsolidator>>()
{
{TickType.Quote, () => new QuoteBarConsolidator(timeSpan)},
{TickType.OpenInterest, ()=> new OpenInterestConsolidator(timeSpan)},
{TickType.Trade, ()=> new TradeBarConsolidator(timeSpan) }
};
var consolidators = new Dictionary<string, IDataConsolidator>();
var configs = new Dictionary<string, SubscriptionDataConfig>();
var outputFiles = new Dictionary<string, StringBuilder>();
var futures = new Dictionary<string, Symbol>();
var date = _fromDate;
while (date <= _toDate)
{
var futureChain = LoadFutureChain(canonical, date, tickType, inputResolution);
foreach (var future in futureChain)
{
if (!futures.ContainsKey(future.Value))
{
futures[future.Value] = future;
var config = new SubscriptionDataConfig(LeanData.GetDataType(outputResolution, tickType),
future, inputResolution, TimeZones.NewYork, TimeZones.NewYork,
false, false, false, false, tickType);
configs[future.Value] = config;
consolidators[future.Value] = tickTypeConsolidatorMap[tickType].Invoke();
var sb = new StringBuilder();
outputFiles[future.Value] = sb;
consolidators[future.Value].DataConsolidated += (sender, bar) =>
{
sb.Append(LeanData.GenerateLine(bar, SecurityType.Future, outputResolution) + Environment.NewLine);
};
}
var leanDataReader = new LeanDataReader(configs[future.Value], future, inputResolution, date, _dataDirectory);
var consolidator = consolidators[future.Value];
foreach (var bar in leanDataReader.Parse())
{
consolidator.Update(bar);
}
}
date = date.AddDays(1);
}
//write all results
foreach (var consolidator in consolidators.Values)
consolidator.Scan(date);
var zip = LeanData.GenerateRelativeZipFilePath(canonical, _fromDate, outputResolution, tickType);
var zipPath = Path.Combine(_dataDirectory, zip);
var fi = new FileInfo(zipPath);
if (!fi.Directory.Exists)
fi.Directory.Create();
foreach (var future in futures.Values)
{
var zipEntry = LeanData.GenerateZipEntryName(future, _fromDate, outputResolution, tickType);
var sb = outputFiles[future.Value];
//Uncomment to write zip files
//QuantConnect.Compression.ZipCreateAppendData(zipPath, zipEntry, sb.ToString());
Assert.IsTrue(sb.Length > 0);
}
}
#endregion
[Test, TestCaseSource(nameof(OptionAndFuturesCases))]
public void ReadLeanFutureAndOptionDataFromFilePath(string composedFilePath, Symbol symbol, int rowsInfile, double sumValue)
{
// Act
var ldr = new LeanDataReader(composedFilePath);
var data = ldr.Parse().ToList();
// Assert
Assert.True(symbol.Equals(data.First().Symbol));
Assert.AreEqual(rowsInfile, data.Count);
Assert.AreEqual(sumValue, data.Sum(c => c.Value));
}
public static object[] OptionAndFuturesCases =
{
new object[]
{
"../../../Data/future/cme/minute/es/20131008_quote.zip#20131008_es_minute_quote_201312_20131220.csv",
LeanData
.ReadSymbolFromZipEntry(Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME),
Resolution.Minute, "20131008_es_minute_quote_201312_20131220.csv"),
1411,
2346061.875
},
new object[]
{
"../../../Data/future/comex/minute/gc/20131010_trade.zip#20131010_gc_minute_trade_201312_20131227.csv",
LeanData.ReadSymbolFromZipEntry(Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX),
Resolution.Minute, "20131010_gc_minute_trade_201312_20131227.csv"),
1379,
1791800.9
},
new object[]
{
"../../../Data/future/comex/tick/gc/20131009_quote.zip#20131009_gc_tick_quote_201406_20140626.csv",
LeanData.ReadSymbolFromZipEntry(Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX),
Resolution.Tick, "20131009_gc_tick_quote_201406_20140626.csv"),
197839,
259245064.8
},
new object[]
{
"../../../Data/future/comex/tick/gc/20131009_trade.zip#20131009_gc_tick_trade_201312_20131227.csv",
LeanData.ReadSymbolFromZipEntry(Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX),
Resolution.Tick, "20131009_gc_tick_trade_201312_20131227.csv"),
64712,
84596673.8
},
new object[]
{
"../../../Data/future/cme/minute/es/20131010_openinterest.zip#20131010_es_minute_openinterest_201312_20131220.csv",
LeanData
.ReadSymbolFromZipEntry(Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME),
Resolution.Minute, "20131010_es_minute_openinterest_201312.csv"),
3,
8119169
},
new object[]
{
"../../../Data/future/comex/tick/gc/20131009_openinterest.zip#20131009_gc_tick_openinterest_201310_20131029.csv",
LeanData.ReadSymbolFromZipEntry(Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX),
Resolution.Tick, "20131009_gc_tick_openinterest_201310_20131029.csv"),
4,
1312
},
new object[]
{
"../../../Data/option/usa/minute/aapl/20140606_quote_american.zip#20140606_aapl_minute_quote_american_put_7500000_20141018.csv",
LeanData.ReadSymbolFromZipEntry(Symbol.Create("AAPL", SecurityType.Option, Market.USA),
Resolution.Minute,
"20140606_aapl_minute_quote_american_put_7500000_20141018.csv"),
391,
44210.7
},
new object[]
{
"../../../Data/option/usa/minute/aapl/20140606_trade_american.zip#20140606_aapl_minute_trade_american_call_6475000_20140606.csv",
LeanData.ReadSymbolFromZipEntry(Symbol.Create("AAPL", SecurityType.Option, Market.USA),
Resolution.Minute,
"20140606_aapl_minute_trade_american_call_6475000_20140606.csv"),
374,
745.35
},
new object[]
{
"../../../Data/option/usa/minute/goog/20151224_openinterest_american.zip#20151224_goog_minute_openinterest_american_call_3000000_20160115.csv",
LeanData.ReadSymbolFromZipEntry(Symbol.Create("GOOG", SecurityType.Option, Market.USA),
Resolution.Minute,
"20151224_goog_minute_openinterest_american_call_3000000_20160115.csv"),
1,
38
}
};
[Test, TestCaseSource(nameof(SpotMarketCases))]
public void ReadLeanSpotMarketsSecuritiesDataFromFilePath(string securityType, string market, string resolution, string ticker, string fileName, int rowsInfile, double sumValue)
{
// Arrange
var filepath = GenerateFilepathForTesting(_dataDirectory, securityType, market, resolution, ticker, fileName);
SecurityType securityTypeEnum;
Enum.TryParse(securityType, true, out securityTypeEnum);
var symbol = Symbol.Create(ticker, securityTypeEnum, market);
// Act
var ldr = new LeanDataReader(filepath);
var data = ldr.Parse().ToList();
// Assert
Assert.True(symbol.Equals(data.First().Symbol));
Assert.AreEqual(rowsInfile, data.Count);
Assert.AreEqual(sumValue, data.Sum(c => c.Value));
}
public static object[] SpotMarketCases =
{
//TODO: generate Low resolution sample data for equities
new object[] {"equity", "usa", "daily", "aig", "aig.zip", 5849, 340770.5801},
new object[] {"equity", "usa", "minute", "aapl", "20140605_trade.zip", 686, 443184.58},
new object[] {"equity", "usa", "minute", "ibm", "20131010_quote.zip", 584, 107061.125},
new object[] {"equity", "usa", "second", "ibm", "20131010_trade.zip", 5060, 929385.34},
new object[] {"equity", "usa", "tick", "bac", "20131011_trade.zip", 112177, 1591680.73},
new object[] {"forex", "oanda", "minute", "eurusd", "20140502_quote.zip", 1222, 1693.578875},
new object[] {"forex", "oanda", "second", "nzdusd", "20140514_quote.zip", 18061, 15638.724575},
new object[] {"forex", "oanda", "tick", "eurusd", "20140507_quote.zip", 41367, 57598.54664},
new object[] {"cfd", "oanda", "hour", "xauusd", "xauusd.zip", 76499, 90453133.772 },
new object[] {"crypto", "gdax", "second", "btcusd", "20161008_trade.zip", 3453, 2137057.57},
new object[] {"crypto", "gdax", "minute", "ethusd", "20170903_trade.zip", 1440, 510470.66},
new object[] {"crypto", "gdax", "daily", "btcusd", "btcusd_trade.zip", 1318, 3725052.03},
};
public static string GenerateFilepathForTesting(string dataDirectory, string securityType, string market, string resolution, string ticker,
string fileName)
{
string filepath;
if (resolution == "daily" || resolution == "hour")
{
filepath = Path.Combine(dataDirectory, securityType, market, resolution, fileName);
}
else
{
filepath = Path.Combine(dataDirectory, securityType, market, resolution, ticker, fileName);
}
return filepath;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.IO;
using System.Linq;
using System.Collections;
using System.Reflection;
using NUnit.Framework.Api;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Filters;
using System.Diagnostics;
using NUnitLite.Runner;
using System.Net;
namespace GuiUnit
{
public class TestRunner : ITestListener
{
internal static MethodInfo LoadFileMethod;
public static int ExitCode = 0;
static bool initialized = false;
static IMainLoopIntegration mainLoop;
public static event EventHandler BeforeShutdown;
static TestRunner ()
{
LoadFileMethod = typeof(Assembly).GetMethods ().FirstOrDefault (m => {
return m.Name == "LoadFrom" && m.GetParameters ().Length == 1 && m.GetParameters () [0].ParameterType == typeof(string);
});
}
public static IMainLoopIntegration MainLoop {
get {
if (initialized)
return mainLoop;
initialized = true;
try { mainLoop = mainLoop ?? new XwtMainLoopIntegration (); } catch { }
try { mainLoop = mainLoop ?? new MonoMacMainLoopIntegration (); } catch { }
try { mainLoop = mainLoop ?? new GtkMainLoopIntegration (); } catch { }
return mainLoop;
} set {
mainLoop = value;
}
}
[STAThread]
public static int Main (string[] args)
{
new TestRunner ().Execute (args);
return ExitCode;
}
private CommandLineOptions commandLineOptions;
private NUnit.ObjectList assemblies = new NUnit.ObjectList();
private TextWriter writer;
private ITestListener listener;
private ITestAssemblyRunner runner;
private bool finished;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="TextUI"/> class.
/// </summary>
public TestRunner() : this(ConsoleWriter.Out, TestListener.NULL) { }
/// <summary>
/// Initializes a new instance of the <see cref="TextUI"/> class.
/// </summary>
/// <param name="writer">The TextWriter to use.</param>
public TestRunner(TextWriter writer) : this(writer, TestListener.NULL) { }
/// <summary>
/// Initializes a new instance of the <see cref="TextUI"/> class.
/// </summary>
/// <param name="writer">The TextWriter to use.</param>
/// <param name="listener">The Test listener to use.</param>
public TestRunner(TextWriter writer, ITestListener listener)
{
// Set the default writer - may be overridden by the args specified
this.writer = writer;
this.runner = new NUnitLiteTestAssemblyRunner(new NUnitLiteTestAssemblyBuilder());
this.listener = listener;
}
#endregion
#region Public Methods
/// <summary>
/// Execute a test run based on the aruments passed
/// from Main.
/// </summary>
/// <param name="args">An array of arguments</param>
public void Execute(string[] args)
{
this.commandLineOptions = new CommandLineOptions();
commandLineOptions.Parse(args);
if (commandLineOptions.OutFile != null)
this.writer = new StreamWriter(commandLineOptions.OutFile);
TcpWriter tcpWriter = null;
if (listener == TestListener.NULL && commandLineOptions.Port != -1) {
tcpWriter = new TcpWriter (new IPEndPoint (IPAddress.Loopback, commandLineOptions.Port));
listener = new XmlTestListener (tcpWriter);
}
// Ensure we always dispose the socket correctly.
using (tcpWriter)
ExecuteWithListener (args, tcpWriter);
}
void ExecuteWithListener (string[] args, TcpWriter tcpWriter)
{
if (!commandLineOptions.NoHeader)
WriteHeader(this.writer);
if (commandLineOptions.ShowHelp)
writer.Write(commandLineOptions.HelpText);
else if (commandLineOptions.Error)
{
writer.WriteLine(commandLineOptions.ErrorMessage);
writer.WriteLine(commandLineOptions.HelpText);
}
else
{
WriteRuntimeEnvironment(this.writer);
if (commandLineOptions.Wait && commandLineOptions.OutFile != null)
writer.WriteLine("Ignoring /wait option - only valid for Console");
#if SILVERLIGHT
IDictionary loadOptions = new System.Collections.Generic.Dictionary<string, string>();
#else
IDictionary loadOptions = new Hashtable();
#endif
//if (options.Load.Count > 0)
// loadOptions["LOAD"] = options.Load;
//IDictionary runOptions = new Hashtable();
//if (commandLineOptions.TestCount > 0)
// runOptions["RUN"] = commandLineOptions.Tests;
ITestFilter filter = commandLineOptions.TestCount > 0
? new SimpleNameFilter(commandLineOptions.Tests)
: TestFilter.Empty;
try
{
if (TestRunner.LoadFileMethod != null) {
foreach (string name in commandLineOptions.Parameters)
assemblies.Add (TestRunner.LoadFileMethod.Invoke (null, new[] { Path.GetFullPath (name) }));
}
if (assemblies.Count == 0)
assemblies.Add (Assembly.GetEntryAssembly ());
// TODO: For now, ignore all but first assembly
Assembly assembly = assemblies[0] as Assembly;
if (!runner.Load(assembly, loadOptions))
{
AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(assembly);
Console.WriteLine("No tests found in assembly {0}", assemblyName.Name);
return;
}
if (commandLineOptions.Explore)
ExploreTests();
else
{
if (commandLineOptions.Include != null && commandLineOptions.Include != string.Empty)
{
TestFilter includeFilter = new SimpleCategoryExpression(commandLineOptions.Include).Filter;
if (filter.IsEmpty)
filter = includeFilter;
else
filter = new AndFilter(filter, includeFilter);
}
if (commandLineOptions.Exclude != null && commandLineOptions.Exclude != string.Empty)
{
TestFilter excludeFilter = new NotFilter(new SimpleCategoryExpression(commandLineOptions.Exclude).Filter);
if (filter.IsEmpty)
filter = excludeFilter;
else if (filter is AndFilter)
((AndFilter)filter).Add(excludeFilter);
else
filter = new AndFilter(filter, excludeFilter);
}
if (MainLoop == null) {
RunTests (filter);
} else {
MainLoop.InitializeToolkit ();
System.Threading.ThreadPool.QueueUserWorkItem (d => {
try {
RunTests (filter);
} catch (Exception ex) {
Console.WriteLine ("Unexpected error while running the tests: {0}", ex);
} finally {
FinishTestExecution();
Shutdown();
}
});
MainLoop.RunMainLoop ();
}
}
}
catch (FileNotFoundException ex)
{
writer.WriteLine(ex.Message);
ExitCode = 1;
}
catch (Exception ex)
{
writer.WriteLine(ex.ToString());
ExitCode = 1;
}
finally
{
FinishTestExecution();
}
}
}
private void FinishTestExecution()
{
if (finished)
return;
finished = true;
if (commandLineOptions.OutFile == null)
{
if (commandLineOptions.Wait)
{
Console.WriteLine("Press Enter key to continue . . .");
Console.ReadLine();
}
}
else
{
writer.Close();
}
}
static void Shutdown ()
{
// Run the shutdown method on the main thread
var helper = new InvokerHelper {
Func = () => {
try {
if (BeforeShutdown != null)
BeforeShutdown (null, EventArgs.Empty);
} catch (Exception ex) {
Console.WriteLine ("Unexpected error during `BeforeShutdown`: {0}", ex);
ExitCode = 1;
} finally {
MainLoop.Shutdown (ExitCode);
}
return null;
}
};
MainLoop.InvokeOnMainLoop (helper);
}
/// <summary>
/// Write the standard header information to a TextWriter.
/// </summary>
/// <param name="writer">The TextWriter to use</param>
public static void WriteHeader(TextWriter writer)
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
#if NUNITLITE
string title = "NUnitLite";
#else
string title = "NUNit Framework";
#endif
AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly);
System.Version version = assemblyName.Version;
string copyright = "Copyright (C) 2012, Charlie Poole";
string build = "";
object[] attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
if (attrs.Length > 0)
{
AssemblyTitleAttribute titleAttr = (AssemblyTitleAttribute)attrs[0];
title = titleAttr.Title;
}
attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
if (attrs.Length > 0)
{
AssemblyCopyrightAttribute copyrightAttr = (AssemblyCopyrightAttribute)attrs[0];
copyright = copyrightAttr.Copyright;
}
attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false);
if (attrs.Length > 0)
{
AssemblyConfigurationAttribute configAttr = (AssemblyConfigurationAttribute)attrs[0];
if (configAttr.Configuration.Length > 0)
build = string.Format("({0})", configAttr.Configuration);
}
writer.WriteLine(String.Format("{0} {1} {2}", title, version.ToString(3), build));
writer.WriteLine(copyright);
writer.WriteLine();
}
/// <summary>
/// Write information about the current runtime environment
/// </summary>
/// <param name="writer">The TextWriter to be used</param>
public static void WriteRuntimeEnvironment(TextWriter writer)
{
string clrPlatform = Type.GetType("Mono.Runtime", false) == null ? ".NET" : "Mono";
writer.WriteLine("Runtime Environment -");
writer.WriteLine(" OS Version: {0}", Environment.OSVersion);
writer.WriteLine(" {0} Version: {1}", clrPlatform, Environment.Version);
writer.WriteLine();
}
#endregion
#region Helper Methods
private void RunTests(ITestFilter filter)
{
ITestResult result = runner.Run(this, filter);
ExitCode = result.FailCount > 0 ? 1 : 0;
new ResultReporter(result, writer).ReportResults();
if (commandLineOptions.ResultFile != null)
{
new NUnit2XmlOutputWriter().WriteResultFile (result, commandLineOptions.ResultFile);
Console.WriteLine();
Console.WriteLine("Results saved as {0}.", commandLineOptions.ResultFile);
}
}
private void ExploreTests()
{
XmlNode testNode = runner.LoadedTest.ToXml(true);
string listFile = commandLineOptions.ExploreFile;
TextWriter textWriter = listFile != null && listFile.Length > 0
? new StreamWriter(listFile)
: Console.Out;
#if CLR_2_0 || CLR_4_0
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Indent = true;
settings.Encoding = System.Text.Encoding.UTF8;
System.Xml.XmlWriter testWriter = System.Xml.XmlWriter.Create(textWriter, settings);
#else
System.Xml.XmlTextWriter testWriter = new System.Xml.XmlTextWriter(textWriter);
testWriter.Formatting = System.Xml.Formatting.Indented;
#endif
testNode.WriteTo(testWriter);
testWriter.Close();
Console.WriteLine();
Console.WriteLine("Test info saved as {0}.", listFile);
}
#endregion
#region ITestListener Members
/// <summary>
/// A test has just started
/// </summary>
/// <param name="test">The test</param>
public void TestStarted(ITest test)
{
if (commandLineOptions.LabelTestsInOutput)
writer.WriteLine("***** {0}", test.FullName);
listener.TestStarted (test);
}
/// <summary>
/// A test has just finished
/// </summary>
/// <param name="result">The result of the test</param>
public void TestFinished(ITestResult result)
{
listener.TestFinished (result);
}
/// <summary>
/// A test has produced some text output
/// </summary>
/// <param name="testOutput">A TestOutput object holding the text that was written</param>
public void TestOutput(TestOutput testOutput)
{
listener.TestOutput (testOutput);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Test.Utilities;
using Xunit;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
internal abstract class AbstractCommandHandlerTestState : IDisposable
{
public readonly TestWorkspace Workspace;
public readonly IEditorOperations EditorOperations;
public readonly ITextUndoHistoryRegistry UndoHistoryRegistry;
private readonly ITextView _textView;
private readonly ITextBuffer _subjectBuffer;
public AbstractCommandHandlerTestState(
XElement workspaceElement,
ComposableCatalog extraParts = null,
bool useMinimumCatalog = false,
string workspaceKind = null)
: this(workspaceElement, GetExportProvider(useMinimumCatalog, extraParts), workspaceKind)
{
}
/// <summary>
/// This can use input files with an (optionally) annotated span 'Selection' and a cursor position ($$),
/// and use it to create a selected span in the TextView.
///
/// For instance, the following will create a TextView that has a multiline selection with the cursor at the end.
///
/// Sub Foo
/// {|Selection:SomeMethodCall()
/// AnotherMethodCall()$$|}
/// End Sub
///
/// You can use multiple selection spans to create box selections.
///
/// Sub Foo
/// {|Selection:$$box|}11111
/// {|Selection:sel|}111
/// {|Selection:ect|}1
/// {|Selection:ion|}1111111
/// End Sub
/// </summary>
public AbstractCommandHandlerTestState(
XElement workspaceElement,
ExportProvider exportProvider,
string workspaceKind)
{
this.Workspace = TestWorkspace.CreateWorkspace(
workspaceElement,
exportProvider: exportProvider,
workspaceKind: workspaceKind);
var cursorDocument = this.Workspace.Documents.First(d => d.CursorPosition.HasValue);
_textView = cursorDocument.GetTextView();
_subjectBuffer = cursorDocument.GetTextBuffer();
if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out var selectionSpanList))
{
var firstSpan = selectionSpanList.First();
var lastSpan = selectionSpanList.Last();
var cursorPosition = cursorDocument.CursorPosition.Value;
Assert.True(cursorPosition == firstSpan.Start || cursorPosition == firstSpan.End
|| cursorPosition == lastSpan.Start || cursorPosition == lastSpan.End,
"cursorPosition wasn't at an endpoint of the 'Selection' annotated span");
_textView.Selection.Mode = selectionSpanList.Count > 1
? TextSelectionMode.Box
: TextSelectionMode.Stream;
SnapshotPoint boxSelectionStart, boxSelectionEnd;
bool isReversed;
if (cursorPosition == firstSpan.Start || cursorPosition == lastSpan.End)
{
// Top-left and bottom-right corners used as anchor points.
boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.Start);
boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.End);
isReversed = cursorPosition == firstSpan.Start;
}
else
{
// Top-right and bottom-left corners used as anchor points.
boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.End);
boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.Start);
isReversed = cursorPosition == firstSpan.End;
}
_textView.Selection.Select(
new SnapshotSpan(boxSelectionStart, boxSelectionEnd),
isReversed: isReversed);
}
else
{
_textView.Caret.MoveTo(
new SnapshotPoint(
_textView.TextBuffer.CurrentSnapshot,
cursorDocument.CursorPosition.Value));
}
this.EditorOperations = GetService<IEditorOperationsFactoryService>().GetEditorOperations(_textView);
this.UndoHistoryRegistry = GetService<ITextUndoHistoryRegistry>();
}
public void Dispose()
{
Workspace.Dispose();
}
public T GetService<T>()
{
return Workspace.GetService<T>();
}
private static ExportProvider GetExportProvider(bool useMinimumCatalog, ComposableCatalog extraParts)
{
var baseCatalog = useMinimumCatalog
? TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic
: TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic;
if (extraParts == null)
{
return MinimalTestExportProvider.CreateExportProvider(baseCatalog);
}
return MinimalTestExportProvider.CreateExportProvider(baseCatalog.WithParts(extraParts));
}
public virtual ITextView TextView
{
get { return _textView; }
}
public virtual ITextBuffer SubjectBuffer
{
get { return _subjectBuffer; }
}
#region MEF
public Lazy<TExport, TMetadata> GetExport<TExport, TMetadata>()
{
return (Lazy<TExport, TMetadata>)(object)Workspace.ExportProvider.GetExport<TExport, TMetadata>();
}
public IEnumerable<Lazy<TExport, TMetadata>> GetExports<TExport, TMetadata>()
{
return Workspace.ExportProvider.GetExports<TExport, TMetadata>();
}
public T GetExportedValue<T>()
{
return Workspace.ExportProvider.GetExportedValue<T>();
}
public IEnumerable<T> GetExportedValues<T>()
{
return Workspace.ExportProvider.GetExportedValues<T>();
}
protected static IEnumerable<Lazy<TProvider, OrderableLanguageMetadata>> CreateLazyProviders<TProvider>(
TProvider[] providers,
string languageName)
{
if (providers == null)
{
return Array.Empty<Lazy<TProvider, OrderableLanguageMetadata>>();
}
return providers.Select(p =>
new Lazy<TProvider, OrderableLanguageMetadata>(
() => p,
new OrderableLanguageMetadata(
new Dictionary<string, object> {
{"Language", languageName },
{"Name", string.Empty }}),
true));
}
protected static IEnumerable<Lazy<TProvider, OrderableLanguageAndRoleMetadata>> CreateLazyProviders<TProvider>(
TProvider[] providers,
string languageName,
string[] roles)
{
if (providers == null)
{
return Array.Empty<Lazy<TProvider, OrderableLanguageAndRoleMetadata>>();
}
return providers.Select(p =>
new Lazy<TProvider, OrderableLanguageAndRoleMetadata>(
() => p,
new OrderableLanguageAndRoleMetadata(
new Dictionary<string, object> {
{"Language", languageName },
{"Name", string.Empty },
{"Roles", roles }}),
true));
}
#endregion
#region editor related operation
public void SendBackspace()
{
EditorOperations.Backspace();
}
public void SendDelete()
{
EditorOperations.Delete();
}
public void SendRightKey(bool extendSelection = false)
{
EditorOperations.MoveToNextCharacter(extendSelection);
}
public void SendLeftKey(bool extendSelection = false)
{
EditorOperations.MoveToPreviousCharacter(extendSelection);
}
public void SendMoveToPreviousCharacter(bool extendSelection = false)
{
EditorOperations.MoveToPreviousCharacter(extendSelection);
}
public void SendDeleteWordToLeft()
{
EditorOperations.DeleteWordToLeft();
}
public void SendUndo(int count = 1)
{
var history = UndoHistoryRegistry.GetHistory(SubjectBuffer);
history.Undo(count);
}
#endregion
#region test/information/verification
public ITextSnapshotLine GetLineFromCurrentCaretPosition()
{
var caretPosition = GetCaretPoint();
return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition.BufferPosition);
}
public string GetLineTextFromCaretPosition()
{
var caretPosition = Workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value;
return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition).GetText();
}
public string GetDocumentText()
{
return SubjectBuffer.CurrentSnapshot.GetText();
}
public CaretPosition GetCaretPoint()
{
return TextView.Caret.Position;
}
/// <summary>
/// Used in synchronous methods to ensure all outstanding <see cref="IAsyncToken"/> work has been
/// completed.
/// </summary>
public void AssertNoAsynchronousOperationsRunning()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
Assert.False(waiters.Any(x => x.HasPendingWork), "IAsyncTokens unexpectedly alive. Call WaitForAsynchronousOperationsAsync before this method");
}
public async Task WaitForAsynchronousOperationsAsync()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
await waiters.WaitAllAsync();
}
public void AssertMatchesTextStartingAtLine(int line, string text)
{
var lines = text.Split('\r');
foreach (var expectedLine in lines)
{
Assert.Equal(expectedLine.Trim(), SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(line).GetText().Trim());
line += 1;
}
}
#endregion
#region command handler
public void SendBackspace(Action<BackspaceKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new BackspaceKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendDelete(Action<DeleteKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new DeleteKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendWordDeleteToStart(Action<WordDeleteToStartCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new WordDeleteToStartCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendEscape(Action<EscapeKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new EscapeKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendUpKey(Action<UpKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new UpKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendDownKey(Action<DownKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new DownKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendTab(Action<TabKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new TabKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendBackTab(Action<BackTabKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new BackTabKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendReturn(Action<ReturnKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new ReturnKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPageUp(Action<PageUpKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PageUpKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPageDown(Action<PageDownKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PageDownKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendCut(Action<CutCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new CutCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPaste(Action<PasteCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PasteCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInvokeCompletionList(Action<InvokeCompletionListCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InvokeCompletionListCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendCommitUniqueCompletionListItem(Action<CommitUniqueCompletionListItemCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new CommitUniqueCompletionListItemCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInsertSnippetCommand(Action<InsertSnippetCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InsertSnippetCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendSurroundWithCommand(Action<SurroundWithCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SurroundWithCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInvokeSignatureHelp(Action<InvokeSignatureHelpCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InvokeSignatureHelpCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendTypeChar(char typeChar, Action<TypeCharCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new TypeCharCommandArgs(TextView, SubjectBuffer, typeChar), nextHandler);
}
public void SendTypeChars(string typeChars, Action<TypeCharCommandArgs, Action> commandHandler)
{
foreach (var ch in typeChars)
{
var localCh = ch;
SendTypeChar(ch, commandHandler, () => EditorOperations.InsertText(localCh.ToString()));
}
}
public void SendSave(Action<SaveCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SaveCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendSelectAll(Action<SelectAllCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SelectAllCommandArgs(TextView, SubjectBuffer), nextHandler);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using KSP.Localization;
namespace KERBALISM
{
public class Reliability : PartModule, ISpecifics, IModuleInfo, IPartCostModifier, IPartMassModifier
{
// config
[KSPField(isPersistant = true)] public string type; // component name
[KSPField] public double mtbf = 3600 * 6 * 1000; // mean time between failures, in seconds
[KSPField] public string repair = string.Empty; // repair crew specs
[KSPField] public string title = string.Empty; // short description of component
[KSPField] public string redundancy = string.Empty; // redundancy group
[KSPField] public double extra_cost; // extra cost for high-quality, in proportion of part cost
[KSPField] public double extra_mass; // extra mass for high-quality, in proportion of part mass
[KSPField] public double rated_radiation = 0; // rad/h this part can sustain without taking any damage. Only effective with MTBF failures.
[KSPField] public double radiation_decay_rate = 1; // time to next failure is reduced by (rad/h - rated_radiation) * radiation_decay_rate per second
// engine only features
[KSPField] public double turnon_failure_probability = -1; // probability of a failure when turned on or staged
[KSPField] public double rated_operation_duration = -1; // failure rate increases dramatically if this is exceeded
[KSPField] public int rated_ignitions = -1; // failure rate increases dramatically if this is exceeded
// persistence
[KSPField(isPersistant = true)] public bool broken; // true if broken
[KSPField(isPersistant = true)] public bool critical; // true if failure can't be repaired
[KSPField(isPersistant = true)] public bool quality; // true if the component is high-quality
[KSPField(isPersistant = true)] public double last = 0.0; // time of last failure
[KSPField(isPersistant = true)] public double next = 0.0; // time of next failure
[KSPField(isPersistant = true)] public double last_inspection = 0.0; // time of last service
[KSPField(isPersistant = true)] public bool needMaintenance = false;// true when component is inspected and about to fail
[KSPField(isPersistant = true)] public bool enforce_breakdown = false; // true when the next failure is enforced
[KSPField(isPersistant = true)] public bool running = false; // true when the next failure is enforced
[KSPField(isPersistant = true)] public double operation_duration = 0.0; // failure rate increases dramatically if this is exceeded
[KSPField(isPersistant = true)] public double fail_duration = 0.0; // fail when operation_duration exceeds this
[KSPField(isPersistant = true)] public int ignitions = 0; // accumulated ignitions
// status ui
[KSPField(guiActive = true, guiActiveEditor = true, guiName = "_", groupName = "Reliability", groupDisplayName = "#KERBALISM_Group_Reliability")]//Reliability
public string Status; // show component status
// data
List<PartModule> modules; // components cache
CrewSpecs repair_cs; // crew specs
bool explode = false;
public override void OnStart(StartState state)
{
// don't break tutorial scenarios
if (Lib.DisableScenario(this)) return;
Fields["Status"].guiName = title;
#if DEBUG_RELIABILITY
Events["Break"].guiName = "Break " + title + " [DEBUG]";
#endif
// do nothing in the editors and when compiling parts
if (!Lib.IsFlight()) return;
if (last_inspection <= 0) last_inspection = Planetarium.GetUniversalTime();
// cache list of modules
if(type.StartsWith("ModuleEngines", StringComparison.Ordinal))
{
// do this generically. there are many different engine types derived from ModuleEngines:
// ModuleEnginesFX, ModuleEnginesRF, all the SolverEngines, possibly more
// this will also reduce the amount of configuration overhead, no need to duplicate the same
// config for stock with ModuleEngines and ModuleEnginesFX
modules = new List<PartModule>();
var engines = part.FindModulesImplementing<ModuleEngines>();
foreach (var engine in engines)
{
modules.Add(engine);
}
}
else
{
modules = part.FindModulesImplementing<PartModule>().FindAll(k => k.moduleName == type);
}
// parse crew specs
repair_cs = new CrewSpecs(repair);
// setup ui
Events["Inspect"].guiName = Local.Reliability_Inspect.Format("<b>"+title+"</b>");//Lib.BuildString("Inspect <<1>>)
Events["Repair"].guiName = Local.Reliability_Repair.Format("<b>"+title+"</b>");//Lib.BuildString("Repair <<1>>)
// sync monobehaviour state with module state
// - required as the monobehaviour state is not serialized
if (broken)
{
foreach (PartModule m in modules)
{
m.enabled = false;
m.isEnabled = false;
}
}
if(broken) StartCoroutine(DeferredApply());
}
public IEnumerator DeferredApply()
{
// wait until vessel is unpacked. doing this will ensure that module
// specific hacks are executed after the module itself was OnStart()ed.
yield return new WaitUntil(() => !vessel.packed);
if (broken)
{
Apply(true);
}
}
/// <summary> Returns true if a failure should be triggered. </summary>
protected bool IgnitionCheck()
{
if (!PreferencesReliability.Instance.engineFailures)
return false;
// don't check for a couple of seconds after the vessel was loaded.
// when loading a quicksave with the engines running, the engine state
// is off at first which would cost an ignition and possibly trigger a failure
if (Time.time < Kerbalism.gameLoadTime + 3)
return false;
ignitions++;
vessel.KerbalismData().ResetReliabilityStatus();
bool fail = false;
bool launchpad = vessel.situation == Vessel.Situations.PRELAUNCH || ignitions <= 1 && vessel.situation == Vessel.Situations.LANDED;
if (turnon_failure_probability > 0)
{
// q = quality indicator
var q = quality ? Settings.QualityScale : 1.0;
if (launchpad) q /= 2.5; // the very first ignition is more likely to fail
q += Lib.Clamp(ignitions - 1, 0.0, 6.0) / 20.0; // subsequent ignition failures become less and less likely, reducing by up to 30%
if (Lib.RandomDouble() < (turnon_failure_probability * PreferencesReliability.Instance.ignitionFailureChance) / q)
{
fail = true;
#if DEBUG_RELIABILITY
Lib.DebugLog("Ignition check: " + part.partInfo.title + " ignitions " + ignitions + " turnon failure");
#endif
}
}
//
if (rated_ignitions > 0)
{
int total_ignitions = EffectiveIgnitions(quality, rated_ignitions);
if (ignitions >= total_ignitions * 0.9) needMaintenance = true;
if (ignitions > total_ignitions)
{
var q = (quality ? Settings.QualityScale : 1.0) * Lib.RandomDouble();
q /= PreferencesReliability.Instance.ignitionFailureChance;
q /= (ignitions - total_ignitions); // progressively increase the odds of a failure with every extra ignition
#if DEBUG_RELIABILITY
Lib.Log("Reliability: ignition exceeded q=" + q + " ignitions=" + ignitions + " total_ignitions=" + total_ignitions);
#endif
if (q < 0.3)
{
fail = true;
}
}
}
if (fail)
{
enforce_breakdown = true;
explode = Lib.RandomDouble() < 0.1;
next = Planetarium.GetUniversalTime() + Lib.RandomDouble() * 2.0;
var fuelSystemFailureProbability = 0.1;
if (launchpad) fuelSystemFailureProbability = 0.5;
if(Lib.RandomDouble() < fuelSystemFailureProbability)
{
// broken fuel line -> delayed kaboom
explode = true;
next += Lib.RandomDouble() * 10 + 4;
FlightLogger.fetch?.LogEvent(Local.FlightLogger_Destruction.Format(part.partInfo.title));// <<1>> fuel system leak caused destruction of the engine"
}
else
{
FlightLogger.fetch?.LogEvent(Local.FlightLogger_Ignition.Format(part.partInfo.title));// <<1>> failure on ignition"
}
}
return fail;
}
public void Update()
{
if (Lib.IsFlight())
{
// enforce state
// - required as things like Configure or AnimationGroup can re-enable broken modules
if (broken)
{
foreach (PartModule m in modules)
{
m.enabled = false;
m.isEnabled = false;
}
}
Status = string.Empty;
// update ui
if (broken)
{
Status = critical ? Lib.Color(Local.Reliability_criticalfailure, Lib.Kolor.Red) : Lib.Color(Local.Reliability_malfunction, Lib.Kolor.Yellow);//"critical failure""malfunction"
}
else
{
if (PreferencesReliability.Instance.engineFailures && (rated_operation_duration > 0 || rated_ignitions > 0))
{
if (rated_operation_duration > 0)
{
double effective_duration = EffectiveDuration(quality, rated_operation_duration);
Status = Lib.BuildString(Local.Reliability_burnremaining ," ", Lib.HumanReadableDuration(Math.Max(0, effective_duration - operation_duration)));//"remaining burn:"
}
if (rated_ignitions > 0)
{
int effective_ignitions = EffectiveIgnitions(quality, rated_ignitions);
Status = Lib.BuildString(Status,
(string.IsNullOrEmpty(Status) ? "" : ", "),
Local.Reliability_ignitions ," ", Math.Max(0, effective_ignitions - ignitions).ToString());//"ignitions:"
}
}
if(rated_radiation > 0)
{
var rated = quality ? rated_radiation * Settings.QualityScale : rated_radiation;
var current = vessel.KerbalismData().EnvRadiation * 3600.0;
if(rated < current)
{
Status = Lib.BuildString(Status, (string.IsNullOrEmpty(Status) ? "" : ", "), Lib.Color(Local.Reliability_takingradiationdamage, Lib.Kolor.Orange));//"taking radiation damage"
}
}
}
if (string.IsNullOrEmpty(Status)) Status = Local.Generic_NOMINAL;//"nominal"
Events["Inspect"].active = !broken && !needMaintenance;
Events["Repair"].active = repair_cs && (broken || needMaintenance) && !critical;
if(needMaintenance) {
Events["Repair"].guiName = Local.Reliability_Service.Format("<b>"+title+"</b>");//Lib.BuildString("Service <<1>>")
}
RunningCheck();
// if it has failed, trigger malfunction
var now = Planetarium.GetUniversalTime();
if (next > 0 && now > next && !broken)
{
#if DEBUG_RELIABILITY
Lib.Log("Reliablity: breakdown for " + part.partInfo.title);
#endif
Break();
}
// set highlight
Highlight(part);
}
else
{
// update ui
Events["Quality"].guiName = Lib.StatusToggle(Local.Reliability_qualityinfo.Format("<b>"+title+"</b>"), quality ? Local.Reliability_qualityhigh : Local.Reliability_qualitystandard);//Lib.BuildString(<<1>> quality")"high""standard"
Status = string.Empty;
if(mtbf > 0 && PreferencesReliability.Instance.mtbfFailures)
{
double effective_mtbf = EffectiveMTBF(quality, mtbf);
Status = Lib.BuildString(Status,
(string.IsNullOrEmpty(Status) ? "" : ", "),
Local.Reliability_MTBF +" ", Lib.HumanReadableDuration(effective_mtbf));//"MTBF:"
}
if (rated_operation_duration > 0 && PreferencesReliability.Instance.engineFailures)
{
double effective_duration = EffectiveDuration(quality, rated_operation_duration);
Status = Lib.BuildString(Status,
(string.IsNullOrEmpty(Status) ? "" : ", "),
Local.Reliability_Burntime +" ",//"Burn time:
Lib.HumanReadableDuration(effective_duration));
}
if (rated_ignitions > 0 && PreferencesReliability.Instance.engineFailures)
{
int effective_ignitions = EffectiveIgnitions(quality, rated_ignitions);
Status = Lib.BuildString(Status,
(string.IsNullOrEmpty(Status) ? "" : ", "),
Local.Reliability_ignitions +" ", effective_ignitions.ToString());//"ignitions:
}
if (rated_radiation > 0 && PreferencesReliability.Instance.mtbfFailures)
{
var r = quality ? rated_radiation * Settings.QualityScale : rated_radiation;
Status = Lib.BuildString(Status,
(string.IsNullOrEmpty(Status) ? "" : ", "),
Lib.HumanReadableRadiation(r / 3600.0));
}
}
}
public void FixedUpdate()
{
// do nothing in the editor
if (Lib.IsEditor()) return;
var now = Planetarium.GetUniversalTime();
// if it has not malfunctioned
if (!broken && mtbf > 0 && PreferencesReliability.Instance.mtbfFailures)
{
// calculate time of next failure if necessary
if (next <= 0)
{
last = now;
var guaranteed = mtbf / 2.0;
var r = 1 - Math.Pow(Lib.RandomDouble(), 3);
next = now + guaranteed + mtbf * (quality ? Settings.QualityScale : 1.0) * r;
#if DEBUG_RELIABILITY
Lib.Log("Reliability: MTBF failure in " + (now - next) + " for " + part.partInfo.title);
#endif
}
var decay = RadiationDecay(quality, vessel.KerbalismData().EnvRadiation, Kerbalism.elapsed_s, rated_radiation, radiation_decay_rate);
next -= decay;
}
}
protected double nextRunningCheck = 0.0;
protected double lastRunningCheck = 0.0;
/// <summary>
/// This checks burn time and ignition failures, which is intended for engines only.
/// Since engines don't run on on unloaded vessels in KSP, this is only implemented
/// for loaded vessels.
/// </summary>
protected void RunningCheck()
{
if (!PreferencesReliability.Instance.engineFailures) return;
// don't count engine running time during time warp (see https://github.com/Kerbalism/Kerbalism/pull/646)
if (TimeWarp.WarpMode == TimeWarp.Modes.HIGH && TimeWarp.CurrentRate > 1)
{
// forget that the engine was running when we're warping. otherwise we might consume engine time
// during warp when it actually didn't run because of KSP physics
lastRunningCheck = 0;
return;
}
if (broken || enforce_breakdown || turnon_failure_probability <= 0 && rated_operation_duration <= 0) return;
double now = Planetarium.GetUniversalTime();
if (now < nextRunningCheck) return;
nextRunningCheck = now + 0.5; // twice a second is fast enough for a smooth countdown in the PAW
if (!running)
{
if (IsRunning())
{
running = true;
if (IgnitionCheck())
Break();
}
}
else
{
running = IsRunning();
}
if (running && rated_operation_duration > 1 && lastRunningCheck > 0)
{
var duration = now - lastRunningCheck;
operation_duration += duration;
vessel.KerbalismData().ResetReliabilityStatus();
if (fail_duration <= 0)
{
// see https://www.desmos.com/calculator/l2sdoauiyw
// these values will give the following result:
// 0% failure at 40% of the operation duration
// 1.68% failure at 100% of the operation duration
// 100% failure at 140% of the operation duration
int r = 8; // the random number exponent
var g = 0.4; // guarantee factor
// calculate a random point on which the engine will fail
var f = rated_operation_duration;
if (quality) f *= Settings.QualityScale;
// extend engine burn duration by preference value
f /= PreferencesReliability.Instance.engineOperationFailureChance;
// random^r so we get an exponentially increasing failure probability
var p = Math.Pow(Lib.RandomDouble(), r);
// 1-p turns the probability of failure into one of non-failure
p = 1 - p;
// 35% guaranteed burn duration
var guaranteed_operation = f * g;
fail_duration = guaranteed_operation + f * p;
#if DEBUG_RELIABILITY
Lib.Log(part.partInfo.title + " will fail after " + Lib.HumanReadableDuration(fail_duration) + " burn time");
#endif
}
if (fail_duration < operation_duration)
{
next = now;
enforce_breakdown = true;
explode = Lib.RandomDouble() < 0.2;
#if DEBUG_RELIABILITY
Lib.Log("Reliability: " + part.partInfo.title + " fails because of material fatigue");
#endif
FlightLogger.fetch?.LogEvent(Local.FlightLogger_MaterialFatigue.Format(part.partInfo.title));// <<1>> failed because of material fatigue"
}
}
lastRunningCheck = now;
}
public static void BackgroundUpdate(Vessel v, ProtoPartSnapshot p, ProtoPartModuleSnapshot m, Reliability reliability, double elapsed_s)
{
if(!PreferencesReliability.Instance.mtbfFailures) return;
// check for existing malfunction and if it actually uses MTBF failures
if (Lib.Proto.GetBool(m, "broken")) return;
if (reliability.mtbf <= 0) return;
// get time of next failure
double next = Lib.Proto.GetDouble(m, "next");
bool quality = Lib.Proto.GetBool(m, "quality");
var now = Planetarium.GetUniversalTime();
// calculate epoch of failure if necessary
if (next <= 0)
{
var guaranteed = reliability.mtbf / 2.0;
var r = 1 - Math.Pow(Lib.RandomDouble(), 3);
next = now + guaranteed + reliability.mtbf * (quality ? Settings.QualityScale : 1.0) * r;
Lib.Proto.Set(m, "last", now);
Lib.Proto.Set(m, "next", next);
#if DEBUG_RELIABILITY
Lib.Log("Reliability: background MTBF failure in " + (now - next) + " for " + p);
#endif
}
var rad = v.KerbalismData().EnvRadiation;
var decay = RadiationDecay(quality, rad, elapsed_s, reliability.rated_radiation, reliability.radiation_decay_rate);
if (decay > 0)
{
next -= decay;
Lib.Proto.Set(m, "next", next);
}
// if it has failed, trigger malfunction
if (now > next)
{
#if DEBUG_RELIABILITY
Lib.Log("Reliablity: background MTBF failure for " + p);
#endif
ProtoBreak(v, p, m);
}
}
[KSPEvent(guiActiveEditor = true, guiName = "_", active = true, groupName = "Reliability", groupDisplayName = "#KERBALISM_Group_Reliability")]//Reliability
// toggle between standard and high quality
public void Quality()
{
quality = !quality;
// sync all other modules in the symmetry group
foreach (Part p in part.symmetryCounterparts)
{
Reliability reliability = p.Modules[part.Modules.IndexOf(this)] as Reliability;
if (reliability != null)
{
reliability.quality = !reliability.quality;
}
}
// refresh VAB/SPH ui
if (Lib.IsEditor()) GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);
}
[KSPEvent(guiActiveUnfocused = true, unfocusedRange = 3.5f, guiName = "_", active = false, groupName = "Reliability", groupDisplayName = "#KERBALISM_Group_Reliability")]//Reliability
// show a message with some hint on time to next failure
public void Inspect()
{
// disable for dead eva kerbals
Vessel v = FlightGlobals.ActiveVessel;
if (v == null || EVA.IsDead(v)) return;
// get normalized time to failure
double time_k = (Planetarium.GetUniversalTime() - last) / (next - last);
needMaintenance = mtbf > 0 && time_k > 0.35;
if (rated_ignitions > 0 && ignitions >= Math.Ceiling(EffectiveIgnitions(quality, rated_ignitions) * 0.4)) needMaintenance = true;
if (rated_operation_duration > 0 && operation_duration >= EffectiveDuration(quality, rated_operation_duration) * 0.4) needMaintenance = true;
v.KerbalismData().ResetReliabilityStatus();
// notify user
if (!needMaintenance)
{
last_inspection = Planetarium.GetUniversalTime();
Message.Post(Lib.TextVariant(
Local.Reliability_MessagePost1,//"It is practically new"
Local.Reliability_MessagePost2,//"It is in good shape"
Local.Reliability_MessagePost3,//"This will last for ages"
Local.Reliability_MessagePost4,//"Brand new!"
Local.Reliability_MessagePost5//"Doesn't look used. Is this even turned on?"
));
}
else
{
Message.Post(Lib.TextVariant(
Local.Reliability_MessagePost6,//"Looks like it's going to fall off soon."
Local.Reliability_MessagePost7,//"Better get the duck tape ready!"
Local.Reliability_MessagePost8,//"It is reaching its operational limits."
Local.Reliability_MessagePost9,//"How is this still working?"
Local.Reliability_MessagePost10//"It could fail at any moment now."
));
}
}
[KSPEvent(guiActiveUnfocused = true, unfocusedRange = 3.5f, guiName = "_", active = false, groupName = "Reliability", groupDisplayName = "#KERBALISM_Group_Reliability")]//Reliability
// repair malfunctioned component
public void Repair()
{
// disable for dead eva kerbals
Vessel v = FlightGlobals.ActiveVessel;
if (v == null || EVA.IsDead(v)) return;
// check trait
if (!repair_cs.Check(v))
{
Message.Post
(
Lib.TextVariant
(
Local.Reliability_MessagePost11,//"I'm not qualified for this"
Local.Reliability_MessagePost12,//"I will not even know where to start"
Local.Reliability_MessagePost13//"I'm afraid I can't do that"
),
repair_cs.Warning()
);
return;
}
needMaintenance = false;
enforce_breakdown = false;
// reset times
last = 0.0;
next = 0.0;
lastRunningCheck = 0;
last_inspection = Planetarium.GetUniversalTime();
operation_duration = 0;
ignitions = 0;
fail_duration = 0;
vessel.KerbalismData().ResetReliabilityStatus();
if (broken)
{
// flag as not broken
broken = false;
// re-enable module
foreach (PartModule m in modules)
{
m.isEnabled = true;
m.enabled = true;
}
// we need to reconfigure the module here, because if all modules of a type
// share the broken state, and these modules are part of a configure setup,
// then repairing will enable all of them, messing up with the configuration
part.FindModulesImplementing<Configure>().ForEach(k => k.DoConfigure());
// type-specific hacks
Apply(false);
// notify user
Message.Post
(
Local.Reliability_MessagePost14.Format("<b>"+title+"</b>"),//Lib.BuildString("<<1>> repaired")
Lib.TextVariant
(
Local.Reliability_MessagePost15,//"A powerkick did the trick."
Local.Reliability_MessagePost16,//"Duct tape, is there something it can't fix?"
Local.Reliability_MessagePost17,//"Fully operational again."
Local.Reliability_MessagePost18//"We are back in business."
)
);
} else {
// notify user
Message.Post
(
Local.Reliability_MessagePost19.Format("<b>"+title+"</b>"),//Lib.BuildString(<<1>> serviced")
Lib.TextVariant
(
Local.Reliability_MessagePost20,//"I don't know how this was still working."
Local.Reliability_MessagePost21,//"Fastened that loose screw."
Local.Reliability_MessagePost22,//"Someone forgot a toothpick in there."
Local.Reliability_MessagePost23//"As good as new!"
)
);
}
}
#if DEBUG_RELIABILITY
[KSPEvent(guiActive = true, guiActiveUnfocused = true, guiName = "_", active = true)] // [for testing]
#endif
public void Break()
{
vessel.KerbalismData().ResetReliabilityStatus();
if (broken) return;
if (explode)
{
foreach (PartModule m in modules)
m.part.explode();
return;
}
// if enforced, manned, or if safemode didn't trigger
if (enforce_breakdown || vessel.KerbalismData().CrewCapacity > 0 || Lib.RandomDouble() > PreferencesReliability.Instance.safeModeChance)
{
// flag as broken
broken = true;
// determine if this is a critical failure
critical = Lib.RandomDouble() < PreferencesReliability.Instance.criticalChance;
// disable module
foreach (PartModule m in modules)
{
m.isEnabled = false;
m.enabled = false;
}
// type-specific hacks
Apply(true);
// notify user
Broken_msg(vessel, title, critical);
}
// safemode
else
{
// reset age
last = 0.0;
next = 0.0;
// notify user
Safemode_msg(vessel, title);
}
// in any case, incentive redundancy
if (PreferencesReliability.Instance.incentiveRedundancy)
{
Incentive_redundancy(vessel, redundancy);
}
}
public static void ProtoBreak(Vessel v, ProtoPartSnapshot p, ProtoPartModuleSnapshot m)
{
v.KerbalismData().ResetReliabilityStatus();
// get reliability module prefab
string type = Lib.Proto.GetString(m, "type", string.Empty);
Reliability reliability = p.partPrefab.FindModulesImplementing<Reliability>().Find(k => k.type == type);
if (reliability == null) return;
bool enforce_breakdown = Lib.Proto.GetBool(m, "enforce_breakdown", false);
// if manned, or if safemode didn't trigger
if (enforce_breakdown || v.KerbalismData().CrewCapacity > 0 || Lib.RandomDouble() > PreferencesReliability.Instance.safeModeChance)
{
// flag as broken
Lib.Proto.Set(m, "broken", true);
// determine if this is a critical failure
bool critical = Lib.RandomDouble() < PreferencesReliability.Instance.criticalChance;
Lib.Proto.Set(m, "critical", critical);
// for each associated module
foreach (var proto_module in p.modules.FindAll(k => k.moduleName == reliability.type))
{
// disable the module
Lib.Proto.Set(proto_module, "isEnabled", false);
}
// type-specific hacks
switch (reliability.type)
{
case "ProcessController":
foreach (ProcessController pc in p.partPrefab.FindModulesImplementing<ProcessController>())
{
ProtoPartResourceSnapshot res = p.resources.Find(k => k.resourceName == pc.resource);
if (res != null) res.flowState = false;
}
break;
}
// show message
Broken_msg(v, reliability.title, critical);
}
// safe mode
else
{
// reset age
Lib.Proto.Set(m, "last", 0.0);
Lib.Proto.Set(m, "next", 0.0);
// notify user
Safemode_msg(v, reliability.title);
}
// in any case, incentive redundancy
if (PreferencesReliability.Instance.incentiveRedundancy)
{
Incentive_redundancy(v, reliability.redundancy);
}
}
// part tooltip
public override string GetInfo()
{
return Specs().Info();
}
public static double EffectiveMTBF(bool quality, double mtbf)
{
return mtbf * (quality ? Settings.QualityScale : 1.0);
}
public static double EffectiveDuration(bool quality, double duration)
{
return duration * (quality ? Settings.QualityScale : 1.0);
}
public static int EffectiveIgnitions(bool quality, int ignitions)
{
if(quality) return ignitions + (int)Math.Ceiling(ignitions * Settings.QualityScale * 0.2);
return ignitions;
}
public static double RadiationDecay(bool quality, double rad, double elapsed_s, double rated_radiation, double radiation_decay_rate)
{
rad *= 3600.0;
if (quality) rated_radiation *= Settings.QualityScale;
if (rad <= 0 || rated_radiation <= 0 || rad < rated_radiation) return 0.0;
rad -= rated_radiation;
return rad * elapsed_s * radiation_decay_rate;
}
// specifics support
public Specifics Specs()
{
Specifics specs = new Specifics();
if (redundancy.Length > 0) specs.Add(Local.Reliability_info1, redundancy);//"Redundancy"
specs.Add(Local.Reliability_info2, new CrewSpecs(repair).Info());//"Repair"
specs.Add(string.Empty);
specs.Add("<color=#00ffff>"+Local.Reliability_info3 +"</color>");//Standard quality
if(mtbf > 0) specs.Add(Local.Reliability_info4, Lib.HumanReadableDuration(EffectiveMTBF(false, mtbf)));//"MTBF"
if (turnon_failure_probability > 0) specs.Add(Local.Reliability_info5, Lib.HumanReadablePerc(turnon_failure_probability, "F1"));//"Ignition failures"
if (rated_operation_duration > 0) specs.Add(Local.Reliability_info6, Lib.HumanReadableDuration(EffectiveDuration(false, rated_operation_duration)));//"Rated burn duration"
if (rated_ignitions > 0) specs.Add(Local.Reliability_info7, EffectiveIgnitions(false, rated_ignitions).ToString());//"Rated ignitions"
if (mtbf > 0 && rated_radiation > 0) specs.Add(Local.Reliability_info8, Lib.HumanReadableRadiation(rated_radiation / 3600.0));//"Radiation rating"
specs.Add(string.Empty);
specs.Add("<color=#00ffff>"+Local.Reliability_info9 +"</color>");//High quality
if (extra_cost > double.Epsilon) specs.Add(Local.Reliability_info10, Lib.HumanReadableCost(extra_cost * part.partInfo.cost));//"Extra cost"
if (extra_mass > double.Epsilon) specs.Add(Local.Reliability_info11, Lib.HumanReadableMass(extra_mass * part.partInfo.partPrefab.mass));//"Extra mass"
if (mtbf > 0) specs.Add(Local.Reliability_info4, Lib.HumanReadableDuration(EffectiveMTBF(true, mtbf)));//"MTBF"
if (turnon_failure_probability > 0) specs.Add(Local.Reliability_info5, Lib.HumanReadablePerc(turnon_failure_probability / Settings.QualityScale, "F1"));//"Ignition failures"
if (rated_operation_duration > 0) specs.Add(Local.Reliability_info6, Lib.HumanReadableDuration(EffectiveDuration(true, rated_operation_duration)));//"Rated burn duration"
if (rated_ignitions > 0) specs.Add(Local.Reliability_info7, EffectiveIgnitions(true, rated_ignitions).ToString());//"Rated ignitions"
if (mtbf > 0 && rated_radiation > 0) specs.Add(Local.Reliability_info8, Lib.HumanReadableRadiation(Settings.QualityScale * rated_radiation / 3600.0));//"Radiation rating"
return specs;
}
// module info support
public string GetModuleTitle() { return Lib.BuildString(title, " Reliability"); }
public override string GetModuleDisplayName() { return Lib.BuildString(title, " ",Local.Reliability_Reliability); }//Reliability
public string GetPrimaryField() { return string.Empty; }
public Callback<Rect> GetDrawModulePanelCallback() { return null; }
// module cost support
public float GetModuleCost(float defaultCost, ModifierStagingSituation sit) { return quality ? (float)extra_cost * part.partInfo.cost : 0.0f; }
// module mass support
public float GetModuleMass(float defaultMass, ModifierStagingSituation sit) { return quality ? (float)extra_mass * part.partInfo.partPrefab.mass : 0.0f; }
public ModifierChangeWhen GetModuleCostChangeWhen() { return ModifierChangeWhen.CONSTANTLY; }
public ModifierChangeWhen GetModuleMassChangeWhen() { return ModifierChangeWhen.CONSTANTLY; }
protected bool IsRunning()
{
if (type.StartsWith("ModuleEngines", StringComparison.Ordinal))
{
foreach (PartModule m in modules)
{
var e = m as ModuleEngines;
return e.currentThrottle > 0 && e.EngineIgnited && e.resultingThrust > 0;
}
return false;
}
switch (type)
{
case "ProcessController":
foreach (PartModule m in modules)
return (m as ProcessController).running;
return false;
case "ModuleLight":
foreach (PartModule m in modules)
return (m as ModuleLight).isOn;
return false;
}
return false;
}
// apply type-specific hacks to enable/disable the module
protected void Apply(bool b)
{
if(b && type.StartsWith("ModuleEngines", StringComparison.Ordinal))
{
foreach (PartModule m in modules)
{
var e = m as ModuleEngines;
e.Shutdown();
e.EngineIgnited = false;
e.flameout = true;
var efx = m as ModuleEnginesFX;
if (efx != null)
{
efx.DeactivateRunningFX();
efx.DeactivatePowerFX();
efx.DeactivateLoopingFX();
}
}
}
switch (type)
{
case "ProcessController":
if (b)
{
foreach (PartModule m in modules)
{
(m as ProcessController).ReliablityEvent(b);
}
}
break;
case "ModuleDeployableRadiator":
if (b)
{
part.FindModelComponents<Animation>().ForEach(k => k.Stop());
}
break;
case "ModuleLight":
if (b)
{
foreach (PartModule m in modules)
{
ModuleLight l = m as ModuleLight;
if (l.animationName.Length > 0)
{
new Animator(part, l.animationName).Still(0.0f);
}
else
{
part.FindModelComponents<Light>().ForEach(k => k.enabled = false);
}
}
}
break;
case "ModuleRCSFX":
if (b)
{
foreach (PartModule m in modules)
{
var e = m as ModuleRCSFX;
if(e != null)
{
e.DeactivateFX();
e.DeactivatePowerFX();
}
}
}
break;
case "ModuleScienceExperiment":
if (b)
{
foreach (PartModule m in modules)
{
(m as ModuleScienceExperiment).SetInoperable();
}
}
break;
case "Experiment":
if (b)
{
foreach (PartModule m in modules)
{
(m as Experiment).ReliablityEvent(b);
}
}
break;
case "SolarPanelFixer":
foreach (PartModule m in modules)
{
(m as SolarPanelFixer).ReliabilityEvent(b);
}
break;
}
API.Failure.Notify(part, type, b);
}
static void Incentive_redundancy(Vessel v, string redundancy)
{
if (v.loaded)
{
foreach (Reliability m in Lib.FindModules<Reliability>(v))
{
if (m.redundancy == redundancy)
{
m.next += m.next - m.last;
}
}
}
else
{
var PD = new Dictionary<string, Lib.Module_prefab_data>();
foreach (ProtoPartSnapshot p in v.protoVessel.protoPartSnapshots)
{
Part part_prefab = PartLoader.getPartInfoByName(p.partName).partPrefab;
var module_prefabs = part_prefab.FindModulesImplementing<PartModule>();
PD.Clear();
foreach (ProtoPartModuleSnapshot m in p.modules)
{
if (m.moduleName != "Reliability") continue;
PartModule module_prefab = Lib.ModulePrefab(module_prefabs, m.moduleName, PD);
if (!module_prefab) continue;
string r = Lib.Proto.GetString(m, "redundancy", string.Empty);
if (r == redundancy)
{
double last = Lib.Proto.GetDouble(m, "last");
double next = Lib.Proto.GetDouble(m, "next");
Lib.Proto.Set(m, "next", next + (next - last));
}
}
}
}
}
// set highlighting
static void Highlight(Part p)
{
if (p.vessel.KerbalismData().cfg_highlights)
{
// get state among all reliability components in the part
bool broken = false;
bool critical = false;
foreach (Reliability m in p.FindModulesImplementing<Reliability>())
{
broken |= m.broken;
critical |= m.critical;
}
if (broken)
{
Highlighter.Set(p.flightID, !critical ? Color.yellow : Color.red);
}
}
}
static void Broken_msg(Vessel v, string title, bool critical)
{
if (v.KerbalismData().cfg_malfunction)
{
if (!critical)
{
Message.Post
(
Severity.warning,
Local.Reliability_MessagePost24.Format("<b>"+title+"</b>","<b>"+v.vesselName+"</b>"),//Lib.BuildString(<<1>> malfunctioned on <<2>>)
Local.Reliability_MessagePost25//"We can still repair it"
);
}
else
{
Message.Post
(
Severity.danger,
Local.Reliability_MessagePost26.Format("<b>" + title + "</b>", "<b>" + v.vesselName + "</b>"),//Lib.BuildString(<<1>> failed on <<2>>)
Local.Reliability_MessagePost27//"It is gone for good"
);
}
}
}
static void Safemode_msg(Vessel v, string title)
{
Message.Post
(
Local.Reliability_MessagePost28.Format("<b>" + title + "</b>", "<b>" + v.vesselName + "</b>"),//Lib.BuildString("There has been a problem with <<1>> on <<2>>)
Local.Reliability_MessagePost29//"We were able to fix it remotely, this time"
);
}
// cause a part at random to malfunction
public static void CauseMalfunction(Vessel v)
{
// if vessel is loaded
if (v.loaded)
{
// choose a module at random
var modules = Lib.FindModules<Reliability>(v).FindAll(k => !k.broken);
if (modules.Count == 0) return;
var m = modules[Lib.RandomInt(modules.Count)];
// break it
m.Break();
}
// if vessel is not loaded
else
{
// choose a module at random
var modules = Lib.FindModules(v.protoVessel, "Reliability").FindAll(k => !Lib.Proto.GetBool(k, "broken"));
if (modules.Count == 0) return;
var m = modules[Lib.RandomInt(modules.Count)];
// find its part
ProtoPartSnapshot p = v.protoVessel.protoPartSnapshots.Find(k => k.modules.Contains(m));
// break it
ProtoBreak(v, p, m);
}
}
// return true if it make sense to trigger a malfunction on the vessel
public static bool CanMalfunction(Vessel v)
{
if (v.loaded)
{
return Lib.HasModule<Reliability>(v, k => !k.broken);
}
else
{
return Lib.HasModule(v.protoVessel, "Reliability", k => !Lib.Proto.GetBool(k, "broken"));
}
}
// return true if at least a component has malfunctioned or had a critical failure
public static bool HasMalfunction(Vessel v)
{
if (v.loaded)
{
foreach (Reliability m in Lib.FindModules<Reliability>(v))
{
if (m.broken) return true;
}
}
else
{
foreach (ProtoPartModuleSnapshot m in Lib.FindModules(v.protoVessel, "Reliability"))
{
if (Lib.Proto.GetBool(m, "broken")) return true;
}
}
return false;
}
// return true if at least a component has a critical failure
public static bool HasCriticalFailure(Vessel v)
{
if (v.loaded)
{
foreach (Reliability m in Lib.FindModules<Reliability>(v))
{
if (m.critical) return true;
}
}
else
{
foreach (ProtoPartModuleSnapshot m in Lib.FindModules(v.protoVessel, "Reliability"))
{
if (Lib.Proto.GetBool(m, "critical")) return true;
}
}
return false;
}
}
} // KERBALISM
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Xml.Xsl.Runtime;
using System.Runtime.Versioning;
namespace System.Xml.Xsl.IlGen
{
using DebuggingModes = DebuggableAttribute.DebuggingModes;
internal enum XmlILMethodAttributes
{
None = 0,
NonUser = 1, // Non-user method which should debugger should step through
Raw = 2, // Raw method which should not add an implicit first argument of type XmlQueryRuntime
}
internal class XmlILModule
{
private static long s_assemblyId; // Unique identifier used to ensure that assembly names are unique within AppDomain
private static readonly ModuleBuilder s_LREModule = CreateLREModule(); // Module used to emit dynamic lightweight-reflection-emit (LRE) methods
private TypeBuilder _typeBldr;
private Hashtable _methods;
private readonly bool _useLRE, _emitSymbols;
private const string RuntimeName = "{" + XmlReservedNs.NsXslDebug + "}" + "runtime";
private static ModuleBuilder CreateLREModule()
{
// 1. LRE assembly only needs to execute
// 2. No temp files need be created
// 3. Never allow assembly to Assert permissions
AssemblyName asmName = CreateAssemblyName();
AssemblyBuilder asmBldr = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
// Add custom attribute to assembly marking it as security transparent so that Assert will not be allowed
// and link demands will be converted to full demands.
asmBldr.SetCustomAttribute(new CustomAttributeBuilder(XmlILConstructors.Transparent, Array.Empty<object>()));
// Store LREModule once. If multiple threads are doing this, then some threads might get different
// modules. This is OK, since it's not mandatory to share, just preferable.
return asmBldr.DefineDynamicModule("System.Xml.Xsl.CompiledQuery");
}
public XmlILModule(TypeBuilder typeBldr)
{
_typeBldr = typeBldr;
_emitSymbols = false;
_useLRE = false;
// Index all methods added to this module by unique name
_methods = new Hashtable();
}
public bool EmitSymbols
{
get
{
return _emitSymbols;
}
}
// SxS note: AssemblyBuilder.DefineDynamicModule() below may be using name which is not SxS safe.
// This file is written only for internal tracing/debugging purposes. In retail builds persistAsm
// will be always false and the file should never be written. As a result it's fine just to suppress
// the SxS warning.
public XmlILModule(bool useLRE, bool emitSymbols)
{
AssemblyName asmName;
AssemblyBuilder asmBldr;
ModuleBuilder modBldr;
Debug.Assert(!(useLRE && emitSymbols));
_useLRE = useLRE;
_emitSymbols = emitSymbols;
// Index all methods added to this module by unique name
_methods = new Hashtable();
if (!useLRE)
{
// 1. If assembly needs to support debugging, then it must be saved and re-loaded (rule of CLR)
// 2. Get path of temp directory, where assembly will be saved
// 3. Never allow assembly to Assert permissions
asmName = CreateAssemblyName();
asmBldr = AssemblyBuilder.DefineDynamicAssembly(
asmName, AssemblyBuilderAccess.Run);
// Add custom attribute to assembly marking it as security transparent so that Assert will not be allowed
// and link demands will be converted to full demands.
asmBldr.SetCustomAttribute(new CustomAttributeBuilder(XmlILConstructors.Transparent, Array.Empty<object>()));
if (emitSymbols)
{
// Add DebuggableAttribute to assembly so that debugging is a better experience
DebuggingModes debuggingModes = DebuggingModes.Default | DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggingModes.DisableOptimizations;
asmBldr.SetCustomAttribute(new CustomAttributeBuilder(XmlILConstructors.Debuggable, new object[] { debuggingModes }));
}
// Create ModuleBuilder
modBldr = asmBldr.DefineDynamicModule("System.Xml.Xsl.CompiledQuery");
_typeBldr = modBldr.DefineType("System.Xml.Xsl.CompiledQuery.Query", TypeAttributes.Public);
}
}
/// <summary>
/// Define a method in this module with the specified name and parameters.
/// </summary>
public MethodInfo DefineMethod(string name, Type returnType, Type[] paramTypes, string[] paramNames, XmlILMethodAttributes xmlAttrs)
{
MethodInfo methResult;
int uniqueId = 1;
string nameOrig = name;
Type[] paramTypesNew;
bool isRaw = (xmlAttrs & XmlILMethodAttributes.Raw) != 0;
// Ensure that name is unique
while (_methods[name] != null)
{
// Add unique id to end of name in order to make it unique within this module
uniqueId++;
name = nameOrig + " (" + uniqueId + ")";
}
if (!isRaw)
{
// XmlQueryRuntime is always 0th parameter
paramTypesNew = new Type[paramTypes.Length + 1];
paramTypesNew[0] = typeof(XmlQueryRuntime);
Array.Copy(paramTypes, 0, paramTypesNew, 1, paramTypes.Length);
paramTypes = paramTypesNew;
}
if (!_useLRE)
{
MethodBuilder methBldr;
methBldr = _typeBldr.DefineMethod(
name,
MethodAttributes.Private | MethodAttributes.Static,
returnType,
paramTypes);
if (_emitSymbols && (xmlAttrs & XmlILMethodAttributes.NonUser) != 0)
{
// Add DebuggerStepThroughAttribute and DebuggerNonUserCodeAttribute to non-user methods so that debugging is a better experience
methBldr.SetCustomAttribute(new CustomAttributeBuilder(XmlILConstructors.StepThrough, Array.Empty<object>()));
methBldr.SetCustomAttribute(new CustomAttributeBuilder(XmlILConstructors.NonUserCode, Array.Empty<object>()));
}
if (!isRaw)
methBldr.DefineParameter(1, ParameterAttributes.None, RuntimeName);
for (int i = 0; i < paramNames.Length; i++)
{
if (paramNames[i] != null && paramNames[i].Length != 0)
methBldr.DefineParameter(i + (isRaw ? 1 : 2), ParameterAttributes.None, paramNames[i]);
}
methResult = methBldr;
}
else
{
DynamicMethod methDyn = new DynamicMethod(name, returnType, paramTypes, s_LREModule);
methDyn.InitLocals = true;
methResult = methDyn;
}
// Index method by name
_methods[name] = methResult;
return methResult;
}
/// <summary>
/// Get an XmlILGenerator that can be used to generate the body of the specified method.
/// </summary>
public static ILGenerator DefineMethodBody(MethodBase methInfo)
{
DynamicMethod methDyn = methInfo as DynamicMethod;
if (methDyn != null)
return methDyn.GetILGenerator();
MethodBuilder methBldr = methInfo as MethodBuilder;
if (methBldr != null)
return methBldr.GetILGenerator();
return ((ConstructorBuilder)methInfo).GetILGenerator();
}
/// <summary>
/// Find a MethodInfo of the specified name and return it. Return null if no such method exists.
/// </summary>
public MethodInfo FindMethod(string name)
{
return (MethodInfo)_methods[name];
}
/// <summary>
/// Define ginitialized data field with the specified name and value.
/// </summary>
public FieldInfo DefineInitializedData(string name, byte[] data)
{
Debug.Assert(!_useLRE, "Cannot create initialized data for an LRE module");
return _typeBldr.DefineInitializedData(name, data, FieldAttributes.Private | FieldAttributes.Static);
}
/// <summary>
/// Define private static field with the specified name and value.
/// </summary>
public FieldInfo DefineField(string fieldName, Type type)
{
Debug.Assert(!_useLRE, "Cannot create field for an LRE module");
return _typeBldr.DefineField(fieldName, type, FieldAttributes.Private | FieldAttributes.Static);
}
/// <summary>
/// Define static constructor for this type.
/// </summary>
public ConstructorInfo DefineTypeInitializer()
{
Debug.Assert(!_useLRE, "Cannot create type initializer for an LRE module");
return _typeBldr.DefineTypeInitializer();
}
/// <summary>
/// Once all methods have been defined, CreateModule must be called in order to "bake" the methods within
/// this module.
/// </summary>
public void BakeMethods()
{
Type typBaked;
Hashtable methodsBaked;
if (!_useLRE)
{
typBaked = _typeBldr.CreateTypeInfo().AsType();
// Replace all MethodInfos in this.methods
methodsBaked = new Hashtable(_methods.Count);
foreach (string methName in _methods.Keys)
{
methodsBaked[methName] = typBaked.GetMethod(methName, BindingFlags.NonPublic | BindingFlags.Static);
}
_methods = methodsBaked;
// Release TypeBuilder and symbol writer resources
_typeBldr = null;
}
}
/// <summary>
/// Wrap a delegate around a MethodInfo of the specified name and type and return it.
/// </summary>
public Delegate CreateDelegate(string name, Type typDelegate)
{
if (!_useLRE)
return ((MethodInfo)_methods[name]).CreateDelegate(typDelegate);
return ((DynamicMethod)_methods[name]).CreateDelegate(typDelegate);
}
/// <summary>
/// Define unique assembly name (within AppDomain).
/// </summary>
private static AssemblyName CreateAssemblyName()
{
AssemblyName name;
System.Threading.Interlocked.Increment(ref s_assemblyId);
name = new AssemblyName();
name.Name = "System.Xml.Xsl.CompiledQuery." + s_assemblyId;
return name;
}
}
}
| |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using PrjYamlDotNet.Core;
using PrjYamlDotNet.Core.Events;
using PrjYamlDotNet.Serialization.EventEmitters;
using PrjYamlDotNet.Serialization.NamingConventions;
using PrjYamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using PrjYamlDotNet.Serialization.ObjectGraphVisitors;
using PrjYamlDotNet.Serialization.TypeInspectors;
using PrjYamlDotNet.Serialization.TypeResolvers;
namespace PrjYamlDotNet.Serialization
{
/// <summary>
/// Writes objects to YAML.
/// </summary>
public sealed class Serializer
{
internal IList<IYamlTypeConverter> Converters { get; private set; }
private readonly SerializationOptions options;
private readonly INamingConvention namingConvention;
private readonly ITypeResolver typeResolver;
/// <summary>
///
/// </summary>
/// <param name="options">Options that control how the serialization is to be performed.</param>
/// <param name="namingConvention">Naming strategy to use for serialized property names</param>
public Serializer(SerializationOptions options = SerializationOptions.None, INamingConvention namingConvention = null)
{
this.options = options;
this.namingConvention = namingConvention ?? new NullNamingConvention();
Converters = new List<IYamlTypeConverter>();
foreach (IYamlTypeConverter yamlTypeConverter in Utilities.YamlTypeConverters.BuiltInConverters)
{
Converters.Add(yamlTypeConverter);
}
typeResolver = IsOptionSet(SerializationOptions.DefaultToStaticType)
? (ITypeResolver)new StaticTypeResolver()
: (ITypeResolver)new DynamicTypeResolver();
}
private bool IsOptionSet(SerializationOptions option)
{
return (options & option) != 0;
}
/// <summary>
/// Registers a type converter to be used to serialize and deserialize specific types.
/// </summary>
public void RegisterTypeConverter(IYamlTypeConverter converter)
{
Converters.Add(converter);
}
/// <summary>
/// Serializes the specified object.
/// </summary>
/// <param name="writer">The <see cref="TextWriter" /> where to serialize the object.</param>
/// <param name="graph">The object to serialize.</param>
public void Serialize(TextWriter writer, object graph)
{
Serialize(new Emitter(writer), graph);
}
/// <summary>
/// Serializes the specified object.
/// </summary>
/// <param name="writer">The <see cref="TextWriter" /> where to serialize the object.</param>
/// <param name="graph">The object to serialize.</param>
/// <param name="type">The static type of the object to serialize.</param>
public void Serialize(TextWriter writer, object graph, Type type)
{
Serialize(new Emitter(writer), graph, type);
}
/// <summary>
/// Serializes the specified object.
/// </summary>
/// <param name="emitter">The <see cref="IEmitter" /> where to serialize the object.</param>
/// <param name="graph">The object to serialize.</param>
public void Serialize(IEmitter emitter, object graph)
{
if (emitter == null)
{
throw new ArgumentNullException("emitter");
}
EmitDocument(emitter, new ObjectDescriptor(graph, graph != null ? graph.GetType() : typeof(object), typeof(object)));
}
/// <summary>
/// Serializes the specified object.
/// </summary>
/// <param name="emitter">The <see cref="IEmitter" /> where to serialize the object.</param>
/// <param name="graph">The object to serialize.</param>
/// <param name="type">The static type of the object to serialize.</param>
public void Serialize(IEmitter emitter, object graph, Type type)
{
if (emitter == null)
{
throw new ArgumentNullException("emitter");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
EmitDocument(emitter, new ObjectDescriptor(graph, type, type));
}
private void EmitDocument(IEmitter emitter, IObjectDescriptor graph)
{
var traversalStrategy = CreateTraversalStrategy();
var eventEmitter = CreateEventEmitter(emitter);
var emittingVisitor = CreateEmittingVisitor(emitter, traversalStrategy, eventEmitter, graph);
emitter.Emit(new StreamStart());
emitter.Emit(new DocumentStart());
traversalStrategy.Traverse(graph, emittingVisitor);
emitter.Emit(new DocumentEnd(true));
emitter.Emit(new StreamEnd());
}
private IObjectGraphVisitor CreateEmittingVisitor(IEmitter emitter, IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IObjectDescriptor graph)
{
IObjectGraphVisitor emittingVisitor = new EmittingObjectGraphVisitor(eventEmitter);
emittingVisitor = new CustomSerializationObjectGraphVisitor(emitter, emittingVisitor, Converters);
if (!IsOptionSet(SerializationOptions.DisableAliases))
{
var anchorAssigner = new AnchorAssigner();
traversalStrategy.Traverse(graph, anchorAssigner);
emittingVisitor = new AnchorAssigningObjectGraphVisitor(emittingVisitor, eventEmitter, anchorAssigner);
}
if (!IsOptionSet(SerializationOptions.EmitDefaults))
{
emittingVisitor = new DefaultExclusiveObjectGraphVisitor(emittingVisitor);
}
return emittingVisitor;
}
private IEventEmitter CreateEventEmitter(IEmitter emitter)
{
var writer = new WriterEventEmitter(emitter);
if (IsOptionSet(SerializationOptions.JsonCompatible))
{
return new JsonEventEmitter(writer);
}
else
{
return new TypeAssigningEventEmitter(writer, IsOptionSet(SerializationOptions.Roundtrip));
}
}
private IObjectGraphTraversalStrategy CreateTraversalStrategy()
{
ITypeInspector typeDescriptor = new ReadablePropertiesTypeInspector(typeResolver);
if (IsOptionSet(SerializationOptions.Roundtrip))
{
typeDescriptor = new ReadableAndWritablePropertiesTypeInspector(typeDescriptor);
}
typeDescriptor = new NamingConventionTypeInspector(typeDescriptor, namingConvention);
typeDescriptor = new YamlAttributesTypeInspector(typeDescriptor);
if (IsOptionSet(SerializationOptions.DefaultToStaticType))
{
typeDescriptor = new CachedTypeInspector(typeDescriptor);
}
if (IsOptionSet(SerializationOptions.Roundtrip))
{
return new RoundtripObjectGraphTraversalStrategy(this, typeDescriptor, typeResolver, 50);
}
else
{
return new FullObjectGraphTraversalStrategy(this, typeDescriptor, typeResolver, 50, namingConvention);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using EasyNetQ.Management.Client.Model;
using JetBrains.Annotations;
namespace EasyNetQ.Management.Client
{
public interface IManagementClient : IDisposable
{
/// <summary>
/// The host URL that this instance is using.
/// </summary>
string HostUrl { get; }
/// <summary>
/// The Username that this instance is connecting as.
/// </summary>
string Username { get; }
/// <summary>
/// The port number this instance connects using.
/// </summary>
int PortNumber { get; }
/// <summary>
/// Various random bits of information that describe the whole system.
/// </summary>
/// <param name="lengthsCriteria">Criteria for getting samples of queue length data</param>
/// <param name="ratesCriteria">Criteria for getting samples of rate data</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<Overview> GetOverviewAsync(
GetLengthsCriteria lengthsCriteria = null,
GetRatesCriteria ratesCriteria = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of nodes in the RabbitMQ cluster.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Node>> GetNodesAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The server definitions - exchanges, queues, bindings, users, virtual hosts, permissions.
/// Everything apart from messages.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<Definitions> GetDefinitionsAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all open connections.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Connection>> GetConnectionsAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all open channels.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Channel>> GetChannelsAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the channel. This returns more detail, including consumers than the GetChannels method.
/// </summary>
/// <returns>The channel.</returns>
/// <param name="channelName">Channel name.</param>
/// <param name="ratesCriteria">Criteria for getting samples of rate data</param>
/// <param name="cancellationToken"></param>
Task<Channel> GetChannelAsync(
string channelName,
GetRatesCriteria ratesCriteria = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all exchanges.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Exchange>> GetExchangesAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all queues.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Queue>> GetQueuesAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all bindings.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Binding>> GetBindingsAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all vhosts.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Vhost>> GetVHostsAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all users.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<User>> GetUsersAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all permissions for all users.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Permission>> GetPermissionsAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Closes the given connection
/// </summary>
/// <param name="connection"></param>
/// <param name="cancellationToken"></param>
Task CloseConnectionAsync(
[NotNull] Connection connection,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the given exchange
/// </summary>
/// <param name="exchangeInfo"></param>
/// <param name="vhost"></param>
/// <param name="cancellationToken"></param>
Task<Exchange> CreateExchangeAsync(
[NotNull] ExchangeInfo exchangeInfo,
[NotNull] Vhost vhost,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete the given exchange
/// </summary>
/// <param name="exchange"></param>
/// <param name="cancellationToken"></param>
Task DeleteExchangeAsync(
[NotNull] Exchange exchange,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all bindings in which a given exchange is the source.
/// </summary>
/// <param name="exchange"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Binding>> GetBindingsWithSourceAsync(
[NotNull] Exchange exchange,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all bindings in which a given exchange is the destination.
/// </summary>
/// <param name="exchange"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Binding>> GetBindingsWithDestinationAsync(
[NotNull] Exchange exchange,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Publish a message to a given exchange.
///
/// Please note that the publish / get paths in the HTTP API are intended for injecting
/// test messages, diagnostics etc - they do not implement reliable delivery and so should
/// be treated as a sysadmin's tool rather than a general API for messaging.
/// </summary>
/// <param name="exchange">The exchange</param>
/// <param name="publishInfo">The publication parameters</param>
/// <param name="cancellationToken"></param>
/// <returns>A PublishResult, routed == true if the message was sent to at least one queue</returns>
Task<PublishResult> PublishAsync(
[NotNull] Exchange exchange,
[NotNull] PublishInfo publishInfo,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create the given queue
/// </summary>
/// <param name="queueInfo"></param>
/// <param name="vhost"></param>
/// <param name="cancellationToken"></param>
Task<Queue> CreateQueueAsync(
[NotNull] QueueInfo queueInfo,
[NotNull] Vhost vhost,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete the given queue
/// </summary>
/// <param name="queue"></param>
/// <param name="cancellationToken"></param>
Task DeleteQueueAsync(
[NotNull] Queue queue,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all bindings on a given queue.
/// </summary>
/// <param name="queue"></param>
/// <param name="cancellationToken"></param>
Task<IEnumerable<Binding>> GetBindingsForQueueAsync(
[NotNull] Queue queue,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Purge a queue of all messages
/// </summary>
/// <param name="queue"></param>
/// <param name="cancellationToken"></param>
Task PurgeAsync(
[NotNull] Queue queue,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get messages from a queue.
///
/// Please note that the publish / get paths in the HTTP API are intended for
/// injecting test messages, diagnostics etc - they do not implement reliable
/// delivery and so should be treated as a sysadmin's tool rather than a
/// general API for messaging.
/// </summary>
/// <param name="queue">The queue to retrieve from</param>
/// <param name="criteria">The criteria for the retrieve</param>
/// <param name="cancellationToken"></param>
/// <returns>Messages</returns>
Task<IEnumerable<Message>> GetMessagesFromQueueAsync(
[NotNull] Queue queue,
GetMessagesCriteria criteria,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create a binding between an exchange and a queue
/// </summary>
/// <param name="exchange">the exchange</param>
/// <param name="queue">the queue</param>
/// <param name="bindingInfo">properties of the binding</param>
/// <param name="cancellationToken"></param>
/// <returns>The binding that was created</returns>
Task CreateBinding(
[NotNull] Exchange exchange,
[NotNull] Queue queue,
[NotNull] BindingInfo bindingInfo,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create a binding between an exchange and an exchange
/// </summary>
/// <param name="sourceExchange">the source exchange</param>
/// <param name="destinationExchange">the destination exchange</param>
/// <param name="bindingInfo">properties of the binding</param>
/// <param name="cancellationToken"></param>
Task CreateBinding(
[NotNull] Exchange sourceExchange,
[NotNull] Exchange destinationExchange,
[NotNull] BindingInfo bindingInfo,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all bindings between an exchange and a queue.
/// Remember, an exchange and a queue can be bound together many times!
/// </summary>
/// <param name="exchange"></param>
/// <param name="queue"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Binding>> GetBindingsAsync(
[NotNull] Exchange exchange,
[NotNull] Queue queue,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A list of all bindings between an exchange and an exchange.
/// </summary>
/// <param name="fromExchange"></param>
/// <param name="toExchange"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<Binding>> GetBindingsAsync(
[NotNull] Exchange fromExchange,
[NotNull] Exchange toExchange,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete the given binding
/// </summary>
/// <param name="binding"></param>
/// <param name="cancellationToken"></param>
Task DeleteBindingAsync(
[NotNull] Binding binding,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create a new virtual host
/// </summary>
/// <param name="virtualHostName">The name of the new virtual host</param>
/// <param name="cancellationToken"></param>
Task<Vhost> CreateVirtualHostAsync(
string virtualHostName,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a virtual host
/// </summary>
/// <param name="vhost">The virtual host to delete</param>
/// <param name="cancellationToken"></param>
Task DeleteVirtualHostAsync(
[NotNull] Vhost vhost,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Enable tracing on given virtual host.
/// </summary>
/// <param name="vhost">The virtual host on which to enable tracing</param>
Task EnableTracingAsync(
[NotNull] Vhost vhost,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Disables tracing on given virtual host.
/// </summary>
/// <param name="vhost">The virtual host on which to disable tracing</param>
Task DisableTracingAsync(
[NotNull] Vhost vhost,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create a new user
/// </summary>
/// <param name="userInfo">The user to create</param>
/// <param name="cancellationToken"></param>
Task<User> CreateUserAsync(
[NotNull] UserInfo userInfo,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a user
/// </summary>
/// <param name="user">The user to delete</param>
/// <param name="cancellationToken"></param>
Task DeleteUserAsync(
[NotNull] User user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create a permission
/// </summary>
/// <param name="permissionInfo">The permission to create</param>
/// <param name="cancellationToken"></param>
Task CreatePermissionAsync(
[NotNull] PermissionInfo permissionInfo,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a permission
/// </summary>
/// <param name="permission">The permission to delete</param>
/// <param name="cancellationToken"></param>
Task DeletePermissionAsync(
[NotNull] Permission permission,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update the password of an user.
/// </summary>
/// <param name="userName">The name of a user</param>
/// <param name="newPassword">The new password to set</param>
/// <param name="cancellationToken"></param>
Task<User> ChangeUserPasswordAsync(
string userName,
string newPassword,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Declares a test queue, then publishes and consumes a message. Intended for use
/// by monitoring tools. If everything is working correctly, will return true.
/// Note: the test queue will not be deleted (to to prevent queue churn if this
/// is repeatedly pinged).
/// </summary>
/// <param name="vhost"></param>
/// <param name="cancellationToken"></param>
Task<bool> IsAliveAsync(
[NotNull] Vhost vhost,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get an individual exchange by name
/// </summary>
/// <param name="exchangeName">The name of the exchange</param>
/// <param name="vhost">The virtual host that contains the exchange</param>
/// <param name="ratesCriteria">Criteria for getting samples of rate data</param>
/// <param name="cancellationToken"></param>
/// <returns>The exchange</returns>
Task<Exchange> GetExchangeAsync(
string exchangeName,
[NotNull] Vhost vhost,
GetRatesCriteria ratesCriteria = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get an individual queue by name
/// </summary>
/// <param name="queueName">The name of the queue</param>
/// <param name="vhost">The virtual host that contains the queue</param>
/// <param name="lengthsCriteria">Criteria for getting samples of queue length data</param>
/// <param name="ratesCriteria">Criteria for getting samples of rate data</param>
/// <param name="cancellationToken"></param>
/// <returns>The Queue</returns>
Task<Queue> GetQueueAsync(
string queueName,
[NotNull] Vhost vhost,
GetLengthsCriteria lengthsCriteria = null,
GetRatesCriteria ratesCriteria = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get an individual vhost by name
/// </summary>
/// <param name="vhostName">The VHost</param>
/// <param name="cancellationToken"></param>
Task<Vhost> GetVhostAsync(
string vhostName,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a user by name
/// </summary>
/// <param name="userName">The name of the user</param>
/// <param name="cancellationToken"></param>
/// <returns>The User</returns>
Task<User> GetUserAsync(
string userName,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get collection of Policies on the cluster
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns>Policies</returns>
Task<IEnumerable<Policy>> GetPoliciesAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a policy on the cluster
/// </summary>
/// <param name="policy">Policy to create</param>
/// <param name="cancellationToken"></param>
Task CreatePolicy(
[NotNull] Policy policy,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a policy from the cluster
/// </summary>
/// <param name="policyName">Policy name</param>
/// <param name="vhost">vhost on which the policy resides</param>
/// <param name="cancellationToken"></param>
Task DeletePolicyAsync(
string policyName,
Vhost vhost,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all parameters on the cluster
/// </summary>
/// <param name="cancellationToken"></param>
Task<IEnumerable<Parameter>> GetParametersAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a parameter on the cluster
/// </summary>
/// <param name="parameter">Parameter to create</param>
/// <param name="cancellationToken"></param>
Task CreateParameterAsync(
[NotNull]Parameter parameter,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a parameter from the cluster
/// </summary>
/// <param name="componentName"></param>
/// <param name="vhost"></param>
/// <param name="name"></param>
/// <param name="cancellationToken"></param>
Task DeleteParameterAsync(
string componentName,
string vhost,
string name,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get list of federations
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<List<Federation>> GetFederationAsync(CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.PE.DotNet.Cil
{
/// <summary>
/// Represents a CIL method body using the fat format.
/// </summary>
/// <remarks>
/// The fat method body format is used when a CIL method body's code size is larger than 64 bytes, has local
/// variables, its max stack size is greater than 8, or uses extra sections (e.g. for storing exception handlers).
///
/// This class does not do any encoding/decoding of the bytes that make up the actual CIL instructions, nor does
/// it do any verification of the code.
/// </remarks>
public class CilRawFatMethodBody : CilRawMethodBody
{
private CilMethodBodyAttributes _attributes;
/// <summary>
/// Creates a new fat method body.
/// </summary>
/// <param name="attributes">The attributes associated to the method body.</param>
/// <param name="maxStack">The maximum amount of values that can be pushed onto the stack.</param>
/// <param name="localVarSigToken">The metadata token that defines the local variables for the method body.</param>
/// <param name="code">The raw code of the method.</param>
public CilRawFatMethodBody(
CilMethodBodyAttributes attributes,
ushort maxStack,
MetadataToken localVarSigToken,
IReadableSegment code)
: base(code)
{
Attributes = attributes;
MaxStack = maxStack;
LocalVarSigToken = localVarSigToken;
}
/// <inheritdoc />
public override bool IsFat => true;
/// <summary>
/// Gets or sets the attributes associated to the method body.
/// </summary>
/// <remarks>
/// This property always has the <see cref="CilMethodBodyAttributes.Fat"/> flag set.
/// </remarks>
public CilMethodBodyAttributes Attributes
{
get => _attributes;
set => _attributes = value | CilMethodBodyAttributes.Fat;
}
/// <summary>
/// Gets or sets a value indicating whether the method body stores extra sections.
/// </summary>
/// <remarks>
/// This property does not automatically update when <see cref="ExtraSections"/> is changed.
/// </remarks>
public bool HasSections
{
get => (Attributes & CilMethodBodyAttributes.MoreSections) != 0;
set => Attributes = (Attributes & ~CilMethodBodyAttributes.MoreSections)
| (value ? CilMethodBodyAttributes.MoreSections : 0);
}
/// <summary>
/// Gets or sets a value indicating whether all locals defined by this method body should be initialized
/// to zero by the runtime upon starting execution of the method body.
/// </summary>
public bool InitLocals
{
get => (Attributes & CilMethodBodyAttributes.InitLocals) != 0;
set => Attributes = (Attributes & ~CilMethodBodyAttributes.InitLocals)
| (value ? CilMethodBodyAttributes.InitLocals : 0);
}
/// <summary>
/// Gets or sets a value indicating the maximum amount of values that can be pushed onto the stack by the
/// code stored in the method body.
/// </summary>
public ushort MaxStack
{
get;
set;
}
/// <summary>
/// Gets or sets the metadata token referencing a signature that defines all local variables in the method body.
/// </summary>
public MetadataToken LocalVarSigToken
{
get;
set;
}
/// <summary>
/// Gets a collection of extra metadata sections that are appended to the method body.
/// </summary>
/// <remarks>
/// These sections are used to encode any exception handler in the method body.
/// </remarks>
public IList<CilExtraSection> ExtraSections
{
get;
} = new List<CilExtraSection>();
/// <summary>
/// Reads a raw method body from the given binary input stream using the fat method body format.
/// </summary>
/// <param name="errorListener">The object responsible for recording parser errors.</param>
/// <param name="reader">The binary input stream to read from.</param>
/// <returns>The raw method body.</returns>
/// <exception cref="FormatException">Occurs when the method header indicates an method body that is not in the
/// fat format.</exception>
public new static CilRawFatMethodBody? FromReader(IErrorListener errorListener, ref BinaryStreamReader reader)
{
ulong fileOffset = reader.Offset;
uint rva = reader.Rva;
// Read flags.
ushort header = reader.ReadUInt16();
var flags = (CilMethodBodyAttributes) (header & 0xFFF);
int headerSize = (header >> 12) * sizeof(uint);
// Verify this is a fat method body.
if ((flags & CilMethodBodyAttributes.Fat) != CilMethodBodyAttributes.Fat)
{
errorListener.BadImage("Invalid fat CIL method body header.");
return null;
}
// Read remaining header.
ushort maxStack = reader.ReadUInt16();
uint codeSize = reader.ReadUInt32();
uint localVarSigToken = reader.ReadUInt32();
// Move to code.
reader.Offset = fileOffset + (ulong) headerSize;
// Verify code size.
if (reader.Offset + codeSize > reader.StartOffset + reader.Length)
{
errorListener.BadImage("Invalid fat CIL method body code size.");
return null;
}
// Read code.
var code = reader.ReadSegment(codeSize);
// Create body.
var body = new CilRawFatMethodBody(flags, maxStack, localVarSigToken, code);
body.UpdateOffsets(fileOffset, rva);
// Read any extra sections.
if (body.HasSections)
{
reader.Align(4);
CilExtraSection section;
do
{
section = CilExtraSection.FromReader(ref reader);
body.ExtraSections.Add(section);
} while (section.HasMoreSections);
}
return body;
}
/// <inheritdoc />
public override void UpdateOffsets(ulong newOffset, uint newRva)
{
base.UpdateOffsets(newOffset, newRva);
Code.UpdateOffsets(newOffset + 12, newRva + 12);
if (HasSections)
{
uint codeSize = Code.GetPhysicalSize();
newOffset = (Code.Offset + codeSize).Align(4);
newRva = (Code.Rva + codeSize).Align(4);
for (int i = 0; i < ExtraSections.Count; i++)
ExtraSections[i].UpdateOffsets(newOffset, newRva);
}
}
/// <inheritdoc />
public override uint GetPhysicalSize()
{
uint length = 12 + Code.GetPhysicalSize();
ulong endOffset = Offset + length;
if (HasSections)
{
ulong sectionsOffset = endOffset.Align(4);
length += (uint) (sectionsOffset - endOffset);
length += (uint) ExtraSections.Sum(x => x.GetPhysicalSize());
}
return length;
}
/// <inheritdoc />
public override void Write(IBinaryStreamWriter writer)
{
writer.WriteUInt16((ushort) ((ushort) _attributes | 0x3000));
writer.WriteUInt16(MaxStack);
writer.WriteUInt32(Code.GetPhysicalSize());
writer.WriteUInt32(LocalVarSigToken.ToUInt32());
Code.Write(writer);
if (HasSections)
{
writer.Align(4);
for (int i = 0; i < ExtraSections.Count; i++)
ExtraSections[i].Write(writer);
}
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Org.OpenAPITools.Converters;
namespace Org.OpenAPITools.Models
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class QueueLeftItem : IEquatable<QueueLeftItem>
{
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Actions
/// </summary>
[DataMember(Name="actions", EmitDefaultValue=false)]
public List<CauseAction> Actions { get; set; }
/// <summary>
/// Gets or Sets Blocked
/// </summary>
[DataMember(Name="blocked", EmitDefaultValue=false)]
public bool Blocked { get; set; }
/// <summary>
/// Gets or Sets Buildable
/// </summary>
[DataMember(Name="buildable", EmitDefaultValue=false)]
public bool Buildable { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int Id { get; set; }
/// <summary>
/// Gets or Sets InQueueSince
/// </summary>
[DataMember(Name="inQueueSince", EmitDefaultValue=false)]
public int InQueueSince { get; set; }
/// <summary>
/// Gets or Sets Params
/// </summary>
[DataMember(Name="params", EmitDefaultValue=false)]
public string Params { get; set; }
/// <summary>
/// Gets or Sets Stuck
/// </summary>
[DataMember(Name="stuck", EmitDefaultValue=false)]
public bool Stuck { get; set; }
/// <summary>
/// Gets or Sets Task
/// </summary>
[DataMember(Name="task", EmitDefaultValue=false)]
public FreeStyleProject Task { get; set; }
/// <summary>
/// Gets or Sets Url
/// </summary>
[DataMember(Name="url", EmitDefaultValue=false)]
public string Url { get; set; }
/// <summary>
/// Gets or Sets Why
/// </summary>
[DataMember(Name="why", EmitDefaultValue=false)]
public string Why { get; set; }
/// <summary>
/// Gets or Sets Cancelled
/// </summary>
[DataMember(Name="cancelled", EmitDefaultValue=false)]
public bool Cancelled { get; set; }
/// <summary>
/// Gets or Sets Executable
/// </summary>
[DataMember(Name="executable", EmitDefaultValue=false)]
public FreeStyleBuild Executable { 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 QueueLeftItem {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Actions: ").Append(Actions).Append("\n");
sb.Append(" Blocked: ").Append(Blocked).Append("\n");
sb.Append(" Buildable: ").Append(Buildable).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" InQueueSince: ").Append(InQueueSince).Append("\n");
sb.Append(" Params: ").Append(Params).Append("\n");
sb.Append(" Stuck: ").Append(Stuck).Append("\n");
sb.Append(" Task: ").Append(Task).Append("\n");
sb.Append(" Url: ").Append(Url).Append("\n");
sb.Append(" Why: ").Append(Why).Append("\n");
sb.Append(" Cancelled: ").Append(Cancelled).Append("\n");
sb.Append(" Executable: ").Append(Executable).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 Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.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 (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((QueueLeftItem)obj);
}
/// <summary>
/// Returns true if QueueLeftItem instances are equal
/// </summary>
/// <param name="other">Instance of QueueLeftItem to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(QueueLeftItem other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Class == other.Class ||
Class != null &&
Class.Equals(other.Class)
) &&
(
Actions == other.Actions ||
Actions != null &&
other.Actions != null &&
Actions.SequenceEqual(other.Actions)
) &&
(
Blocked == other.Blocked ||
Blocked.Equals(other.Blocked)
) &&
(
Buildable == other.Buildable ||
Buildable.Equals(other.Buildable)
) &&
(
Id == other.Id ||
Id.Equals(other.Id)
) &&
(
InQueueSince == other.InQueueSince ||
InQueueSince.Equals(other.InQueueSince)
) &&
(
Params == other.Params ||
Params != null &&
Params.Equals(other.Params)
) &&
(
Stuck == other.Stuck ||
Stuck.Equals(other.Stuck)
) &&
(
Task == other.Task ||
Task != null &&
Task.Equals(other.Task)
) &&
(
Url == other.Url ||
Url != null &&
Url.Equals(other.Url)
) &&
(
Why == other.Why ||
Why != null &&
Why.Equals(other.Why)
) &&
(
Cancelled == other.Cancelled ||
Cancelled.Equals(other.Cancelled)
) &&
(
Executable == other.Executable ||
Executable != null &&
Executable.Equals(other.Executable)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
// Suitable nullity checks etc, of course :)
if (Class != null)
hashCode = hashCode * 59 + Class.GetHashCode();
if (Actions != null)
hashCode = hashCode * 59 + Actions.GetHashCode();
hashCode = hashCode * 59 + Blocked.GetHashCode();
hashCode = hashCode * 59 + Buildable.GetHashCode();
hashCode = hashCode * 59 + Id.GetHashCode();
hashCode = hashCode * 59 + InQueueSince.GetHashCode();
if (Params != null)
hashCode = hashCode * 59 + Params.GetHashCode();
hashCode = hashCode * 59 + Stuck.GetHashCode();
if (Task != null)
hashCode = hashCode * 59 + Task.GetHashCode();
if (Url != null)
hashCode = hashCode * 59 + Url.GetHashCode();
if (Why != null)
hashCode = hashCode * 59 + Why.GetHashCode();
hashCode = hashCode * 59 + Cancelled.GetHashCode();
if (Executable != null)
hashCode = hashCode * 59 + Executable.GetHashCode();
return hashCode;
}
}
#region Operators
#pragma warning disable 1591
public static bool operator ==(QueueLeftItem left, QueueLeftItem right)
{
return Equals(left, right);
}
public static bool operator !=(QueueLeftItem left, QueueLeftItem right)
{
return !Equals(left, right);
}
#pragma warning restore 1591
#endregion Operators
}
}
| |
// 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.Text;
using Xunit;
namespace System.Text.Encodings.Tests
{
public class DecoderMiscTests
{
[Fact]
public static unsafe void ConvertTest()
{
string s1 = "This is simple ascii string";
string s2 = "\uD800\uDC00\u0200"; // non ascii letters
string s3 = s1 + s2;
Encoding utf8 = Encoding.UTF8;
Decoder decoder = utf8.GetDecoder();
char [] chars = new char[200];
byte [] bytes1 = utf8.GetBytes(s1);
byte [] bytes2 = utf8.GetBytes(s2);
byte [] bytes3 = utf8.GetBytes(s3);
int bytesUsed;
int charsUsed;
bool completed;
fixed (byte *pBytes1 = bytes1)
fixed (byte *pBytes2 = bytes2)
fixed (byte *pBytes3 = bytes3)
fixed (char *pChars = chars)
{
decoder.Convert(pBytes1, bytes1.Length, pChars, chars.Length, true, out bytesUsed, out charsUsed, out completed);
string s = new string(chars, 0, charsUsed);
Assert.Equal(bytes1.Length, bytesUsed);
Assert.Equal(s1.Length, charsUsed);
Assert.True(completed, "Expected to have the full operation compeleted with bytes1");
Assert.Equal(s1, s);
decoder.Convert(pBytes2, bytes2.Length, pChars, chars.Length, true, out bytesUsed, out charsUsed, out completed);
s = new string(chars, 0, charsUsed);
Assert.Equal(bytes2.Length, bytesUsed);
Assert.Equal(s2.Length, charsUsed);
Assert.True(completed, "Expected to have the full operation compeleted with bytes2");
Assert.Equal(s2, s);
decoder.Convert(pBytes3, bytes3.Length, pChars, chars.Length, true, out bytesUsed, out charsUsed, out completed);
s = new string(chars, 0, charsUsed);
Assert.Equal(bytes3.Length, bytesUsed);
Assert.Equal(s3.Length, charsUsed);
Assert.True(completed, "Expected to have the full operation compeleted with bytes3");
Assert.Equal(s3, s);
decoder.Convert(pBytes3 + bytes1.Length, bytes3.Length - bytes1.Length, pChars, chars.Length, true, out bytesUsed, out charsUsed, out completed);
s = new string(chars, 0, charsUsed);
Assert.Equal(bytes2.Length, bytesUsed);
Assert.Equal(s2.Length, charsUsed);
Assert.True(completed, "Expected to have the full operation compeleted with bytes3+bytes1.Length");
Assert.Equal(s2, s);
decoder.Convert(pBytes3 + bytes1.Length, bytes3.Length - bytes1.Length, pChars, 2, true, out bytesUsed, out charsUsed, out completed);
s = new string(chars, 0, charsUsed);
Assert.True(bytes2.Length > bytesUsed, "Expected to use less bytes when there is not enough char buffer");
Assert.Equal(2, charsUsed);
Assert.False(completed, "Expected to have the operation not fully completed");
Assert.Equal(s2.Substring(0, 2), s);
int encodedBytes = bytesUsed;
decoder.Convert(pBytes3 + bytes1.Length + bytesUsed, bytes3.Length - bytes1.Length - encodedBytes, pChars, 1, true, out bytesUsed, out charsUsed, out completed);
Assert.Equal(bytes3.Length - bytes1.Length - encodedBytes, bytesUsed);
Assert.Equal(1, charsUsed);
Assert.True(completed, "expected to flush the remaining character");
Assert.Equal(s2[s2.Length - 1], pChars[0]);
}
}
[Fact]
public static unsafe void ConvertNegativeTest()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
int bytesUsed;
int charsUsed;
bool completed;
byte [] bytes = Encoding.UTF8.GetBytes("\u0D800\uDC00");
fixed (byte *bytesPtr = bytes)
fixed (char *charsPtr = new char[1])
{
byte *pBytes = bytesPtr;
char *pChars = charsPtr;
AssertExtensions.Throws<ArgumentNullException>("chars", () => decoder.Convert(pBytes, bytes.Length, null, 1, true, out bytesUsed, out charsUsed, out completed));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.Convert(null, bytes.Length, pChars, 1, true, out bytesUsed, out charsUsed, out completed));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => decoder.Convert(pBytes, -1, pChars, 1, true, out bytesUsed, out charsUsed, out completed));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => decoder.Convert(pBytes, bytes.Length, pChars, -1, true, out bytesUsed, out charsUsed, out completed));
AssertExtensions.Throws<ArgumentException>("chars", () => decoder.Convert(pBytes, bytes.Length, pChars, 0, true, out bytesUsed, out charsUsed, out completed));
}
decoder = Encoding.GetEncoding("us-ascii", new EncoderExceptionFallback(), new DecoderExceptionFallback()).GetDecoder();
fixed (byte *bytesPtr = new byte [] { 0xFF, 0xFF })
fixed (char *charsPtr = new char[2])
{
byte *pBytes = bytesPtr;
char *pChars = charsPtr;
Assert.Throws<DecoderFallbackException>(() => decoder.Convert(pBytes, 2, pChars, 2, true, out bytesUsed, out charsUsed, out completed));
}
}
[Fact]
public static unsafe void GetCharsTest()
{
string s1 = "This is simple ascii string";
string s2 = "\uD800\uDC00\u0200"; // non ascii letters
string s3 = s1 + s2;
Encoding utf8 = Encoding.UTF8;
Decoder decoder = utf8.GetDecoder();
char [] chars = new char[200];
byte [] bytes1 = utf8.GetBytes(s1);
byte [] bytes2 = utf8.GetBytes(s2);
byte [] bytes3 = utf8.GetBytes(s3);
fixed (byte *pBytes1 = bytes1)
fixed (byte *pBytes2 = bytes2)
fixed (byte *pBytes3 = bytes3)
fixed (char *pChars = chars)
{
int charsUsed = decoder.GetChars(pBytes1, bytes1.Length, pChars, chars.Length, true);
string s = new string(chars, 0, charsUsed);
Assert.Equal(s1.Length, charsUsed);
Assert.Equal(s1.Length, decoder.GetCharCount(pBytes1, bytes1.Length, true));
Assert.Equal(s1, s);
charsUsed = decoder.GetChars(pBytes2, bytes2.Length, pChars, chars.Length, true);
s = new string(chars, 0, charsUsed);
Assert.Equal(s2.Length, charsUsed);
Assert.Equal(s2.Length, decoder.GetCharCount(pBytes2, bytes2.Length, true));
Assert.Equal(s2, s);
charsUsed = decoder.GetChars(pBytes3, bytes3.Length, pChars, chars.Length, true);
s = new string(chars, 0, charsUsed);
Assert.Equal(s3.Length, charsUsed);
Assert.Equal(s3.Length, decoder.GetCharCount(pBytes3, bytes3.Length, true));
Assert.Equal(s3, s);
charsUsed = decoder.GetChars(pBytes3 + bytes1.Length, bytes3.Length - bytes1.Length, pChars, chars.Length, true);
s = new string(chars, 0, charsUsed);
Assert.Equal(s2.Length, charsUsed);
Assert.Equal(s2.Length, decoder.GetCharCount(pBytes3 + bytes1.Length, bytes3.Length - bytes1.Length, true));
Assert.Equal(s2, s);
}
}
[Fact]
public static unsafe void GetCharsNegativeTest()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
byte [] bytes = Encoding.UTF8.GetBytes("\u0D800\uDC00");
fixed (byte *bytesPtr = bytes)
fixed (char *charsPtr = new char[1])
{
byte *pBytes = bytesPtr;
char *pChars = charsPtr;
AssertExtensions.Throws<ArgumentNullException>("chars", () => decoder.GetChars(pBytes, bytes.Length, null, 1, true));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.GetChars(null, bytes.Length, pChars, 1, true));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.GetCharCount(null, bytes.Length, true));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => decoder.GetChars(pBytes, -1, pChars, 1, true));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => decoder.GetChars(pBytes, bytes.Length, pChars, -1, true));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => decoder.GetCharCount(pBytes, -1, true));
AssertExtensions.Throws<ArgumentException>("chars", () => decoder.GetChars(pBytes, bytes.Length, pChars, 1, true));
}
decoder = Encoding.GetEncoding("us-ascii", new EncoderExceptionFallback(), new DecoderExceptionFallback()).GetDecoder();
fixed (byte *bytesPtr = new byte [] { 0xFF, 0xFF })
fixed (char *charsPtr = new char[2])
{
byte *pBytes = bytesPtr;
char *pChars = charsPtr;
Assert.Throws<DecoderFallbackException>(() => decoder.GetChars(pBytes, 2, pChars, 2, true));
Assert.Throws<DecoderFallbackException>(() => decoder.GetCharCount(pBytes, 2, true));
}
}
[Fact]
public static void DecoderExceptionFallbackBufferTest()
{
Decoder decoder = Encoding.GetEncoding("us-ascii", new EncoderExceptionFallback(), new DecoderExceptionFallback()).GetDecoder();
byte [] bytes = new byte [] { 0xFF, 0xFF };
char [] chars = new char [bytes.Length];
Assert.Throws<DecoderFallbackException>(() => decoder.GetChars(bytes, 0, 2, chars, 2));
DecoderFallbackBuffer fallbackBuffer = decoder.FallbackBuffer;
Assert.True(fallbackBuffer is DecoderExceptionFallbackBuffer, "Expected to get DecoderExceptionFallbackBuffer type");
Assert.Throws<DecoderFallbackException>(() => fallbackBuffer.Fallback(bytes, 0));
Assert.Throws<DecoderFallbackException>(() => fallbackBuffer.Fallback(new byte [] { 0x40, 0x60 }, 0));
Assert.Equal(0, fallbackBuffer.Remaining);
Assert.Equal('\u0000', fallbackBuffer.GetNextChar());
Assert.False(fallbackBuffer.MovePrevious(), "MovePrevious expected to always return false");
fallbackBuffer.Reset();
Assert.Equal(0, fallbackBuffer.Remaining);
Assert.Equal('\u0000', fallbackBuffer.GetNextChar());
}
[Fact]
public static void DecoderReplacementFallbackBufferTest()
{
Decoder decoder = Encoding.GetEncoding("us-ascii", new EncoderReplacementFallback(), new DecoderReplacementFallback()).GetDecoder();
byte [] bytes = new byte [] { 0xFF, 0xFF };
char [] chars = new char [bytes.Length];
DecoderFallbackBuffer fallbackBuffer = decoder.FallbackBuffer;
Assert.True(fallbackBuffer is DecoderReplacementFallbackBuffer, "Expected to get DecoderReplacementFallbackBuffer type");
Assert.True(fallbackBuffer.Fallback(bytes, 0), "Expected we fallback on the given buffer");
Assert.Equal(1, fallbackBuffer.Remaining);
Assert.False(fallbackBuffer.MovePrevious(), "Expected we cannot move back on the replacement buffer as we are at the Beginning of the buffer");
Assert.Equal('?', fallbackBuffer.GetNextChar());
Assert.True(fallbackBuffer.MovePrevious(), "Expected we can move back on the replacement buffer");
Assert.Equal('?', fallbackBuffer.GetNextChar());
fallbackBuffer.Reset();
Assert.Equal(0, fallbackBuffer.Remaining);
Assert.Equal('\u0000', fallbackBuffer.GetNextChar());
Assert.False(fallbackBuffer.MovePrevious(), "Expected we cannot move back on the replacement buffer as we are rest the buffer");
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using Mono.Cecil.PE;
using Mono.Collections.Generic;
using RVA = System.UInt32;
namespace Mono.Cecil.Cil {
sealed class CodeReader : BinaryStreamReader {
readonly internal MetadataReader reader;
int start;
MethodDefinition method;
MethodBody body;
int Offset {
get { return Position - start; }
}
public CodeReader (MetadataReader reader)
: base (reader.image.Stream.value)
{
this.reader = reader;
}
public int MoveTo (MethodDefinition method)
{
this.method = method;
this.reader.context = method;
var position = this.Position;
this.Position = (int) reader.image.ResolveVirtualAddress ((uint) method.RVA);
return position;
}
void MoveBackTo (int position)
{
this.reader.context = null;
this.Position = position;
}
public MethodBody ReadMethodBody (MethodDefinition method)
{
var position = MoveTo (method);
this.body = new MethodBody (method);
ReadMethodBody ();
MoveBackTo (position);
return this.body;
}
void ReadMethodBody ()
{
var flags = ReadByte ();
switch (flags & 0x3) {
case 0x2: // tiny
body.code_size = flags >> 2;
body.MaxStackSize = 8;
ReadCode ();
break;
case 0x3: // fat
Advance (-1);
ReadFatMethod ();
break;
default:
throw new InvalidOperationException ();
}
var symbol_reader = reader.module.symbol_reader;
if (symbol_reader != null && method.debug_info == null)
method.debug_info = symbol_reader.Read (method);
if (method.debug_info != null)
ReadDebugInfo ();
}
void ReadDebugInfo ()
{
if (method.debug_info.sequence_points != null)
ReadSequencePoints ();
if (method.debug_info.scope != null)
ReadScope (method.debug_info.scope);
if (method.custom_infos != null)
ReadCustomDebugInformations (method);
}
void ReadCustomDebugInformations (MethodDefinition method)
{
var custom_infos = method.custom_infos;
for (int i = 0; i < custom_infos.Count; i++) {
var state_machine_scope = custom_infos [i] as StateMachineScopeDebugInformation;
if (state_machine_scope != null)
ReadStateMachineScope (state_machine_scope);
var async_method = custom_infos [i] as AsyncMethodBodyDebugInformation;
if (async_method != null)
ReadAsyncMethodBody (async_method);
}
}
void ReadAsyncMethodBody (AsyncMethodBodyDebugInformation async_method)
{
if (async_method.catch_handler.Offset > -1)
async_method.catch_handler = new InstructionOffset (GetInstruction (async_method.catch_handler.Offset));
if (!async_method.yields.IsNullOrEmpty ())
for (int i = 0; i < async_method.yields.Count; i++)
async_method.yields [i] = new InstructionOffset (GetInstruction (async_method.yields [i].Offset));
if (!async_method.resumes.IsNullOrEmpty ())
for (int i = 0; i < async_method.resumes.Count; i++)
async_method.resumes [i] = new InstructionOffset (GetInstruction (async_method.resumes [i].Offset));
}
void ReadStateMachineScope (StateMachineScopeDebugInformation state_machine_scope)
{
state_machine_scope.start = new InstructionOffset (GetInstruction (state_machine_scope.start.Offset));
var end_instruction = GetInstruction (state_machine_scope.end.Offset);
state_machine_scope.end = end_instruction == null
? new InstructionOffset ()
: new InstructionOffset (end_instruction);
}
void ReadSequencePoints ()
{
var symbol = method.debug_info;
for (int i = 0; i < symbol.sequence_points.Count; i++) {
var sequence_point = symbol.sequence_points [i];
var instruction = GetInstruction (sequence_point.Offset);
if (instruction != null)
sequence_point.offset = new InstructionOffset (instruction);
}
}
void ReadScopes (Collection<ScopeDebugInformation> scopes)
{
for (int i = 0; i < scopes.Count; i++)
ReadScope (scopes [i]);
}
void ReadScope (ScopeDebugInformation scope)
{
var start_instruction = GetInstruction (scope.Start.Offset);
if (start_instruction != null)
scope.Start = new InstructionOffset (start_instruction);
var end_instruction = GetInstruction (scope.End.Offset);
if (end_instruction != null)
scope.End = new InstructionOffset (end_instruction);
if (!scope.variables.IsNullOrEmpty ()) {
for (int i = 0; i < scope.variables.Count; i++) {
var variable_info = scope.variables [i];
var variable = GetVariable (variable_info.Index);
if (variable != null)
variable_info.index = new VariableIndex (variable);
}
}
if (!scope.scopes.IsNullOrEmpty ())
ReadScopes (scope.scopes);
}
void ReadFatMethod ()
{
var flags = ReadUInt16 ();
body.max_stack_size = ReadUInt16 ();
body.code_size = (int) ReadUInt32 ();
body.local_var_token = new MetadataToken (ReadUInt32 ());
body.init_locals = (flags & 0x10) != 0;
if (body.local_var_token.RID != 0)
body.variables = ReadVariables (body.local_var_token);
ReadCode ();
if ((flags & 0x8) != 0)
ReadSection ();
}
public VariableDefinitionCollection ReadVariables (MetadataToken local_var_token)
{
var position = reader.position;
var variables = reader.ReadVariables (local_var_token);
reader.position = position;
return variables;
}
void ReadCode ()
{
start = Position;
var code_size = body.code_size;
if (code_size < 0 || Length <= (uint) (code_size + Position))
code_size = 0;
var end = start + code_size;
var instructions = body.instructions = new InstructionCollection (method, (code_size + 1) / 2);
while (Position < end) {
var offset = Position - start;
var opcode = ReadOpCode ();
var current = new Instruction (offset, opcode);
if (opcode.OperandType != OperandType.InlineNone)
current.operand = ReadOperand (current);
instructions.Add (current);
}
ResolveBranches (instructions);
}
OpCode ReadOpCode ()
{
var il_opcode = ReadByte ();
return il_opcode != 0xfe
? OpCodes.OneByteOpCode [il_opcode]
: OpCodes.TwoBytesOpCode [ReadByte ()];
}
object ReadOperand (Instruction instruction)
{
switch (instruction.opcode.OperandType) {
case OperandType.InlineSwitch:
var length = ReadInt32 ();
var base_offset = Offset + (4 * length);
var branches = new int [length];
for (int i = 0; i < length; i++)
branches [i] = base_offset + ReadInt32 ();
return branches;
case OperandType.ShortInlineBrTarget:
return ReadSByte () + Offset;
case OperandType.InlineBrTarget:
return ReadInt32 () + Offset;
case OperandType.ShortInlineI:
if (instruction.opcode == OpCodes.Ldc_I4_S)
return ReadSByte ();
return ReadByte ();
case OperandType.InlineI:
return ReadInt32 ();
case OperandType.ShortInlineR:
return ReadSingle ();
case OperandType.InlineR:
return ReadDouble ();
case OperandType.InlineI8:
return ReadInt64 ();
case OperandType.ShortInlineVar:
return GetVariable (ReadByte ());
case OperandType.InlineVar:
return GetVariable (ReadUInt16 ());
case OperandType.ShortInlineArg:
return GetParameter (ReadByte ());
case OperandType.InlineArg:
return GetParameter (ReadUInt16 ());
case OperandType.InlineSig:
return GetCallSite (ReadToken ());
case OperandType.InlineString:
return GetString (ReadToken ());
case OperandType.InlineTok:
case OperandType.InlineType:
case OperandType.InlineMethod:
case OperandType.InlineField:
return reader.LookupToken (ReadToken ());
default:
throw new NotSupportedException ();
}
}
public string GetString (MetadataToken token)
{
return reader.image.UserStringHeap.Read (token.RID);
}
public ParameterDefinition GetParameter (int index)
{
return body.GetParameter (index);
}
public VariableDefinition GetVariable (int index)
{
return body.GetVariable (index);
}
public CallSite GetCallSite (MetadataToken token)
{
return reader.ReadCallSite (token);
}
void ResolveBranches (Collection<Instruction> instructions)
{
var items = instructions.items;
var size = instructions.size;
for (int i = 0; i < size; i++) {
var instruction = items [i];
switch (instruction.opcode.OperandType) {
case OperandType.ShortInlineBrTarget:
case OperandType.InlineBrTarget:
instruction.operand = GetInstruction ((int) instruction.operand);
break;
case OperandType.InlineSwitch:
var offsets = (int []) instruction.operand;
var branches = new Instruction [offsets.Length];
for (int j = 0; j < offsets.Length; j++)
branches [j] = GetInstruction (offsets [j]);
instruction.operand = branches;
break;
}
}
}
Instruction GetInstruction (int offset)
{
return GetInstruction (body.Instructions, offset);
}
static Instruction GetInstruction (Collection<Instruction> instructions, int offset)
{
var size = instructions.size;
var items = instructions.items;
if (offset < 0 || offset > items [size - 1].offset)
return null;
int min = 0;
int max = size - 1;
while (min <= max) {
int mid = min + ((max - min) / 2);
var instruction = items [mid];
var instruction_offset = instruction.offset;
if (offset == instruction_offset)
return instruction;
if (offset < instruction_offset)
max = mid - 1;
else
min = mid + 1;
}
return null;
}
void ReadSection ()
{
Align (4);
const byte fat_format = 0x40;
const byte more_sects = 0x80;
var flags = ReadByte ();
if ((flags & fat_format) == 0)
ReadSmallSection ();
else
ReadFatSection ();
if ((flags & more_sects) != 0)
ReadSection ();
}
void ReadSmallSection ()
{
var count = ReadByte () / 12;
Advance (2);
ReadExceptionHandlers (
count,
() => (int) ReadUInt16 (),
() => (int) ReadByte ());
}
void ReadFatSection ()
{
Advance (-1);
var count = (ReadInt32 () >> 8) / 24;
ReadExceptionHandlers (
count,
ReadInt32,
ReadInt32);
}
// inline ?
void ReadExceptionHandlers (int count, Func<int> read_entry, Func<int> read_length)
{
for (int i = 0; i < count; i++) {
var handler = new ExceptionHandler (
(ExceptionHandlerType) (read_entry () & 0x7));
handler.TryStart = GetInstruction (read_entry ());
handler.TryEnd = GetInstruction (handler.TryStart.Offset + read_length ());
handler.HandlerStart = GetInstruction (read_entry ());
handler.HandlerEnd = GetInstruction (handler.HandlerStart.Offset + read_length ());
ReadExceptionHandlerSpecific (handler);
this.body.ExceptionHandlers.Add (handler);
}
}
void ReadExceptionHandlerSpecific (ExceptionHandler handler)
{
switch (handler.HandlerType) {
case ExceptionHandlerType.Catch:
handler.CatchType = (TypeReference) reader.LookupToken (ReadToken ());
break;
case ExceptionHandlerType.Filter:
handler.FilterStart = GetInstruction (ReadInt32 ());
break;
default:
Advance (4);
break;
}
}
void Align (int align)
{
align--;
var position = Position;
Advance (((position + align) & ~align) - position);
}
public MetadataToken ReadToken ()
{
return new MetadataToken (ReadUInt32 ());
}
#if !READ_ONLY
public ByteBuffer PatchRawMethodBody (MethodDefinition method, CodeWriter writer, out int code_size, out MetadataToken local_var_token)
{
var position = MoveTo (method);
var buffer = new ByteBuffer ();
var flags = ReadByte ();
switch (flags & 0x3) {
case 0x2: // tiny
buffer.WriteByte (flags);
local_var_token = MetadataToken.Zero;
code_size = flags >> 2;
PatchRawCode (buffer, code_size, writer);
break;
case 0x3: // fat
Advance (-1);
PatchRawFatMethod (buffer, writer, out code_size, out local_var_token);
break;
default:
throw new NotSupportedException ();
}
MoveBackTo (position);
return buffer;
}
void PatchRawFatMethod (ByteBuffer buffer, CodeWriter writer, out int code_size, out MetadataToken local_var_token)
{
var flags = ReadUInt16 ();
buffer.WriteUInt16 (flags);
buffer.WriteUInt16 (ReadUInt16 ());
code_size = ReadInt32 ();
buffer.WriteInt32 (code_size);
local_var_token = ReadToken ();
if (local_var_token.RID > 0) {
var variables = ReadVariables (local_var_token);
buffer.WriteUInt32 (variables != null
? writer.GetStandAloneSignature (variables).ToUInt32 ()
: 0);
} else
buffer.WriteUInt32 (0);
PatchRawCode (buffer, code_size, writer);
if ((flags & 0x8) != 0)
PatchRawSection (buffer, writer.metadata);
}
void PatchRawCode (ByteBuffer buffer, int code_size, CodeWriter writer)
{
var metadata = writer.metadata;
buffer.WriteBytes (ReadBytes (code_size));
var end = buffer.position;
buffer.position -= code_size;
while (buffer.position < end) {
OpCode opcode;
var il_opcode = buffer.ReadByte ();
if (il_opcode != 0xfe) {
opcode = OpCodes.OneByteOpCode [il_opcode];
} else {
var il_opcode2 = buffer.ReadByte ();
opcode = OpCodes.TwoBytesOpCode [il_opcode2];
}
switch (opcode.OperandType) {
case OperandType.ShortInlineI:
case OperandType.ShortInlineBrTarget:
case OperandType.ShortInlineVar:
case OperandType.ShortInlineArg:
buffer.position += 1;
break;
case OperandType.InlineVar:
case OperandType.InlineArg:
buffer.position += 2;
break;
case OperandType.InlineBrTarget:
case OperandType.ShortInlineR:
case OperandType.InlineI:
buffer.position += 4;
break;
case OperandType.InlineI8:
case OperandType.InlineR:
buffer.position += 8;
break;
case OperandType.InlineSwitch:
var length = buffer.ReadInt32 ();
buffer.position += length * 4;
break;
case OperandType.InlineString:
var @string = GetString (new MetadataToken (buffer.ReadUInt32 ()));
buffer.position -= 4;
buffer.WriteUInt32 (
new MetadataToken (
TokenType.String,
metadata.user_string_heap.GetStringIndex (@string)).ToUInt32 ());
break;
case OperandType.InlineSig:
var call_site = GetCallSite (new MetadataToken (buffer.ReadUInt32 ()));
buffer.position -= 4;
buffer.WriteUInt32 (writer.GetStandAloneSignature (call_site).ToUInt32 ());
break;
case OperandType.InlineTok:
case OperandType.InlineType:
case OperandType.InlineMethod:
case OperandType.InlineField:
var provider = reader.LookupToken (new MetadataToken (buffer.ReadUInt32 ()));
buffer.position -= 4;
buffer.WriteUInt32 (metadata.LookupToken (provider).ToUInt32 ());
break;
}
}
}
void PatchRawSection (ByteBuffer buffer, MetadataBuilder metadata)
{
var position = Position;
Align (4);
buffer.WriteBytes (Position - position);
const byte fat_format = 0x40;
const byte more_sects = 0x80;
var flags = ReadByte ();
if ((flags & fat_format) == 0) {
buffer.WriteByte (flags);
PatchRawSmallSection (buffer, metadata);
} else
PatchRawFatSection (buffer, metadata);
if ((flags & more_sects) != 0)
PatchRawSection (buffer, metadata);
}
void PatchRawSmallSection (ByteBuffer buffer, MetadataBuilder metadata)
{
var length = ReadByte ();
buffer.WriteByte (length);
Advance (2);
buffer.WriteUInt16 (0);
var count = length / 12;
PatchRawExceptionHandlers (buffer, metadata, count, false);
}
void PatchRawFatSection (ByteBuffer buffer, MetadataBuilder metadata)
{
Advance (-1);
var length = ReadInt32 ();
buffer.WriteInt32 (length);
var count = (length >> 8) / 24;
PatchRawExceptionHandlers (buffer, metadata, count, true);
}
void PatchRawExceptionHandlers (ByteBuffer buffer, MetadataBuilder metadata, int count, bool fat_entry)
{
const int fat_entry_size = 16;
const int small_entry_size = 6;
for (int i = 0; i < count; i++) {
ExceptionHandlerType handler_type;
if (fat_entry) {
var type = ReadUInt32 ();
handler_type = (ExceptionHandlerType) (type & 0x7);
buffer.WriteUInt32 (type);
} else {
var type = ReadUInt16 ();
handler_type = (ExceptionHandlerType) (type & 0x7);
buffer.WriteUInt16 (type);
}
buffer.WriteBytes (ReadBytes (fat_entry ? fat_entry_size : small_entry_size));
switch (handler_type) {
case ExceptionHandlerType.Catch:
var exception = reader.LookupToken (ReadToken ());
buffer.WriteUInt32 (metadata.LookupToken (exception).ToUInt32 ());
break;
default:
buffer.WriteUInt32 (ReadUInt32 ());
break;
}
}
}
#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.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Threading;
using CFStringRef = System.IntPtr;
using CFRunLoopRef = System.IntPtr;
namespace System.Net.NetworkInformation
{
// OSX implementation of NetworkChange
// See <SystemConfiguration/SystemConfiguration.h> and its documentation, as well as
// the documentation for CFRunLoop for more information on the components involved.
public class NetworkChange
{
private static object s_lockObj = new object();
// The list of current address-changed subscribers.
private static NetworkAddressChangedEventHandler s_addressChangedSubscribers;
// The list of current availability-changed subscribers.
private static NetworkAvailabilityChangedEventHandler s_availabilityChangedSubscribers;
// The dynamic store. We listen to changes in the IPv4 and IPv6 address keys.
// When those keys change, our callback below is called (OnAddressChanged).
private static SafeCreateHandle s_dynamicStoreRef;
// The callback used when registered keys in the dynamic store change.
private static readonly Interop.SystemConfiguration.SCDynamicStoreCallBack s_storeCallback = OnAddressChanged;
// The RunLoop source, created over the above SCDynamicStore.
private static SafeCreateHandle s_runLoopSource;
// Listener thread that adds the RunLoopSource to its RunLoop.
private static Thread s_runLoopThread;
// The listener thread's CFRunLoop.
private static CFRunLoopRef s_runLoop;
// Use an event to try to prevent StartRaisingEvents from returning before the
// RunLoop actually begins. This will mitigate a race condition where the watcher
// thread hasn't completed initialization and stop is called before the RunLoop has even started.
private static readonly AutoResetEvent s_runLoopStartedEvent = new AutoResetEvent(false);
private static readonly AutoResetEvent s_runLoopEndedEvent = new AutoResetEvent(false);
//introduced for supporting design-time loading of System.Windows.dll
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
public static void RegisterNetworkChange(NetworkChange nc) { }
public static event NetworkAddressChangedEventHandler NetworkAddressChanged
{
add
{
lock (s_lockObj)
{
if (s_addressChangedSubscribers == null && s_availabilityChangedSubscribers == null)
{
CreateAndStartRunLoop();
}
s_addressChangedSubscribers += value;
}
}
remove
{
lock (s_lockObj)
{
bool hadAddressChangedSubscribers = s_addressChangedSubscribers != null;
s_addressChangedSubscribers -= value;
if (hadAddressChangedSubscribers && s_addressChangedSubscribers == null && s_availabilityChangedSubscribers == null)
{
StopRunLoop();
}
}
}
}
public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged
{
add
{
lock (s_lockObj)
{
if (s_addressChangedSubscribers == null && s_availabilityChangedSubscribers == null)
{
CreateAndStartRunLoop();
}
else
{
Debug.Assert(s_runLoop != IntPtr.Zero);
}
s_availabilityChangedSubscribers += value;
}
}
remove
{
lock (s_lockObj)
{
bool hadSubscribers = s_addressChangedSubscribers != null || s_availabilityChangedSubscribers != null;
s_availabilityChangedSubscribers -= value;
if (hadSubscribers && s_addressChangedSubscribers == null && s_availabilityChangedSubscribers == null)
{
StopRunLoop();
}
}
}
}
private static unsafe void CreateAndStartRunLoop()
{
Debug.Assert(s_dynamicStoreRef == null);
var storeContext = new Interop.SystemConfiguration.SCDynamicStoreContext();
using (SafeCreateHandle storeName = Interop.CoreFoundation.CFStringCreateWithCString("NetworkAddressChange.OSX"))
{
s_dynamicStoreRef = Interop.SystemConfiguration.SCDynamicStoreCreate(
storeName.DangerousGetHandle(),
s_storeCallback,
&storeContext);
}
// Notification key string parts. We want to match notification keys
// for any kind of IP address change, addition, or removal.
using (SafeCreateHandle dynamicStoreDomainStateString = Interop.CoreFoundation.CFStringCreateWithCString("State:"))
using (SafeCreateHandle compAnyRegexString = Interop.CoreFoundation.CFStringCreateWithCString("[^/]+"))
using (SafeCreateHandle entNetIpv4String = Interop.CoreFoundation.CFStringCreateWithCString("IPv4"))
using (SafeCreateHandle entNetIpv6String = Interop.CoreFoundation.CFStringCreateWithCString("IPv6"))
{
if (dynamicStoreDomainStateString.IsInvalid || compAnyRegexString.IsInvalid
|| entNetIpv4String.IsInvalid || entNetIpv6String.IsInvalid)
{
s_dynamicStoreRef.Dispose();
s_dynamicStoreRef = null;
throw new NetworkInformationException(SR.net_PInvokeError);
}
using (SafeCreateHandle ipv4Pattern = Interop.SystemConfiguration.SCDynamicStoreKeyCreateNetworkServiceEntity(
dynamicStoreDomainStateString.DangerousGetHandle(),
compAnyRegexString.DangerousGetHandle(),
entNetIpv4String.DangerousGetHandle()))
using (SafeCreateHandle ipv6Pattern = Interop.SystemConfiguration.SCDynamicStoreKeyCreateNetworkServiceEntity(
dynamicStoreDomainStateString.DangerousGetHandle(),
compAnyRegexString.DangerousGetHandle(),
entNetIpv6String.DangerousGetHandle()))
using (SafeCreateHandle patterns = Interop.CoreFoundation.CFArrayCreate(
new CFStringRef[2]
{
ipv4Pattern.DangerousGetHandle(),
ipv6Pattern.DangerousGetHandle()
}, (UIntPtr)2))
{
// Try to register our pattern strings with the dynamic store instance.
if (patterns.IsInvalid || !Interop.SystemConfiguration.SCDynamicStoreSetNotificationKeys(
s_dynamicStoreRef.DangerousGetHandle(),
IntPtr.Zero,
patterns.DangerousGetHandle()))
{
s_dynamicStoreRef.Dispose();
s_dynamicStoreRef = null;
throw new NetworkInformationException(SR.net_PInvokeError);
}
// Create a "RunLoopSource" that can be added to our listener thread's RunLoop.
s_runLoopSource = Interop.SystemConfiguration.SCDynamicStoreCreateRunLoopSource(
s_dynamicStoreRef.DangerousGetHandle(),
IntPtr.Zero);
}
}
s_runLoopThread = new Thread(RunLoopThreadStart);
s_runLoopThread.Start();
s_runLoopStartedEvent.WaitOne(); // Wait for the new thread to finish initialization.
}
private static void RunLoopThreadStart()
{
Debug.Assert(s_runLoop == IntPtr.Zero);
s_runLoop = Interop.RunLoop.CFRunLoopGetCurrent();
Interop.RunLoop.CFRunLoopAddSource(
s_runLoop,
s_runLoopSource.DangerousGetHandle(),
Interop.RunLoop.kCFRunLoopDefaultMode.DangerousGetHandle());
s_runLoopStartedEvent.Set();
Interop.RunLoop.CFRunLoopRun();
Interop.RunLoop.CFRunLoopRemoveSource(
s_runLoop,
s_runLoopSource.DangerousGetHandle(),
Interop.RunLoop.kCFRunLoopDefaultMode.DangerousGetHandle());
s_runLoop = IntPtr.Zero;
s_runLoopSource.Dispose();
s_runLoopSource = null;
s_dynamicStoreRef.Dispose();
s_dynamicStoreRef = null;
s_runLoopEndedEvent.Set();
}
private static void StopRunLoop()
{
Debug.Assert(s_runLoop != IntPtr.Zero);
Debug.Assert(s_runLoopSource != null);
Debug.Assert(s_dynamicStoreRef != null);
// Allow RunLoop to finish current processing.
SpinWait.SpinUntil(() => Interop.RunLoop.CFRunLoopIsWaiting(s_runLoop));
Interop.RunLoop.CFRunLoopStop(s_runLoop);
s_runLoopEndedEvent.WaitOne();
}
private static void OnAddressChanged(IntPtr store, IntPtr changedKeys, IntPtr info)
{
s_addressChangedSubscribers?.Invoke(null, EventArgs.Empty);
s_availabilityChangedSubscribers?.Invoke(null, new NetworkAvailabilityEventArgs(NetworkInterface.GetIsNetworkAvailable()));
}
}
}
| |
using DotNet.HighStock.Attributes;
using DotNet.HighStock.Enums;
using DotNet.HighStock.Helpers;
using System;
using System.Drawing;
namespace DotNet.HighStock.Options
{
/// <summary>
/// The legend is a box containing a symbol and name for each series item or point item in the chart.
/// </summary>
public class Legend
{
/// <summary>
/// The horizontal alignment of the legend box within the chart area. Valid values are <code>'left'</code>, <code>'center'</code> and <code>'right'</code>.
/// Default: center
/// </summary>
public HorizontalAligns? Align
{
get;
set;
}
/// <summary>
/// The background color of the legend.
/// </summary>
[JsonFormatter(addPropertyName: true, useCurlyBracketsForObject: false)]
public BackColorOrGradient BackgroundColor
{
get;
set;
}
/// <summary>
/// The color of the drawn border around the legend.
/// Default: #909090
/// </summary>
public Color? BorderColor
{
get;
set;
}
/// <summary>
/// The border corner radius of the legend.
/// Default: 0
/// </summary>
public Number? BorderRadius
{
get;
set;
}
/// <summary>
/// The width of the drawn border around the legend.
/// Default: 0
/// </summary>
public Number? BorderWidth
{
get;
set;
}
/// <summary>
/// Enable or disable the legend.
/// Default: true
/// </summary>
public bool? Enabled
{
get;
set;
}
/// <summary>
/// When the legend is floating, the plot area ignores it and is allowed to be placed below it.
/// Default: false
/// </summary>
public bool? Floating
{
get;
set;
}
/// <summary>
/// In a legend with horizontal layout, the itemDistance defines the pixel distance between each item.
/// Default: 20
/// </summary>
public Number? ItemDistance
{
get;
set;
}
/// <summary>
/// CSS styles for each legend item when the corresponding series or point is hidden. Only a subset of CSS is supported, notably those options related to text. Properties are inherited from <code>style</code> unless overridden here. Defaults to:<pre>itemHiddenStyle: { color: '#CCC'}</pre>
/// </summary>
[JsonFormatter("{{ {0} }}")]
public string ItemHiddenStyle
{
get;
set;
}
/// <summary>
/// CSS styles for each legend item in hover mode. Only a subset of CSS is supported, notably those options related to text. Properties are inherited from <code>style</code> unless overridden here. Defaults to:<pre>itemHoverStyle: { color: '#000'}</pre>
/// </summary>
[JsonFormatter("{{ {0} }}")]
public string ItemHoverStyle
{
get;
set;
}
/// <summary>
/// The pixel bottom margin for each legend item.
/// Default: 0
/// </summary>
public Number? ItemMarginBottom
{
get;
set;
}
/// <summary>
/// The pixel top margin for each legend item.
/// Default: 0
/// </summary>
public Number? ItemMarginTop
{
get;
set;
}
/// <summary>
/// CSS styles for each legend item. Only a subset of CSS is supported, notably those options related to text.
/// Default: { "color": "#333333", "cursor": "pointer", "fontSize": "12px", "fontWeight": "bold" }
/// </summary>
[JsonFormatter("{{ {0} }}")]
public string ItemStyle
{
get;
set;
}
/// <summary>
/// The width for each legend item. This is useful in a horizontal layout with many items when you want the items to align vertically. .
/// </summary>
public Number? ItemWidth
{
get;
set;
}
/// <summary>
/// A <a href='http://www.highstock.com/docs/chart-concepts/labels-and-string-formatting'>format string</a> for each legend label. Available variables relates to properties on the series, or the point in case of pies.
/// Default: {name}
/// </summary>
public string LabelFormat
{
get;
set;
}
/// <summary>
/// Callback function to format each of the series' labels. The <em>this</em> keyword refers to the series object, or the point object in case of pie charts. By default the series or point name is printed.
/// </summary>
[JsonFormatter("{0}")]
public string LabelFormatter
{
get;
set;
}
/// <summary>
/// The layout of the legend items. Can be one of 'horizontal' or 'vertical'.
/// Default: horizontal
/// </summary>
public Layouts? Layout
{
get;
set;
}
/// <summary>
/// Line height for the legend items. Deprecated as of 2.1. Instead, the line height for each item can be set using itemStyle.lineHeight, and the padding between items using itemMarginTop and itemMarginBottom.
/// Default: 16
/// </summary>
public Number? LineHeight
{
get;
set;
}
/// <summary>
/// If the plot area sized is calculated automatically and the legend is not floating, the legend margin is the space between the legend and the axis labels or plot area.
/// Default: 15
/// </summary>
public Number? Margin
{
get;
set;
}
/// <summary>
/// Maximum pixel height for the legend. When the maximum height is extended, navigation will show.
/// </summary>
public Number? MaxHeight
{
get;
set;
}
/// <summary>
/// Options for the paging or navigation appearing when the legend is overflown. When <a href='#legend.useHTML'>legend.useHTML</a> is enabled, navigation is disabled.
/// </summary>
public LegendNavigation Navigation
{
get;
set;
}
/// <summary>
/// The inner padding of the legend box.
/// Default: 8
/// </summary>
public Number? Padding
{
get;
set;
}
/// <summary>
/// Whether to reverse the order of the legend items compared to the order of the series or points as defined in the configuration object.
/// Default: false
/// </summary>
public bool? Reversed
{
get;
set;
}
/// <summary>
/// Whether to show the symbol on the right side of the text rather than the left side. This is common in Arabic and Hebraic.
/// Default: false
/// </summary>
public bool? Rtl
{
get;
set;
}
/// <summary>
/// Whether to apply a drop shadow to the legend. A <code>backgroundColor</code> also needs to be applied for this to take effect. Since 2.3 the shadow can be an object configuration containing <code>color</code>, <code>offsetX</code>, <code>offsetY</code>, <code>opacity</code> and <code>width</code>.
/// Default: false
/// </summary>
public bool? Shadow
{
get;
set;
}
[Obsolete("CSS styles for the legend area. In the 1.x versions the position of the legend area was determined by CSS. In 2.x, the position is determined by properties like <code>align</code>, <code>verticalAlign</code>, <code>x</code> and <code>y</code>, but the styles are still parsed for backwards compatibility.")]
[JsonFormatter("{{ {0} }}")]
public string Style
{
get;
set;
}
/// <summary>
/// The pixel height of the symbol for series types that use a rectangle in the legend.
/// Default: 12
/// </summary>
public Number? SymbolHeight
{
get;
set;
}
/// <summary>
/// The pixel padding between the legend item symbol and the legend item text.
/// Default: 5
/// </summary>
public Number? SymbolPadding
{
get;
set;
}
/// <summary>
/// The border radius of the symbol for series types that use a rectangle in the legend.
/// Default: 2
/// </summary>
public Number? SymbolRadius
{
get;
set;
}
/// <summary>
/// The pixel width of the legend item symbol.
/// Default: 16
/// </summary>
public Number? SymbolWidth
{
get;
set;
}
/// <summary>
/// A title to be added on top of the legend.
/// </summary>
public LegendTitle Title
{
get;
set;
}
/// <summary>
/// <p>Whether to <a href='http://www.highstock.com/docs/chart-concepts/labels-and-string-formatting#html'>use HTML</a> to render the legend item texts. When using HTML, <a href='#legend.navigation'>legend.navigation</a> is disabled.</p>
/// Default: false
/// </summary>
public bool? UseHTML
{
get;
set;
}
/// <summary>
/// The vertical alignment of the legend box. Can be one of 'top', 'middle' or 'bottom'. Vertical position can be further determined by the <code>y</code> option.
/// Default: bottom
/// </summary>
public VerticalAligns? VerticalAlign
{
get;
set;
}
/// <summary>
/// The width of the legend box.
/// </summary>
public Number? Width
{
get;
set;
}
/// <summary>
/// The x offset of the legend relative to its horizontal alignment <code>align</code> within chart.spacingLeft and chart.spacingRight. Negative x moves it to the left, positive x moves it to the right.
/// Default: 0
/// </summary>
public Number? X
{
get;
set;
}
/// <summary>
/// The vertical offset of the legend relative to it's vertical alignment <code>verticalAlign</code> within chart.spacingTop and chart.spacingBottom. Negative y moves it up, positive y moves it down.
/// Default: 0
/// </summary>
public Number? Y
{
get;
set;
}
}
}
| |
// 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 gclv = Google.Cloud.Logging.V2;
using sys = System;
namespace Google.Cloud.Logging.V2
{
/// <summary>Resource name for the <c>Log</c> resource.</summary>
public sealed partial class LogName : gax::IResourceName, sys::IEquatable<LogName>
{
/// <summary>The possible contents of <see cref="LogName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/logs/{log}</c>.</summary>
ProjectLog = 1,
/// <summary>A resource name with pattern <c>organizations/{organization}/logs/{log}</c>.</summary>
OrganizationLog = 2,
/// <summary>A resource name with pattern <c>folders/{folder}/logs/{log}</c>.</summary>
FolderLog = 3,
/// <summary>A resource name with pattern <c>billingAccounts/{billing_account}/logs/{log}</c>.</summary>
BillingAccountLog = 4,
}
private static gax::PathTemplate s_projectLog = new gax::PathTemplate("projects/{project}/logs/{log}");
private static gax::PathTemplate s_organizationLog = new gax::PathTemplate("organizations/{organization}/logs/{log}");
private static gax::PathTemplate s_folderLog = new gax::PathTemplate("folders/{folder}/logs/{log}");
private static gax::PathTemplate s_billingAccountLog = new gax::PathTemplate("billingAccounts/{billing_account}/logs/{log}");
/// <summary>Creates a <see cref="LogName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="LogName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static LogName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new LogName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="LogName"/> with the pattern <c>projects/{project}/logs/{log}</c>.</summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="logId">The <c>Log</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="LogName"/> constructed from the provided ids.</returns>
public static LogName FromProjectLog(string projectId, string logId) =>
new LogName(ResourceNameType.ProjectLog, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), logId: gax::GaxPreconditions.CheckNotNullOrEmpty(logId, nameof(logId)));
/// <summary>
/// Creates a <see cref="LogName"/> with the pattern <c>organizations/{organization}/logs/{log}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="logId">The <c>Log</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="LogName"/> constructed from the provided ids.</returns>
public static LogName FromOrganizationLog(string organizationId, string logId) =>
new LogName(ResourceNameType.OrganizationLog, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), logId: gax::GaxPreconditions.CheckNotNullOrEmpty(logId, nameof(logId)));
/// <summary>Creates a <see cref="LogName"/> with the pattern <c>folders/{folder}/logs/{log}</c>.</summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="logId">The <c>Log</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="LogName"/> constructed from the provided ids.</returns>
public static LogName FromFolderLog(string folderId, string logId) =>
new LogName(ResourceNameType.FolderLog, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), logId: gax::GaxPreconditions.CheckNotNullOrEmpty(logId, nameof(logId)));
/// <summary>
/// Creates a <see cref="LogName"/> with the pattern <c>billingAccounts/{billing_account}/logs/{log}</c>.
/// </summary>
/// <param name="billingAccountId">The <c>BillingAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="logId">The <c>Log</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="LogName"/> constructed from the provided ids.</returns>
public static LogName FromBillingAccountLog(string billingAccountId, string logId) =>
new LogName(ResourceNameType.BillingAccountLog, billingAccountId: gax::GaxPreconditions.CheckNotNullOrEmpty(billingAccountId, nameof(billingAccountId)), logId: gax::GaxPreconditions.CheckNotNullOrEmpty(logId, nameof(logId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="LogName"/> with pattern
/// <c>projects/{project}/logs/{log}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="logId">The <c>Log</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="LogName"/> with pattern <c>projects/{project}/logs/{log}</c>.
/// </returns>
public static string Format(string projectId, string logId) => FormatProjectLog(projectId, logId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="LogName"/> with pattern
/// <c>projects/{project}/logs/{log}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="logId">The <c>Log</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="LogName"/> with pattern <c>projects/{project}/logs/{log}</c>.
/// </returns>
public static string FormatProjectLog(string projectId, string logId) =>
s_projectLog.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(logId, nameof(logId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="LogName"/> with pattern
/// <c>organizations/{organization}/logs/{log}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="logId">The <c>Log</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="LogName"/> with pattern
/// <c>organizations/{organization}/logs/{log}</c>.
/// </returns>
public static string FormatOrganizationLog(string organizationId, string logId) =>
s_organizationLog.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(logId, nameof(logId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="LogName"/> with pattern
/// <c>folders/{folder}/logs/{log}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="logId">The <c>Log</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="LogName"/> with pattern <c>folders/{folder}/logs/{log}</c>.
/// </returns>
public static string FormatFolderLog(string folderId, string logId) =>
s_folderLog.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(logId, nameof(logId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="LogName"/> with pattern
/// <c>billingAccounts/{billing_account}/logs/{log}</c>.
/// </summary>
/// <param name="billingAccountId">The <c>BillingAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="logId">The <c>Log</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="LogName"/> with pattern
/// <c>billingAccounts/{billing_account}/logs/{log}</c>.
/// </returns>
public static string FormatBillingAccountLog(string billingAccountId, string logId) =>
s_billingAccountLog.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(billingAccountId, nameof(billingAccountId)), gax::GaxPreconditions.CheckNotNullOrEmpty(logId, nameof(logId)));
/// <summary>Parses the given resource name string into a new <see cref="LogName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/logs/{log}</c></description></item>
/// <item><description><c>organizations/{organization}/logs/{log}</c></description></item>
/// <item><description><c>folders/{folder}/logs/{log}</c></description></item>
/// <item><description><c>billingAccounts/{billing_account}/logs/{log}</c></description></item>
/// </list>
/// </remarks>
/// <param name="logName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="LogName"/> if successful.</returns>
public static LogName Parse(string logName) => Parse(logName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="LogName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/logs/{log}</c></description></item>
/// <item><description><c>organizations/{organization}/logs/{log}</c></description></item>
/// <item><description><c>folders/{folder}/logs/{log}</c></description></item>
/// <item><description><c>billingAccounts/{billing_account}/logs/{log}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="logName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="LogName"/> if successful.</returns>
public static LogName Parse(string logName, bool allowUnparsed) =>
TryParse(logName, allowUnparsed, out LogName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>Tries to parse the given resource name string into a new <see cref="LogName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/logs/{log}</c></description></item>
/// <item><description><c>organizations/{organization}/logs/{log}</c></description></item>
/// <item><description><c>folders/{folder}/logs/{log}</c></description></item>
/// <item><description><c>billingAccounts/{billing_account}/logs/{log}</c></description></item>
/// </list>
/// </remarks>
/// <param name="logName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="LogName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string logName, out LogName result) => TryParse(logName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="LogName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/logs/{log}</c></description></item>
/// <item><description><c>organizations/{organization}/logs/{log}</c></description></item>
/// <item><description><c>folders/{folder}/logs/{log}</c></description></item>
/// <item><description><c>billingAccounts/{billing_account}/logs/{log}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="logName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="LogName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string logName, bool allowUnparsed, out LogName result)
{
gax::GaxPreconditions.CheckNotNull(logName, nameof(logName));
gax::TemplatedResourceName resourceName;
if (s_projectLog.TryParseName(logName, out resourceName))
{
result = FromProjectLog(resourceName[0], resourceName[1]);
return true;
}
if (s_organizationLog.TryParseName(logName, out resourceName))
{
result = FromOrganizationLog(resourceName[0], resourceName[1]);
return true;
}
if (s_folderLog.TryParseName(logName, out resourceName))
{
result = FromFolderLog(resourceName[0], resourceName[1]);
return true;
}
if (s_billingAccountLog.TryParseName(logName, out resourceName))
{
result = FromBillingAccountLog(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(logName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private LogName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string billingAccountId = null, string folderId = null, string logId = null, string organizationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
BillingAccountId = billingAccountId;
FolderId = folderId;
LogId = logId;
OrganizationId = organizationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="LogName"/> class from the component parts of pattern
/// <c>projects/{project}/logs/{log}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="logId">The <c>Log</c> ID. Must not be <c>null</c> or empty.</param>
public LogName(string projectId, string logId) : this(ResourceNameType.ProjectLog, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), logId: gax::GaxPreconditions.CheckNotNullOrEmpty(logId, nameof(logId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>BillingAccount</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string BillingAccountId { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Log</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LogId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLog: return s_projectLog.Expand(ProjectId, LogId);
case ResourceNameType.OrganizationLog: return s_organizationLog.Expand(OrganizationId, LogId);
case ResourceNameType.FolderLog: return s_folderLog.Expand(FolderId, LogId);
case ResourceNameType.BillingAccountLog: return s_billingAccountLog.Expand(BillingAccountId, LogId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as LogName);
/// <inheritdoc/>
public bool Equals(LogName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(LogName a, LogName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(LogName a, LogName b) => !(a == b);
}
public partial class LogEntry
{
/// <summary>
/// <see cref="gclv::LogName"/>-typed view over the <see cref="LogName"/> resource name property.
/// </summary>
public gclv::LogName LogNameAsLogName
{
get => string.IsNullOrEmpty(LogName) ? null : gclv::LogName.Parse(LogName, allowUnparsed: true);
set => LogName = value?.ToString() ?? "";
}
}
}
| |
using dotless.Core.Parser.Infrastructure;
using dotless.Core.Test.Plugins;
namespace dotless.Core.Test.Specs
{
using NUnit.Framework;
using dotless.Core.Exceptions;
using System.Text.RegularExpressions;
using System;
public class CommentsFixture : SpecFixtureBase
{
[Test]
public void CommentHeader()
{
var input =
@"
/******************\
* *
* Comment Header *
* *
\******************/
";
AssertLessUnchanged(input);
}
[Test]
public void MultilineComment()
{
var input =
@"
/*
Comment
*/
";
AssertLessUnchanged(input);
}
[Test]
public void MultilineComment2()
{
var input =
@"
/*
* Comment Test
*
* - dotless (http://dotlesscss.com)
*
*/
";
AssertLessUnchanged(input);
}
[Test]
public void LineCommentGetsRemoved()
{
var input = "////////////////";
var expected = "";
AssertLess(input, expected);
}
[Test]
public void ColorInsideComments()
{
var input =
@"
/* Colors
* ------
* #EDF8FC (background blue)
* #166C89 (darkest blue)
*
* Text:
* #333 (standard text)
* #1F9EC9 (standard link)
*
*/
";
AssertLessUnchanged(input);
}
[Test]
public void CommentInsideAComment()
{
var input =
@"
/*
* Comment Test
*
* // A comment within a comment!
*
*/
";
AssertLessUnchanged(input);
}
[Test]
public void VariablesInsideComments()
{
var input =
@"
/* @group Variables
------------------- */
";
AssertLessUnchanged(input);
}
[Test]
public void BlockCommentAfterSelector()
{
var input =
@"
#comments /* boo */ {
color: red;
}
";
var expected = @"
#comments/* boo */ {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void EmptyComment()
{
var input =
@"
#comments {
border: solid black;
/**/
color: red;
}
";
var expected =
@"
#comments {
border: solid black;
/**/
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentAfterPropertyMissingSemiColon()
{
var input = @"
#comments {
border: solid black;
color: red /* A C-style comment */
}
";
var expected = @"
#comments {
border: solid black;
color: red/* A C-style comment */;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentAfterPropertyMissingSemiColonDimension()
{
var input = @"
#comments {
border: 1px /* A C-style comment */
}
";
var expected = @"
#comments {
border: 1px/* A C-style comment */;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentAfterPropertyMissingSemiColonColor()
{
var input = @"
#comments {
color: #ff1000 /* A C-style comment */
}
";
var expected = @"
#comments {
color: #ff1000/* A C-style comment */;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentAfterMixinCallMissingSemiColon()
{
var input = @"
.cla (@a) {
color: @a;
}
#comments {
border: solid black;
.cla(red) /* A C-style comment */
}
";
var expected = @"
#comments {
border: solid black;
color: red;
/* A C-style comment */
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentAfterProperty()
{
var input =
@"
#comments {
border: solid black;
color: red; /* A C-style comment */
padding: 0;
}
";
var expected =
@"
#comments {
border: solid black;
color: red;
/* A C-style comment */
padding: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void LineCommentAfterProperty()
{
var input =
@"
#comments {
border: solid black;
color: red; // A little comment
padding: 0;
}
";
var expected = @"
#comments {
border: solid black;
color: red;
padding: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentBeforeProperty()
{
var input =
@"
#comments {
border: solid black;
/* comment */ color: red;
padding: 0;
}
";
var expected = @"
#comments {
border: solid black;
/* comment */
color: red;
padding: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void LineCommentAfterALineComment()
{
var input =
@"
#comments {
border: solid black;
// comment //
color: red;
padding: 0;
}
";
var expected = @"
#comments {
border: solid black;
color: red;
padding: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void LineCommentAfterBlock()
{
var input =
@"
#comments /* boo */ {
color: red;
} // comment
";
var expected = @"
#comments/* boo */ {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommented1()
{
var input =
@"
/* commented out
#more-comments {
color: grey;
}
*/
";
AssertLessUnchanged(input);
}
[Test]
public void BlockCommented2()
{
var input =
@"
/*
#signup form h3.title {
background:transparent url(../img/ui/signup.png) no-repeat 50px top;
height:100px;
}
*/
";
AssertLessUnchanged(input);
}
[Test]
public void BlockCommented3()
{
var input =
@"
#more-comments {
quotes: ""/*"" ""*/"";
}
";
AssertLessUnchanged(input);
}
[Test]
public void CommentOnLastLine()
{
var input =
@"
#last { color: blue }
//
";
var expected = @"
#last {
color: blue;
}
";
AssertLess(input, expected);
}
[Test]
public void CheckCommentsAreNotAcceptedAsASelector()
{
// Note: https://github.com/dotless/dotless/issues/31
var input = @"/* COMMENT *//* COMMENT */, /* COMMENT */,/* COMMENT */ .clb /* COMMENT */ {background-image: url(pickture.asp);}";
Assert.Throws<ParserException>(() => AssertLessUnchanged(input));
}
[Test]
public void CheckCommentsAreAcceptedBetweenSelectors()
{
// Note: https://github.com/dotless/dotless/issues/31
var input = @"/* COMMENT */body/* COMMENT */,/* COMMENT */ .clb /* COMMENT */ {background-image: url(pickture.asp);}";
var expected = @"/* COMMENT */
body/* COMMENT */,
/* COMMENT */ .clb/* COMMENT */ {
background-image: url(pickture.asp);
}";
AssertLess(input, expected);
}
[Test]
public void CheckCommentsAreAcceptedWhereWhitespaceIsAllowed()
{
// Note: https://github.com/dotless/dotless/issues/31
var input = @"/* COMMENT */body/* COMMENT */, /* COMMENT */.cls/* COMMENT */ .cla,/* COMMENT */ .clb /* COMMENT */ {background-image: url(pickture.asp);}";
var expected = @"/* COMMENT */
body/* COMMENT */,
/* COMMENT */ .cls/* COMMENT */ .cla,
/* COMMENT */ .clb/* COMMENT */ {
background-image: url(pickture.asp);
}";
AssertLess(input, expected);
}
[Test]
public void CommentCSSHackException1Accepted()
{
var input = @"/*\*/.cls {background-image: url(picture.asp);} /**/";
var expected = @"/*\*/
.cls {
background-image: url(picture.asp);
}
/**/";
AssertLess(input, expected);
}
[Test]
public void CommentCSSHackException2Accepted()
{
var input = @"/*\*/
/*/
.cls {background-image: url(picture.asp);} /**/";
AssertLessUnchanged(input);
}
[Test]
public void CommentBeforeMixinDefinition()
{
var input = @"/* COMMENT */.clb(@a) { font-size: @a; }
.cla { .clb(10); }";
var expected = @"/* COMMENT */
.cla {
font-size: 10;
}";
AssertLess(input, expected);
}
[Test]
public void CommentBeforeAndAfterMixinDefinition()
{
var input = @"/* COMMENT */.clb(/* COMMENT */@a/* COMMENT */,/* COMMENT */@b)/* COMMENT */ { font-size: @a; }
.cla { .clb(10, 10); }";
var expected = @"/* COMMENT */
.cla {
font-size: 10;
}";
AssertLess(input, expected);
}
[Test]
public void CommentBeforeAndAfterMixinDefinitionWithDefaultArgs()
{
var input = @"/* COMMENT */.clb(/* COMMENT */@a/* COMMENT */:/* COMMENT */10/* COMMENT */,/* COMMENT */@b/* COMMENT */:/* COMMENT */7px/* COMMENT */)/* COMMENT */ { font-size: @a; }
.cla { .clb(10, 10); }";
var expected = @"/* COMMENT */
.cla {
font-size: 10;
}";
AssertLess(input, expected);
}
[Test]
public void CommentBeforeVariableRuleKept()
{
var input = @"/* COMMENT */@a : 10px;/* COMMENT */
.cla { font-size: @a; }";
var expected = @"/* COMMENT */
/* COMMENT */
.cla {
font-size: 10px;
}";
AssertLess(input, expected);
}
[Test]
[Ignore("")]
public void CommentsInVariableRuleAccepted()
{
var input = @"/* COM1 */@a /* COM2 */: /* COM3 */10px/* COM4 */;/* COM5 */
.cla { font-size: @a; }";
var expected = @"/* COM1 */
/* COM5 */
.cla {
font-size: /* COM3 */10px/* COM4 */;
}";
AssertLess(input, expected);
}
[Test]
public void CommentsInDirective1()
{
var input = @"/* COMMENT */@charset /* COMMENT */""utf-8""/* COMMENT */;";
var expected = @"/* COMMENT */
@charset /* COMMENT */""utf-8""/* COMMENT */;";
AssertLess(input, expected);
}
[Test]
public void CommentsInDirective2()
{
var input = @"@media/*COM1*/ print /*COM2*/ {/*COM3*/
font-size: 3em;
}/*COM 6*/
@font-face /*COM4*/ { /*COM5*/
font-size: 3em;
}/*COM 6*/
";
var expected = @"@media /*COM1*/print/*COM2*/ {
/*COM3*/
font-size: 3em;
}
/*COM 6*/
@font-face/*COM4*/ {
/*COM5*/
font-size: 3em;
}
/*COM 6*/";
AssertLess(input, expected);
}
[Test]
public void CommentsInDirective3()
{
var input = @"@media/*COM1*/ print {
font-size: 3em;
}
";
var expected = @"@media /*COM1*/print {
font-size: 3em;
}";
AssertLess(input, expected);
}
[Test]
public void CommentsInSelectorPsuedos()
{
var input = @"p/*CO1*/:not/*CO1*/([class*=""lead""])/*CO2*/{ font-size: 10px; }";
var expected = @"p/*CO1*/:not/*CO1*/([class*=""lead""])/*CO2*/ {
font-size: 10px;
}";
AssertLess(input, expected);
}
[Test, Ignore("Unsupported - Requires an attribute node")]
public void CommentsInSelectorAttributes()
{
var input = @"p/*CO2*/[/*CO3*/type=""checkbox""/*CO5*/]/*CO6*/[/*CO7*/type/*CO8*/] { font-size: 10px; }";
var expected = @"p/*CO2*/[/*CO3*/type=""checkbox""/*CO5*/]/*CO6*/[/*CO7*/type/*CO8*/] {
font-size: 10px;
}";
AssertLess(input, expected);
}
[Test]
public void CommentsInUrl()
{
var input = @"url(/*A*/""test""/*R*/)/*S*/";
var expected = @"url(/*A*/""test""/*R*/)/*S*/";
AssertExpression(expected, input);
}
private void AssertExpressionWithAndWithoutComments(string expected, string input)
{
Regex removeComments = new Regex(@"(//[^\n]*|(/\*(.|[\r\n])*?\*/))");
string inputNC = removeComments.Replace(input, "");
string expectedNC = removeComments.Replace(expected, "");
AssertExpression(expectedNC, inputNC);
AssertExpression(expected, input);
}
[Test]
public void CommentsInExpression1Paren()
{
// drops some comments, but this is better than throwing an exception
var input = @"/*A*/(/*B*/12/*C*/+/*D*/(/*E*/7/*F*/-/*G*/(/*H*/8px/*I*/*/*J*/(/*K*/9/*L*/-/*M*/3/*N*/)/*O*/)/*P*/)/*Q*/)/*R*/";
var expected = @"/*A*/-29px/*B*//*C*//*D*//*E*//*F*//*G*//*H*//*I*//*J*//*K*//*L*//*M*//*N*//*O*//*P*//*Q*//*R*/";
AssertExpressionWithAndWithoutComments(expected, input);
}
[Test]
public void CommentsInExpression1NoParen()
{
var input = @"/*A*/12/*B*/+/*C*/7/*D*/-/*E*/8px/*F*/*/*G*/9/*H*/-/*I*/3/*J*/";
var expected = @"/*A*/-56px/*B*//*C*//*D*//*E*//*F*//*G*//*H*//*I*//*J*/";
AssertExpressionWithAndWithoutComments(expected, input);
}
[Test]
public void CommentsInExpressionMultiplication()
{
var input = @"8/*A*/*/*B*/1";
var expected = @"8/*A*//*B*/";
AssertExpressionWithAndWithoutComments(expected, input);
}
[Test]
public void CommentsInExpression2()
{
var input = @"/*A*/12px/*B*/ /*C*/4px/*D*/";
var expected = @"/*A*/12px/*B*//*C*/ 4px/*D*/";
AssertExpressionWithAndWithoutComments(expected, input);
}
[Test]
public void CommentsInExpression3()
{
var input = @"/*A*/12px/*B*/ !important";
var expected = @"/*A*/12px/*B*/ !important";
AssertExpressionWithAndWithoutComments(expected, input);
}
[Test]
public void ImportantCommentIsLeftInOutputWithMinificationEnabled()
{
var input = @"/*! don't remove me */";
DefaultEnv = () => {
var env = new Env();
env.AddPlugin(new PassThroughAfterPlugin());
env.AddPlugin(new PassThroughBeforePlugin());
env.KeepFirstSpecialComment = true;
env.Compress = true;
return env;
};
AssertLessUnchanged(input, DefaultParser());
}
}
}
| |
/*
* QUANTCONNECT.COM - Extension routines for QC.
* QC.Math Library of Statistics Routines for Algorithm
*/
/**********************************************************
* USING NAMESPACES
**********************************************************/
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
//QuantConnect Project Libraries:
using QuantConnect.Logging;
namespace QuantConnect {
/********************************************************
* CLASS DEFINITIONS
*********************************************************/
public partial class QCMath {
/********************************************************
* CLASS VARIABLES
*********************************************************/
public static readonly decimal Pi = 3.14159265358979323846264338327950288419716939937510m;
public static readonly decimal Phi = 1.6180339887498948482m;
public static readonly decimal InvPhi = 0.6180339887498948482m;
public static readonly decimal Phi618 = 0.6180339887498948482m;
public static readonly decimal Phi381 = 0.5819660112501051518m;
/********************************************************
* CLASS METHODS
*********************************************************/
/// <summary>
/// Wrapper for System.Math Power Function
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static double Pow(double x, double y) {
return System.Math.Pow(x, y);
}
/// <summary>
/// Wrapper for System.Math.Round.
/// </summary>
/// <param name="dNumber">Number to Round.</param>
/// <param name="iDecimalPlaces">Number of Decimal Places</param>
/// <returns></returns>
public static decimal Round(decimal dNumber, int iDecimalPlaces = 2) {
return System.Math.Round(dNumber, iDecimalPlaces);
}
/// <summary>
/// Returns a random number within range.
/// </summary>
/// <returns></returns>
public static decimal Random(bool bRound = false, int iRoundDP = 0) {
decimal dRandom = 0;
System.Random rGenerator = new System.Random();
dRandom = (decimal)rGenerator.NextDouble();
if (bRound) {
dRandom = Math.Round(dRandom, iRoundDP);
}
return dRandom;
}
/// <summary>
/// Find the mean value of a stock
/// </summary>
/// <param name="dX">dX Array</param>
/// <returns>decimal Average Value</returns>
public static decimal Average(decimal[] dX) {
return dX.Average();
}
/// <summary>
/// Calculate the Spread of Prices from first to last price
/// </summary>
/// <param name="dX">decimal Price Array</param>
/// <returns>decimal dDollar shift</returns>
public static decimal Spread(decimal[] dX) {
if (dX.Length > 0) {
//Find the spread of the most recent price to the first one.
return (dX[dX.Length - 1] - dX[0]);
} else {
return 0;
}
}
/// <summary>
/// A multiple max filter:
/// </summary>
public static decimal Max(params decimal[] dValues) {
decimal dMax = decimal.MinValue;
for (int i = 0; i < dValues.Length; i++) {
if (dValues[i] > dMax) dMax = dValues[i];
}
return dMax;
}
/// <summary>
/// A multiple min filter:
/// </summary>
public static decimal Min(params decimal[] dValues) {
decimal dMin = decimal.MaxValue;
for (int i = 0; i < dValues.Length; i++) {
if (dValues[i] < dMin) dMin = dValues[i];
}
return dMin;
}
/// <summary>
/// Find the Absolulte Spread of prices inthe time period.
/// </summary>
/// <param name="dX">decimal Price Array</param>
/// <returns>Dollars shift</returns>
public static decimal AbsSpread(decimal[] dX) {
if (dX.Length > 0) {
//Find the % AbsSpread of the Highest Price to Lowest Price in this period.
return (dX.Max() - dX.Min());
} else {
return 0;
}
}
/// <summary>
/// Return the absolute value
/// </summary>
/// <param name="dValue">+- value.</param>
/// <returns>Absolute</returns>
public static decimal Abs(decimal dValue) {
return System.Math.Abs(dValue);
}
/// <summary>
/// Return the Median value from a set of data
/// </summary>
/// <param name="sortedprice"> SORTED Price Array </param>
/// <param name="startIndex"></param>
/// <param name="endIndex"></param>
public static decimal GetMedian(decimal[] sortedprice, int startIndex = 0, int endIndex = 0) {
int i = 0;
return GetMedian(sortedprice, out i, false, startIndex, endIndex);
}
/// <summary>
/// Get the Median of an array
/// </summary>
/// <param name="sortedprice"></param>
/// <param name="medianIndex"></param>
/// <param name="bSort"></param>
/// <param name="startIndex"></param>
/// <param name="endIndex"></param>
/// <returns></returns>
public static decimal GetMedian(decimal[] sortedprice, out int medianIndex, bool bSort = false, int startIndex = 0, int endIndex = 0) {
//Data Model:
// a,b,c,d,e
// 0,1,2,3,4 = 5
decimal median = 0;
decimal priceCount;
//Artificially set end point of the data
if (endIndex > 0) {
priceCount = endIndex - startIndex;
} else {
priceCount = sortedprice.Count();
}
//Find out if even or odd number of data points:
bool even = ((priceCount % 2) == 0);
//Find the mid point
decimal midNumber = startIndex + (priceCount / 2);
//Sort the data so can accuractely pick median
if (bSort) {
sortedprice.OrderBy(x => x);
}
//For odd count arrays, index is direct, for even, is average.
medianIndex = (int)System.Math.Floor(midNumber);
try {
if (even) {
if (priceCount > 2) {
//If an even number of data points, need to find the average of B & C.
median = (sortedprice[medianIndex] + sortedprice[medianIndex + 1]) / 2;
} else {
//If its only one or two entries in the dataarray, just return approximation
median = sortedprice[medianIndex];
}
} else {
//If this is an odd number
median = sortedprice[medianIndex];
}
} catch (Exception err) {
//Break if there is an error finding the median.
Log.Error("QCMath: GetMedian(): " + err.Message);
}
return median;
}
/// <summary>
/// Get the Profitability on the predicted price vs current avgHoldings price
/// </summary>
/// <param name="dPredicteprice">Predicted price.</param>
/// <param name="dAvgHoldingsPrice">Current holdings price.</param>
/// <returns>Profitability percentage.</returns>
public static decimal GetProfitability(decimal dPredicteprice, decimal dAvgHoldingsPrice) {
return Math.Round(dPredicteprice / dAvgHoldingsPrice, 3);
}
/// <summary>
/// Multiply two decimal arrays return the vector results
/// </summary>
/// <param name="dX">Vector A to multiply</param>
/// <param name="dY">Vector B to multiply</param>
/// <returns>Return the vector multiplication</returns>
public static decimal[] VectorMultiply(decimal[] dX, decimal[] dY) {
decimal[] dNew = new decimal[dX.Length];
for (int i = 0; i < dX.Length; i++) {
dNew[i] = dX[i] * dY[i];
}
return dNew;
}
/// <summary>
/// Multiply two decimal arrays return the vector results
/// </summary>
/// <param name="dX">Vector A to Square</param>
/// <returns>Return the vector multiplication</returns>
public static decimal VectorSquaredSum(IList<decimal> dX) {
decimal dSum = 0;
for (int i = 0; i < dX.Count; i++) {
dSum += dX[i] * dX[i];
}
return dSum;
}
/// <summary>
/// Check if a dSubject is within dError% of a dTarget.
/// </summary>
public static bool WithinError(decimal dTest, decimal dTargetCenter, decimal dError, bool bUseAbsolute = false) {
decimal dLowBracket = 1 - dError;
decimal dHighBracket = 1 + dError;
if (!bUseAbsolute) {
if (dTest > 0) {
if ((dTargetCenter * dHighBracket) > dTest && (dTargetCenter * dLowBracket) < dTest) {
return true;
}
} else {
Log.Error("QCMath.WithinError(): Only useful above zero.");
}
} else {
//Use the error term as an absolute error.
if ((dTargetCenter + dError) > dTest && (dTargetCenter - dError) < dTest) {
return true;
}
}
return false;
}
/// <summary>
/// Bracket Zero E.g.: X gt -50, X lt 50. Within error of Zero.
/// Test if dSubject brackets Zero within dBracket
/// </summary>
public static bool BracketZero(decimal dSubject, decimal dBracket) {
//E.g.: X > -50, X < 50. Within error of Zero.
if ((dSubject > -dBracket) && (dSubject < dBracket)) {
//Within error bracket.
return true;
}
return false;
}
/// <summary>
/// Check if the subject is greater than the limit, if greater- cap subject at limit. If less return subject.
/// </summary>
public static decimal LimitMax(decimal dSubject, decimal dLimit, decimal? dSetTo = null) {
if (dSubject > dLimit) {
if (dSetTo == null) {
return dLimit;
} else {
return dSetTo.Value;
}
} else {
return dSubject;
}
}
/// <summary>
/// Check if the subject is less than the limit, if lesser - fix subject at limit. If less return subject.
/// </summary>
public static decimal LimitMin(decimal dSubject, decimal dLimit, decimal? dSetTo = null) {
if (dSubject < dLimit) {
if (dSetTo == null) {
return dLimit;
} else {
return dSetTo.Value;
}
} else {
return dSubject;
}
}
/// <summary>
/// Convert Radians to Degrees for Ease of use:
/// </summary>
/// <param name="dAngle">Angle in Radians (0-2pi)</param>
/// <returns>Degrees (0-360)</returns>
public static decimal DegreeToRadian(decimal dAngle) {
return (QCMath.Pi * dAngle / (decimal)180.0);
}
/// <summary>
/// Return a tidied string value of dollars.
/// </summary>
/// <param name="price"></param>
/// <param name="decimals"></param>
/// <returns></returns>
public static string TidyToDollars(decimal price, int decimals = 2) {
return Math.Round(price, decimals).ToString("C" + decimals.ToString());
}
/// <summary>
/// Get the Variance of our dataset.
/// </summary>
public static decimal Variance(decimal[] dX) {
return QCMath.QCStandardDeviation.GetVariance(dX);
}
/// <summary>
/// Get the standard deviation of an array dataset.
/// </summary>
public static decimal StandardDeviation(decimal[] dX) {
if (dX.Length == 0) return 0;
return QCMath.QCStandardDeviation.GetDeviation(dX);
}
/// <summary>
/// Tidy a text box number into a string.
/// </summary>
/// <param name="sNumberString"></param>
/// <returns></returns>
public static int TidyStringInt(string sNumberString) {
return (int)TidyStringNumber(sNumberString);
}
/// <summary>
/// Tidy a string into a decimal, return 0 if not parsable.
/// </summary>
/// <param name="sNumberString">Number in a string</param>
/// <returns>decimal value of string.</returns>
public static decimal TidyStringNumber(string sNumberString) {
decimal dDollars = 0;
string sDollars = "";
//Attempt to filter out the number
try {
CultureInfo MyCultureInfo = new CultureInfo("en-US");
char[] cNumberString = sNumberString.ToCharArray();
//Robust method for making a number from a string, remove the characters:
foreach (char c in cNumberString) {
//Comma or Dot we'll slide as non numeric characters to add.
if ((c == '.') || (c == ',') || (c == '-')) {
sDollars += c.ToString();
continue;
} else if (c == '(') {
//Include the subtrOrderDirection as well.
sDollars += '-';
} else if (IsNumber(c)) {
//Otherwise if its a number add it to string. Skip "E" "Euro" etc.
sDollars += c.ToString();
}
}
try {
dDollars = (decimal)Decimal.Parse(sDollars, NumberStyles.Currency, MyCultureInfo);
} catch (Exception err) {
//No point logging, can happen often.
Log.Trace("TidyStringNumber() Error Parsing Number(" + sNumberString + "): " + err.Message);
dDollars = 0;
}
} catch {
//De nada
}
return dDollars;
}
/// <summary>
/// Test if a string is a number and can be parsed
/// </summary>
/// <param name="Expression">String to be tested.</param>
/// <returns>Bool/Number</returns>
public static bool IsNumber(object Expression) {
bool bIsNum;
decimal dRetNum;
bIsNum = decimal.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any,
System.Globalization.NumberFormatInfo.InvariantInfo, out dRetNum);
return bIsNum;
}
/// <summary>
/// Test if the variable "x" is between A and B
/// </summary>
/// <param name="x"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static bool XisBetweenAandB(decimal x, decimal a, decimal b) {
if ((x >= a) && (x <= b)) {
//X is within or ON the boundariesof A and B
return true;
} else {
return false;
}
}
} // End of Math
} // End of Namespace
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !SILVERLIGHT || WINDOWS_PHONE
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
#if !NET20
using System.Xml.Linq;
#endif
using Newtonsoft.Json.Utilities;
using System.Linq;
namespace Newtonsoft.Json.Converters
{
#region XmlNodeWrappers
#if !SILVERLIGHT
internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument
{
private XmlDocument _document;
public XmlDocumentWrapper(XmlDocument document)
: base(document)
{
_document = document;
}
public IXmlNode CreateComment(string data)
{
return new XmlNodeWrapper(_document.CreateComment(data));
}
public IXmlNode CreateTextNode(string text)
{
return new XmlNodeWrapper(_document.CreateTextNode(text));
}
public IXmlNode CreateCDataSection(string data)
{
return new XmlNodeWrapper(_document.CreateCDataSection(data));
}
public IXmlNode CreateWhitespace(string text)
{
return new XmlNodeWrapper(_document.CreateWhitespace(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
{
return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text));
}
public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone)
{
return new XmlNodeWrapper(_document.CreateXmlDeclaration(version, encoding, standalone));
}
public IXmlNode CreateProcessingInstruction(string target, string data)
{
return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data));
}
public IXmlElement CreateElement(string elementName)
{
return new XmlElementWrapper(_document.CreateElement(elementName));
}
public IXmlElement CreateElement(string qualifiedName, string namespaceURI)
{
return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceURI));
}
public IXmlNode CreateAttribute(string name, string value)
{
XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name));
attribute.Value = value;
return attribute;
}
public IXmlNode CreateAttribute(string qualifiedName, string namespaceURI, string value)
{
XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceURI));
attribute.Value = value;
return attribute;
}
public IXmlElement DocumentElement
{
get
{
if (_document.DocumentElement == null)
return null;
return new XmlElementWrapper(_document.DocumentElement);
}
}
}
internal class XmlElementWrapper : XmlNodeWrapper, IXmlElement
{
private XmlElement _element;
public XmlElementWrapper(XmlElement element)
: base(element)
{
_element = element;
}
public void SetAttributeNode(IXmlNode attribute)
{
XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute;
_element.SetAttributeNode((XmlAttribute) xmlAttributeWrapper.WrappedNode);
}
public string GetPrefixOfNamespace(string namespaceURI)
{
return _element.GetPrefixOfNamespace(namespaceURI);
}
}
internal class XmlDeclarationWrapper : XmlNodeWrapper, IXmlDeclaration
{
private XmlDeclaration _declaration;
public XmlDeclarationWrapper(XmlDeclaration declaration)
: base(declaration)
{
_declaration = declaration;
}
public string Version
{
get { return _declaration.Version; }
}
public string Encoding
{
get { return _declaration.Encoding; }
set { _declaration.Encoding = value; }
}
public string Standalone
{
get { return _declaration.Standalone; }
set { _declaration.Standalone = value; }
}
}
internal class XmlNodeWrapper : IXmlNode
{
private readonly XmlNode _node;
public XmlNodeWrapper(XmlNode node)
{
_node = node;
}
public object WrappedNode
{
get { return _node; }
}
public XmlNodeType NodeType
{
get { return _node.NodeType; }
}
public string Name
{
get { return _node.Name; }
}
public string LocalName
{
get { return _node.LocalName; }
}
public IList<IXmlNode> ChildNodes
{
get { return _node.ChildNodes.Cast<XmlNode>().Select(n => WrapNode(n)).ToList(); }
}
private IXmlNode WrapNode(XmlNode node)
{
switch (node.NodeType)
{
case XmlNodeType.Element:
return new XmlElementWrapper((XmlElement) node);
case XmlNodeType.XmlDeclaration:
return new XmlDeclarationWrapper((XmlDeclaration) node);
default:
return new XmlNodeWrapper(node);
}
}
public IList<IXmlNode> Attributes
{
get
{
if (_node.Attributes == null)
return null;
return _node.Attributes.Cast<XmlAttribute>().Select(a => WrapNode(a)).ToList();
}
}
public IXmlNode ParentNode
{
get
{
XmlNode node = (_node is XmlAttribute)
? ((XmlAttribute) _node).OwnerElement
: _node.ParentNode;
if (node == null)
return null;
return WrapNode(node);
}
}
public string Value
{
get { return _node.Value; }
set { _node.Value = value; }
}
public IXmlNode AppendChild(IXmlNode newChild)
{
XmlNodeWrapper xmlNodeWrapper = (XmlNodeWrapper) newChild;
_node.AppendChild(xmlNodeWrapper._node);
return newChild;
}
public string Prefix
{
get { return _node.Prefix; }
}
public string NamespaceURI
{
get { return _node.NamespaceURI; }
}
}
#endif
#endregion
#region Interfaces
internal interface IXmlDocument : IXmlNode
{
IXmlNode CreateComment(string text);
IXmlNode CreateTextNode(string text);
IXmlNode CreateCDataSection(string data);
IXmlNode CreateWhitespace(string text);
IXmlNode CreateSignificantWhitespace(string text);
IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone);
IXmlNode CreateProcessingInstruction(string target, string data);
IXmlElement CreateElement(string elementName);
IXmlElement CreateElement(string qualifiedName, string namespaceURI);
IXmlNode CreateAttribute(string name, string value);
IXmlNode CreateAttribute(string qualifiedName, string namespaceURI, string value);
IXmlElement DocumentElement { get; }
}
internal interface IXmlDeclaration : IXmlNode
{
string Version { get; }
string Encoding { get; set; }
string Standalone { get; set; }
}
internal interface IXmlElement : IXmlNode
{
void SetAttributeNode(IXmlNode attribute);
string GetPrefixOfNamespace(string namespaceURI);
}
internal interface IXmlNode
{
XmlNodeType NodeType { get; }
string LocalName { get; }
IList<IXmlNode> ChildNodes { get; }
IList<IXmlNode> Attributes { get; }
IXmlNode ParentNode { get; }
string Value { get; set; }
IXmlNode AppendChild(IXmlNode newChild);
string NamespaceURI { get; }
object WrappedNode { get; }
}
#endregion
#region XNodeWrappers
#if !NET20
internal class XDeclarationWrapper : XObjectWrapper, IXmlDeclaration
{
internal readonly XDeclaration _declaration;
public XDeclarationWrapper(XDeclaration declaration)
: base(null)
{
_declaration = declaration;
}
public override XmlNodeType NodeType
{
get { return XmlNodeType.XmlDeclaration; }
}
public string Version
{
get { return _declaration.Version; }
}
public string Encoding
{
get { return _declaration.Encoding; }
set { _declaration.Encoding = value; }
}
public string Standalone
{
get { return _declaration.Standalone; }
set { _declaration.Standalone = value; }
}
}
internal class XDocumentWrapper : XContainerWrapper, IXmlDocument
{
private XDocument Document
{
get { return (XDocument)WrappedNode; }
}
public XDocumentWrapper(XDocument document)
: base(document)
{
}
public override IList<IXmlNode> ChildNodes
{
get
{
IList<IXmlNode> childNodes = base.ChildNodes;
if (Document.Declaration != null)
childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration));
return childNodes;
}
}
public IXmlNode CreateComment(string text)
{
return new XObjectWrapper(new XComment(text));
}
public IXmlNode CreateTextNode(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateCDataSection(string data)
{
return new XObjectWrapper(new XCData(data));
}
public IXmlNode CreateWhitespace(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone)
{
return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone));
}
public IXmlNode CreateProcessingInstruction(string target, string data)
{
return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data));
}
public IXmlElement CreateElement(string elementName)
{
return new XElementWrapper(new XElement(elementName));
}
public IXmlElement CreateElement(string qualifiedName, string namespaceURI)
{
string localName = MiscellaneousUtils.GetLocalName(qualifiedName);
return new XElementWrapper(new XElement(XName.Get(localName, namespaceURI)));
}
public IXmlNode CreateAttribute(string name, string value)
{
return new XAttributeWrapper(new XAttribute(name, value));
}
public IXmlNode CreateAttribute(string qualifiedName, string namespaceURI, string value)
{
string localName = MiscellaneousUtils.GetLocalName(qualifiedName);
return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceURI), value));
}
public IXmlElement DocumentElement
{
get
{
if (Document.Root == null)
return null;
return new XElementWrapper(Document.Root);
}
}
public override IXmlNode AppendChild(IXmlNode newChild)
{
XDeclarationWrapper declarationWrapper = newChild as XDeclarationWrapper;
if (declarationWrapper != null)
{
Document.Declaration = declarationWrapper._declaration;
return declarationWrapper;
}
else
{
return base.AppendChild(newChild);
}
}
}
internal class XTextWrapper : XObjectWrapper
{
private XText Text
{
get { return (XText)WrappedNode; }
}
public XTextWrapper(XText text)
: base(text)
{
}
public override string Value
{
get { return Text.Value; }
set { Text.Value = value; }
}
public override IXmlNode ParentNode
{
get
{
if (Text.Parent == null)
return null;
return XContainerWrapper.WrapNode(Text.Parent);
}
}
}
internal class XCommentWrapper : XObjectWrapper
{
private XComment Text
{
get { return (XComment)WrappedNode; }
}
public XCommentWrapper(XComment text)
: base(text)
{
}
public override string Value
{
get { return Text.Value; }
set { Text.Value = value; }
}
public override IXmlNode ParentNode
{
get
{
if (Text.Parent == null)
return null;
return XContainerWrapper.WrapNode(Text.Parent);
}
}
}
internal class XProcessingInstructionWrapper : XObjectWrapper
{
private XProcessingInstruction ProcessingInstruction
{
get { return (XProcessingInstruction)WrappedNode; }
}
public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction)
: base(processingInstruction)
{
}
public override string LocalName
{
get { return ProcessingInstruction.Target; }
}
public override string Value
{
get { return ProcessingInstruction.Data; }
set { ProcessingInstruction.Data = value; }
}
}
internal class XContainerWrapper : XObjectWrapper
{
private XContainer Container
{
get { return (XContainer)WrappedNode; }
}
public XContainerWrapper(XContainer container)
: base(container)
{
}
public override IList<IXmlNode> ChildNodes
{
get { return Container.Nodes().Select(n => WrapNode(n)).ToList(); }
}
public override IXmlNode ParentNode
{
get
{
if (Container.Parent == null)
return null;
return WrapNode(Container.Parent);
}
}
internal static IXmlNode WrapNode(XObject node)
{
if (node is XDocument)
return new XDocumentWrapper((XDocument)node);
else if (node is XElement)
return new XElementWrapper((XElement)node);
else if (node is XContainer)
return new XContainerWrapper((XContainer)node);
else if (node is XProcessingInstruction)
return new XProcessingInstructionWrapper((XProcessingInstruction)node);
else if (node is XText)
return new XTextWrapper((XText)node);
else if (node is XComment)
return new XCommentWrapper((XComment)node);
else if (node is XAttribute)
return new XAttributeWrapper((XAttribute) node);
else
return new XObjectWrapper(node);
}
public override IXmlNode AppendChild(IXmlNode newChild)
{
Container.Add(newChild.WrappedNode);
return newChild;
}
}
internal class XObjectWrapper : IXmlNode
{
private readonly XObject _xmlObject;
public XObjectWrapper(XObject xmlObject)
{
_xmlObject = xmlObject;
}
public object WrappedNode
{
get { return _xmlObject; }
}
public virtual XmlNodeType NodeType
{
get { return _xmlObject.NodeType; }
}
public virtual string LocalName
{
get { return null; }
}
public virtual IList<IXmlNode> ChildNodes
{
get { return new List<IXmlNode>(); }
}
public virtual IList<IXmlNode> Attributes
{
get { return null; }
}
public virtual IXmlNode ParentNode
{
get { return null; }
}
public virtual string Value
{
get { return null; }
set { throw new InvalidOperationException(); }
}
public virtual IXmlNode AppendChild(IXmlNode newChild)
{
throw new InvalidOperationException();
}
public virtual string NamespaceURI
{
get { return null; }
}
}
internal class XAttributeWrapper : XObjectWrapper
{
private XAttribute Attribute
{
get { return (XAttribute)WrappedNode; }
}
public XAttributeWrapper(XAttribute attribute)
: base(attribute)
{
}
public override string Value
{
get { return Attribute.Value; }
set { Attribute.Value = value; }
}
public override string LocalName
{
get { return Attribute.Name.LocalName; }
}
public override string NamespaceURI
{
get { return Attribute.Name.NamespaceName; }
}
public override IXmlNode ParentNode
{
get
{
if (Attribute.Parent == null)
return null;
return XContainerWrapper.WrapNode(Attribute.Parent);
}
}
}
internal class XElementWrapper : XContainerWrapper, IXmlElement
{
private XElement Element
{
get { return (XElement) WrappedNode; }
}
public XElementWrapper(XElement element)
: base(element)
{
}
public void SetAttributeNode(IXmlNode attribute)
{
XObjectWrapper wrapper = (XObjectWrapper)attribute;
Element.Add(wrapper.WrappedNode);
}
public override IList<IXmlNode> Attributes
{
get { return Element.Attributes().Select(a => new XAttributeWrapper(a)).Cast<IXmlNode>().ToList(); }
}
public override string Value
{
get { return Element.Value; }
set { Element.Value = value; }
}
public override string LocalName
{
get { return Element.Name.LocalName; }
}
public override string NamespaceURI
{
get { return Element.Name.NamespaceName; }
}
public string GetPrefixOfNamespace(string namespaceURI)
{
return Element.GetPrefixOfNamespace(namespaceURI);
}
}
#endif
#endregion
/// <summary>
/// Converts XML to and from JSON.
/// </summary>
public class XmlNodeConverter : JsonConverter
{
private const string TextName = "#text";
private const string CommentName = "#comment";
private const string CDataName = "#cdata-section";
private const string WhitespaceName = "#whitespace";
private const string SignificantWhitespaceName = "#significant-whitespace";
private const string DeclarationName = "?xml";
private const string JsonNamespaceUri = "http://james.newtonking.com/projects/json";
/// <summary>
/// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produces multiple root elements.
/// </summary>
/// <value>The name of the deserialize root element.</value>
public string DeserializeRootElementName { get; set; }
/// <summary>
/// Gets or sets a flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </summary>
/// <value><c>true</c> if the array attibute is written to the XML; otherwise, <c>false</c>.</value>
public bool WriteArrayAttribute { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to write the root JSON object.
/// </summary>
/// <value><c>true</c> if the JSON root object is omitted; otherwise, <c>false</c>.</value>
public bool OmitRootObject { get; set; }
#region Writing
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="serializer">The calling serializer.</param>
/// <param name="value">The value.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
IXmlNode node = WrapXml(value);
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
PushParentNamespaces(node, manager);
if (!OmitRootObject)
writer.WriteStartObject();
SerializeNode(writer, node, manager, !OmitRootObject);
if (!OmitRootObject)
writer.WriteEndObject();
}
private IXmlNode WrapXml(object value)
{
#if !NET20
if (value is XObject)
return XContainerWrapper.WrapNode((XObject)value);
#endif
#if !SILVERLIGHT
if (value is XmlNode)
return new XmlNodeWrapper((XmlNode)value);
#endif
throw new ArgumentException("Value must be an XML object.", "value");
}
private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager)
{
List<IXmlNode> parentElements = null;
IXmlNode parent = node;
while ((parent = parent.ParentNode) != null)
{
if (parent.NodeType == XmlNodeType.Element)
{
if (parentElements == null)
parentElements = new List<IXmlNode>();
parentElements.Add(parent);
}
}
if (parentElements != null)
{
parentElements.Reverse();
foreach (IXmlNode parentElement in parentElements)
{
manager.PushScope();
foreach (IXmlNode attribute in parentElement.Attributes)
{
if (attribute.NamespaceURI == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns")
manager.AddNamespace(attribute.LocalName, attribute.Value);
}
}
}
}
private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager)
{
string prefix = (node.NamespaceURI == null || (node.LocalName == "xmlns" && node.NamespaceURI == "http://www.w3.org/2000/xmlns/"))
? null
: manager.LookupPrefix(node.NamespaceURI);
if (!string.IsNullOrEmpty(prefix))
return prefix + ":" + node.LocalName;
else
return node.LocalName;
}
private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager)
{
switch (node.NodeType)
{
case XmlNodeType.Attribute:
if (node.NamespaceURI == JsonNamespaceUri)
return "$" + node.LocalName;
else
return "@" + ResolveFullName(node, manager);
case XmlNodeType.CDATA:
return CDataName;
case XmlNodeType.Comment:
return CommentName;
case XmlNodeType.Element:
return ResolveFullName(node, manager);
case XmlNodeType.ProcessingInstruction:
return "?" + ResolveFullName(node, manager);
case XmlNodeType.XmlDeclaration:
return DeclarationName;
case XmlNodeType.SignificantWhitespace:
return SignificantWhitespaceName;
case XmlNodeType.Text:
return TextName;
case XmlNodeType.Whitespace:
return WhitespaceName;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType);
}
}
private bool IsArray(IXmlNode node)
{
IXmlNode jsonArrayAttribute = (node.Attributes != null)
? node.Attributes.SingleOrDefault(a => a.LocalName == "Array" && a.NamespaceURI == JsonNamespaceUri)
: null;
return (jsonArrayAttribute != null && XmlConvert.ToBoolean(jsonArrayAttribute.Value));
}
private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName)
{
// group nodes together by name
Dictionary<string, List<IXmlNode>> nodesGroupedByName = new Dictionary<string, List<IXmlNode>>();
for (int i = 0; i < node.ChildNodes.Count; i++)
{
IXmlNode childNode = node.ChildNodes[i];
string nodeName = GetPropertyName(childNode, manager);
List<IXmlNode> nodes;
if (!nodesGroupedByName.TryGetValue(nodeName, out nodes))
{
nodes = new List<IXmlNode>();
nodesGroupedByName.Add(nodeName, nodes);
}
nodes.Add(childNode);
}
// loop through grouped nodes. write single name instances as normal,
// write multiple names together in an array
foreach (KeyValuePair<string, List<IXmlNode>> nodeNameGroup in nodesGroupedByName)
{
List<IXmlNode> groupedNodes = nodeNameGroup.Value;
bool writeArray;
if (groupedNodes.Count == 1)
{
writeArray = IsArray(groupedNodes[0]);
}
else
{
writeArray = true;
}
if (!writeArray)
{
SerializeNode(writer, groupedNodes[0], manager, writePropertyName);
}
else
{
string elementNames = nodeNameGroup.Key;
if (writePropertyName)
writer.WritePropertyName(elementNames);
writer.WriteStartArray();
for (int i = 0; i < groupedNodes.Count; i++)
{
SerializeNode(writer, groupedNodes[i], manager, false);
}
writer.WriteEndArray();
}
}
}
private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName)
{
switch (node.NodeType)
{
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
SerializeGroupedNodes(writer, node, manager, writePropertyName);
break;
case XmlNodeType.Element:
if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0)
{
SerializeGroupedNodes(writer, node, manager, false);
}
else
{
foreach (IXmlNode attribute in node.Attributes)
{
if (attribute.NamespaceURI == "http://www.w3.org/2000/xmlns/")
{
string prefix = (attribute.LocalName != "xmlns")
? attribute.LocalName
: string.Empty;
manager.AddNamespace(prefix, attribute.Value);
}
}
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node, manager));
if (ValueAttributes(node.Attributes).Count() == 0 && node.ChildNodes.Count == 1
&& node.ChildNodes[0].NodeType == XmlNodeType.Text)
{
// write elements with a single text child as a name value pair
writer.WriteValue(node.ChildNodes[0].Value);
}
else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes))
{
// empty element
writer.WriteNull();
}
else
{
writer.WriteStartObject();
for (int i = 0; i < node.Attributes.Count; i++)
{
SerializeNode(writer, node.Attributes[i], manager, true);
}
SerializeGroupedNodes(writer, node, manager, true);
writer.WriteEndObject();
}
}
break;
case XmlNodeType.Comment:
if (writePropertyName)
writer.WriteComment(node.Value);
break;
case XmlNodeType.Attribute:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if (node.NamespaceURI == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri)
return;
if (node.NamespaceURI == JsonNamespaceUri)
{
if (node.LocalName == "Array")
return;
}
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteValue(node.Value);
break;
case XmlNodeType.XmlDeclaration:
IXmlDeclaration declaration = (IXmlDeclaration)node;
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteStartObject();
if (!string.IsNullOrEmpty(declaration.Version))
{
writer.WritePropertyName("@version");
writer.WriteValue(declaration.Version);
}
if (!string.IsNullOrEmpty(declaration.Encoding))
{
writer.WritePropertyName("@encoding");
writer.WriteValue(declaration.Encoding);
}
if (!string.IsNullOrEmpty(declaration.Standalone))
{
writer.WritePropertyName("@standalone");
writer.WriteValue(declaration.Standalone);
}
writer.WriteEndObject();
break;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType);
}
}
#endregion
#region Reading
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
IXmlDocument document = null;
IXmlNode rootNode = null;
#if !NET20
if (typeof(XObject).IsAssignableFrom(objectType))
{
if (objectType != typeof (XDocument) && objectType != typeof (XElement))
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement.");
XDocument d = new XDocument();
document = new XDocumentWrapper(d);
rootNode = document;
}
#endif
#if !SILVERLIGHT
if (typeof(XmlNode).IsAssignableFrom(objectType))
{
if (objectType != typeof (XmlDocument))
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments");
XmlDocument d = new XmlDocument();
document = new XmlDocumentWrapper(d);
rootNode = document;
}
#endif
if (document == null || rootNode == null)
throw new JsonSerializationException("Unexpected type when converting XML: " + objectType);
if (reader.TokenType != JsonToken.StartObject)
throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object.");
if (!string.IsNullOrEmpty(DeserializeRootElementName))
{
//rootNode = document.CreateElement(DeserializeRootElementName);
//document.AppendChild(rootNode);
ReadElement(reader, document, rootNode, DeserializeRootElementName, manager);
}
else
{
reader.Read();
DeserializeNode(reader, document, manager, rootNode);
}
#if !NET20
if (objectType == typeof(XElement))
{
XElement element = (XElement)document.DocumentElement.WrappedNode;
element.Remove();
return element;
}
#endif
return document.WrappedNode;
}
private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, string propertyName, IXmlNode currentNode)
{
switch (propertyName)
{
case TextName:
currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString()));
break;
case CDataName:
currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString()));
break;
case WhitespaceName:
currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString()));
break;
case SignificantWhitespaceName:
currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString()));
break;
default:
// processing instructions and the xml declaration start with ?
if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?')
{
CreateInstruction(reader, document, currentNode, propertyName);
}
else
{
if (reader.TokenType == JsonToken.StartArray)
{
// handle nested arrays
ReadArrayElements(reader, document, propertyName, currentNode, manager);
return;
}
// have to wait until attributes have been parsed before creating element
// attributes may contain namespace info used by the element
ReadElement(reader, document, currentNode, propertyName, manager);
}
break;
}
}
private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager)
{
if (string.IsNullOrEmpty(propertyName))
throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML.");
Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager);
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager);
currentNode.AppendChild(element);
// add attributes to newly created element
foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
{
string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value)
: document.CreateAttribute(nameValue.Key, nameValue.Value);
element.SetAttributeNode(attribute);
}
if (reader.TokenType == JsonToken.String
|| reader.TokenType == JsonToken.Integer
|| reader.TokenType == JsonToken.Float
|| reader.TokenType == JsonToken.Boolean
|| reader.TokenType == JsonToken.Date)
{
element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader)));
}
else if (reader.TokenType == JsonToken.Null)
{
// empty element. do nothing
}
else
{
// finished element will have no children to deserialize
if (reader.TokenType != JsonToken.EndObject)
{
manager.PushScope();
DeserializeNode(reader, document, manager, element);
manager.PopScope();
}
}
}
private string ConvertTokenToXmlValue(JsonReader reader)
{
if (reader.TokenType == JsonToken.String)
{
return reader.Value.ToString();
}
else if (reader.TokenType == JsonToken.Integer)
{
return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Float)
{
return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Boolean)
{
return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Date)
{
DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture);
return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind));
}
else if (reader.TokenType == JsonToken.Null)
{
return null;
}
else
{
throw new Exception("Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager)
{
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager);
currentNode.AppendChild(nestedArrayElement);
int count = 0;
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, nestedArrayElement);
count++;
}
if (WriteArrayAttribute)
{
AddJsonArrayAttribute(nestedArrayElement, document);
}
if (count == 1 && WriteArrayAttribute)
{
IXmlElement arrayElement = nestedArrayElement.ChildNodes.CastValid<IXmlElement>().Single(n => n.LocalName == propertyName);
AddJsonArrayAttribute(arrayElement, document);
}
}
private void AddJsonArrayAttribute(IXmlElement element, IXmlDocument document)
{
element.SetAttributeNode(document.CreateAttribute("json:Array", JsonNamespaceUri, "true"));
#if !NET20
// linq to xml doesn't automatically include prefixes via the namespace manager
if (element is XElementWrapper)
{
if (element.GetPrefixOfNamespace(JsonNamespaceUri) == null)
{
element.SetAttributeNode(document.CreateAttribute("xmlns:json", "http://www.w3.org/2000/xmlns/", JsonNamespaceUri));
}
}
#endif
}
private Dictionary<string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager)
{
Dictionary<string, string> attributeNameValues = new Dictionary<string, string>();
bool finishedAttributes = false;
bool finishedElement = false;
// a string token means the element only has a single text child
if (reader.TokenType != JsonToken.String
&& reader.TokenType != JsonToken.Null
&& reader.TokenType != JsonToken.Boolean
&& reader.TokenType != JsonToken.Integer
&& reader.TokenType != JsonToken.Float
&& reader.TokenType != JsonToken.Date
&& reader.TokenType != JsonToken.StartConstructor)
{
// read properties until first non-attribute is encountered
while (!finishedAttributes && !finishedElement && reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string attributeName = reader.Value.ToString();
string attributeValue;
if (!string.IsNullOrEmpty(attributeName))
{
char firstChar = attributeName[0];
switch (firstChar)
{
case '@':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = ConvertTokenToXmlValue(reader);
attributeNameValues.Add(attributeName, attributeValue);
string namespacePrefix;
if (IsNamespaceAttribute(attributeName, out namespacePrefix))
{
manager.AddNamespace(namespacePrefix, attributeValue);
}
break;
case '$':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = reader.Value.ToString();
// check that JsonNamespaceUri is in scope
// if it isn't then add it to document and namespace manager
string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri);
if (jsonPrefix == null)
{
// ensure that the prefix used is free
int? i = null;
while (manager.LookupNamespace("json" + i) != null)
{
i = i.GetValueOrDefault() + 1;
}
jsonPrefix = "json" + i;
attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri);
manager.AddNamespace(jsonPrefix, JsonNamespaceUri);
}
attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue);
break;
default:
finishedAttributes = true;
break;
}
}
else
{
finishedAttributes = true;
}
break;
case JsonToken.EndObject:
finishedElement = true;
break;
default:
throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType);
}
}
}
return attributeNameValues;
}
private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName)
{
if (propertyName == DeclarationName)
{
string version = null;
string encoding = null;
string standalone = null;
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
switch (reader.Value.ToString())
{
case "@version":
reader.Read();
version = reader.Value.ToString();
break;
case "@encoding":
reader.Read();
encoding = reader.Value.ToString();
break;
case "@standalone":
reader.Read();
standalone = reader.Value.ToString();
break;
default:
throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value);
}
}
IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone);
currentNode.AppendChild(declaration);
}
else
{
IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString());
currentNode.AppendChild(instruction);
}
}
private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager)
{
return (!string.IsNullOrEmpty(elementPrefix))
? document.CreateElement(elementName, manager.LookupNamespace(elementPrefix))
: document.CreateElement(elementName);
}
private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode)
{
do
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null)
throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.");
string propertyName = reader.Value.ToString();
reader.Read();
if (reader.TokenType == JsonToken.StartArray)
{
int count = 0;
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
count++;
}
if (count == 1 && WriteArrayAttribute)
{
IXmlElement arrayElement = currentNode.ChildNodes.CastValid<IXmlElement>().Single(n => n.LocalName == propertyName);
AddJsonArrayAttribute(arrayElement, document);
}
}
else
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
}
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
while (reader.Read() && reader.TokenType != JsonToken.EndConstructor)
{
DeserializeValue(reader, document, manager, constructorName, currentNode);
}
break;
case JsonToken.Comment:
currentNode.AppendChild(document.CreateComment((string)reader.Value));
break;
case JsonToken.EndObject:
case JsonToken.EndArray:
return;
default:
throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType);
}
} while (reader.TokenType == JsonToken.PropertyName || reader.Read());
// don't read if current token is a property. token was already read when parsing element attributes
}
/// <summary>
/// Checks if the attributeName is a namespace attribute.
/// </summary>
/// <param name="attributeName">Attribute name to test.</param>
/// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param>
/// <returns>True if attribute name is for a namespace attribute, otherwise false.</returns>
private bool IsNamespaceAttribute(string attributeName, out string prefix)
{
if (attributeName.StartsWith("xmlns", StringComparison.Ordinal))
{
if (attributeName.Length == 5)
{
prefix = string.Empty;
return true;
}
else if (attributeName[5] == ':')
{
prefix = attributeName.Substring(6, attributeName.Length - 6);
return true;
}
}
prefix = null;
return false;
}
private IEnumerable<IXmlNode> ValueAttributes(IEnumerable<IXmlNode> c)
{
return c.Where(a => a.NamespaceURI != JsonNamespaceUri);
}
#endregion
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
#if !NET20
if (typeof(XObject).IsAssignableFrom(valueType))
return true;
#endif
#if !SILVERLIGHT
if (typeof(XmlNode).IsAssignableFrom(valueType))
return true;
#endif
return false;
}
}
}
#endif
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Parameters;
namespace NBitcoin.BouncyCastle.Crypto.Engines
{
/**
* Serpent is a 128-bit 32-round block cipher with variable key lengths,
* including 128, 192 and 256 bit keys conjectured to be at least as
* secure as three-key triple-DES.
* <p>
* Serpent was designed by Ross Anderson, Eli Biham and Lars Knudsen as a
* candidate algorithm for the NIST AES Quest.>
* </p>
* <p>
* For full details see the <a href="http://www.cl.cam.ac.uk/~rja14/serpent.html">The Serpent home page</a>
* </p>
*/
public class SerpentEngine
: IBlockCipher
{
private const int BLOCK_SIZE = 16;
static readonly int ROUNDS = 32;
static readonly int PHI = unchecked((int)0x9E3779B9); // (Sqrt(5) - 1) * 2**31
private bool encrypting;
private int[] wKey;
private int X0, X1, X2, X3; // registers
/**
* initialise a Serpent cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException("invalid parameter passed to Serpent init - " + parameters.GetType().ToString());
this.encrypting = forEncryption;
this.wKey = MakeWorkingKey(((KeyParameter)parameters).GetKey());
}
public string AlgorithmName
{
get { return "Serpent"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return BLOCK_SIZE;
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (wKey == null)
throw new InvalidOperationException("Serpent not initialised");
if ((inOff + BLOCK_SIZE) > input.Length)
throw new DataLengthException("input buffer too short");
if ((outOff + BLOCK_SIZE) > output.Length)
throw new DataLengthException("output buffer too short");
if (encrypting)
{
EncryptBlock(input, inOff, output, outOff);
}
else
{
DecryptBlock(input, inOff, output, outOff);
}
return BLOCK_SIZE;
}
public void Reset()
{
}
/**
* Expand a user-supplied key material into a session key.
*
* @param key The user-key bytes (multiples of 4) to use.
* @exception ArgumentException
*/
private int[] MakeWorkingKey(
byte[] key)
{
//
// pad key to 256 bits
//
int[] kPad = new int[16];
int off = 0;
int length = 0;
for (off = key.Length - 4; off > 0; off -= 4)
{
kPad[length++] = BytesToWord(key, off);
}
if (off == 0)
{
kPad[length++] = BytesToWord(key, 0);
if (length < 8)
{
kPad[length] = 1;
}
}
else
{
throw new ArgumentException("key must be a multiple of 4 bytes");
}
//
// expand the padded key up to 33 x 128 bits of key material
//
int amount = (ROUNDS + 1) * 4;
int[] w = new int[amount];
//
// compute w0 to w7 from w-8 to w-1
//
for (int i = 8; i < 16; i++)
{
kPad[i] = RotateLeft(kPad[i - 8] ^ kPad[i - 5] ^ kPad[i - 3] ^ kPad[i - 1] ^ PHI ^ (i - 8), 11);
}
Array.Copy(kPad, 8, w, 0, 8);
//
// compute w8 to w136
//
for (int i = 8; i < amount; i++)
{
w[i] = RotateLeft(w[i - 8] ^ w[i - 5] ^ w[i - 3] ^ w[i - 1] ^ PHI ^ i, 11);
}
//
// create the working keys by processing w with the Sbox and IP
//
Sb3(w[0], w[1], w[2], w[3]);
w[0] = X0; w[1] = X1; w[2] = X2; w[3] = X3;
Sb2(w[4], w[5], w[6], w[7]);
w[4] = X0; w[5] = X1; w[6] = X2; w[7] = X3;
Sb1(w[8], w[9], w[10], w[11]);
w[8] = X0; w[9] = X1; w[10] = X2; w[11] = X3;
Sb0(w[12], w[13], w[14], w[15]);
w[12] = X0; w[13] = X1; w[14] = X2; w[15] = X3;
Sb7(w[16], w[17], w[18], w[19]);
w[16] = X0; w[17] = X1; w[18] = X2; w[19] = X3;
Sb6(w[20], w[21], w[22], w[23]);
w[20] = X0; w[21] = X1; w[22] = X2; w[23] = X3;
Sb5(w[24], w[25], w[26], w[27]);
w[24] = X0; w[25] = X1; w[26] = X2; w[27] = X3;
Sb4(w[28], w[29], w[30], w[31]);
w[28] = X0; w[29] = X1; w[30] = X2; w[31] = X3;
Sb3(w[32], w[33], w[34], w[35]);
w[32] = X0; w[33] = X1; w[34] = X2; w[35] = X3;
Sb2(w[36], w[37], w[38], w[39]);
w[36] = X0; w[37] = X1; w[38] = X2; w[39] = X3;
Sb1(w[40], w[41], w[42], w[43]);
w[40] = X0; w[41] = X1; w[42] = X2; w[43] = X3;
Sb0(w[44], w[45], w[46], w[47]);
w[44] = X0; w[45] = X1; w[46] = X2; w[47] = X3;
Sb7(w[48], w[49], w[50], w[51]);
w[48] = X0; w[49] = X1; w[50] = X2; w[51] = X3;
Sb6(w[52], w[53], w[54], w[55]);
w[52] = X0; w[53] = X1; w[54] = X2; w[55] = X3;
Sb5(w[56], w[57], w[58], w[59]);
w[56] = X0; w[57] = X1; w[58] = X2; w[59] = X3;
Sb4(w[60], w[61], w[62], w[63]);
w[60] = X0; w[61] = X1; w[62] = X2; w[63] = X3;
Sb3(w[64], w[65], w[66], w[67]);
w[64] = X0; w[65] = X1; w[66] = X2; w[67] = X3;
Sb2(w[68], w[69], w[70], w[71]);
w[68] = X0; w[69] = X1; w[70] = X2; w[71] = X3;
Sb1(w[72], w[73], w[74], w[75]);
w[72] = X0; w[73] = X1; w[74] = X2; w[75] = X3;
Sb0(w[76], w[77], w[78], w[79]);
w[76] = X0; w[77] = X1; w[78] = X2; w[79] = X3;
Sb7(w[80], w[81], w[82], w[83]);
w[80] = X0; w[81] = X1; w[82] = X2; w[83] = X3;
Sb6(w[84], w[85], w[86], w[87]);
w[84] = X0; w[85] = X1; w[86] = X2; w[87] = X3;
Sb5(w[88], w[89], w[90], w[91]);
w[88] = X0; w[89] = X1; w[90] = X2; w[91] = X3;
Sb4(w[92], w[93], w[94], w[95]);
w[92] = X0; w[93] = X1; w[94] = X2; w[95] = X3;
Sb3(w[96], w[97], w[98], w[99]);
w[96] = X0; w[97] = X1; w[98] = X2; w[99] = X3;
Sb2(w[100], w[101], w[102], w[103]);
w[100] = X0; w[101] = X1; w[102] = X2; w[103] = X3;
Sb1(w[104], w[105], w[106], w[107]);
w[104] = X0; w[105] = X1; w[106] = X2; w[107] = X3;
Sb0(w[108], w[109], w[110], w[111]);
w[108] = X0; w[109] = X1; w[110] = X2; w[111] = X3;
Sb7(w[112], w[113], w[114], w[115]);
w[112] = X0; w[113] = X1; w[114] = X2; w[115] = X3;
Sb6(w[116], w[117], w[118], w[119]);
w[116] = X0; w[117] = X1; w[118] = X2; w[119] = X3;
Sb5(w[120], w[121], w[122], w[123]);
w[120] = X0; w[121] = X1; w[122] = X2; w[123] = X3;
Sb4(w[124], w[125], w[126], w[127]);
w[124] = X0; w[125] = X1; w[126] = X2; w[127] = X3;
Sb3(w[128], w[129], w[130], w[131]);
w[128] = X0; w[129] = X1; w[130] = X2; w[131] = X3;
return w;
}
private int RotateLeft(
int x,
int bits)
{
return ((x << bits) | (int) ((uint)x >> (32 - bits)));
}
private int RotateRight(
int x,
int bits)
{
return ( (int)((uint)x >> bits) | (x << (32 - bits)));
}
private int BytesToWord(
byte[] src,
int srcOff)
{
return (((src[srcOff] & 0xff) << 24) | ((src[srcOff + 1] & 0xff) << 16) |
((src[srcOff + 2] & 0xff) << 8) | ((src[srcOff + 3] & 0xff)));
}
private void WordToBytes(
int word,
byte[] dst,
int dstOff)
{
dst[dstOff + 3] = (byte)(word);
dst[dstOff + 2] = (byte)((uint)word >> 8);
dst[dstOff + 1] = (byte)((uint)word >> 16);
dst[dstOff] = (byte)((uint)word >> 24);
}
/**
* Encrypt one block of plaintext.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
*/
private void EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
X3 = BytesToWord(input, inOff);
X2 = BytesToWord(input, inOff + 4);
X1 = BytesToWord(input, inOff + 8);
X0 = BytesToWord(input, inOff + 12);
Sb0(wKey[0] ^ X0, wKey[1] ^ X1, wKey[2] ^ X2, wKey[3] ^ X3); LT();
Sb1(wKey[4] ^ X0, wKey[5] ^ X1, wKey[6] ^ X2, wKey[7] ^ X3); LT();
Sb2(wKey[8] ^ X0, wKey[9] ^ X1, wKey[10] ^ X2, wKey[11] ^ X3); LT();
Sb3(wKey[12] ^ X0, wKey[13] ^ X1, wKey[14] ^ X2, wKey[15] ^ X3); LT();
Sb4(wKey[16] ^ X0, wKey[17] ^ X1, wKey[18] ^ X2, wKey[19] ^ X3); LT();
Sb5(wKey[20] ^ X0, wKey[21] ^ X1, wKey[22] ^ X2, wKey[23] ^ X3); LT();
Sb6(wKey[24] ^ X0, wKey[25] ^ X1, wKey[26] ^ X2, wKey[27] ^ X3); LT();
Sb7(wKey[28] ^ X0, wKey[29] ^ X1, wKey[30] ^ X2, wKey[31] ^ X3); LT();
Sb0(wKey[32] ^ X0, wKey[33] ^ X1, wKey[34] ^ X2, wKey[35] ^ X3); LT();
Sb1(wKey[36] ^ X0, wKey[37] ^ X1, wKey[38] ^ X2, wKey[39] ^ X3); LT();
Sb2(wKey[40] ^ X0, wKey[41] ^ X1, wKey[42] ^ X2, wKey[43] ^ X3); LT();
Sb3(wKey[44] ^ X0, wKey[45] ^ X1, wKey[46] ^ X2, wKey[47] ^ X3); LT();
Sb4(wKey[48] ^ X0, wKey[49] ^ X1, wKey[50] ^ X2, wKey[51] ^ X3); LT();
Sb5(wKey[52] ^ X0, wKey[53] ^ X1, wKey[54] ^ X2, wKey[55] ^ X3); LT();
Sb6(wKey[56] ^ X0, wKey[57] ^ X1, wKey[58] ^ X2, wKey[59] ^ X3); LT();
Sb7(wKey[60] ^ X0, wKey[61] ^ X1, wKey[62] ^ X2, wKey[63] ^ X3); LT();
Sb0(wKey[64] ^ X0, wKey[65] ^ X1, wKey[66] ^ X2, wKey[67] ^ X3); LT();
Sb1(wKey[68] ^ X0, wKey[69] ^ X1, wKey[70] ^ X2, wKey[71] ^ X3); LT();
Sb2(wKey[72] ^ X0, wKey[73] ^ X1, wKey[74] ^ X2, wKey[75] ^ X3); LT();
Sb3(wKey[76] ^ X0, wKey[77] ^ X1, wKey[78] ^ X2, wKey[79] ^ X3); LT();
Sb4(wKey[80] ^ X0, wKey[81] ^ X1, wKey[82] ^ X2, wKey[83] ^ X3); LT();
Sb5(wKey[84] ^ X0, wKey[85] ^ X1, wKey[86] ^ X2, wKey[87] ^ X3); LT();
Sb6(wKey[88] ^ X0, wKey[89] ^ X1, wKey[90] ^ X2, wKey[91] ^ X3); LT();
Sb7(wKey[92] ^ X0, wKey[93] ^ X1, wKey[94] ^ X2, wKey[95] ^ X3); LT();
Sb0(wKey[96] ^ X0, wKey[97] ^ X1, wKey[98] ^ X2, wKey[99] ^ X3); LT();
Sb1(wKey[100] ^ X0, wKey[101] ^ X1, wKey[102] ^ X2, wKey[103] ^ X3); LT();
Sb2(wKey[104] ^ X0, wKey[105] ^ X1, wKey[106] ^ X2, wKey[107] ^ X3); LT();
Sb3(wKey[108] ^ X0, wKey[109] ^ X1, wKey[110] ^ X2, wKey[111] ^ X3); LT();
Sb4(wKey[112] ^ X0, wKey[113] ^ X1, wKey[114] ^ X2, wKey[115] ^ X3); LT();
Sb5(wKey[116] ^ X0, wKey[117] ^ X1, wKey[118] ^ X2, wKey[119] ^ X3); LT();
Sb6(wKey[120] ^ X0, wKey[121] ^ X1, wKey[122] ^ X2, wKey[123] ^ X3); LT();
Sb7(wKey[124] ^ X0, wKey[125] ^ X1, wKey[126] ^ X2, wKey[127] ^ X3);
WordToBytes(wKey[131] ^ X3, outBytes, outOff);
WordToBytes(wKey[130] ^ X2, outBytes, outOff + 4);
WordToBytes(wKey[129] ^ X1, outBytes, outOff + 8);
WordToBytes(wKey[128] ^ X0, outBytes, outOff + 12);
}
/**
* Decrypt one block of ciphertext.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
*/
private void DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
X3 = wKey[131] ^ BytesToWord(input, inOff);
X2 = wKey[130] ^ BytesToWord(input, inOff + 4);
X1 = wKey[129] ^ BytesToWord(input, inOff + 8);
X0 = wKey[128] ^ BytesToWord(input, inOff + 12);
Ib7(X0, X1, X2, X3);
X0 ^= wKey[124]; X1 ^= wKey[125]; X2 ^= wKey[126]; X3 ^= wKey[127];
InverseLT(); Ib6(X0, X1, X2, X3);
X0 ^= wKey[120]; X1 ^= wKey[121]; X2 ^= wKey[122]; X3 ^= wKey[123];
InverseLT(); Ib5(X0, X1, X2, X3);
X0 ^= wKey[116]; X1 ^= wKey[117]; X2 ^= wKey[118]; X3 ^= wKey[119];
InverseLT(); Ib4(X0, X1, X2, X3);
X0 ^= wKey[112]; X1 ^= wKey[113]; X2 ^= wKey[114]; X3 ^= wKey[115];
InverseLT(); Ib3(X0, X1, X2, X3);
X0 ^= wKey[108]; X1 ^= wKey[109]; X2 ^= wKey[110]; X3 ^= wKey[111];
InverseLT(); Ib2(X0, X1, X2, X3);
X0 ^= wKey[104]; X1 ^= wKey[105]; X2 ^= wKey[106]; X3 ^= wKey[107];
InverseLT(); Ib1(X0, X1, X2, X3);
X0 ^= wKey[100]; X1 ^= wKey[101]; X2 ^= wKey[102]; X3 ^= wKey[103];
InverseLT(); Ib0(X0, X1, X2, X3);
X0 ^= wKey[96]; X1 ^= wKey[97]; X2 ^= wKey[98]; X3 ^= wKey[99];
InverseLT(); Ib7(X0, X1, X2, X3);
X0 ^= wKey[92]; X1 ^= wKey[93]; X2 ^= wKey[94]; X3 ^= wKey[95];
InverseLT(); Ib6(X0, X1, X2, X3);
X0 ^= wKey[88]; X1 ^= wKey[89]; X2 ^= wKey[90]; X3 ^= wKey[91];
InverseLT(); Ib5(X0, X1, X2, X3);
X0 ^= wKey[84]; X1 ^= wKey[85]; X2 ^= wKey[86]; X3 ^= wKey[87];
InverseLT(); Ib4(X0, X1, X2, X3);
X0 ^= wKey[80]; X1 ^= wKey[81]; X2 ^= wKey[82]; X3 ^= wKey[83];
InverseLT(); Ib3(X0, X1, X2, X3);
X0 ^= wKey[76]; X1 ^= wKey[77]; X2 ^= wKey[78]; X3 ^= wKey[79];
InverseLT(); Ib2(X0, X1, X2, X3);
X0 ^= wKey[72]; X1 ^= wKey[73]; X2 ^= wKey[74]; X3 ^= wKey[75];
InverseLT(); Ib1(X0, X1, X2, X3);
X0 ^= wKey[68]; X1 ^= wKey[69]; X2 ^= wKey[70]; X3 ^= wKey[71];
InverseLT(); Ib0(X0, X1, X2, X3);
X0 ^= wKey[64]; X1 ^= wKey[65]; X2 ^= wKey[66]; X3 ^= wKey[67];
InverseLT(); Ib7(X0, X1, X2, X3);
X0 ^= wKey[60]; X1 ^= wKey[61]; X2 ^= wKey[62]; X3 ^= wKey[63];
InverseLT(); Ib6(X0, X1, X2, X3);
X0 ^= wKey[56]; X1 ^= wKey[57]; X2 ^= wKey[58]; X3 ^= wKey[59];
InverseLT(); Ib5(X0, X1, X2, X3);
X0 ^= wKey[52]; X1 ^= wKey[53]; X2 ^= wKey[54]; X3 ^= wKey[55];
InverseLT(); Ib4(X0, X1, X2, X3);
X0 ^= wKey[48]; X1 ^= wKey[49]; X2 ^= wKey[50]; X3 ^= wKey[51];
InverseLT(); Ib3(X0, X1, X2, X3);
X0 ^= wKey[44]; X1 ^= wKey[45]; X2 ^= wKey[46]; X3 ^= wKey[47];
InverseLT(); Ib2(X0, X1, X2, X3);
X0 ^= wKey[40]; X1 ^= wKey[41]; X2 ^= wKey[42]; X3 ^= wKey[43];
InverseLT(); Ib1(X0, X1, X2, X3);
X0 ^= wKey[36]; X1 ^= wKey[37]; X2 ^= wKey[38]; X3 ^= wKey[39];
InverseLT(); Ib0(X0, X1, X2, X3);
X0 ^= wKey[32]; X1 ^= wKey[33]; X2 ^= wKey[34]; X3 ^= wKey[35];
InverseLT(); Ib7(X0, X1, X2, X3);
X0 ^= wKey[28]; X1 ^= wKey[29]; X2 ^= wKey[30]; X3 ^= wKey[31];
InverseLT(); Ib6(X0, X1, X2, X3);
X0 ^= wKey[24]; X1 ^= wKey[25]; X2 ^= wKey[26]; X3 ^= wKey[27];
InverseLT(); Ib5(X0, X1, X2, X3);
X0 ^= wKey[20]; X1 ^= wKey[21]; X2 ^= wKey[22]; X3 ^= wKey[23];
InverseLT(); Ib4(X0, X1, X2, X3);
X0 ^= wKey[16]; X1 ^= wKey[17]; X2 ^= wKey[18]; X3 ^= wKey[19];
InverseLT(); Ib3(X0, X1, X2, X3);
X0 ^= wKey[12]; X1 ^= wKey[13]; X2 ^= wKey[14]; X3 ^= wKey[15];
InverseLT(); Ib2(X0, X1, X2, X3);
X0 ^= wKey[8]; X1 ^= wKey[9]; X2 ^= wKey[10]; X3 ^= wKey[11];
InverseLT(); Ib1(X0, X1, X2, X3);
X0 ^= wKey[4]; X1 ^= wKey[5]; X2 ^= wKey[6]; X3 ^= wKey[7];
InverseLT(); Ib0(X0, X1, X2, X3);
WordToBytes(X3 ^ wKey[3], outBytes, outOff);
WordToBytes(X2 ^ wKey[2], outBytes, outOff + 4);
WordToBytes(X1 ^ wKey[1], outBytes, outOff + 8);
WordToBytes(X0 ^ wKey[0], outBytes, outOff + 12);
}
/*
* The sboxes below are based on the work of Brian Gladman and
* Sam Simpson, whose original notice appears below.
* <p>
* For further details see:
* http://fp.gladman.plus.com/cryptography_technology/serpent/
* </p>
*/
/* Partially optimised Serpent S Box bool functions derived */
/* using a recursive descent analyser but without a full search */
/* of all subtrees. This set of S boxes is the result of work */
/* by Sam Simpson and Brian Gladman using the spare time on a */
/* cluster of high capacity servers to search for S boxes with */
/* this customised search engine. There are now an average of */
/* 15.375 terms per S box. */
/* */
/* Copyright: Dr B. R Gladman (gladman@seven77.demon.co.uk) */
/* and Sam Simpson (s.simpson@mia.co.uk) */
/* 17th December 1998 */
/* */
/* We hereby give permission for information in this file to be */
/* used freely subject only to acknowledgement of its origin. */
/**
* S0 - { 3, 8,15, 1,10, 6, 5,11,14,13, 4, 2, 7, 0, 9,12 } - 15 terms.
*/
private void Sb0(int a, int b, int c, int d)
{
int t1 = a ^ d;
int t3 = c ^ t1;
int t4 = b ^ t3;
X3 = (a & d) ^ t4;
int t7 = a ^ (b & t1);
X2 = t4 ^ (c | t7);
int t12 = X3 & (t3 ^ t7);
X1 = (~t3) ^ t12;
X0 = t12 ^ (~t7);
}
/**
* InvSO - {13, 3,11, 0,10, 6, 5,12, 1,14, 4, 7,15, 9, 8, 2 } - 15 terms.
*/
private void Ib0(int a, int b, int c, int d)
{
int t1 = ~a;
int t2 = a ^ b;
int t4 = d ^ (t1 | t2);
int t5 = c ^ t4;
X2 = t2 ^ t5;
int t8 = t1 ^ (d & t2);
X1 = t4 ^ (X2 & t8);
X3 = (a & t4) ^ (t5 | X1);
X0 = X3 ^ (t5 ^ t8);
}
/**
* S1 - {15,12, 2, 7, 9, 0, 5,10, 1,11,14, 8, 6,13, 3, 4 } - 14 terms.
*/
private void Sb1(int a, int b, int c, int d)
{
int t2 = b ^ (~a);
int t5 = c ^ (a | t2);
X2 = d ^ t5;
int t7 = b ^ (d | t2);
int t8 = t2 ^ X2;
X3 = t8 ^ (t5 & t7);
int t11 = t5 ^ t7;
X1 = X3 ^ t11;
X0 = t5 ^ (t8 & t11);
}
/**
* InvS1 - { 5, 8, 2,14,15, 6,12, 3,11, 4, 7, 9, 1,13,10, 0 } - 14 steps.
*/
private void Ib1(int a, int b, int c, int d)
{
int t1 = b ^ d;
int t3 = a ^ (b & t1);
int t4 = t1 ^ t3;
X3 = c ^ t4;
int t7 = b ^ (t1 & t3);
int t8 = X3 | t7;
X1 = t3 ^ t8;
int t10 = ~X1;
int t11 = X3 ^ t7;
X0 = t10 ^ t11;
X2 = t4 ^ (t10 | t11);
}
/**
* S2 - { 8, 6, 7, 9, 3,12,10,15,13, 1,14, 4, 0,11, 5, 2 } - 16 terms.
*/
private void Sb2(int a, int b, int c, int d)
{
int t1 = ~a;
int t2 = b ^ d;
int t3 = c & t1;
X0 = t2 ^ t3;
int t5 = c ^ t1;
int t6 = c ^ X0;
int t7 = b & t6;
X3 = t5 ^ t7;
X2 = a ^ ((d | t7) & (X0 | t5));
X1 = (t2 ^ X3) ^ (X2 ^ (d | t1));
}
/**
* InvS2 - {12, 9,15, 4,11,14, 1, 2, 0, 3, 6,13, 5, 8,10, 7 } - 16 steps.
*/
private void Ib2(int a, int b, int c, int d)
{
int t1 = b ^ d;
int t2 = ~t1;
int t3 = a ^ c;
int t4 = c ^ t1;
int t5 = b & t4;
X0 = t3 ^ t5;
int t7 = a | t2;
int t8 = d ^ t7;
int t9 = t3 | t8;
X3 = t1 ^ t9;
int t11 = ~t4;
int t12 = X0 | X3;
X1 = t11 ^ t12;
X2 = (d & t11) ^ (t3 ^ t12);
}
/**
* S3 - { 0,15,11, 8,12, 9, 6, 3,13, 1, 2, 4,10, 7, 5,14 } - 16 terms.
*/
private void Sb3(int a, int b, int c, int d)
{
int t1 = a ^ b;
int t2 = a & c;
int t3 = a | d;
int t4 = c ^ d;
int t5 = t1 & t3;
int t6 = t2 | t5;
X2 = t4 ^ t6;
int t8 = b ^ t3;
int t9 = t6 ^ t8;
int t10 = t4 & t9;
X0 = t1 ^ t10;
int t12 = X2 & X0;
X1 = t9 ^ t12;
X3 = (b | d) ^ (t4 ^ t12);
}
/**
* InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms
*/
private void Ib3(int a, int b, int c, int d)
{
int t1 = a | b;
int t2 = b ^ c;
int t3 = b & t2;
int t4 = a ^ t3;
int t5 = c ^ t4;
int t6 = d | t4;
X0 = t2 ^ t6;
int t8 = t2 | t6;
int t9 = d ^ t8;
X2 = t5 ^ t9;
int t11 = t1 ^ t9;
int t12 = X0 & t11;
X3 = t4 ^ t12;
X1 = X3 ^ (X0 ^ t11);
}
/**
* S4 - { 1,15, 8, 3,12, 0,11, 6, 2, 5, 4,10, 9,14, 7,13 } - 15 terms.
*/
private void Sb4(int a, int b, int c, int d)
{
int t1 = a ^ d;
int t2 = d & t1;
int t3 = c ^ t2;
int t4 = b | t3;
X3 = t1 ^ t4;
int t6 = ~b;
int t7 = t1 | t6;
X0 = t3 ^ t7;
int t9 = a & X0;
int t10 = t1 ^ t6;
int t11 = t4 & t10;
X2 = t9 ^ t11;
X1 = (a ^ t3) ^ (t10 & X2);
}
/**
* InvS4 - { 5, 0, 8, 3,10, 9, 7,14, 2,12,11, 6, 4,15,13, 1 } - 15 terms.
*/
private void Ib4(int a, int b, int c, int d)
{
int t1 = c | d;
int t2 = a & t1;
int t3 = b ^ t2;
int t4 = a & t3;
int t5 = c ^ t4;
X1 = d ^ t5;
int t7 = ~a;
int t8 = t5 & X1;
X3 = t3 ^ t8;
int t10 = X1 | t7;
int t11 = d ^ t10;
X0 = X3 ^ t11;
X2 = (t3 & t11) ^ (X1 ^ t7);
}
/**
* S5 - {15, 5, 2,11, 4,10, 9,12, 0, 3,14, 8,13, 6, 7, 1 } - 16 terms.
*/
private void Sb5(int a, int b, int c, int d)
{
int t1 = ~a;
int t2 = a ^ b;
int t3 = a ^ d;
int t4 = c ^ t1;
int t5 = t2 | t3;
X0 = t4 ^ t5;
int t7 = d & X0;
int t8 = t2 ^ X0;
X1 = t7 ^ t8;
int t10 = t1 | X0;
int t11 = t2 | t7;
int t12 = t3 ^ t10;
X2 = t11 ^ t12;
X3 = (b ^ t7) ^ (X1 & t12);
}
/**
* InvS5 - { 8,15, 2, 9, 4, 1,13,14,11, 6, 5, 3, 7,12,10, 0 } - 16 terms.
*/
private void Ib5(int a, int b, int c, int d)
{
int t1 = ~c;
int t2 = b & t1;
int t3 = d ^ t2;
int t4 = a & t3;
int t5 = b ^ t1;
X3 = t4 ^ t5;
int t7 = b | X3;
int t8 = a & t7;
X1 = t3 ^ t8;
int t10 = a | d;
int t11 = t1 ^ t7;
X0 = t10 ^ t11;
X2 = (b & t10) ^ (t4 | (a ^ c));
}
/**
* S6 - { 7, 2,12, 5, 8, 4, 6,11,14, 9, 1,15,13, 3,10, 0 } - 15 terms.
*/
private void Sb6(int a, int b, int c, int d)
{
int t1 = ~a;
int t2 = a ^ d;
int t3 = b ^ t2;
int t4 = t1 | t2;
int t5 = c ^ t4;
X1 = b ^ t5;
int t7 = t2 | X1;
int t8 = d ^ t7;
int t9 = t5 & t8;
X2 = t3 ^ t9;
int t11 = t5 ^ t8;
X0 = X2 ^ t11;
X3 = (~t5) ^ (t3 & t11);
}
/**
* InvS6 - {15,10, 1,13, 5, 3, 6, 0, 4, 9,14, 7, 2,12, 8,11 } - 15 terms.
*/
private void Ib6(int a, int b, int c, int d)
{
int t1 = ~a;
int t2 = a ^ b;
int t3 = c ^ t2;
int t4 = c | t1;
int t5 = d ^ t4;
X1 = t3 ^ t5;
int t7 = t3 & t5;
int t8 = t2 ^ t7;
int t9 = b | t8;
X3 = t5 ^ t9;
int t11 = b | X3;
X0 = t8 ^ t11;
X2 = (d & t1) ^ (t3 ^ t11);
}
/**
* S7 - { 1,13,15, 0,14, 8, 2,11, 7, 4,12,10, 9, 3, 5, 6 } - 16 terms.
*/
private void Sb7(int a, int b, int c, int d)
{
int t1 = b ^ c;
int t2 = c & t1;
int t3 = d ^ t2;
int t4 = a ^ t3;
int t5 = d | t1;
int t6 = t4 & t5;
X1 = b ^ t6;
int t8 = t3 | X1;
int t9 = a & t4;
X3 = t1 ^ t9;
int t11 = t4 ^ t8;
int t12 = X3 & t11;
X2 = t3 ^ t12;
X0 = (~t11) ^ (X3 & X2);
}
/**
* InvS7 - { 3, 0, 6,13, 9,14,15, 8, 5,12,11, 7,10, 1, 4, 2 } - 17 terms.
*/
private void Ib7(int a, int b, int c, int d)
{
int t3 = c | (a & b);
int t4 = d & (a | b);
X3 = t3 ^ t4;
int t6 = ~d;
int t7 = b ^ t4;
int t9 = t7 | (X3 ^ t6);
X1 = a ^ t9;
X0 = (c ^ t7) ^ (d | X1);
X2 = (t3 ^ X1) ^ (X0 ^ (a & X3));
}
/**
* Apply the linear transformation to the register set.
*/
private void LT()
{
int x0 = RotateLeft(X0, 13);
int x2 = RotateLeft(X2, 3);
int x1 = X1 ^ x0 ^ x2 ;
int x3 = X3 ^ x2 ^ x0 << 3;
X1 = RotateLeft(x1, 1);
X3 = RotateLeft(x3, 7);
X0 = RotateLeft(x0 ^ X1 ^ X3, 5);
X2 = RotateLeft(x2 ^ X3 ^ (X1 << 7), 22);
}
/**
* Apply the inverse of the linear transformation to the register set.
*/
private void InverseLT()
{
int x2 = RotateRight(X2, 22) ^ X3 ^ (X1 << 7);
int x0 = RotateRight(X0, 5) ^ X1 ^ X3;
int x3 = RotateRight(X3, 7);
int x1 = RotateRight(X1, 1);
X3 = x3 ^ x2 ^ x0 << 3;
X1 = x1 ^ x0 ^ x2;
X2 = RotateRight(x2, 3);
X0 = RotateRight(x0, 13);
}
}
}
| |
using System.Globalization;
namespace Meziantou.Framework.CodeDom;
public partial class CSharpCodeGenerator
{
protected virtual void WriteExpression(IndentedTextWriter writer, Expression? expression)
{
if (expression == null)
return;
WriteBeforeComments(writer, expression);
switch (expression)
{
case BinaryExpression o:
WriteBinaryExpression(writer, o);
break;
case UnaryExpression o:
WriteUnaryExpression(writer, o);
break;
case LiteralExpression o:
WriteLiteralExpression(writer, o);
break;
case ArgumentReferenceExpression o:
WriteArgumentReferenceExpression(writer, o);
break;
case MemberReferenceExpression o:
WriteMemberReferenceExpression(writer, o);
break;
case MethodInvokeExpression o:
WriteMethodInvokeExpression(writer, o);
break;
case ThisExpression o:
WriteThisExpression(writer, o);
break;
case MethodInvokeArgumentExpression o:
WriteMethodInvokeArgumentExpression(writer, o);
break;
case ArrayIndexerExpression o:
WriteArrayIndexerExpression(writer, o);
break;
case BaseExpression o:
WriteBaseExpression(writer, o);
break;
case DefaultValueExpression o:
WriteDefaultValueExpression(writer, o);
break;
case NameofExpression o:
WriteNameofExpression(writer, o);
break;
case NewObjectExpression o:
WriteNewObjectExpression(writer, o);
break;
case SnippetExpression o:
WriteSnippetExpression(writer, o);
break;
case ValueArgumentExpression o:
WriteValueArgumentExpression(writer, o);
break;
case CastExpression o:
WriteCastExpression(writer, o);
break;
case ConvertExpression o:
WriteConvertExpression(writer, o);
break;
case TypeOfExpression o:
WriteTypeOfExpression(writer, o);
break;
case VariableReferenceExpression o:
WriteVariableReferenceExpression(writer, o);
break;
case TypeReferenceExpression o:
WriteTypeReferenceExpression(writer, o);
break;
case AwaitExpression o:
WriteAwaitExpression(writer, o);
break;
case NewArrayExpression o:
WriteNewArrayExpression(writer, o);
break;
case IsInstanceOfTypeExpression o:
WriteIsInstanceOfTypeExpression(writer, o);
break;
default:
throw new NotSupportedException();
}
WriteAfterComments(writer, expression);
}
protected virtual void WriteIsInstanceOfTypeExpression(IndentedTextWriter writer, IsInstanceOfTypeExpression expression)
{
writer.Write("(");
WriteExpression(writer, expression.Expression);
writer.Write(" is ");
WriteTypeReference(writer, expression.Type);
writer.Write(")");
}
protected virtual void WriteTypeReferenceExpression(IndentedTextWriter writer, TypeReferenceExpression expression)
{
WriteTypeReference(writer, expression.Type);
}
protected virtual void WriteThisExpression(IndentedTextWriter writer, ThisExpression expression)
{
writer.Write("this");
}
protected virtual void WriteBaseExpression(IndentedTextWriter writer, BaseExpression expression)
{
writer.Write("base");
}
protected virtual void WriteMethodInvokeExpression(IndentedTextWriter writer, MethodInvokeExpression expression)
{
WriteExpression(writer, expression.Method);
WriteGenericParameters(writer, expression.Parameters);
writer.Write("(");
Write(writer, expression.Arguments, ", ");
writer.Write(")");
}
protected virtual void WriteMethodInvokeArgumentExpression(IndentedTextWriter writer, MethodInvokeArgumentExpression expression)
{
WriteDirection(writer, expression.Direction);
if (!string.IsNullOrEmpty(expression.Name))
{
WriteIdentifier(writer, expression.Name);
writer.Write(": ");
}
WriteExpression(writer, expression.Value);
}
protected virtual void WriteArgumentReferenceExpression(IndentedTextWriter writer, ArgumentReferenceExpression expression)
{
WriteIdentifier(writer, expression.Name);
}
protected virtual void WriteMemberReferenceExpression(IndentedTextWriter writer, MemberReferenceExpression expression)
{
if (expression.TargetObject != null)
{
WriteExpression(writer, expression.TargetObject);
writer.Write(".");
}
WriteIdentifier(writer, expression.Name);
}
protected virtual void WriteLiteralExpression(IndentedTextWriter writer, LiteralExpression expression)
{
switch (expression.Value)
{
case null:
WriteNullLiteral(writer);
return;
case bool value:
WriteBooleanLiteral(writer, value);
break;
case sbyte value:
WriteSByteLiteral(writer, value);
return;
case byte value:
WriteByteLiteral(writer, value);
return;
case short value:
WriteInt16Literal(writer, value);
return;
case ushort value:
WriteUInt16Literal(writer, value);
return;
case int value:
WriteInt32Literal(writer, value);
return;
case uint value:
WriteUint32Literal(writer, value);
return;
case long value:
Int64Literal(writer, value);
return;
case ulong value:
WriteUInt64Literal(writer, value);
return;
case float value:
WriteSingleLiteral(writer, value);
return;
case double value:
WriteDoubleLiteral(writer, value);
return;
case decimal value:
WriteDecimalLiteral(writer, value);
return;
case char value:
WriteCharLiteral(writer, value);
break;
case string value:
WriteStringLiteral(writer, value);
return;
default:
throw new NotSupportedException();
}
}
protected virtual void WriteNullLiteral(IndentedTextWriter writer)
{
writer.Write("null");
}
protected virtual void WriteBooleanLiteral(IndentedTextWriter writer, bool value)
{
if (value)
{
writer.Write("true");
}
else
{
writer.Write("false");
}
}
protected virtual void WriteSByteLiteral(IndentedTextWriter writer, sbyte value)
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
}
protected virtual void WriteByteLiteral(IndentedTextWriter writer, byte value)
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
}
protected virtual void WriteInt16Literal(IndentedTextWriter writer, short value)
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
}
protected virtual void WriteUInt16Literal(IndentedTextWriter writer, ushort value)
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
}
protected virtual void WriteInt32Literal(IndentedTextWriter writer, int value)
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
}
protected virtual void WriteUint32Literal(IndentedTextWriter writer, uint value)
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
writer.Write("u");
}
protected virtual void Int64Literal(IndentedTextWriter writer, long value)
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
writer.Write("L");
}
protected virtual void WriteUInt64Literal(IndentedTextWriter writer, ulong value)
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
writer.Write("uL");
}
protected virtual void WriteStringLiteral(IndentedTextWriter writer, string value)
{
writer.Write("\"");
foreach (var c in value)
{
switch (c)
{
case '"':
writer.Write("\\\"");
break;
case '\t':
writer.Write(@"\t");
break;
case '\r':
writer.Write(@"\r");
break;
case '\n':
writer.Write(@"\n");
break;
case '\a':
writer.Write(@"\a");
break;
case '\b':
writer.Write(@"\b");
break;
case '\f':
writer.Write(@"\f");
break;
case '\v':
writer.Write(@"\v");
break;
case '\0':
writer.Write(@"\0");
break;
case '\\':
writer.Write(@"\\");
break;
default:
writer.Write(c);
break;
}
}
writer.Write("\"");
}
protected virtual void WriteCharLiteral(IndentedTextWriter writer, char value)
{
writer.Write('\'');
writer.Write(value);
writer.Write('\'');
}
protected virtual void WriteDecimalLiteral(IndentedTextWriter writer, decimal value)
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
writer.Write("m");
}
protected virtual void WriteSingleLiteral(IndentedTextWriter writer, float value)
{
if (float.IsNaN(value))
{
writer.Write("float.NaN");
}
else if (float.IsNegativeInfinity(value))
{
writer.Write("float.NegativeInfinity");
}
else if (float.IsPositiveInfinity(value))
{
writer.Write("float.PositiveInfinity");
}
else
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
writer.Write("F");
}
}
protected virtual void WriteDoubleLiteral(IndentedTextWriter writer, double value)
{
if (double.IsNaN(value))
{
writer.Write("double.NaN");
}
else if (double.IsNegativeInfinity(value))
{
writer.Write("double.NegativeInfinity");
}
else if (double.IsPositiveInfinity(value))
{
writer.Write("double.PositiveInfinity");
}
else
{
writer.Write(value.ToString("R", CultureInfo.InvariantCulture));
writer.Write("D");
}
}
protected virtual void WriteBinaryExpression(IndentedTextWriter writer, BinaryExpression expression)
{
writer.Write("(");
WriteExpression(writer, expression.LeftExpression);
writer.Write(" ");
writer.Write(WriteBinaryOperator(expression.Operator));
writer.Write(" ");
WriteExpression(writer, expression.RightExpression);
writer.Write(")");
}
protected virtual void WriteUnaryExpression(IndentedTextWriter writer, UnaryExpression expression)
{
writer.Write("(");
if (IsPrefixOperator(expression.Operator))
{
writer.Write(WriteUnaryOperator(expression.Operator));
WriteExpression(writer, expression.Expression);
}
else
{
WriteExpression(writer, expression.Expression);
writer.Write(WriteUnaryOperator(expression.Operator));
}
writer.Write(")");
}
protected virtual void WriteArrayIndexerExpression(IndentedTextWriter writer, ArrayIndexerExpression expression)
{
WriteExpression(writer, expression.ArrayExpression);
writer.Write("[");
Write(writer, expression.Indices, ", ");
writer.Write("]");
}
protected virtual void WriteDefaultValueExpression(IndentedTextWriter writer, DefaultValueExpression expression)
{
writer.Write("default");
if (expression.Type != null)
{
writer.Write("(");
WriteTypeReference(writer, expression.Type);
writer.Write(")");
}
}
protected virtual void WriteNameofExpression(IndentedTextWriter writer, NameofExpression expression)
{
writer.Write("nameof(");
WriteExpression(writer, expression.Expression);
writer.Write(")");
}
protected virtual void WriteNewObjectExpression(IndentedTextWriter writer, NewObjectExpression expression)
{
writer.Write("new ");
WriteTypeReference(writer, expression.Type);
writer.Write("(");
Write(writer, expression.Arguments, ", ");
writer.Write(")");
}
protected virtual void WriteNewArrayExpression(IndentedTextWriter writer, NewArrayExpression expression)
{
writer.Write("new ");
WriteTypeReference(writer, expression.Type);
writer.Write("[");
Write(writer, expression.Arguments, ", ");
writer.Write("]");
}
protected virtual void WriteSnippetExpression(IndentedTextWriter writer, SnippetExpression expression)
{
writer.Write(expression.Expression);
}
protected virtual void WriteValueArgumentExpression(IndentedTextWriter writer, ValueArgumentExpression expression)
{
writer.Write("value");
}
protected virtual void WriteCastExpression(IndentedTextWriter writer, CastExpression expression)
{
writer.Write("(");
writer.Write("(");
WriteTypeReference(writer, expression.Type);
writer.Write(")");
WriteExpression(writer, expression.Expression);
writer.Write(")");
}
protected virtual void WriteConvertExpression(IndentedTextWriter writer, ConvertExpression expression)
{
writer.Write("(");
WriteExpression(writer, expression.Expression);
writer.Write(" as ");
WriteTypeReference(writer, expression.Type);
writer.Write(")");
}
protected virtual void WriteTypeOfExpression(IndentedTextWriter writer, TypeOfExpression expression)
{
writer.Write("typeof(");
WriteTypeReference(writer, expression.Type);
writer.Write(")");
}
protected virtual void WriteVariableReferenceExpression(IndentedTextWriter writer, VariableReferenceExpression expression)
{
WriteIdentifier(writer, expression.Name);
}
protected virtual void WriteAwaitExpression(IndentedTextWriter writer, AwaitExpression expression)
{
writer.Write("await ");
if (expression.Expression != null)
{
WriteExpression(writer, expression.Expression);
}
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Text;
namespace Alphaleonis.Win32.Security
{
internal static partial class NativeMethods
{
#region AdjustTokenPrivileges
/// <summary>The AdjustTokenPrivileges function enables or disables privileges in the specified access token. Enabling or disabling privileges in an access token requires TOKEN_ADJUST_PRIVILEGES access.</summary>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// To determine whether the function adjusted all of the specified privileges, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, ref TokenPrivileges newState, uint bufferLength, out TokenPrivileges previousState, out uint returnLength);
#endregion // AdjustTokenPrivileges
#region LookupPrivilegeDisplayName
/// <summary>The LookupPrivilegeDisplayName function retrieves the display name that represents a specified privilege.</summary>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, it returns zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "LookupPrivilegeDisplayNameW")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool LookupPrivilegeDisplayName([MarshalAs(UnmanagedType.LPWStr)] string lpSystemName, [MarshalAs(UnmanagedType.LPWStr)] string lpName, ref StringBuilder lpDisplayName, ref uint cchDisplayName, out uint lpLanguageId);
#endregion // LookupPrivilegeDisplayName
#region LookupPrivilegeValue
/// <summary>The LookupPrivilegeValue function retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name.</summary>
/// <returns>
/// If the function succeeds, the function returns nonzero.
/// If the function fails, it returns zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "LookupPrivilegeValueW")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool LookupPrivilegeValue([MarshalAs(UnmanagedType.LPWStr)] string lpSystemName, [MarshalAs(UnmanagedType.LPWStr)] string lpName, out Luid lpLuid);
#endregion // LookupPrivilegeValue
#region GetNamedSecurityInfo
/// <summary>The GetNamedSecurityInfo function retrieves a copy of the security descriptor for an object specified by name.
/// <para> </para>
/// <returns>
/// <para>If the function succeeds, the return value is ERROR_SUCCESS.</para>
/// <para>If the function fails, the return value is a nonzero error code defined in WinError.h.</para>
/// </returns>
/// <para> </para>
/// <remarks>
/// <para>Minimum supported client: Windows XP [desktop apps only]</para>
/// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
/// </remarks>
/// </summary>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetNamedSecurityInfoW")]
[return: MarshalAs(UnmanagedType.U4)]
internal static extern uint GetNamedSecurityInfo([MarshalAs(UnmanagedType.LPWStr)] string pObjectName, ObjectType objectType, SecurityInformation securityInfo, out IntPtr pSidOwner, out IntPtr pSidGroup, out IntPtr pDacl, out IntPtr pSacl, out SafeGlobalMemoryBufferHandle pSecurityDescriptor);
#endregion // GetNamedSecurityInfo
#region GetSecurityInfo
/// <summary>The GetSecurityInfo function retrieves a copy of the security descriptor for an object specified by a handle.</summary>
/// <returns>
/// If the function succeeds, the function returns nonzero.
/// If the function fails, it returns zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.U4)]
internal static extern uint GetSecurityInfo(SafeHandle handle, ObjectType objectType, SecurityInformation securityInfo, out IntPtr pSidOwner, out IntPtr pSidGroup, out IntPtr pDacl, out IntPtr pSacl, out SafeGlobalMemoryBufferHandle pSecurityDescriptor);
#endregion // GetSecurityInfo
#region SetSecurityInfo
/// <summary>The SetSecurityInfo function sets specified security information in the security descriptor of a specified object.
/// The caller identifies the object by a handle.</summary>
/// <returns>
/// If the function succeeds, the function returns ERROR_SUCCESS.
/// If the function fails, it returns a nonzero error code defined in WinError.h.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.U4)]
internal static extern uint SetSecurityInfo(SafeHandle handle, ObjectType objectType, SecurityInformation securityInfo, IntPtr psidOwner, IntPtr psidGroup, IntPtr pDacl, IntPtr pSacl);
#endregion // SetSecurityInfo
#region SetNamedSecurityInfo
/// <summary>The SetNamedSecurityInfo function sets specified security information in the security descriptor of a specified object. The caller identifies the object by name.
/// <para> </para>
/// <returns>
/// <para>If the function succeeds, the function returns ERROR_SUCCESS.</para>
/// <para>If the function fails, it returns a nonzero error code defined in WinError.h.</para>
/// </returns>
/// <para> </para>
/// <remarks>
/// <para>Minimum supported client: Windows XP [desktop apps only]</para>
/// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
/// </remarks>
/// </summary>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetNamedSecurityInfoW")]
[return: MarshalAs(UnmanagedType.U4)]
internal static extern uint SetNamedSecurityInfo([MarshalAs(UnmanagedType.LPWStr)] string pObjectName, ObjectType objectType, SecurityInformation securityInfo, IntPtr pSidOwner, IntPtr pSidGroup, IntPtr pDacl, IntPtr pSacl);
#endregion // SetNamedSecurityInfo
#region GetSecurityDescriptorDacl
/// <summary>The GetSecurityDescriptorDacl function retrieves a pointer to the discretionary access control list (DACL) in a specified security descriptor.</summary>
/// <returns>
/// If the function succeeds, the function returns nonzero.
/// If the function fails, it returns zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetSecurityDescriptorDacl(SafeGlobalMemoryBufferHandle pSecurityDescriptor, [MarshalAs(UnmanagedType.Bool)] out bool lpbDaclPresent, out IntPtr pDacl, [MarshalAs(UnmanagedType.Bool)] out bool lpbDaclDefaulted);
#endregion // GetSecurityDescriptorDacl
#region GetSecurityDescriptorSacl
/// <summary>The GetSecurityDescriptorSacl function retrieves a pointer to the system access control list (SACL) in a specified security descriptor.</summary>
/// <returns>
/// If the function succeeds, the function returns nonzero.
/// If the function fails, it returns zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetSecurityDescriptorSacl(SafeGlobalMemoryBufferHandle pSecurityDescriptor, [MarshalAs(UnmanagedType.Bool)] out bool lpbSaclPresent, out IntPtr pSacl, [MarshalAs(UnmanagedType.Bool)] out bool lpbSaclDefaulted);
#endregion // GetSecurityDescriptorSacl
#region GetSecurityDescriptorGroup
/// <summary>The GetSecurityDescriptorGroup function retrieves the primary group information from a security descriptor.</summary>
/// <returns>
/// If the function succeeds, the function returns nonzero.
/// If the function fails, it returns zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetSecurityDescriptorGroup(SafeGlobalMemoryBufferHandle pSecurityDescriptor, out IntPtr pGroup, [MarshalAs(UnmanagedType.Bool)] out bool lpbGroupDefaulted);
#endregion // GetSecurityDescriptorGroup
#region GetSecurityDescriptorControl
/// <summary>The GetSecurityDescriptorControl function retrieves a security descriptor control and revision information.</summary>
/// <returns>
/// If the function succeeds, the function returns nonzero.
/// If the function fails, it returns zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetSecurityDescriptorControl(SafeGlobalMemoryBufferHandle pSecurityDescriptor, out SecurityDescriptorControl pControl, out uint lpdwRevision);
#endregion // GetSecurityDescriptorControl
#region GetSecurityDescriptorOwner
/// <summary>The GetSecurityDescriptorOwner function retrieves the owner information from a security descriptor.</summary>
/// <returns>
/// If the function succeeds, the function returns nonzero.
/// If the function fails, it returns zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetSecurityDescriptorOwner(SafeGlobalMemoryBufferHandle pSecurityDescriptor, out IntPtr pOwner, [MarshalAs(UnmanagedType.Bool)] out bool lpbOwnerDefaulted);
#endregion // GetSecurityDescriptorOwner
#region GetSecurityDescriptorLength
/// <summary>The GetSecurityDescriptorLength function returns the length, in bytes, of a structurally valid security descriptor. The length includes the length of all associated structures.</summary>
/// <returns>
/// If the function succeeds, the function returns the length, in bytes, of the SECURITY_DESCRIPTOR structure.
/// If the SECURITY_DESCRIPTOR structure is not valid, the return value is undefined.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.U4)]
internal static extern uint GetSecurityDescriptorLength(SafeGlobalMemoryBufferHandle pSecurityDescriptor);
#endregion // GetSecurityDescriptorLength
#region LocalFree
/// <summary>Frees the specified local memory object and invalidates its handle.</summary>
/// <returns>
/// If the function succeeds, the return value is <see langword="null"/>.
/// If the function fails, the return value is equal to a handle to the local memory object. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>SetLastError is set to <see langword="false"/>.</remarks>
/// <remarks>
/// Note The local functions have greater overhead and provide fewer features than other memory management functions.
/// New applications should use the heap functions unless documentation states that a local function should be used.
/// For more information, see Global and Local Functions.
/// </remarks>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)]
internal static extern IntPtr LocalFree(IntPtr hMem);
#endregion // LocalFree
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace NamelessInteractive.AASA.JoyOfLiving.WebHost.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);
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the DescribeSnapshots operation.
/// Describes one or more of the EBS snapshots available to you. Available snapshots include
/// public snapshots available for any AWS account to launch, private snapshots that you
/// own, and private snapshots owned by another AWS account but for which you've been
/// given explicit create volume permissions.
///
///
/// <para>
/// The create volume permissions fall into the following categories:
/// </para>
/// <ul> <li> <i>public</i>: The owner of the snapshot granted create volume permissions
/// for the snapshot to the <code>all</code> group. All AWS accounts have create volume
/// permissions for these snapshots.</li> <li> <i>explicit</i>: The owner of the snapshot
/// granted create volume permissions to a specific AWS account.</li> <li> <i>implicit</i>:
/// An AWS account has implicit create volume permissions for all snapshots it owns.</li>
/// </ul>
/// <para>
/// The list of snapshots returned can be modified by specifying snapshot IDs, snapshot
/// owners, or AWS accounts with create volume permissions. If no options are specified,
/// Amazon EC2 returns all snapshots for which you have create volume permissions.
/// </para>
///
/// <para>
/// If you specify one or more snapshot IDs, only snapshots that have the specified IDs
/// are returned. If you specify an invalid snapshot ID, an error is returned. If you
/// specify a snapshot ID for which you do not have access, it is not included in the
/// returned results.
/// </para>
///
/// <para>
/// If you specify one or more snapshot owners, only snapshots from the specified owners
/// and for which you have access are returned. The results can include the AWS account
/// IDs of the specified owners, <code>amazon</code> for snapshots owned by Amazon, or
/// <code>self</code> for snapshots that you own.
/// </para>
///
/// <para>
/// If you specify a list of restorable users, only snapshots with create snapshot permissions
/// for those users are returned. You can specify AWS account IDs (if you own the snapshots),
/// <code>self</code> for snapshots for which you own or have explicit permissions, or
/// <code>all</code> for public snapshots.
/// </para>
///
/// <para>
/// If you are describing a long list of snapshots, you can paginate the output to make
/// the list more manageable. The <code>MaxResults</code> parameter sets the maximum number
/// of results returned in a single page. If the list of results exceeds your <code>MaxResults</code>
/// value, then that number of results is returned along with a <code>NextToken</code>
/// value that can be passed to a subsequent <code>DescribeSnapshots</code> request to
/// retrieve the remaining results.
/// </para>
///
/// <para>
/// For more information about EBS snapshots, see <a href='http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html'>Amazon
/// EBS Snapshots</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public partial class DescribeSnapshotsRequest : AmazonEC2Request
{
private List<Filter> _filters = new List<Filter>();
private int? _maxResults;
private string _nextToken;
private List<string> _ownerIds = new List<string>();
private List<string> _restorableByUserIds = new List<string>();
private List<string> _snapshotIds = new List<string>();
/// <summary>
/// Gets and sets the property Filters.
/// <para>
/// One or more filters.
/// </para>
/// <ul> <li>
/// <para>
/// <code>description</code> - A description of the snapshot.
/// </para>
/// </li> <li>
/// <para>
/// <code>owner-alias</code> - The AWS account alias (for example, <code>amazon</code>)
/// that owns the snapshot.
/// </para>
/// </li> <li>
/// <para>
/// <code>owner-id</code> - The ID of the AWS account that owns the snapshot.
/// </para>
/// </li> <li>
/// <para>
/// <code>progress</code> - The progress of the snapshot, as a percentage (for example,
/// 80%).
/// </para>
/// </li> <li>
/// <para>
/// <code>snapshot-id</code> - The snapshot ID.
/// </para>
/// </li> <li>
/// <para>
/// <code>start-time</code> - The time stamp when the snapshot was initiated.
/// </para>
/// </li> <li>
/// <para>
/// <code>status</code> - The status of the snapshot (<code>pending</code> | <code>completed</code>
/// | <code>error</code>).
/// </para>
/// </li> <li>
/// <para>
/// <code>tag</code>:<i>key</i>=<i>value</i> - The key/value combination of a tag assigned
/// to the resource.
/// </para>
/// </li> <li>
/// <para>
/// <code>tag-key</code> - The key of a tag assigned to the resource. This filter is independent
/// of the <code>tag-value</code> filter. For example, if you use both the filter "tag-key=Purpose"
/// and the filter "tag-value=X", you get any resources assigned both the tag key Purpose
/// (regardless of what the tag's value is), and the tag value X (regardless of what the
/// tag's key is). If you want to list only resources where Purpose is X, see the <code>tag</code>:<i>key</i>=<i>value</i>
/// filter.
/// </para>
/// </li> <li>
/// <para>
/// <code>tag-value</code> - The value of a tag assigned to the resource. This filter
/// is independent of the <code>tag-key</code> filter.
/// </para>
/// </li> <li>
/// <para>
/// <code>volume-id</code> - The ID of the volume the snapshot is for.
/// </para>
/// </li> <li>
/// <para>
/// <code>volume-size</code> - The size of the volume, in GiB.
/// </para>
/// </li> </ul>
/// </summary>
public List<Filter> Filters
{
get { return this._filters; }
set { this._filters = value; }
}
// Check to see if Filters property is set
internal bool IsSetFilters()
{
return this._filters != null && this._filters.Count > 0;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of snapshot results returned by <code>DescribeSnapshots</code>
/// in paginated output. When this parameter is used, <code>DescribeSnapshots</code> only
/// returns <code>MaxResults</code> results in a single page along with a <code>NextToken</code>
/// response element. The remaining results of the initial request can be seen by sending
/// another <code>DescribeSnapshots</code> request with the returned <code>NextToken</code>
/// value. This value can be between 5 and 1000; if <code>MaxResults</code> is given a
/// value larger than 1000, only 1000 results are returned. If this parameter is not used,
/// then <code>DescribeSnapshots</code> returns all results. You cannot specify this parameter
/// and the snapshot IDs parameter in the same request.
/// </para>
/// </summary>
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The <code>NextToken</code> value returned from a previous paginated <code>DescribeSnapshots</code>
/// request where <code>MaxResults</code> was used and the results exceeded the value
/// of that parameter. Pagination continues from the end of the previous results that
/// returned the <code>NextToken</code> value. This value is <code>null</code> when there
/// are no more results to return.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property OwnerIds.
/// <para>
/// Returns the snapshots owned by the specified owner. Multiple owners can be specified.
/// </para>
/// </summary>
public List<string> OwnerIds
{
get { return this._ownerIds; }
set { this._ownerIds = value; }
}
// Check to see if OwnerIds property is set
internal bool IsSetOwnerIds()
{
return this._ownerIds != null && this._ownerIds.Count > 0;
}
/// <summary>
/// Gets and sets the property RestorableByUserIds.
/// <para>
/// One or more AWS accounts IDs that can create volumes from the snapshot.
/// </para>
/// </summary>
public List<string> RestorableByUserIds
{
get { return this._restorableByUserIds; }
set { this._restorableByUserIds = value; }
}
// Check to see if RestorableByUserIds property is set
internal bool IsSetRestorableByUserIds()
{
return this._restorableByUserIds != null && this._restorableByUserIds.Count > 0;
}
/// <summary>
/// Gets and sets the property SnapshotIds.
/// <para>
/// One or more snapshot IDs.
/// </para>
///
/// <para>
/// Default: Describes snapshots for which you have launch permissions.
/// </para>
/// </summary>
public List<string> SnapshotIds
{
get { return this._snapshotIds; }
set { this._snapshotIds = value; }
}
// Check to see if SnapshotIds property is set
internal bool IsSetSnapshotIds()
{
return this._snapshotIds != null && this._snapshotIds.Count > 0;
}
}
}
| |
/***************************************************************************
* PluginDialog.cs
*
* Copyright (C) 2005-2006 Novell, Inc.
* Written by Aaron Bockover (aaron@aaronbock.net)
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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;
#if !win32
using Mono.Unix;
using Gtk;
#else
using Banshee.Winforms;
using System.Windows.Forms;
#endif
using Banshee.Base;
using Banshee.Configuration;
namespace Banshee.Plugins
{
#if !win32
internal class PluginDialog : Dialog
#else
internal class PluginDialog : Form
#endif
{
private TreeView plugin_tree;
#if !win32
private ListStore plugin_store;
#endif
private Label name_label;
private Label description_label;
private Label authors_label;
public PluginDialog()
{
}
public void Run()
{
Banshee.Winforms.Gui.Dialogs.PluginDialog plugin_dialog = new Banshee.Winforms.Gui.Dialogs.PluginDialog();
plugin_dialog.ShowDialog();
}
#if !win32
private HBox disabled_box;
private Notebook plugin_notebook;
private Gdk.Color normal_color;
private Gdk.Color disabled_color;
public PluginDialog() : base(
Catalog.GetString("Banshee Plugins"),
null,
DialogFlags.Modal | DialogFlags.NoSeparator,
Stock.Close,
ResponseType.Close)
{
BorderWidth = 10;
HBox box = new HBox();
box.Spacing = 10;
plugin_tree = new TreeView();
TreeViewColumn name_column = new TreeViewColumn(Catalog.GetString("Plugin Name"),
new CellRendererText(), "text", 0, "foreground-gdk", 3);
name_column.Expand = true;
plugin_tree.AppendColumn(name_column);
CellRendererToggle toggle_cell = new CellRendererToggle();
TreeViewColumn toggle_column = new TreeViewColumn(Catalog.GetString("Enabled"),
toggle_cell, "active", 1);
toggle_cell.Activatable = true;
toggle_cell.Toggled += OnActiveToggled;
toggle_column.Expand = false;
plugin_tree.AppendColumn(toggle_column);
plugin_tree.CursorChanged += OnCursorChanged;
ScrolledWindow scroll = new ScrolledWindow();
scroll.Add(plugin_tree);
scroll.ShadowType = ShadowType.In;
scroll.HscrollbarPolicy = PolicyType.Never;
plugin_notebook = new Notebook();
VBox info_box = new VBox();
info_box.BorderWidth = 12;
info_box.Spacing = 10;
plugin_notebook.AppendPage(info_box, new Label(Catalog.GetString("Overview")));
name_label = new Label();
CreateInfoRow(info_box, Catalog.GetString("Plugin Name"), name_label);
description_label = new Label();
description_label.LineWrap = true;
CreateInfoRow(info_box, Catalog.GetString("Description"), description_label);
authors_label = new Label();
CreateInfoRow(info_box, Catalog.GetString("Author(s)"), authors_label);
disabled_box = new HBox();
disabled_box.Spacing = 5;
Image disabled_image = new Image(Stock.DialogError, IconSize.Menu);
Label disabled_label = new Label(Catalog.GetString("This plugin could not be initialized."));
disabled_label.Xalign = 0.0f;
disabled_box.PackStart(disabled_image, false, false, 0);
disabled_box.PackStart(disabled_label, true, true, 0);
info_box.PackStart(disabled_box, false, false, 0);
box.PackStart(scroll, false, false, 0);
box.PackStart(plugin_notebook, true, true, 0);
VBox.PackStart(box, true, true, 0);
VBox.Spacing = 10;
normal_color = plugin_tree.Style.Foreground(StateType.Normal);
disabled_color = plugin_tree.Style.Foreground(StateType.Insensitive);
FillTree();
plugin_tree.ColumnsAutosize();
IconThemeUtils.SetWindowIcon(this);
box.ShowAll();
disabled_box.Hide();
WindowPosition = WindowPosition.Center;
}
private void CreateInfoRow(Box parent, string name, Label valueLabel)
{
VBox box = new VBox();
box.Spacing = 2;
Label label = new Label();
label.Xalign = 0.0f;
label.Markup = "<b>" + GLib.Markup.EscapeText(name) + "</b>";
valueLabel.Xalign = 0.0f;
box.PackStart(label, false, false, 0);
box.PackStart(valueLabel, false, false, 0);
parent.PackStart(box, false, false, 0);
}
private void FillTree()
{
plugin_store = new ListStore(typeof(string), typeof(bool), typeof(Plugin), typeof(Gdk.Color));
foreach(Plugin plugin in PluginCore.Factory) {
plugin_store.AppendValues(plugin.DisplayName, plugin.Initialized, plugin,
plugin.Broken ? disabled_color : normal_color);
}
plugin_tree.Model = plugin_store;
}
private void OnCursorChanged(object o, EventArgs args)
{
TreeIter iter;
if(!plugin_tree.Selection.GetSelected(out iter)) {
return;
}
Plugin plugin = plugin_store.GetValue(iter, 2) as Plugin;
if(plugin == null) {
return;
}
string authors = String.Empty;
foreach(string author in plugin.Authors) {
authors += author + "\n";
}
name_label.Text = plugin.DisplayName;
description_label.Text = plugin.Description;
authors_label.Text = authors;
if(plugin.Broken) {
disabled_box.ShowAll();
} else {
disabled_box.Hide();
}
if(plugin_notebook.NPages > 1) {
plugin_notebook.RemovePage(1);
}
if(!plugin.Broken && plugin.Initialized && plugin.HasConfigurationWidget) {
Alignment alignment = new Alignment(0.0f, 0.0f, 1.0f, 1.0f);
alignment.BorderWidth = 12;
Widget widget = plugin.GetConfigurationWidget();
alignment.Add(widget);
plugin_notebook.AppendPage(alignment, new Label(Catalog.GetString("Configuration")));
widget.Show();
alignment.Show();
}
}
private void OnActiveToggled(object o, ToggledArgs args)
{
TreeIter iter;
if(plugin_store.GetIter(out iter, new TreePath(args.Path))) {
Plugin plugin = plugin_store.GetValue(iter, 2) as Plugin;
bool initialize = !(bool)plugin_store.GetValue(iter, 1);
if(plugin == null || plugin.Broken) {
return;
}
if(initialize) {
plugin.Initialize();
} else {
plugin.Dispose();
}
plugin_store.SetValue(iter, 1, plugin.Initialized);
plugin_store.SetValue(iter, 3, plugin.Broken ? disabled_color : normal_color);
ConfigurationClient.Set<bool>(plugin.ConfigurationNamespace, "enabled", plugin.Initialized);
}
}
#endif
}
}
| |
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 SimplesE.API.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;
}
}
}
| |
/*
* 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.IO;
using Lucene.Net.Support;
using NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using English = Lucene.Net.Util.English;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Store
{
/// <summary> JUnit testcase to test RAMDirectory. RAMDirectory itself is used in many testcases,
/// but not one of them uses an different constructor other than the default constructor.
/// </summary>
[TestFixture]
public class TestRAMDirectory:LuceneTestCase
{
private class AnonymousClassThread:ThreadClass
{
public AnonymousClassThread(int num, Lucene.Net.Index.IndexWriter writer, Lucene.Net.Store.MockRAMDirectory ramDir, TestRAMDirectory enclosingInstance)
{
InitBlock(num, writer, ramDir, enclosingInstance);
}
private void InitBlock(int num, Lucene.Net.Index.IndexWriter writer, Lucene.Net.Store.MockRAMDirectory ramDir, TestRAMDirectory enclosingInstance)
{
this.num = num;
this.writer = writer;
this.ramDir = ramDir;
this.enclosingInstance = enclosingInstance;
}
private int num;
private Lucene.Net.Index.IndexWriter writer;
private Lucene.Net.Store.MockRAMDirectory ramDir;
private TestRAMDirectory enclosingInstance;
public TestRAMDirectory Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
override public void Run()
{
for (int j = 1; j < Enclosing_Instance.docsPerThread; j++)
{
Document doc = new Document();
doc.Add(new Field("sizeContent", English.IntToEnglish(num * Enclosing_Instance.docsPerThread + j).Trim(), Field.Store.YES, Field.Index.NOT_ANALYZED));
try
{
writer.AddDocument(doc);
}
catch (System.IO.IOException e)
{
throw new System.SystemException("", e);
}
}
}
}
private System.IO.DirectoryInfo indexDir = null;
// add enough document so that the index will be larger than RAMDirectory.READ_BUFFER_SIZE
private int docsToAdd = 500;
// setup the index
[SetUp]
public override void SetUp()
{
base.SetUp();
System.String tempDir = System.IO.Path.GetTempPath();
if (tempDir == null)
throw new System.IO.IOException("java.io.tmpdir undefined, cannot run test");
indexDir = new System.IO.DirectoryInfo(Path.Combine(tempDir, "RAMDirIndex"));
Directory dir = FSDirectory.Open(indexDir);
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
// add some documents
Document doc = null;
for (int i = 0; i < docsToAdd; i++)
{
doc = new Document();
doc.Add(new Field("content", English.IntToEnglish(i).Trim(), Field.Store.YES, Field.Index.NOT_ANALYZED));
writer.AddDocument(doc);
}
Assert.AreEqual(docsToAdd, writer.MaxDoc());
writer.Close();
dir.Close();
}
[Test]
public virtual void TestRAMDirectory_Renamed()
{
Directory dir = FSDirectory.Open(indexDir);
MockRAMDirectory ramDir = new MockRAMDirectory(dir);
// close the underlaying directory
dir.Close();
// Check size
Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());
// open reader to test document count
IndexReader reader = IndexReader.Open(ramDir, true);
Assert.AreEqual(docsToAdd, reader.NumDocs());
// open search zo check if all doc's are there
IndexSearcher searcher = new IndexSearcher(reader);
// search for all documents
for (int i = 0; i < docsToAdd; i++)
{
Document doc = searcher.Doc(i);
Assert.IsTrue(doc.GetField("content") != null);
}
// cleanup
reader.Close();
searcher.Close();
}
private int numThreads = 10;
private int docsPerThread = 40;
[Test]
public virtual void TestRAMDirectorySize()
{
Directory dir = FSDirectory.Open(indexDir);
MockRAMDirectory ramDir = new MockRAMDirectory(dir);
dir.Close();
IndexWriter writer = new IndexWriter(ramDir, new WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.LIMITED);
writer.Optimize();
Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());
ThreadClass[] threads = new ThreadClass[numThreads];
for (int i = 0; i < numThreads; i++)
{
int num = i;
threads[i] = new AnonymousClassThread(num, writer, ramDir, this);
}
for (int i = 0; i < numThreads; i++)
threads[i].Start();
for (int i = 0; i < numThreads; i++)
threads[i].Join();
writer.Optimize();
Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());
writer.Close();
}
[Test]
public virtual void TestSerializable()
{
Directory dir = new RAMDirectory();
System.IO.MemoryStream bos = new System.IO.MemoryStream(1024);
Assert.AreEqual(0, bos.Length, "initially empty");
System.IO.BinaryWriter out_Renamed = new System.IO.BinaryWriter(bos);
long headerSize = bos.Length;
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(out_Renamed.BaseStream, dir);
out_Renamed.Flush(); // In Java, this is Close(), but we can't do this in .NET, and the Close() is moved to after the validation check
Assert.IsTrue(headerSize < bos.Length, "contains more then just header");
out_Renamed.Close();
}
[TearDown]
public override void TearDown()
{
base.TearDown();
// cleanup
if(System.IO.Directory.Exists(indexDir.FullName))
{
System.IO.Directory.Delete(indexDir.FullName, true);
}
}
// LUCENE-1196
[Test]
public virtual void TestIllegalEOF()
{
RAMDirectory dir = new RAMDirectory();
IndexOutput o = dir.CreateOutput("out");
byte[] b = new byte[1024];
o.WriteBytes(b, 0, 1024);
o.Close();
IndexInput i = dir.OpenInput("out");
i.Seek(1024);
i.Close();
dir.Close();
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using System.Resources;
using System.Windows.Forms;
namespace HtmlHelp.UIComponents
{
/// <summary>
/// The class <c>ResourceHelper</c> implements methods for easy resource loading/using
/// </summary>
public sealed class ResourceHelper
{
/// <summary>
/// Internal member storing the default resource namespace
/// </summary>
private string _defaultNamespace = "";
/// <summary>
/// Internal member storing the resource assembly
/// </summary>
private Assembly _resAssembly = null;
/// <summary>
/// Internal resource manager
/// </summary>
private ResourceManager m_resourceManager;
/// <summary>
/// Internal member storing the bitmap/icon/images default namepsace
/// </summary>
private string _defaultBitmapNamespace = "";
/// <summary>
/// Internal member storing the default namespace for string resources
/// </summary>
private string _defaultStringNamespace = "";
/// <summary>
/// Constructs a new resource helper class.
/// </summary>
/// <remarks>Uses "<c>Flextronics.eLounge2.Application</c>" as default namespace and the current module's assembly
/// as default resource assembly.</remarks>
public ResourceHelper() : this("HtmlHelp", null)
{
}
/// <summary>
/// Constructs a new resource helper class.
/// </summary>
/// <param name="resAssembly">resource assembly</param>
/// <remarks>Uses "<c>Flextronics.eLounge2.Application</c>" as default namespace.</remarks>
public ResourceHelper(Assembly resAssembly) : this("HtmlHelp", resAssembly)
{
}
/// <summary>
/// Constructs a new resource helper class.
/// </summary>
/// <param name="defaultNamespace">default namespace for loading resources</param>
/// <remarks>Uses the current module's assembly as default resource assembly.</remarks>
public ResourceHelper(string defaultNamespace) : this (defaultNamespace, null)
{
}
/// <summary>
/// Constructs a new resource helper class.
/// </summary>
/// <param name="defaultNamespace">default namespace for loading resources</param>
/// <param name="resAssembly">resource assembly</param>
public ResourceHelper(string defaultNamespace, Assembly resAssembly)
{
if(resAssembly == null)
_resAssembly = this.GetType().Module.Assembly;
else
_resAssembly = resAssembly;
_defaultNamespace = defaultNamespace;
}
/// <summary>
/// Gets the default resource namespace
/// </summary>
public string DefaultNamespace
{
get { return _defaultNamespace; }
}
/// <summary>
/// Gets the default resource assembly
/// </summary>
public Assembly ResourceAssembly
{
get { return _resAssembly; }
}
/// <summary>
/// Gets the name of the default resource assembly
/// </summary>
public string ResourceAssemblyName
{
get
{
if(_resAssembly == null)
return "";
return _resAssembly.FullName;
}
}
/// <summary>
/// Gets/sets the default namespace for loading bitmaps/icons/images etc.
/// </summary>
/// <remarks>This namespace will be combined with the <see cref="DefaultNamespace">DefaultNamespace</see> property.</remarks>
public string DefaultBitmapNamespace
{
get { return _defaultBitmapNamespace; }
set { _defaultBitmapNamespace = value; }
}
/// <summary>
/// Gets/sets the default namespace for loading string resources.
/// </summary>
/// <remarks>This namespace will be combined with the <see cref="DefaultNamespace">DefaultNamespace</see> property.</remarks>
public string DefaultStringNamespace
{
get { return _defaultStringNamespace; }
set { _defaultStringNamespace = value; }
}
/// <summary>
/// Loads a bitmap from the combined resources and returns an <see cref="System.Drawing.Bitmap">Bitmap</see> instance to the caller.
/// </summary>
/// <param name="name">name of the bitmap file/resource</param>
/// <returns>Returns an <see cref="System.Drawing.Bitmap">Bitmap</see> instance to the caller.</returns>
public Bitmap LoadBitmap(string name)
{
return LoadBitmap(DefaultBitmapNamespace, name);
}
/// <summary>
/// Loads an icon from the combined resources and returns an <see cref="System.Drawing.Bitmap">Bitmap</see> instance to the caller.
/// </summary>
/// <param name="bmpNamespace">bitmap namespace used for loading the resource</param>
/// <param name="name">name of the bitmap file/resource</param>
/// <returns>Returns an <see cref="System.Drawing.Bitmap">Bitmap</see> instance to the caller.</returns>
/// <remarks>The bitmap namespace will be combined with the <see cref="DefaultNamespace">DefaultNamespace</see> property.</remarks>
public Bitmap LoadBitmap(string bmpNamespace, string name)
{
string fullNamePrefix = CombineResource(DefaultNamespace, bmpNamespace);
return new Bitmap(ResourceAssembly.GetManifestResourceStream(CombineResource(fullNamePrefix, name)));
}
/// <summary>
/// Loads a bitmap from the combined resources and returns an <see cref="System.Drawing.Icon">Icon</see> instance to the caller.
/// </summary>
/// <param name="name">name of the icon file/resource</param>
/// <returns>Returns an <see cref="System.Drawing.Bitmap">Bitmap</see> instance to the caller.</returns>
public Icon LoadIcon(string name)
{
return LoadIcon(DefaultBitmapNamespace, name);
}
/// <summary>
/// Loads an icon from the combined resources and returns an <see cref="System.Drawing.Icon">Icon</see> instance to the caller.
/// </summary>
/// <param name="bmpNamespace">bitmap namespace used for loading the resource</param>
/// <param name="name">name of the icon file/resource</param>
/// <returns>Returns an <see cref="System.Drawing.Icon">Icon</see> instance to the caller.</returns>
/// <remarks>The bitmap namespace will be combined with the <see cref="DefaultNamespace">DefaultNamespace</see> property.</remarks>
public Icon LoadIcon(string bmpNamespace, string name)
{
string fullNamePrefix = CombineResource(DefaultNamespace, bmpNamespace);
return new Icon(ResourceAssembly.GetManifestResourceStream(CombineResource(fullNamePrefix, name)));
}
/// <summary>
/// Loads a resource string from.
/// </summary>
/// <param name="name">name of the string resource</param>
/// <returns>Returns a string value for the given resource name</returns>
public string GetString(string name)
{
return GetString(DefaultStringNamespace, name);
}
/// <summary>
/// Loads a resource string from.
/// </summary>
/// <param name="strNamespace">namespace for loading string resources</param>
/// <param name="name">name of the string resource</param>
/// <returns>Returns a string value for the given resource name</returns>
/// <remarks>The string namespace will be combined with the <see cref="DefaultNamespace">DefaultNamespace</see> property.</remarks>
public string GetString(string strNamespace, string name)
{
m_resourceManager = new ResourceManager(CombineResource(_defaultNamespace, strNamespace), _resAssembly);
return m_resourceManager.GetString(name);
}
/// <summary>
/// Combines two namespacestrings into one.
/// </summary>
/// <param name="namePrefix">namespace prefix</param>
/// <param name="resourceName">resource name or sub namespace</param>
/// <returns>A combine resource name or resource namespace name</returns>
private string CombineResource(string namePrefix, string resourceName)
{
if( namePrefix[ namePrefix.Length-1 ] != '.')
namePrefix += ".";
return namePrefix + resourceName;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace Palaso.UI.WindowsForms.Widgets
{
/// ----------------------------------------------------------------------------------------
public class XButton : Label
{
public delegate bool DrawBackgroundHandler(XButton button, PaintEventArgs e, PaintState state);
public event DrawBackgroundHandler DrawBackground;
private bool m_drawLeftArrowButton;
private bool m_drawRightArrowButton;
private bool m_checked;
private bool m_mouseDown;
private bool m_mouseOver;
private PaintState m_state = PaintState.Normal;
/// ------------------------------------------------------------------------------------
public XButton()
{
base.AutoSize = false;
base.BackColor = SystemColors.Control;
base.Font = new Font("Marlett", 9, GraphicsUnit.Point);
Size = new Size(16, 16);
SetStyle(ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer, true);
FormatFlags = TextFormatFlags.NoPadding |
TextFormatFlags.HorizontalCenter | TextFormatFlags.NoPrefix |
TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine |
TextFormatFlags.PreserveGraphicsClipping;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets or sets a value indicating whether or not the button's checked state changes
/// when clicked.
/// </summary>
/// ------------------------------------------------------------------------------------
public bool CanBeChecked { get; set; }
/// ------------------------------------------------------------------------------------
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public TextFormatFlags FormatFlags { get; set; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets or sets a value indicating whether or not the button is checked.
/// </summary>
/// ------------------------------------------------------------------------------------
public bool Checked
{
get { return m_checked; }
set
{
if (CanBeChecked)
{
m_checked = value;
Invalidate();
}
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets or sets a value indicating whether or not an X is drawn on the button when no
/// image, text or arrow direction is specified. By default, when no image, text or
/// arrow direction is specified, the button is drawn with an X (like a close window-
/// type of X). However, when DrawEmtpy is true, nothing will be drawn except the
/// highlighted look given when the mouse is over or down or when the button is checked.
/// </summary>
/// ------------------------------------------------------------------------------------
public bool DrawEmpty { get; set; }
/// ------------------------------------------------------------------------------------
public new Image Image
{
get { return base.Image; }
set
{
base.Image = value;
if (value != null)
{
m_drawLeftArrowButton = false;
m_drawRightArrowButton = false;
}
OnSystemColorsChanged(null);
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets or sets a value indicating whether or not the button should be drawn with a
/// left pointing arrow (like the left button of a horizontal scrollbar).
/// </summary>
/// ------------------------------------------------------------------------------------
public bool DrawLeftArrowButton
{
get { return m_drawLeftArrowButton; }
set
{
m_drawLeftArrowButton = value;
if (value)
{
m_drawRightArrowButton = false;
base.Image = null;
}
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets or sets a value indicating whether or not the button should be drawn with a
/// right pointing arrow (like the right button of a horizontal scrollbar).
/// </summary>
/// ------------------------------------------------------------------------------------
public bool DrawRightArrowButton
{
get { return m_drawRightArrowButton; }
set
{
m_drawRightArrowButton = value;
if (value)
{
m_drawLeftArrowButton = false;
base.Image = null;
}
}
}
/// ------------------------------------------------------------------------------------
public void PerformClick()
{
InvokeOnClick(this, EventArgs.Empty);
}
/// ------------------------------------------------------------------------------------
protected override void OnSystemColorsChanged(EventArgs e)
{
base.OnSystemColorsChanged(e);
if (Image != null)
BackColor = Color.Transparent;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Repaint the button when the mouse isn't over it.
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
m_mouseOver = false;
Invalidate();
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Change appearance when mouse is pressed.
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
{
m_mouseDown = true;
Invalidate();
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Change appearance when the mouse button is released.
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button == MouseButtons.Left)
{
m_mouseDown = false;
Invalidate();
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Track when the mouse leaves the control when a mouse button is pressed.
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
m_mouseOver = ClientRectangle.Contains(e.Location);
PaintState newState = (m_mouseOver ? PaintState.Hot : PaintState.Normal);
if (m_mouseOver && m_mouseDown)
newState = PaintState.HotDown;
if (newState != m_state)
{
m_state = newState;
Invalidate();
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
if (m_mouseOver || Checked)
m_state = (m_mouseDown ? PaintState.HotDown : PaintState.Hot);
else
m_state = PaintState.Normal;
if (DrawBackground != null && DrawBackground(this, e, m_state))
return;
Rectangle rc = ClientRectangle;
using (SolidBrush br = new SolidBrush(BackColor))
e.Graphics.FillRectangle(br, rc);
if (m_state != PaintState.Normal)
PaintingHelper.DrawHotBackground(e.Graphics, rc, m_state);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnPaint(PaintEventArgs e)
{
if (Image != null)
DrawWithImage(e);
else if (m_drawLeftArrowButton || m_drawRightArrowButton)
DrawArrow(e);
else if (!string.IsNullOrEmpty(Text))
DrawText(e);
else if (!DrawEmpty)
DrawWithX(e);
else
base.OnPaint(e);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Draws the button's text.
/// </summary>
/// ------------------------------------------------------------------------------------
public void DrawText(PaintEventArgs e)
{
Color clr = (Enabled ? ForeColor : SystemColors.GrayText);
TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, clr, FormatFlags);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Draw the button with text.
/// </summary>
/// ------------------------------------------------------------------------------------
private void DrawWithX(PaintEventArgs e)
{
Rectangle rc = ClientRectangle;
Color clr = (m_state == PaintState.Normal ? SystemColors.ControlDarkDark :
SystemColors.ControlText);
// The 'r' in the Marlette font is the close button symbol 'X'
TextRenderer.DrawText(e.Graphics, "r", Font, rc, clr, FormatFlags);
// Draw the border around the button.
rc.Width--;
rc.Height--;
using (Pen pen = new Pen(clr))
e.Graphics.DrawRectangle(pen, rc);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Draws the button with an image.
/// </summary>
/// ------------------------------------------------------------------------------------
private void DrawWithImage(PaintEventArgs e)
{
if (Image == null)
return;
int x = (Width - Image.Width) / 2;
int y = (Height - Image.Height) / 2;
Rectangle rc = new Rectangle(x, y, Image.Width, Image.Height);
if (Enabled)
e.Graphics.DrawImageUnscaledAndClipped(Image, rc);
else
ControlPaint.DrawImageDisabled(e.Graphics, Image, x, y, SystemColors.Control);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Draws the button with an image.
/// </summary>
/// ------------------------------------------------------------------------------------
public void DrawArrow(PaintEventArgs e)
{
Rectangle rc = ClientRectangle;
// If possible, render the button with visual styles. Otherwise,
// paint the plain Windows 2000 push button.
var element = GetCorrectVisualStyleArrowElement();
if (PaintingHelper.CanPaintVisualStyle(element))
{
VisualStyleRenderer renderer = new VisualStyleRenderer(element);
renderer.DrawParentBackground(e.Graphics, rc, this);
renderer.DrawBackground(e.Graphics, rc);
return;
}
if (Font.SizeInPoints != 12)
Font = new Font(Font.FontFamily, 12, GraphicsUnit.Point);
ControlPaint.DrawButton(e.Graphics, rc,
(m_state == PaintState.HotDown ? ButtonState.Pushed : ButtonState.Normal));
// In the Marlette font, '3' is the left arrow and '4' is the right.
string arrowGlyph = (m_drawLeftArrowButton ? "3" : "4");
Color clr = (Enabled ? SystemColors.ControlText : SystemColors.GrayText);
// The 'r' in the Marlette font is the close button symbol 'X'
TextRenderer.DrawText(e.Graphics, arrowGlyph, Font, rc, clr, FormatFlags);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the correct visual style arrow button and in the correct state.
/// </summary>
/// ------------------------------------------------------------------------------------
private VisualStyleElement GetCorrectVisualStyleArrowElement()
{
if (m_drawLeftArrowButton)
{
if (!Enabled)
return VisualStyleElement.Spin.DownHorizontal.Disabled;
if (m_state == PaintState.Normal)
return VisualStyleElement.Spin.DownHorizontal.Normal;
return (m_state == PaintState.Hot ?
VisualStyleElement.Spin.DownHorizontal.Hot :
VisualStyleElement.Spin.DownHorizontal.Pressed);
}
if (!Enabled)
return VisualStyleElement.Spin.UpHorizontal.Disabled;
if (m_state == PaintState.Normal)
return VisualStyleElement.Spin.UpHorizontal.Normal;
return (m_state == PaintState.Hot ?
VisualStyleElement.Spin.UpHorizontal.Hot :
VisualStyleElement.Spin.UpHorizontal.Pressed);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/**
This testcase attempts to delete some directories in a mounted volume
- Different drive is mounted on the current drive
- Current drive is mounted on a different drive
- Current drive is mounted on current directory
- refer to the directory in a recursive manner in addition to the normal one
**/
using System;
using System.IO;
using System.Text;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
public class Directory_Delete_MountVolume
{
private delegate void ExceptionCode();
private static bool s_pass = true;
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(PlatformID.Windows)] // testing volumes / mounts / drive letters
public static void RunTest()
{
try
{
const String MountPrefixName = "LaksMount";
String mountedDirName;
String dirName;
String dirNameWithoutRoot;
String dirNameReferedFromMountedDrive;
//Adding debug info since this test hangs sometime in RTS runs
String debugFileName = "Co7604Delete_MountVolume_Debug.txt";
DeleteFile(debugFileName);
String scenarioDescription;
scenarioDescription = "Scenario 1: Vanilla - Different drive is mounted on the current drive";
try
{
File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine));
string otherDriveInMachine = IOServices.GetNtfsDriveOtherThanCurrent();
//out labs use UIP tools in one drive and dont expect this drive to be used by others. We avoid this problem by not testing if the other drive is not NTFS
if (FileSystemDebugInfo.IsCurrentDriveNTFS() && otherDriveInMachine != null)
{
Console.WriteLine(scenarioDescription);
mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Path.DirectorySeparatorChar.ToString(), MountPrefixName));
try
{
Directory.CreateDirectory(mountedDirName);
File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", otherDriveInMachine.Substring(0, 2), mountedDirName, Environment.NewLine));
MountHelper.Mount(otherDriveInMachine.Substring(0, 2), mountedDirName);
dirName = ManageFileSystem.GetNonExistingDir(otherDriveInMachine, ManageFileSystem.DirPrefixName);
File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine));
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
Eval(Directory.Exists(dirName), "Err_3974g! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName));
//Lets refer to these via mounted drive and check
dirNameWithoutRoot = dirName.Substring(3);
dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot);
Directory.Delete(dirNameReferedFromMountedDrive, true);
Task.Delay(300).Wait();
Eval(!Directory.Exists(dirName), "Err_20387g! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName));
}
}
finally
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine));
}
else
File.AppendAllText(debugFileName, String.Format("Scenario 1 - Vanilla - NOT RUN: Different drive is mounted on the current drive {0}", Environment.NewLine));
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_768lme! Exception caught in scenario: {0}", ex);
}
scenarioDescription = "Scenario 2: Current drive is mounted on a different drive";
Console.WriteLine(scenarioDescription);
File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine));
try
{
string otherDriveInMachine = IOServices.GetNtfsDriveOtherThanCurrent();
if (otherDriveInMachine != null)
{
mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(otherDriveInMachine.Substring(0, 3), MountPrefixName));
try
{
Directory.CreateDirectory(mountedDirName);
File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine));
MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName);
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine));
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
Eval(Directory.Exists(dirName), "Err_239ufz! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName));
//Lets refer to these via mounted drive and check
dirNameWithoutRoot = dirName.Substring(3);
dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot);
Directory.Delete(dirNameReferedFromMountedDrive, true);
Task.Delay(300).Wait();
Eval(!Directory.Exists(dirName), "Err_794aiu! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName));
}
}
finally
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine));
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_231vwf! Exception caught in scenario: {0}", ex);
}
//scenario 3.1: Current drive is mounted on current drive
scenarioDescription = "Scenario 3.1 - Current drive is mounted on current drive";
try
{
if (FileSystemDebugInfo.IsCurrentDriveNTFS())
{
File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine));
mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Path.DirectorySeparatorChar.ToString(), MountPrefixName));
try
{
Directory.CreateDirectory(mountedDirName);
File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine));
MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName);
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine));
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
Eval(Directory.Exists(dirName), "Err_324eez! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName));
//Lets refer to these via mounted drive and check
dirNameWithoutRoot = dirName.Substring(3);
dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot);
Directory.Delete(dirNameReferedFromMountedDrive, true);
Task.Delay(300).Wait();
Eval(!Directory.Exists(dirName), "Err_195whv! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName));
}
}
finally
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine));
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_493ojg! Exception caught in scenario: {0}", ex);
}
//scenario 3.2: Current drive is mounted on current directory
scenarioDescription = "Scenario 3.2 - Current drive is mounted on current directory";
try
{
if (FileSystemDebugInfo.IsCurrentDriveNTFS())
{
File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine));
mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), MountPrefixName));
try
{
Directory.CreateDirectory(mountedDirName);
File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine));
MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName);
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine));
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
Eval(Directory.Exists(dirName), "Err_951ipb! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName));
//Lets refer to these via mounted drive and check
dirNameWithoutRoot = dirName.Substring(3);
dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot);
Directory.Delete(dirNameReferedFromMountedDrive, true);
Task.Delay(300).Wait();
Eval(!Directory.Exists(dirName), "Err_493yin! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName));
}
}
finally
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine));
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_432qcp! Exception caught in scenario: {0}", ex);
}
//@WATCH - potentially dangerous code - can delete the whole drive!!
//scenario 3.3: we call delete on the mounted volume - this should only delete the mounted drive?
//Current drive is mounted on current directory
scenarioDescription = "Scenario 3.3 - we call delete on the mounted volume";
try
{
if (FileSystemDebugInfo.IsCurrentDriveNTFS())
{
File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine));
mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), MountPrefixName));
try
{
Directory.CreateDirectory(mountedDirName);
File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine));
MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName);
Directory.Delete(mountedDirName, true);
Task.Delay(300).Wait();
}
finally
{
if (!Eval(!Directory.Exists(mountedDirName), "Err_001yph! Directory {0} still exist: {1}", mountedDirName, Directory.Exists(mountedDirName)))
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
}
File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine));
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_386rpj! Exception caught in scenario: {0}", ex);
}
//@WATCH - potentially dangerous code - can delete the whole drive!!
//scenario 3.4: we call delete on parent directory of the mounted volume, the parent directoriy will have some other directories and files
//Current drive is mounted on current directory
scenarioDescription = "Scenario 3.4 - we call delete on parent directory of the mounted volume, the parent directoriy will have some other directories and files";
try
{
if (FileSystemDebugInfo.IsCurrentDriveNTFS())
{
File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine));
mountedDirName = null;
try
{
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine));
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 2, 20))
{
Eval(Directory.Exists(dirName), "Err_469yvh! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName));
String[] dirs = fileManager.GetDirectories(1);
mountedDirName = Path.GetFullPath(dirs[0]);
if (Eval(Directory.GetDirectories(mountedDirName).Length == 0, "Err_974tsg! the sub directory has directories: {0}", mountedDirName))
{
foreach (String file in Directory.GetFiles(mountedDirName))
File.Delete(file);
if (Eval(Directory.GetFiles(mountedDirName).Length == 0, "Err_13ref! the mounted directory has files: {0}", mountedDirName))
{
File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine));
MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName);
//now lets call delete on the parent directory
Directory.Delete(dirName, true);
Task.Delay(300).Wait();
Eval(!Directory.Exists(dirName), "Err_006jsf! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName));
Console.WriteLine("Completed Scenario 3.4");
}
}
}
}
finally
{
if (!Eval(!Directory.Exists(mountedDirName), "Err_625ckx! Directory {0} still exist: {1}", mountedDirName, Directory.Exists(mountedDirName)))
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
}
File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine));
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_578tni! Exception caught in scenario: {0}", ex);
}
//@WATCH - potentially dangerous code - can delete the whole drive!!
//scenario 3.5: we call delete on parent directory of the mounted volume, the parent directoriy will have some other directories and files
//we call a different directory than the first
//Current drive is mounted on current directory
scenarioDescription = "Scenario 3.5 - we call delete on parent directory of the mounted volume, the parent directoriy will have some other directories and files";
try
{
if (FileSystemDebugInfo.IsCurrentDriveNTFS())
{
File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine));
mountedDirName = null;
try
{
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine));
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 2, 30))
{
Eval(Directory.Exists(dirName), "Err_715tdq! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName));
String[] dirs = fileManager.GetDirectories(1);
mountedDirName = Path.GetFullPath(dirs[0]);
if (dirs.Length > 1)
mountedDirName = Path.GetFullPath(dirs[1]);
if (Eval(Directory.GetDirectories(mountedDirName).Length == 0, "Err_492qwl! the sub directory has directories: {0}", mountedDirName))
{
foreach (String file in Directory.GetFiles(mountedDirName))
File.Delete(file);
if (Eval(Directory.GetFiles(mountedDirName).Length == 0, "Err_904kij! the mounted directory has files: {0}", mountedDirName))
{
File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine));
MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName);
//now lets call delete on the parent directory
Directory.Delete(dirName, true);
Task.Delay(300).Wait();
Eval(!Directory.Exists(dirName), "Err_900edl! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName));
Console.WriteLine("Completed Scenario 3.5: {0}", mountedDirName);
}
}
}
}
finally
{
if (!Eval(!Directory.Exists(mountedDirName), "Err_462xtc! Directory {0} still exist: {1}", mountedDirName, Directory.Exists(mountedDirName)))
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
}
File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine));
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_471jli! Exception caught in scenario: {0}", ex);
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_234rsgf! Uncaught exception in RunTest: {0}", ex);
}
finally
{
Assert.True(s_pass);
}
}
private static void DeleteFile(String debugFileName)
{
if (File.Exists(debugFileName))
File.Delete(debugFileName);
}
private static void DeleteDir(String debugFileName, bool sub)
{
bool deleted = false; int maxAttempts = 5;
while (!deleted && maxAttempts > 0)
{
if (Directory.Exists(debugFileName))
{
try
{
Directory.Delete(debugFileName, sub);
deleted = true;
}
catch (Exception)
{
if (--maxAttempts == 0)
throw;
else
Task.Delay(300).Wait();
}
}
}
}
//Checks for error
private static bool Eval(bool expression, String msg, params Object[] values)
{
return Eval(expression, String.Format(msg, values));
}
private static bool Eval<T>(T actual, T expected, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return retValue;
}
private static bool Eval(bool expression, String msg)
{
if (!expression)
{
s_pass = false;
Console.WriteLine(msg);
}
return expression;
}
//Checks for a particular type of exception
private static void CheckException<E>(ExceptionCode test, string error)
{
CheckException<E>(test, error, null);
}
//Checks for a particular type of exception and an Exception msg in the English locale
private static void CheckException<E>(ExceptionCode test, string error, String msgExpected)
{
bool exception = false;
try
{
test();
error = String.Format("{0} Exception NOT thrown ", error);
}
catch (Exception e)
{
if (e.GetType() == typeof(E))
{
exception = true;
if (System.Globalization.CultureInfo.CurrentUICulture.Name == "en-US" && msgExpected != null && e.Message != msgExpected)
{
exception = false;
error = String.Format("{0} Message Different: <{1}>", error, e.Message);
}
}
else
error = String.Format("{0} Exception type: {1}", error, e.GetType().Name);
}
Eval(exception, error);
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.IO;
using System.Text;
namespace Abc.Zebus.Serialization.Protobuf
{
/// <summary>
/// Encodes and writes protocol message fields.
/// </summary>
/// <remarks>
/// <para>
/// This class is generally used by generated code to write appropriate
/// primitives to the stream. It effectively encapsulates the lowest
/// levels of protocol buffer format. Unlike some other implementations,
/// this does not include combined "write tag and value" methods. Generated
/// code knows the exact byte representations of the tags they're going to write,
/// so there's no need to re-encode them each time. Manually-written code calling
/// this class should just call one of the <c>WriteTag</c> overloads before each value.
/// </para>
/// <para>
/// Repeated fields and map fields are not handled by this class; use <c>RepeatedField<T></c>
/// and <c>MapField<TKey, TValue></c> to serialize such fields.
/// </para>
/// </remarks>
internal sealed partial class CodedOutputStream
{
// "Local" copy of Encoding.UTF8, for efficiency. (Yes, it makes a difference.)
internal static readonly Encoding Utf8Encoding = Encoding.UTF8;
/// <summary>
/// The buffer size used by CreateInstance(Stream).
/// </summary>
public static readonly int DefaultBufferSize = 4096;
private byte[] buffer;
private int position;
private int? savedPosition;
#region Construction
public CodedOutputStream() : this(new byte[DefaultBufferSize])
{
}
/// <summary>
/// Creates a new CodedOutputStream that writes directly to the given
/// byte array. If more bytes are written than fit in the array,
/// OutOfSpaceException will be thrown.
/// </summary>
public CodedOutputStream(byte[] buffer)
{
this.buffer = buffer;
}
#endregion
public byte[] Buffer { get { return buffer; } }
/// <summary>
/// Returns the current position in the stream, or the position in the output buffer
/// </summary>
public int Position
{
get { return position; }
}
public void Reset()
{
position = 0;
savedPosition = null;
}
public byte[] ToArray()
{
var buffer = new byte[position];
ByteArray.Copy(Buffer, 0, buffer, 0, position);
return buffer;
}
public void SavePosition()
{
savedPosition = position;
}
public bool TryWriteBoolAtSavedPosition(bool value)
{
if (savedPosition == null)
return false;
buffer[savedPosition.Value] = value ? (byte)1 : (byte)0;
return true;
}
#region Writing of values (not including tags)
/// <summary>
/// Writes a double field value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteDouble(double value)
{
WriteRawLittleEndian64((ulong)BitConverter.DoubleToInt64Bits(value));
}
/// <summary>
/// Writes a float field value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteFloat(float value)
{
byte[] rawBytes = BitConverter.GetBytes(value);
if (!BitConverter.IsLittleEndian)
{
ByteArray.Reverse(rawBytes);
}
if (buffer.Length - position >= 4)
{
buffer[position++] = rawBytes[0];
buffer[position++] = rawBytes[1];
buffer[position++] = rawBytes[2];
buffer[position++] = rawBytes[3];
}
else
{
WriteRawBytes(rawBytes, 0, 4);
}
}
/// <summary>
/// Writes a uint64 field value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteUInt64(ulong value)
{
WriteRawVarint64(value);
}
/// <summary>
/// Writes an int64 field value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteInt64(long value)
{
WriteRawVarint64((ulong) value);
}
/// <summary>
/// Writes an int32 field value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteInt32(int value)
{
if (value >= 0)
{
WriteRawVarint32((uint) value);
}
else
{
// Must sign-extend.
WriteRawVarint64((ulong) value);
}
}
/// <summary>
/// Writes a fixed64 field value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteFixed64(ulong value)
{
WriteRawLittleEndian64(value);
}
/// <summary>
/// Writes a fixed32 field value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteFixed32(uint value)
{
WriteRawLittleEndian32(value);
}
/// <summary>
/// Writes a bool field value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteBool(bool value)
{
WriteRawByte(value ? (byte) 1 : (byte) 0);
}
/// <summary>
/// Writes a string field value, without a tag, to the stream.
/// The data is length-prefixed.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteString(string value)
{
int length = Utf8Encoding.GetByteCount(value);
WriteString(value, length);
}
/// <summary>
/// Writes a string field value, without a tag, to the stream.
/// The data is length-prefixed.
/// </summary>
/// <param name="value">The value to write</param>
/// <param name="length"></param>
public void WriteString(string value, int length)
{
// Optimise the case where we have enough space to write
// the string directly to the buffer, which should be common.
WriteLength(length);
if (buffer.Length - position >= length)
{
if (length == value.Length) // Must be all ASCII...
{
for (int i = 0; i < length; i++)
{
buffer[position + i] = (byte)value[i];
}
}
else
{
Utf8Encoding.GetBytes(value, 0, value.Length, buffer, position);
}
position += length;
}
else
{
byte[] bytes = Utf8Encoding.GetBytes(value);
WriteRawBytes(bytes);
}
}
/// <summary>
/// Writes a uint32 value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteUInt32(uint value)
{
WriteRawVarint32(value);
}
/// <summary>
/// Writes an enum value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteEnum(int value)
{
WriteInt32(value);
}
/// <summary>
/// Writes an sfixed32 value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write.</param>
public void WriteSFixed32(int value)
{
WriteRawLittleEndian32((uint) value);
}
/// <summary>
/// Writes an sfixed64 value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteSFixed64(long value)
{
WriteRawLittleEndian64((ulong) value);
}
/// <summary>
/// Writes an sint32 value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteSInt32(int value)
{
WriteRawVarint32(EncodeZigZag32(value));
}
/// <summary>
/// Writes an sint64 value, without a tag, to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteSInt64(long value)
{
WriteRawVarint64(EncodeZigZag64(value));
}
/// <summary>
/// Writes a length (in bytes) for length-delimited data.
/// </summary>
/// <remarks>
/// This method simply writes a rawint, but exists for clarity in calling code.
/// </remarks>
/// <param name="length">Length value, in bytes.</param>
public void WriteLength(int length)
{
WriteRawVarint32((uint) length);
}
#endregion
#region Raw tag writing
/// <summary>
/// Encodes and writes a tag.
/// </summary>
/// <param name="fieldNumber">The number of the field to write the tag for</param>
/// <param name="type">The wire format type of the tag to write</param>
public void WriteTag(int fieldNumber, WireFormat.WireType type)
{
WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type));
}
/// <summary>
/// Writes an already-encoded tag.
/// </summary>
/// <param name="tag">The encoded tag</param>
public void WriteTag(uint tag)
{
WriteRawVarint32(tag);
}
/// <summary>
/// Writes the given single-byte tag directly to the stream.
/// </summary>
/// <param name="b1">The encoded tag</param>
public void WriteRawTag(byte b1)
{
WriteRawByte(b1);
}
/// <summary>
/// Writes the given two-byte tag directly to the stream.
/// </summary>
/// <param name="b1">The first byte of the encoded tag</param>
/// <param name="b2">The second byte of the encoded tag</param>
public void WriteRawTag(byte b1, byte b2)
{
WriteRawByte(b1);
WriteRawByte(b2);
}
/// <summary>
/// Writes the given three-byte tag directly to the stream.
/// </summary>
/// <param name="b1">The first byte of the encoded tag</param>
/// <param name="b2">The second byte of the encoded tag</param>
/// <param name="b3">The third byte of the encoded tag</param>
public void WriteRawTag(byte b1, byte b2, byte b3)
{
WriteRawByte(b1);
WriteRawByte(b2);
WriteRawByte(b3);
}
/// <summary>
/// Writes the given four-byte tag directly to the stream.
/// </summary>
/// <param name="b1">The first byte of the encoded tag</param>
/// <param name="b2">The second byte of the encoded tag</param>
/// <param name="b3">The third byte of the encoded tag</param>
/// <param name="b4">The fourth byte of the encoded tag</param>
public void WriteRawTag(byte b1, byte b2, byte b3, byte b4)
{
WriteRawByte(b1);
WriteRawByte(b2);
WriteRawByte(b3);
WriteRawByte(b4);
}
/// <summary>
/// Writes the given five-byte tag directly to the stream.
/// </summary>
/// <param name="b1">The first byte of the encoded tag</param>
/// <param name="b2">The second byte of the encoded tag</param>
/// <param name="b3">The third byte of the encoded tag</param>
/// <param name="b4">The fourth byte of the encoded tag</param>
/// <param name="b5">The fifth byte of the encoded tag</param>
public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5)
{
WriteRawByte(b1);
WriteRawByte(b2);
WriteRawByte(b3);
WriteRawByte(b4);
WriteRawByte(b5);
}
#endregion
#region Underlying writing primitives
/// <summary>
/// Writes a 32 bit value as a varint. The fast route is taken when
/// there's enough buffer space left to whizz through without checking
/// for each byte; otherwise, we resort to calling WriteRawByte each time.
/// </summary>
internal void WriteRawVarint32(uint value)
{
// Optimize for the common case of a single byte value
if (value < 128 && position < buffer.Length)
{
buffer[position++] = (byte)value;
return;
}
while (value > 127 && position < buffer.Length)
{
buffer[position++] = (byte) ((value & 0x7F) | 0x80);
value >>= 7;
}
while (value > 127)
{
WriteRawByte((byte) ((value & 0x7F) | 0x80));
value >>= 7;
}
if (position < buffer.Length)
{
buffer[position++] = (byte) value;
}
else
{
WriteRawByte((byte) value);
}
}
internal void WriteRawVarint64(ulong value)
{
while (value > 127 && position < buffer.Length)
{
buffer[position++] = (byte) ((value & 0x7F) | 0x80);
value >>= 7;
}
while (value > 127)
{
WriteRawByte((byte) ((value & 0x7F) | 0x80));
value >>= 7;
}
if (position < buffer.Length)
{
buffer[position++] = (byte) value;
}
else
{
WriteRawByte((byte) value);
}
}
internal void WriteRawLittleEndian32(uint value)
{
if (position + 4 > buffer.Length)
{
WriteRawByte((byte) value);
WriteRawByte((byte) (value >> 8));
WriteRawByte((byte) (value >> 16));
WriteRawByte((byte) (value >> 24));
}
else
{
buffer[position++] = ((byte) value);
buffer[position++] = ((byte) (value >> 8));
buffer[position++] = ((byte) (value >> 16));
buffer[position++] = ((byte) (value >> 24));
}
}
internal void WriteRawLittleEndian64(ulong value)
{
if (position + 8 > buffer.Length)
{
WriteRawByte((byte) value);
WriteRawByte((byte) (value >> 8));
WriteRawByte((byte) (value >> 16));
WriteRawByte((byte) (value >> 24));
WriteRawByte((byte) (value >> 32));
WriteRawByte((byte) (value >> 40));
WriteRawByte((byte) (value >> 48));
WriteRawByte((byte) (value >> 56));
}
else
{
buffer[position++] = ((byte) value);
buffer[position++] = ((byte) (value >> 8));
buffer[position++] = ((byte) (value >> 16));
buffer[position++] = ((byte) (value >> 24));
buffer[position++] = ((byte) (value >> 32));
buffer[position++] = ((byte) (value >> 40));
buffer[position++] = ((byte) (value >> 48));
buffer[position++] = ((byte) (value >> 56));
}
}
internal void WriteRawByte(byte value)
{
EnsureCapacity(1);
buffer[position++] = value;
}
internal void WriteRawByte(uint value)
{
WriteRawByte((byte) value);
}
public void WriteGuid(Guid value)
{
EnsureCapacity(GuidSize + 1);
buffer[position++] = GuidSize; // length
var blob = value.ToByteArray();
buffer[position++] = 1 << 3 | 1; // tag
for (var i = 0; i < 8; i++)
{
buffer[position++] = blob[i];
}
buffer[position++] = 2 << 3 | 1; // tag
for (var i = 8; i < 16; i++)
{
buffer[position++] = blob[i];
}
}
/// <summary>
/// Writes out an array of bytes.
/// </summary>
internal void WriteRawBytes(byte[] value)
{
WriteRawBytes(value, 0, value.Length);
}
/// <summary>
/// Writes out part of an array of bytes.
/// </summary>
internal void WriteRawBytes(byte[] value, int offset, int length)
{
EnsureCapacity(length);
ByteArray.Copy(value, offset, buffer, position, length);
// We have room in the current buffer.
position += length;
}
public void WriteRawStream(Stream stream)
{
var length = (int)stream.Length;
EnsureCapacity(length);
stream.Position = 0;
var memoryStream = stream as MemoryStream;
if (memoryStream != null)
position += memoryStream.Read(buffer, position, length);
else
WriteRawStreamSlow(stream);
}
private void WriteRawStreamSlow(Stream stream)
{
const int blockSize = 4096;
while (true)
{
var readCount = stream.Read(buffer, position, blockSize);
position += readCount;
if (readCount != blockSize)
break;
}
}
private void EnsureCapacity(int length)
{
if (buffer.Length - position >= length)
return;
var newBufferLength = Math.Max(position + length, buffer.Length * 2);
var newBuffer = new byte[newBufferLength];
ByteArray.Copy(buffer, 0, newBuffer, 0, buffer.Length);
buffer = newBuffer;
}
#endregion
/// <summary>
/// Encode a 32-bit value with ZigZag encoding.
/// </summary>
/// <remarks>
/// ZigZag encodes signed integers into values that can be efficiently
/// encoded with varint. (Otherwise, negative values must be
/// sign-extended to 64 bits to be varint encoded, thus always taking
/// 10 bytes on the wire.)
/// </remarks>
internal static uint EncodeZigZag32(int n)
{
// Note: the right-shift must be arithmetic
return (uint) ((n << 1) ^ (n >> 31));
}
/// <summary>
/// Encode a 64-bit value with ZigZag encoding.
/// </summary>
/// <remarks>
/// ZigZag encodes signed integers into values that can be efficiently
/// encoded with varint. (Otherwise, negative values must be
/// sign-extended to 64 bits to be varint encoded, thus always taking
/// 10 bytes on the wire.)
/// </remarks>
internal static ulong EncodeZigZag64(long n)
{
return (ulong) ((n << 1) ^ (n >> 63));
}
private void RefreshBuffer()
{
position = 0;
}
/// <summary>
/// Indicates that a CodedOutputStream wrapping a flat byte array
/// ran out of space.
/// </summary>
public sealed class OutOfSpaceException : IOException
{
internal OutOfSpaceException()
: base("CodedOutputStream was writing to a flat byte array and ran out of space.")
{
}
}
/// <summary>
/// Flushes any buffered data to the underlying stream (if there is one).
/// </summary>
public void Flush()
{
position = 0;
}
/// <summary>
/// Verifies that SpaceLeft returns zero. It's common to create a byte array
/// that is exactly big enough to hold a message, then write to it with
/// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
/// the message was actually as big as expected, which can help bugs.
/// </summary>
public void CheckNoSpaceLeft()
{
if (SpaceLeft != 0)
{
throw new InvalidOperationException("Did not write as much data as expected.");
}
}
/// <summary>
/// If writing to a flat array, returns the space left in the array.
/// </summary>
public int SpaceLeft
{
get { return buffer.Length - position; }
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Drawing.Printing;
using System.Reflection;
using System.Text;
using PCSComUtils.Common;
using PCSUtils.Utils;
using C1.Win.C1Preview;
using C1.C1Report;
using PCSUtils.Framework.ReportFrame;
using C1PrintPreviewDialog = PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog;
namespace PurchaseReportImportPartByMaker
{
public class PurchaseReportImportPartByMaker : MarshalByRefObject, IDynamicReport
{
#region IDynamicReport Members
private string mConnectionString;
/// <summary>
/// ConnectionString, provide for the Dynamic Report
/// ALlow Dynamic Report to access the DataBase of PCS
/// </summary>
public string PCSConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
private ReportBuilder mReportBuilder;
/// <summary>
/// Report Builder Utility Object
/// Dynamic Report can use this object to render, modify, layout the report
/// </summary>
public ReportBuilder PCSReportBuilder
{
get { return mReportBuilder; }
set { mReportBuilder = value; }
}
private C1PrintPreviewControl mViewer;
/// <summary>
/// ReportViewer Object, provide for the DynamicReport,
/// allow Dynamic Report to manipulate with the REportViewer,
/// modify the report after rendered if needed
/// </summary>
public C1PrintPreviewControl PCSReportViewer
{
get { return mViewer; }
set { mViewer = value; }
}
private object mResult;
/// <summary>
/// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid
/// </summary>
public object Result
{
get { return mResult; }
set { mResult = value; }
}
private bool mUseEngine;
/// <summary>
/// Notify PCS whether the rendering report process is run by
/// this IDynamicReport
/// or the ReportViewer Engine (in the ReportViewer form)
/// </summary>
public bool UseReportViewerRenderEngine
{
get { return mUseEngine; }
set { mUseEngine = value; }
}
private string mReportFolder;
/// <summary>
/// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path )
/// </summary>
public string ReportDefinitionFolder
{
get { return mReportFolder; }
set { mReportFolder = value; }
}
private string mLayoutFile;
/// <summary>
/// Inform External Process about the Layout file
/// in which PCS instruct to use
/// (PCS will assign this property while ReportViewer Form execute,
/// ReportVIewer form will use the layout file in the report config entry to put in this property)
/// </summary>
public string ReportLayoutFile
{
get { return mLayoutFile; }
set { mLayoutFile = value; }
}
/// <summary>
///
/// </summary>
/// <param name="pstrMethod">name of the method to call (which declare in the DynamicReport C# file)</param>
/// <param name="pobjParameters">Array of parameters provide to call the Method with method name = pstrMethod</param>
/// <returns></returns>
public object Invoke(string pstrMethod, object[] pobjParameters)
{
return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters);
}
#endregion
public DataTable ExecuteReport(string pstrCCNID, string pstrYear, string pstrMonth, string pstrCurrencyID, string pstrExRate)
{
// start of month
DateTime dtmStartOfMonth = new DateTime(Convert.ToInt32(pstrYear), Convert.ToInt32(pstrMonth), 1);
// end of month
DateTime dtmEndOfMonth = dtmStartOfMonth.AddMonths(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);
DataTable dtbData = GetInvoice(pstrCCNID, dtmStartOfMonth, dtmEndOfMonth, pstrExRate);
#region report
C1Report rptReport = new C1Report();
mLayoutFile = "PurchaseReportImportPartByMaker.xml";
rptReport.Load(mReportFolder + "\\" + mLayoutFile, rptReport.GetReportInfo(mReportFolder + "\\" + mLayoutFile)[0]);
rptReport.Layout.PaperSize = PaperKind.A4;
#region report parameter
try
{
rptReport.Fields["fldCCN"].Text = GetCCN(pstrCCNID);
}
catch{}
try
{
rptReport.Fields["fldMonth"].Text = dtmStartOfMonth.ToString("MMM-yyyy");
}
catch{}
try
{
rptReport.Fields["fldCurrency"].Text = GetCurrency(pstrCurrencyID);
}
catch{}
try
{
rptReport.Fields["fldExRate"].Text = pstrExRate;
}
catch{}
#endregion
// set datasource object that provides data to report.
rptReport.DataSource.Recordset = dtbData;
// render report
rptReport.Render();
// render the report into the PrintPreviewControl
C1PrintPreviewDialog ppvViewer = new C1PrintPreviewDialog();
ppvViewer.FormTitle = "Purchase Report Import Part By Maker";
ppvViewer.ReportViewer.Document = rptReport.Document;
ppvViewer.Show();
#endregion
return dtbData;
}
private DataTable GetInvoice(string pstrCCNID, DateTime pdtmStartOfMonth, DateTime pdtmEndOfMonth, string pstrExRate)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "SELECT SUM(CIPAmount * PO_InvoiceMaster.ExchangeRate)/? AS CIP, SUM(InvoiceQuantity) AS Quantity, "
+ " SUM(InvoiceQuantity * PO_PurchaseOrderDetail.UnitPrice * PO_PurchaseOrderMaster.ExchangeRate)/? AS EXGO,"
+ " PO_PurchaseOrderMaster.MakerID, MST_Party.Code AS Maker"
+ " FROM PO_InvoiceDetail JOIN PO_InvoiceMaster"
+ " ON PO_InvoiceDetail.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID"
+ " JOIN PO_PurchaseOrderMaster"
+ " ON PO_InvoiceDetail.PurchaseOrderMasterID = PO_PurchaseOrderMaster.PurchaseOrderMasterID"
+ " JOIN PO_PurchaseOrderDetail"
+ " ON PO_InvoiceDetail.PurchaseOrderDetailID = PO_PurchaseOrderDetail.PurchaseOrderDetailID"
+ " JOIN MST_Party"
+ " ON PO_PurchaseOrderMaster.MakerID = MST_Party.PartyID"
+ " WHERE PO_InvoiceMaster.CCNID = " + pstrCCNID
+ " AND PO_InvoiceMaster.PostDate >= ?"
+ " AND PO_InvoiceMaster.PostDate <= ?"
+ " AND MST_Party.CountryID <> (SELECT CountryID FROM MST_CCN WHERE CCNID = " + pstrCCNID + ")"
+ " AND MST_Party.Type <> 0"
+ " GROUP BY PO_PurchaseOrderMaster.MakerID, MST_Party.Code"
+ " ORDER BY MST_Party.Code";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Parameters.Add(new OleDbParameter("FirstNum", OleDbType.Decimal)).Value = pstrExRate;
ocmdPCS.Parameters.Add(new OleDbParameter("NextNum", OleDbType.Decimal)).Value = pstrExRate;
ocmdPCS.Parameters.Add(new OleDbParameter("StartOfMonth", OleDbType.Date)).Value = pdtmStartOfMonth;
ocmdPCS.Parameters.Add(new OleDbParameter("EndOfMonth", OleDbType.Date)).Value = pdtmEndOfMonth;
ocmdPCS.Connection.Open();
DataTable dtbData = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private string GetCCN(string pstrCCNID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "SELECT Code + ' (' + Description + ')' FROM MST_CCN WHERE CCNID = " + pstrCCNID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
return objResult.ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private string GetCurrency(string pstrCurrencyID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "SELECT Code + ' (' + Name + ')' FROM MST_Currency WHERE CurrencyID = " + pstrCurrencyID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
return objResult.ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
}
}
| |
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
namespace Berrybrew
{
public class Berrybrew
{
static void Main(string[] args)
{
if (args.Length == 0)
{
PrintHelp();
Environment.Exit(0);
}
switch(args[0])
{
case "install":
if (args.Length == 1)
{
Console.WriteLine("install command requires a version argument. Use the available command to see what versions of Strawberry Perl are available");
Environment.Exit(0);
}
try
{
StrawberryPerl perl = ResolveVersion(args[1]);
string archive_path = Fetch(perl);
Extract(perl, archive_path);
Available();
}
catch (ArgumentException)
{
Console.WriteLine("Unknown version of Perl. Use the available command to see what versions of Strawberry Perl are available");
Environment.Exit(0);
}
break;
case "switch":
if (args.Length == 1)
{
Console.WriteLine("switch command requires a version argument. Use the available command to see what versions of Strawberry Perl are available");
Environment.Exit(0);
}
Switch(args[1]);
break;
case "available":
Available();
break;
case "config":
Config();
break;
case "remove":
if (args.Length == 1)
{
Console.WriteLine("remove command requires a version argument. Use the available command to see what versions of Strawberry Perl are available");
Environment.Exit(0);
}
RemovePerl(args[1]);
break;
case "exec":
if (args.Length == 1)
{
Console.WriteLine("exec command requires a command to run.");
Environment.Exit(0);
}
args[0] = "";
Exec(String.Join(" ", args).Trim());
break;
default:
PrintHelp();
break;
}
}
internal static void Exec (string command)
{
List<StrawberryPerl> perls_installed = GetInstalledPerls();
foreach (StrawberryPerl perl in perls_installed)
{
Console.WriteLine("Perl-" + perl.Name + "\n==============");
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c " + perl.PerlPath + @"\" + command;
process.StartInfo = startInfo;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.Start();
Console.WriteLine(process.StandardOutput.ReadToEnd());
Console.WriteLine(process.StandardError.ReadToEnd());
process.WaitForExit();
}
}
internal static bool PerlInstalled (StrawberryPerl perl)
{
if (Directory.Exists(perl.InstallPath)
&& File.Exists(perl.PerlPath + @"\perl.exe"))
{
return true;
}
return false;
}
internal static List<StrawberryPerl> GetInstalledPerls ()
{
List<StrawberryPerl> perls = GatherPerls();
List<StrawberryPerl> perls_installed = new List<StrawberryPerl>();
foreach (StrawberryPerl perl in perls)
{
if (PerlInstalled(perl))
perls_installed.Add(perl);
}
return perls_installed;
}
internal static void Config ()
{
Console.WriteLine("\nThis is berrybrew, version " + Version() + "\n");
if ( ! ScanUserPath(new Regex("berrybrew.bin"))
&& ! ScanSystemPath(new Regex("berrybrew.bin")) )
{
Console.Write("Would you like to add berrybrew to your user PATH? y/n [n] ");
if (Console.ReadLine() == "y")
{
//get the full path of the assembly
string assembly_path = Assembly.GetExecutingAssembly().Location;
//get the parent directory
string assembly_directory = Path.GetDirectoryName( assembly_path );
AddBinToPath(assembly_directory);
if (ScanUserPath(new Regex("berrybrew.bin")))
{
Console.WriteLine("berrybrew was successfully added to the user PATH, start a new terminal to use it.");
}
else
{
Console.WriteLine("Error adding berrybrew to the user PATH");
}
}
}
else
{
Console.Write("berrybrew is already configured on this system.\n");
}
}
internal static string Version ()
{
return "0.10";
}
internal static string Fetch (StrawberryPerl perl)
{
WebClient webClient = new WebClient();
string archive_path = GetDownloadPath(perl);
// Download if archive doesn't already exist
if (! File.Exists(archive_path))
{
Console.WriteLine("Downloading " + perl.Url + " to " + archive_path);
webClient.DownloadFile(perl.Url, archive_path);
}
Console.WriteLine("Confirming checksum ...");
using(var cryptoProvider = new SHA1CryptoServiceProvider())
{
using (var stream = File.OpenRead(archive_path))
{
string hash = BitConverter.ToString(cryptoProvider.ComputeHash(stream)).Replace("-","").ToLower();
if (perl.Sha1Checksum != hash)
{
Console.WriteLine("Error checksum of downloaded archive does not match expected output\nexpected: "
+ perl.Sha1Checksum
+ "\n got: " + hash);
Environment.Exit(0);
}
}
}
return archive_path;
}
internal static string GetDownloadPath (StrawberryPerl perl)
{
string path;
try
{
if (! Directory.Exists(perl.ArchivePath))
Directory.CreateDirectory(perl.ArchivePath);
return perl.ArchivePath + @"\" + perl.ArchiveName;
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Error, do not have permissions to create directory: " + perl.ArchivePath);
}
Console.WriteLine("Creating temporary directory instead");
do {
path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
} while (Directory.Exists(path));
Directory.CreateDirectory(path);
return path + @"\" + perl.ArchiveName;
}
internal static StrawberryPerl ResolveVersion (string version_to_resolve)
{
foreach (StrawberryPerl perl in GatherPerls())
{
if (perl.Name == version_to_resolve)
return perl;
}
throw new ArgumentException("Unknown version: " + version_to_resolve);
}
internal static void Extract (StrawberryPerl perl, string archive_path)
{
if (File.Exists(archive_path))
{
Console.WriteLine("Extracting " + archive_path);
ExtractZip(archive_path, perl.InstallPath);
}
}
internal static void Switch (string version_to_switch)
{
try {
StrawberryPerl perl = ResolveVersion(version_to_switch);
// if Perl version not installed, can't switch
if (! PerlInstalled(perl))
{
Console.WriteLine("Perl version " + perl.Name + " is not installed. Run the command:\n\n\tberrybrew install " + perl.Name);
Environment.Exit(0);
}
RemovePerlFromPath();
if (ScanUserPath(new Regex("perl.bin")))
{
Console.WriteLine("Warning! Perl binary found in your user PATH: "
+ "\nYou should remove this as it can prevent berrybrew from working.");
}
if (ScanSystemPath(new Regex("perl.bin")) )
{
Console.WriteLine("Warning! Perl binary found in your system PATH: "
+ "\nYou should remove this as it can prevent berrybrew from working.");
}
AddPerlToPath(perl);
Console.WriteLine("Switched to " + version_to_switch + ", start a new terminal to use it.");
}
catch (ArgumentException)
{
Console.WriteLine("Unknown version of Perl. Use the available command to see what versions of Strawberry Perl are available");
Environment.Exit(0);
}
}
internal static bool ScanUserPath(Regex bin_pattern)
{
string user_path = Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.User);
if (user_path != null)
{
foreach (string user_p in user_path.Split(';'))
{
if (bin_pattern.Match(user_p).Success)
return true;
}
}
return false;
}
internal static bool ScanSystemPath(Regex bin_pattern)
{
string system_path = Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Machine);
if (system_path != null)
{
foreach (string sys_p in system_path.Split(';'))
{
if (bin_pattern.Match(sys_p).Success)
return true;
}
}
return false;
}
internal static void RemovePerlFromPath()
{
// get user PATH and remove trailing semicolon if exists
string path = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User);
if (path != null)
{
string[] paths = path.Split(';');
foreach (StrawberryPerl perl in GatherPerls())
{
for (int i = 0; i < paths.Length; i++)
{
if (paths[i] == perl.PerlPath
|| paths[i] == perl.CPath
|| paths[i] == perl.PerlSitePath)
{
paths[i] = "";
}
}
}
// Update user path and parse out unnecessary semicolons
string new_path = String.Join(";", paths);
Regex multi_semicolon = new Regex(";{2,}");
new_path = multi_semicolon.Replace(new_path, ";");
Regex lead_semicolon = new Regex("^;");
new_path = lead_semicolon.Replace(new_path, "");
Environment.SetEnvironmentVariable("Path", new_path, EnvironmentVariableTarget.User);
}
}
internal static StrawberryPerl CheckWhichPerlInPath()
{
// get user PATH and remove trailing semicolon if exists
string path = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User);
StrawberryPerl current_perl = new StrawberryPerl();
if (path != null)
{
string[] paths = path.Split(';');
foreach (StrawberryPerl perl in GatherPerls())
{
for (int i = 0; i < paths.Length; i++)
{
if (paths[i] == perl.PerlPath
|| paths[i] == perl.CPath
|| paths[i] == perl.PerlSitePath)
{
current_perl = perl;
break;
}
}
}
}
return current_perl;
}
internal static void AddPerlToPath(StrawberryPerl perl)
{
// get user PATH and remove trailing semicolon if exists
string path = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User);
string[] new_path;
if (path == null)
{
new_path = new string[] { perl.CPath, perl.PerlPath, perl.PerlSitePath };
}
else
{
if (path[path.Length - 1] == ';')
path = path.Substring(0, path.Length - 1);
new_path = new string[] { path, perl.CPath, perl.PerlPath, perl.PerlSitePath };
}
Environment.SetEnvironmentVariable("PATH", String.Join(";", new_path), EnvironmentVariableTarget.User);
}
internal static void AddBinToPath(string bin_path)
{
// get user PATH and remove trailing semicolon if exists
string path = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User);
string[] new_path;
if (path == null)
{
new_path = new string[] { bin_path };
}
else
{
if (path[path.Length - 1] == ';')
path = path.Substring(0, path.Length - 1);
new_path = new string[] { path, bin_path };
}
Environment.SetEnvironmentVariable("PATH", String.Join(";", new_path), EnvironmentVariableTarget.User);
}
internal static void Available ()
{
List<StrawberryPerl> perls = GatherPerls();
Console.WriteLine("\nThe following Strawberry Perls are available:\n");
StrawberryPerl current_perl = CheckWhichPerlInPath();
string column_spaces = " ";
foreach (StrawberryPerl perl in perls)
{
// cheap printf
string name_to_print = perl.Name + column_spaces.Substring(0, column_spaces.Length - perl.Name.Length);
Console.Write("\t" + name_to_print);
if (PerlInstalled(perl))
Console.Write(" [installed]");
if (perl.Name == current_perl.Name)
Console.Write("*");
Console.Write("\n");
}
Console.WriteLine("\n* Currently using");
}
internal static void PrintHelp()
{
Console.WriteLine("\nThis is berrybrew, version " + Version() + "\n");
Console.WriteLine(@"
berrybrew <command> [option]
available List available Strawberry Perl versions and which are installed
config Add berrybrew to your PATH
install Download, extract and install a Strawberry Perl
remove Uninstall a Strawberry Perl
switch Switch to use a different Strawberry Perl
exec Run a command for every installed Strawberry Perl
");
}
// From https://github.com/icsharpcode/SharpZipLib
internal static void ExtractZip(string archive_path, string outFolder)
{
ZipFile zf = null;
try {
FileStream fs = File.OpenRead(archive_path);
zf = new ZipFile(fs);
foreach (ZipEntry zipEntry in zf) {
if (!zipEntry.IsFile) {
continue; // Ignore directories
}
String entryFileName = zipEntry.Name;
// to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
// Optionally match entrynames against a selection list here to skip as desired.
// The unpacked length is available in the zipEntry.Size property.
byte[] buffer = new byte[4096]; // 4K is optimum
Stream zipStream = zf.GetInputStream(zipEntry);
// Manipulate the output filename here as desired.
String fullZipToPath = Path.Combine(outFolder, entryFileName);
string directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0)
Directory.CreateDirectory(directoryName);
// Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
// of the file, but does not waste memory.
// The "using" will close the stream even if an exception occurs.
using (FileStream streamWriter = File.Create(fullZipToPath))
{
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
}
finally
{
if (zf != null) {
zf.IsStreamOwner = true; // Makes close also shut the underlying stream
zf.Close(); // Ensure we release resources
}
}
}
internal static List<StrawberryPerl> GatherPerls ()
{
List<StrawberryPerl> perls = new List<StrawberryPerl> ();
perls.Add(new StrawberryPerl (
"5.22.0_64",
"strawberry-perl-5.22.0.1-64bit-portable.zip",
"http://strawberryperl.com/download/5.22.0.1/strawberry-perl-5.22.0.1-64bit-portable.zip",
"5.22.0",
"ffc41fe8ebc03802ea59f4b88aa34a154af4d55d")
);
perls.Add(new StrawberryPerl (
"5.22.0_64_PDL",
"strawberry-perl-5.22.0.1-64bit-PDL.zip",
"9024ce63c2fe404e7488db827171a9262c5a4830",
"5.22.0",
"http://strawberryperl.com/download/5.22.0.1/strawberry-perl-5.22.0.1-64bit-PDL.zip")
);
perls.Add(new StrawberryPerl (
"5.22.0_32",
"strawberry-perl-5.22.0.1-32bit-portable.zip",
"http://strawberryperl.com/download/5.22.0.1/strawberry-perl-5.22.0.1-32bit-portable.zip",
"5.22.0",
"9769b6e140ad98a113741f34086c251af7849626")
);
perls.Add(new StrawberryPerl (
"5.22.0_32_PDL",
"strawberry-perl-5.22.0.1-32bit-PDL.zip",
"http://strawberryperl.com/download/5.22.0.1/strawberry-perl-5.22.0.1-32bit-PDL.zip",
"5.22.0",
"b55fa64331be2ef425d175c95023331d3478ef56")
);
perls.Add(new StrawberryPerl (
"5.20.3_64",
"strawberry-perl-5.20.2.1-64bit-portable.zip",
"http://strawberryperl.com/download/5.20.3.1/strawberry-perl-5.20.3.1-64bit-portable.zip",
"5.20.3",
"e1bf9e4f6965a5a1278a013a39f46f4c251221a0")
);
perls.Add(new StrawberryPerl (
"5.20.3_64_PDL",
"strawberry-perl-5.20.3.1-64bit-PDL.zip",
"http://strawberryperl.com/download/5.20.3.1/strawberry-perl-5.20.3.1-64bit-PDL.zip",
"5.20.3",
"50322e6b82db3a2811d0d8bc3390e5dbf9517467")
);
perls.Add(new StrawberryPerl (
"5.20.3_32",
"strawberry-perl-5.20.3.1-32bit-portable.zip",
"http://strawberryperl.com/download/5.20.3.1/strawberry-perl-5.20.3.1-32bit-portable.zip",
"5.20.3",
"69986aefb00f635d3e21eef32ce6bd717faaaf35")
);
perls.Add(new StrawberryPerl (
"5.20.3_32_PDL",
"strawberry-perl-5.20.3.1-32bit-PDL.zip",
"http://strawberryperl.com/download/5.20.3.1/strawberry-perl-5.20.3.1-32bit-PDL.zip",
"5.20.3",
"539f8e1a2e14c178dd186f5870e0802a749b2e7c")
);
perls.Add(new StrawberryPerl (
"5.18.4_64",
"strawberry-perl-5.18.4.1-64bit-portable.zip",
"http://strawberryperl.com/download/5.18.4.1/strawberry-perl-5.18.4.1-64bit-portable.zip",
"5.18.4",
"cd0809c5d885043d1f14a47f6192503359914d8a")
);
perls.Add(new StrawberryPerl (
"5.18.4_32",
"strawberry-perl-5.18.4.1-32bit-portable.zip",
"http://strawberryperl.com/download/5.18.4.1/strawberry-perl-5.18.4.1-32bit-portable.zip",
"5.18.4",
"f6118ba24e4430a7ddab1200746725f262117fbf")
);
perls.Add(new StrawberryPerl (
"5.16.3_64",
"strawberry-perl-5.16.3.1-64bit-portable.zip",
"http://strawberryperl.com/download/5.16.3.1/strawberry-perl-5.16.3.1-64bit-portable.zip",
"5.16.3",
"07573b99e40355a4920fc9c07fb594575a53c107")
);
perls.Add(new StrawberryPerl (
"5.16.3_32",
"strawberry-perl-5.16.3.1-32bit-portable.zip",
"http://strawberryperl.com/download/5.16.3.1/strawberry-perl-5.16.3.1-32bit-portable.zip",
"5.16.3",
"3b9c4c32bf29e141329c3be417d9c425a7f6c2ff")
);
perls.Add(new StrawberryPerl (
"5.14.4_64",
"strawberry-perl-5.14.4.1-64bit-portable.zip",
"http://strawberryperl.com/download/5.14.4.1/strawberry-perl-5.14.4.1-64bit-portable.zip",
"5.14.4",
"73ac65962e68f68cf551c3911ab81dcf6f73e018")
);
perls.Add(new StrawberryPerl (
"5.14.4_32",
"strawberry-perl-5.14.4.1-32bit-portable.zip",
"http://strawberryperl.com/download/5.14.4.1/strawberry-perl-5.14.4.1-32bit-portable.zip",
"5.14.4",
"42f092619704763d4c3cd4f3e1183d3e58d9d02c")
);
perls.Add(new StrawberryPerl (
"5.12.3_32",
"strawberry-perl-5.12.3.0-portable.zip",
"http://strawberryperl.com/download/5.12.3.0/strawberry-perl-5.12.3.0-portable.zip",
"5.12.3",
"dc6facf9fb7ce2de2e42ee65e84805a6d0dd5fbc")
);
perls.Add(new StrawberryPerl (
"5.10.1_32",
"strawberry-perl-5.10.1.2-portable.zip",
"http://strawberryperl.com/download/5.10.1.2/strawberry-perl-5.10.1.2-portable.zip",
"5.10.1",
"f86ae4b14daf0b1162d2c4c90a9d22e4c2452a98")
);
return perls;
}
internal static void RemovePerl(string version_to_remove)
{
try {
StrawberryPerl perl = ResolveVersion(version_to_remove);
StrawberryPerl current_perl = CheckWhichPerlInPath();
if (perl.Name == current_perl.Name)
{
Console.WriteLine("Removing Perl " + version_to_remove + " from PATH");
RemovePerlFromPath();
}
if (Directory.Exists(perl.InstallPath))
{
try
{
Directory.Delete(perl.InstallPath, true);
Console.WriteLine("Successfully removed Strawberry Perl " + version_to_remove);
}
catch (System.IO.IOException)
{
Console.WriteLine("Unable to completely remove Strawberry Perl " + version_to_remove + " some files may remain");
}
}
else
{
Console.WriteLine("Strawberry Perl " + version_to_remove + " not found (are you sure it's installed?");
Environment.Exit(0);
}
}
catch (ArgumentException)
{
Console.WriteLine("Unknown version of Perl. Use the available command to see what versions of Strawberry Perl are available");
Environment.Exit(0);
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Unable to remove Strawberry Perl " + version_to_remove + " permission was denied by System");
}
}
}
public struct StrawberryPerl
{
public string Name;
public string ArchiveName;
public string Url;
public string Version;
public string ArchivePath;
public string InstallPath;
public string CPath;
public string PerlPath;
public string PerlSitePath;
public string Sha1Checksum;
public StrawberryPerl (string n, string a, string u, string v, string c)
{
this.Name = n;
this.ArchiveName = a;
this.Url = u;
this.Version = v;
this.ArchivePath = @"C:\berrybrew\temp";
this.InstallPath = @"C:\berrybrew\" + n;
this.CPath = @"C:\berrybrew\" + n + @"\c\bin";
this.PerlPath = @"C:\berrybrew\" + n + @"\perl\bin";
this.PerlSitePath = @"C:\berrybrew\" + n + @"\perl\site\bin";
this.Sha1Checksum = c;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices
{
/// <summary>
/// Buffer that deals in char size increments. Dispose to free memory. Always makes ordinal
/// comparisons. Not thread safe.
///
/// A more performant replacement for StringBuilder when performing native interop.
///
/// "No copy" valuetype. Has to be passed as "ref".
///
/// </summary>
/// <remarks>
/// Suggested use through P/Invoke: define DllImport arguments that take a character buffer as SafeHandle and pass StringBuffer.GetHandle().
/// </remarks>
internal struct StringBuffer
{
private char[] _buffer;
private int _length;
/// <summary>
/// Instantiate the buffer with capacity for at least the specified number of characters. Capacity
/// includes the trailing null character.
/// </summary>
public StringBuffer(int initialCapacity)
{
_buffer = ArrayPool<char>.Shared.Rent(initialCapacity);
_length = 0;
}
/// <summary>
/// Get/set the character at the given index.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown if attempting to index outside of the buffer length.</exception>
public char this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (index >= _length) throw new ArgumentOutOfRangeException(nameof(index));
return _buffer[index];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
if (index >= _length) throw new ArgumentOutOfRangeException(nameof(index));
_buffer[index] = value;
}
}
/// <summary>
/// Underlying storage of the buffer. Used for interop.
/// </summary>
public char[] UnderlyingArray => _buffer;
/// <summary>
/// Character capacity of the buffer. Includes the count for the trailing null character.
/// </summary>
public int Capacity => _buffer.Length;
/// <summary>
/// Ensure capacity in characters is at least the given minimum.
/// </summary>
/// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception>
public void EnsureCapacity(int minCapacity)
{
if (minCapacity > Capacity)
{
char[] oldBuffer = _buffer;
_buffer = ArrayPool<char>.Shared.Rent(minCapacity);
Array.Copy(oldBuffer, 0, _buffer, 0, oldBuffer.Length);
ArrayPool<char>.Shared.Return(oldBuffer);
}
}
/// <summary>
/// The logical length of the buffer in characters. (Does not include the final null.) Will automatically attempt to increase capacity.
/// This is where the usable data ends.
/// </summary>
/// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the set size in bytes is int.MaxValue (as space is implicitly reserved for the trailing null).</exception>
public int Length
{
get { return _length; }
set
{
// Null terminate
EnsureCapacity(checked(value + 1));
_buffer[value] = '\0';
_length = value;
}
}
/// <summary>
/// True if the buffer contains the given character.
/// </summary>
public unsafe bool Contains(char value)
{
fixed (char* start = _buffer)
{
int length = _length;
for (int i = 0; i < length; i++)
{
if (start[i] == value) return true;
}
}
return false;
}
/// <summary>
/// Returns true if the buffer starts with the given string.
/// </summary>
public bool StartsWith(string value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
if (_length < value.Length) return false;
return SubstringEquals(value, startIndex: 0, count: value.Length);
}
/// <summary>
/// Returns true if the specified StringBuffer substring equals the given value.
/// </summary>
/// <param name="value">The value to compare against the specified substring.</param>
/// <param name="startIndex">Start index of the sub string.</param>
/// <param name="count">Length of the substring, or -1 to check all remaining.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range
/// of the buffer's length.
/// </exception>
public unsafe bool SubstringEquals(string value, int startIndex = 0, int count = -1)
{
if (value == null) return false;
if (count < -1) throw new ArgumentOutOfRangeException(nameof(count));
if (startIndex > _length) throw new ArgumentOutOfRangeException(nameof(startIndex));
int realCount = count == -1 ? _length - startIndex : (int)count;
if (checked(startIndex + realCount) > _length) throw new ArgumentOutOfRangeException(nameof(count));
int length = value.Length;
// Check the substring length against the input length
if (realCount != length) return false;
fixed (char* valueStart = value)
fixed (char* bufferStart = _buffer)
{
char* subStringStart = bufferStart + startIndex;
for (int i = 0; i < length; i++)
{
if (subStringStart[i] != valueStart[i]) return false;
}
}
return true;
}
/// <summary>
/// Append the given string.
/// </summary>
/// <param name="value">The string to append.</param>
/// <param name="startIndex">The index in the input string to start appending from.</param>
/// <param name="count">The count of characters to copy from the input string, or -1 for all remaining.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range
/// of <paramref name="value"/> characters.
/// </exception>
public void Append(string value, int startIndex = 0, int count = -1)
{
CopyFrom(
bufferIndex: _length,
source: value,
sourceIndex: startIndex,
count: count);
}
/// <summary>
/// Append the given buffer.
/// </summary>
/// <param name="value">The buffer to append.</param>
/// <param name="startIndex">The index in the input buffer to start appending from.</param>
/// <param name="count">The count of characters to copy from the buffer string.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range
/// of <paramref name="value"/> characters.
/// </exception>
public void Append(ref StringBuffer value, int startIndex = 0)
{
if (value.Length == 0) return;
value.CopyTo(
bufferIndex: startIndex,
destination: ref this,
destinationIndex: _length,
count: value.Length);
}
/// <summary>
/// Append the given buffer.
/// </summary>
/// <param name="value">The buffer to append.</param>
/// <param name="startIndex">The index in the input buffer to start appending from.</param>
/// <param name="count">The count of characters to copy from the buffer string.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range
/// of <paramref name="value"/> characters.
/// </exception>
public void Append(ref StringBuffer value, int startIndex, int count)
{
if (count == 0) return;
value.CopyTo(
bufferIndex: startIndex,
destination: ref this,
destinationIndex: _length,
count: count);
}
/// <summary>
/// Copy contents to the specified buffer. Destination index must be within current destination length.
/// Will grow the destination buffer if needed.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="bufferIndex"/> or <paramref name="destinationIndex"/> or <paramref name="count"/> are outside the range
/// of <paramref name="value"/> characters.
/// </exception>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="destination"/> is null.</exception>
public void CopyTo(int bufferIndex, ref StringBuffer destination, int destinationIndex, int count)
{
if (destinationIndex > destination._length) throw new ArgumentOutOfRangeException(nameof(destinationIndex));
if (bufferIndex >= _length) throw new ArgumentOutOfRangeException(nameof(bufferIndex));
if (_length < checked(bufferIndex + count)) throw new ArgumentOutOfRangeException(nameof(count));
if (count == 0) return;
int lastIndex = checked(destinationIndex + count);
if (destination.Length < lastIndex) destination.Length = lastIndex;
Array.Copy(UnderlyingArray, bufferIndex, destination.UnderlyingArray, destinationIndex, count);
}
/// <summary>
/// Copy contents from the specified string into the buffer at the given index. Start index must be within the current length of
/// the buffer, will grow as necessary.
/// </summary>
public void CopyFrom(int bufferIndex, string source, int sourceIndex = 0, int count = -1)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (bufferIndex > _length) throw new ArgumentOutOfRangeException(nameof(bufferIndex));
if (sourceIndex < 0 || sourceIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(sourceIndex));
if (count == -1) count = source.Length - sourceIndex;
if (count < 0 || source.Length - count < sourceIndex) throw new ArgumentOutOfRangeException(nameof(count));
if (count == 0) return;
int lastIndex = bufferIndex + (int)count;
if (_length < lastIndex) Length = lastIndex;
source.CopyTo(sourceIndex, UnderlyingArray, bufferIndex, count);
}
/// <summary>
/// Trim the specified values from the end of the buffer. If nothing is specified, nothing is trimmed.
/// </summary>
public void TrimEnd(char[] values)
{
if (values == null || values.Length == 0 || _length == 0) return;
while (_length > 0 && Array.IndexOf(values, _buffer[_length - 1]) >= 0)
{
Length = _length - 1;
}
}
/// <summary>
/// String representation of the entire buffer. If the buffer is larger than the maximum size string (int.MaxValue) this will throw.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the buffer is too big to fit into a string.</exception>
public override string ToString()
{
return new string(_buffer, startIndex: 0, length: _length);
}
/// <summary>
/// Get the given substring in the buffer.
/// </summary>
/// <param name="count">Count of characters to take, or remaining characters from <paramref name="startIndex"/> if -1.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range of the buffer's length
/// or count is greater than the maximum string size (int.MaxValue).
/// </exception>
public string Substring(int startIndex, int count = -1)
{
if (startIndex > (_length == 0 ? 0 : _length - 1)) throw new ArgumentOutOfRangeException(nameof(startIndex));
if (count < -1) throw new ArgumentOutOfRangeException(nameof(count));
int realCount = count == -1 ? _length - startIndex : (int)count;
if (realCount > int.MaxValue || checked(startIndex + realCount) > _length) throw new ArgumentOutOfRangeException(nameof(count));
// The buffer could be bigger than will fit into a string, but the substring might fit. As the starting
// index might be bigger than int we need to index ourselves.
return new string(_buffer, startIndex: startIndex, length: realCount);
}
public void Free()
{
ArrayPool<char>.Shared.Return(_buffer);
_buffer = null;
_length = 0;
}
}
}
| |
namespace DemoFramework.Meshes
{
public static class Bunny
{
public static readonly float[] Vertices = new[]
{
-0.334392f, 0.133007f, 0.062259f,
-0.350189f, 0.150354f, -0.147769f,
-0.234201f, 0.343811f, -0.174307f,
-0.200259f, 0.285207f, 0.093749f,
0.003520f, 0.475208f, -0.159365f,
0.001856f, 0.419203f, 0.098582f,
-0.252802f, 0.093666f, 0.237538f,
-0.162901f, 0.237984f, 0.206905f,
0.000865f, 0.318141f, 0.235370f,
-0.414624f, 0.164083f, -0.278254f,
-0.262213f, 0.357334f, -0.293246f,
0.004628f, 0.482694f, -0.338626f,
-0.402162f, 0.133528f, -0.443247f,
-0.243781f, 0.324275f, -0.436763f,
0.005293f, 0.437592f, -0.458332f,
-0.339884f, -0.041150f, -0.668211f,
-0.248382f, 0.255825f, -0.627493f,
0.006261f, 0.376103f, -0.631506f,
-0.216201f, -0.126776f, -0.886936f,
-0.171075f, 0.011544f, -0.881386f,
-0.181074f, 0.098223f, -0.814779f,
-0.119891f, 0.218786f, -0.760153f,
-0.078895f, 0.276780f, -0.739281f,
0.006801f, 0.310959f, -0.735661f,
-0.168842f, 0.102387f, -0.920381f,
-0.104072f, 0.177278f, -0.952530f,
-0.129704f, 0.211848f, -0.836678f,
-0.099875f, 0.310931f, -0.799381f,
0.007237f, 0.361687f, -0.794439f,
-0.077913f, 0.258753f, -0.921640f,
0.007957f, 0.282241f, -0.931680f,
-0.252222f, -0.550401f, -0.557810f,
-0.267633f, -0.603419f, -0.655209f,
-0.446838f, -0.118517f, -0.466159f,
-0.459488f, -0.093017f, -0.311341f,
-0.370645f, -0.100108f, -0.159454f,
-0.371984f, -0.091991f, -0.011044f,
-0.328945f, -0.098269f, 0.088659f,
-0.282452f, -0.018862f, 0.311501f,
-0.352403f, -0.131341f, 0.144902f,
-0.364126f, -0.200299f, 0.202388f,
-0.283965f, -0.231869f, 0.023668f,
-0.298943f, -0.155218f, 0.369716f,
-0.293787f, -0.121856f, 0.419097f,
-0.290163f, -0.290797f, 0.107824f,
-0.264165f, -0.272849f, 0.036347f,
-0.228567f, -0.372573f, 0.290309f,
-0.190431f, -0.286997f, 0.421917f,
-0.191039f, -0.240973f, 0.507118f,
-0.287272f, -0.276431f, -0.065444f,
-0.295675f, -0.280818f, -0.174200f,
-0.399537f, -0.313131f, -0.376167f,
-0.392666f, -0.488581f, -0.427494f,
-0.331669f, -0.570185f, -0.466054f,
-0.282290f, -0.618140f, -0.589220f,
-0.374238f, -0.594882f, -0.323298f,
-0.381071f, -0.629723f, -0.350777f,
-0.382112f, -0.624060f, -0.221577f,
-0.272701f, -0.566522f, 0.259157f,
-0.256702f, -0.663406f, 0.286079f,
-0.280948f, -0.428359f, 0.055790f,
-0.184974f, -0.508894f, 0.326265f,
-0.279971f, -0.526918f, 0.395319f,
-0.282599f, -0.663393f, 0.412411f,
-0.188329f, -0.475093f, 0.417954f,
-0.263384f, -0.663396f, 0.466604f,
-0.209063f, -0.663393f, 0.509344f,
-0.002044f, -0.319624f, 0.553078f,
-0.001266f, -0.371260f, 0.413296f,
-0.219753f, -0.339762f, -0.040921f,
-0.256986f, -0.282511f, -0.006349f,
-0.271706f, -0.260881f, 0.001764f,
-0.091191f, -0.419184f, -0.045912f,
-0.114944f, -0.429752f, -0.124739f,
-0.113970f, -0.382987f, -0.188540f,
-0.243012f, -0.464942f, -0.242850f,
-0.314815f, -0.505402f, -0.324768f,
0.002774f, -0.437526f, -0.262766f,
-0.072625f, -0.417748f, -0.221440f,
-0.160112f, -0.476932f, -0.293450f,
0.003859f, -0.453425f, -0.443916f,
-0.120363f, -0.581567f, -0.438689f,
-0.091499f, -0.584191f, -0.294511f,
-0.116469f, -0.599861f, -0.188308f,
-0.208032f, -0.513640f, -0.134649f,
-0.235749f, -0.610017f, -0.040939f,
-0.344916f, -0.622487f, -0.085380f,
-0.336401f, -0.531864f, -0.212298f,
0.001961f, -0.459550f, -0.135547f,
-0.058296f, -0.430536f, -0.043440f,
0.001378f, -0.449511f, -0.037762f,
-0.130135f, -0.510222f, 0.079144f,
0.000142f, -0.477549f, 0.157064f,
-0.114284f, -0.453206f, 0.304397f,
-0.000592f, -0.443558f, 0.285401f,
-0.056215f, -0.663402f, 0.326073f,
-0.026248f, -0.568010f, 0.273318f,
-0.049261f, -0.531064f, 0.389854f,
-0.127096f, -0.663398f, 0.479316f,
-0.058384f, -0.663401f, 0.372891f,
-0.303961f, 0.054199f, 0.625921f,
-0.268594f, 0.193403f, 0.502766f,
-0.277159f, 0.126123f, 0.443289f,
-0.287605f, -0.005722f, 0.531844f,
-0.231396f, -0.121289f, 0.587387f,
-0.253475f, -0.081797f, 0.756541f,
-0.195164f, -0.137969f, 0.728011f,
-0.167673f, -0.156573f, 0.609388f,
-0.145917f, -0.169029f, 0.697600f,
-0.077776f, -0.214247f, 0.622586f,
-0.076873f, -0.214971f, 0.696301f,
-0.002341f, -0.233135f, 0.622859f,
-0.002730f, -0.213526f, 0.691267f,
-0.003136f, -0.192628f, 0.762731f,
-0.056136f, -0.201222f, 0.763806f,
-0.114589f, -0.166192f, 0.770723f,
-0.155145f, -0.129632f, 0.791738f,
-0.183611f, -0.058705f, 0.847012f,
-0.165562f, 0.001980f, 0.833386f,
-0.220084f, 0.019914f, 0.768935f,
-0.255730f, 0.090306f, 0.670782f,
-0.255594f, 0.113833f, 0.663389f,
-0.226380f, 0.212655f, 0.617740f,
-0.003367f, -0.195342f, 0.799680f,
-0.029743f, -0.210508f, 0.827180f,
-0.003818f, -0.194783f, 0.873636f,
-0.004116f, -0.157907f, 0.931268f,
-0.031280f, -0.184555f, 0.889476f,
-0.059885f, -0.184448f, 0.841330f,
-0.135333f, -0.164332f, 0.878200f,
-0.085574f, -0.170948f, 0.925547f,
-0.163833f, -0.094170f, 0.897114f,
-0.138444f, -0.104250f, 0.945975f,
-0.083497f, -0.084934f, 0.979607f,
-0.004433f, -0.146642f, 0.985872f,
-0.150715f, 0.032650f, 0.884111f,
-0.135892f, -0.035520f, 0.945455f,
-0.070612f, 0.036849f, 0.975733f,
-0.004458f, -0.042526f, 1.015670f,
-0.004249f, 0.046042f, 1.003240f,
-0.086969f, 0.133224f, 0.947633f,
-0.003873f, 0.161605f, 0.970499f,
-0.125544f, 0.140012f, 0.917678f,
-0.125651f, 0.250246f, 0.857602f,
-0.003127f, 0.284070f, 0.878870f,
-0.159174f, 0.125726f, 0.888878f,
-0.183807f, 0.196970f, 0.844480f,
-0.159890f, 0.291736f, 0.732480f,
-0.199495f, 0.207230f, 0.779864f,
-0.206182f, 0.164608f, 0.693257f,
-0.186315f, 0.160689f, 0.817193f,
-0.192827f, 0.166706f, 0.782271f,
-0.175112f, 0.110008f, 0.860621f,
-0.161022f, 0.057420f, 0.855111f,
-0.172319f, 0.036155f, 0.816189f,
-0.190318f, 0.064083f, 0.760605f,
-0.195072f, 0.129179f, 0.731104f,
-0.203126f, 0.410287f, 0.680536f,
-0.216677f, 0.309274f, 0.642272f,
-0.241515f, 0.311485f, 0.587832f,
-0.002209f, 0.366663f, 0.749413f,
-0.088230f, 0.396265f, 0.678635f,
-0.170147f, 0.109517f, 0.840784f,
-0.160521f, 0.067766f, 0.830650f,
-0.181546f, 0.139805f, 0.812146f,
-0.180495f, 0.148568f, 0.776087f,
-0.180255f, 0.129125f, 0.744192f,
-0.186298f, 0.078308f, 0.769352f,
-0.167622f, 0.060539f, 0.806675f,
-0.189876f, 0.102760f, 0.802582f,
-0.108340f, 0.455446f, 0.657174f,
-0.241585f, 0.527592f, 0.669296f,
-0.265676f, 0.513366f, 0.634594f,
-0.203073f, 0.478550f, 0.581526f,
-0.266772f, 0.642330f, 0.602061f,
-0.216961f, 0.564846f, 0.535435f,
-0.202210f, 0.525495f, 0.475944f,
-0.193888f, 0.467925f, 0.520606f,
-0.265837f, 0.757267f, 0.500933f,
-0.240306f, 0.653440f, 0.463215f,
-0.309239f, 0.776868f, 0.304726f,
-0.271009f, 0.683094f, 0.382018f,
-0.312111f, 0.671099f, 0.286687f,
-0.268791f, 0.624342f, 0.377231f,
-0.302457f, 0.533996f, 0.360289f,
-0.263656f, 0.529310f, 0.412564f,
-0.282311f, 0.415167f, 0.447666f,
-0.239201f, 0.442096f, 0.495604f,
-0.220043f, 0.569026f, 0.445877f,
-0.001263f, 0.395631f, 0.602029f,
-0.057345f, 0.442535f, 0.572224f,
-0.088927f, 0.506333f, 0.529106f,
-0.125738f, 0.535076f, 0.612913f,
-0.126251f, 0.577170f, 0.483159f,
-0.149594f, 0.611520f, 0.557731f,
-0.163188f, 0.660791f, 0.491080f,
-0.172482f, 0.663387f, 0.415416f,
-0.160464f, 0.591710f, 0.370659f,
-0.156445f, 0.536396f, 0.378302f,
-0.136496f, 0.444358f, 0.425226f,
-0.095564f, 0.373768f, 0.473659f,
-0.104146f, 0.315912f, 0.498104f,
-0.000496f, 0.384194f, 0.473817f,
-0.000183f, 0.297770f, 0.401486f,
-0.129042f, 0.270145f, 0.434495f,
0.000100f, 0.272963f, 0.349138f,
-0.113060f, 0.236984f, 0.385554f,
0.007260f, 0.016311f, -0.883396f,
0.007865f, 0.122104f, -0.956137f,
-0.032842f, 0.115282f, -0.953252f,
-0.089115f, 0.108449f, -0.950317f,
-0.047440f, 0.014729f, -0.882756f,
-0.104458f, 0.013137f, -0.882070f,
-0.086439f, -0.584866f, -0.608343f,
-0.115026f, -0.662605f, -0.436732f,
-0.071683f, -0.665372f, -0.606385f,
-0.257884f, -0.665381f, -0.658052f,
-0.272542f, -0.665381f, -0.592063f,
-0.371322f, -0.665382f, -0.353620f,
-0.372362f, -0.665381f, -0.224420f,
-0.335166f, -0.665380f, -0.078623f,
-0.225999f, -0.665375f, -0.038981f,
-0.106719f, -0.665374f, -0.186351f,
-0.081749f, -0.665372f, -0.292554f,
0.006943f, -0.091505f, -0.858354f,
0.006117f, -0.280985f, -0.769967f,
0.004495f, -0.502360f, -0.559799f,
-0.198638f, -0.302135f, -0.845816f,
-0.237395f, -0.542544f, -0.587188f,
-0.270001f, -0.279489f, -0.669861f,
-0.134547f, -0.119852f, -0.959004f,
-0.052088f, -0.122463f, -0.944549f,
-0.124463f, -0.293508f, -0.899566f,
-0.047616f, -0.289643f, -0.879292f,
-0.168595f, -0.529132f, -0.654931f,
-0.099793f, -0.515719f, -0.645873f,
-0.186168f, -0.605282f, -0.724690f,
-0.112970f, -0.583097f, -0.707469f,
-0.108152f, -0.665375f, -0.700408f,
-0.183019f, -0.665378f, -0.717630f,
-0.349529f, -0.334459f, -0.511985f,
-0.141182f, -0.437705f, -0.798194f,
-0.212670f, -0.448725f, -0.737447f,
-0.261111f, -0.414945f, -0.613835f,
-0.077364f, -0.431480f, -0.778113f,
0.005174f, -0.425277f, -0.651592f,
0.089236f, -0.431732f, -0.777093f,
0.271006f, -0.415749f, -0.610577f,
0.223981f, -0.449384f, -0.734774f,
0.153275f, -0.438150f, -0.796391f,
0.358414f, -0.335529f, -0.507649f,
0.193434f, -0.665946f, -0.715325f,
0.118363f, -0.665717f, -0.699021f,
0.123515f, -0.583454f, -0.706020f,
0.196851f, -0.605860f, -0.722345f,
0.109788f, -0.516035f, -0.644590f,
0.178656f, -0.529656f, -0.652804f,
0.061157f, -0.289807f, -0.878626f,
0.138234f, -0.293905f, -0.897958f,
0.066933f, -0.122643f, -0.943820f,
0.149571f, -0.120281f, -0.957264f,
0.280989f, -0.280321f, -0.666487f,
0.246581f, -0.543275f, -0.584224f,
0.211720f, -0.302754f, -0.843303f,
0.086966f, -0.665627f, -0.291520f,
0.110634f, -0.665702f, -0.185021f,
0.228099f, -0.666061f, -0.036201f,
0.337743f, -0.666396f, -0.074503f,
0.376722f, -0.666513f, -0.219833f,
0.377265f, -0.666513f, -0.349036f,
0.281411f, -0.666217f, -0.588670f,
0.267564f, -0.666174f, -0.654834f,
0.080745f, -0.665602f, -0.605452f,
0.122016f, -0.662963f, -0.435280f,
0.095767f, -0.585141f, -0.607228f,
0.118944f, 0.012799f, -0.880702f,
0.061944f, 0.014564f, -0.882086f,
0.104725f, 0.108156f, -0.949130f,
0.048513f, 0.115159f, -0.952753f,
0.112696f, 0.236643f, 0.386937f,
0.128177f, 0.269757f, 0.436071f,
0.102643f, 0.315600f, 0.499370f,
0.094535f, 0.373481f, 0.474824f,
0.136270f, 0.443946f, 0.426895f,
0.157071f, 0.535923f, 0.380222f,
0.161350f, 0.591224f, 0.372630f,
0.173035f, 0.662865f, 0.417531f,
0.162808f, 0.660299f, 0.493077f,
0.148250f, 0.611070f, 0.559555f,
0.125719f, 0.576790f, 0.484702f,
0.123489f, 0.534699f, 0.614440f,
0.087621f, 0.506066f, 0.530188f,
0.055321f, 0.442365f, 0.572915f,
0.219936f, 0.568361f, 0.448571f,
0.238099f, 0.441375f, 0.498528f,
0.281711f, 0.414315f, 0.451121f,
0.263833f, 0.528513f, 0.415794f,
0.303284f, 0.533081f, 0.363998f,
0.269687f, 0.623528f, 0.380528f,
0.314255f, 0.670153f, 0.290524f,
0.272023f, 0.682273f, 0.385343f,
0.311480f, 0.775931f, 0.308527f,
0.240239f, 0.652714f, 0.466159f,
0.265619f, 0.756464f, 0.504187f,
0.192562f, 0.467341f, 0.522972f,
0.201605f, 0.524885f, 0.478417f,
0.215743f, 0.564193f, 0.538084f,
0.264969f, 0.641527f, 0.605317f,
0.201031f, 0.477940f, 0.584002f,
0.263086f, 0.512567f, 0.637832f,
0.238615f, 0.526867f, 0.672237f,
0.105309f, 0.455123f, 0.658482f,
0.183993f, 0.102195f, 0.804872f,
0.161563f, 0.060042f, 0.808692f,
0.180748f, 0.077754f, 0.771600f,
0.175168f, 0.128588f, 0.746368f,
0.175075f, 0.148030f, 0.778264f,
0.175658f, 0.139265f, 0.814333f,
0.154191f, 0.067291f, 0.832578f,
0.163818f, 0.109013f, 0.842830f,
0.084760f, 0.396004f, 0.679695f,
0.238888f, 0.310760f, 0.590775f,
0.213380f, 0.308625f, 0.644905f,
0.199666f, 0.409678f, 0.683003f,
0.190143f, 0.128597f, 0.733463f,
0.184833f, 0.063516f, 0.762902f,
0.166070f, 0.035644f, 0.818261f,
0.154361f, 0.056943f, 0.857042f,
0.168542f, 0.109489f, 0.862725f,
0.187387f, 0.166131f, 0.784599f,
0.180428f, 0.160135f, 0.819438f,
0.201823f, 0.163991f, 0.695756f,
0.194206f, 0.206635f, 0.782275f,
0.155438f, 0.291260f, 0.734412f,
0.177696f, 0.196424f, 0.846693f,
0.152305f, 0.125256f, 0.890786f,
0.119546f, 0.249876f, 0.859104f,
0.118369f, 0.139643f, 0.919173f,
0.079410f, 0.132973f, 0.948652f,
0.062419f, 0.036648f, 0.976547f,
0.127847f, -0.035919f, 0.947070f,
0.143624f, 0.032206f, 0.885913f,
0.074888f, -0.085173f, 0.980577f,
0.130184f, -0.104656f, 0.947620f,
0.156201f, -0.094653f, 0.899074f,
0.077366f, -0.171194f, 0.926545f,
0.127722f, -0.164729f, 0.879810f,
0.052670f, -0.184618f, 0.842019f,
0.023477f, -0.184638f, 0.889811f,
0.022626f, -0.210587f, 0.827500f,
0.223089f, 0.211976f, 0.620493f,
0.251444f, 0.113067f, 0.666494f,
0.251419f, 0.089540f, 0.673887f,
0.214360f, 0.019258f, 0.771595f,
0.158999f, 0.001490f, 0.835374f,
0.176696f, -0.059249f, 0.849218f,
0.148696f, -0.130091f, 0.793599f,
0.108290f, -0.166528f, 0.772088f,
0.049820f, -0.201382f, 0.764454f,
0.071341f, -0.215195f, 0.697209f,
0.073148f, -0.214475f, 0.623510f,
0.140502f, -0.169461f, 0.699354f,
0.163374f, -0.157073f, 0.611416f,
0.189466f, -0.138550f, 0.730366f,
0.247593f, -0.082554f, 0.759610f,
0.227468f, -0.121982f, 0.590197f,
0.284702f, -0.006586f, 0.535347f,
0.275741f, 0.125287f, 0.446676f,
0.266650f, 0.192594f, 0.506044f,
0.300086f, 0.053287f, 0.629620f,
0.055450f, -0.663935f, 0.375065f,
0.122854f, -0.664138f, 0.482323f,
0.046520f, -0.531571f, 0.391918f,
0.024824f, -0.568450f, 0.275106f,
0.053855f, -0.663931f, 0.328224f,
0.112829f, -0.453549f, 0.305788f,
0.131265f, -0.510617f, 0.080746f,
0.061174f, -0.430716f, -0.042710f,
0.341019f, -0.532887f, -0.208150f,
0.347705f, -0.623533f, -0.081139f,
0.238040f, -0.610732f, -0.038037f,
0.211764f, -0.514274f, -0.132078f,
0.120605f, -0.600219f, -0.186856f,
0.096985f, -0.584476f, -0.293357f,
0.127621f, -0.581941f, -0.437170f,
0.165902f, -0.477425f, -0.291453f,
0.077720f, -0.417975f, -0.220519f,
0.320892f, -0.506363f, -0.320874f,
0.248214f, -0.465684f, -0.239842f,
0.118764f, -0.383338f, -0.187114f,
0.118816f, -0.430106f, -0.123307f,
0.094131f, -0.419464f, -0.044777f,
0.274526f, -0.261706f, 0.005110f,
0.259842f, -0.283292f, -0.003185f,
0.222861f, -0.340431f, -0.038210f,
0.204445f, -0.664380f, 0.513353f,
0.259286f, -0.664547f, 0.471281f,
0.185402f, -0.476020f, 0.421718f,
0.279163f, -0.664604f, 0.417328f,
0.277157f, -0.528122f, 0.400208f,
0.183069f, -0.509812f, 0.329995f,
0.282599f, -0.429210f, 0.059242f,
0.254816f, -0.664541f, 0.290687f,
0.271436f, -0.567707f, 0.263966f,
0.386561f, -0.625221f, -0.216870f,
0.387086f, -0.630883f, -0.346073f,
0.380021f, -0.596021f, -0.318679f,
0.291269f, -0.619007f, -0.585707f,
0.339280f, -0.571198f, -0.461946f,
0.400045f, -0.489778f, -0.422640f,
0.406817f, -0.314349f, -0.371230f,
0.300588f, -0.281718f, -0.170549f,
0.290866f, -0.277304f, -0.061905f,
0.187735f, -0.241545f, 0.509437f,
0.188032f, -0.287569f, 0.424234f,
0.227520f, -0.373262f, 0.293102f,
0.266526f, -0.273650f, 0.039597f,
0.291592f, -0.291676f, 0.111386f,
0.291914f, -0.122741f, 0.422683f,
0.297574f, -0.156119f, 0.373368f,
0.286603f, -0.232731f, 0.027162f,
0.364663f, -0.201399f, 0.206850f,
0.353855f, -0.132408f, 0.149228f,
0.282208f, -0.019715f, 0.314960f,
0.331187f, -0.099266f, 0.092701f,
0.375463f, -0.093120f, -0.006467f,
0.375917f, -0.101236f, -0.154882f,
0.466635f, -0.094416f, -0.305669f,
0.455805f, -0.119881f, -0.460632f,
0.277465f, -0.604242f, -0.651871f,
0.261022f, -0.551176f, -0.554667f,
0.093627f, 0.258494f, -0.920589f,
0.114248f, 0.310608f, -0.798070f,
0.144232f, 0.211434f, -0.835001f,
0.119916f, 0.176940f, -0.951159f,
0.184061f, 0.101854f, -0.918220f,
0.092431f, 0.276521f, -0.738231f,
0.133504f, 0.218403f, -0.758602f,
0.194987f, 0.097655f, -0.812476f,
0.185542f, 0.011005f, -0.879202f,
0.230315f, -0.127450f, -0.884202f,
0.260471f, 0.255056f, -0.624378f,
0.351567f, -0.042194f, -0.663976f,
0.253742f, 0.323524f, -0.433716f,
0.411612f, 0.132299f, -0.438264f,
0.270513f, 0.356530f, -0.289984f,
0.422146f, 0.162819f, -0.273130f,
0.164724f, 0.237490f, 0.208912f,
0.253806f, 0.092900f, 0.240640f,
0.203608f, 0.284597f, 0.096223f,
0.241006f, 0.343093f, -0.171396f,
0.356076f, 0.149288f, -0.143443f,
0.337656f, 0.131992f, 0.066374f
};
public static readonly int[] Indices = new[]
{
126,134,133,
342,138,134,
133,134,138,
126,342,134,
312,316,317,
169,163,162,
312,317,319,
312,319,318,
169,162,164,
169,168,163,
312,314,315,
169,164,165,
169,167,168,
312,315,316,
312,313,314,
169,165,166,
169,166,167,
312,318,313,
308,304,305,
308,305,306,
179,181,188,
177,173,175,
177,175,176,
302,293,300,
322,294,304,
188,176,175,
188,175,179,
158,177,187,
305,293,302,
305,302,306,
322,304,308,
188,181,183,
158,173,177,
293,298,300,
304,294,296,
304,296,305,
185,176,188,
185,188,183,
187,177,176,
187,176,185,
305,296,298,
305,298,293,
436,432, 28,
436, 28, 23,
434,278,431,
30,208,209,
30,209, 29,
19, 20, 24,
208,207,211,
208,211,209,
19,210,212,
433,434,431,
433,431,432,
433,432,436,
436,437,433,
277,275,276,
277,276,278,
209,210, 25,
21, 26, 24,
21, 24, 20,
25, 26, 27,
25, 27, 29,
435,439,277,
439,275,277,
432,431, 30,
432, 30, 28,
433,437,438,
433,438,435,
434,277,278,
24, 25,210,
24, 26, 25,
29, 27, 28,
29, 28, 30,
19, 24,210,
208, 30,431,
208,431,278,
435,434,433,
435,277,434,
25, 29,209,
27, 22, 23,
27, 23, 28,
26, 22, 27,
26, 21, 22,
212,210,209,
212,209,211,
207,208,278,
207,278,276,
439,435,438,
12, 9, 10,
12, 10, 13,
2, 3, 5,
2, 5, 4,
16, 13, 14,
16, 14, 17,
22, 21, 16,
13, 10, 11,
13, 11, 14,
1, 0, 3,
1, 3, 2,
15, 12, 16,
19, 18, 15,
19, 15, 16,
19, 16, 20,
9, 1, 2,
9, 2, 10,
3, 7, 8,
3, 8, 5,
16, 17, 23,
16, 23, 22,
21, 20, 16,
10, 2, 4,
10, 4, 11,
0, 6, 7,
0, 7, 3,
12, 13, 16,
451,446,445,
451,445,450,
442,440,439,
442,439,438,
442,438,441,
421,420,422,
412,411,426,
412,426,425,
408,405,407,
413, 67, 68,
413, 68,414,
391,390,412,
80,384,386,
404,406,378,
390,391,377,
390,377, 88,
400,415,375,
398,396,395,
398,395,371,
398,371,370,
112,359,358,
112,358,113,
351,352,369,
125,349,348,
345,343,342,
342,340,339,
341,335,337,
328,341,327,
331,323,333,
331,322,323,
327,318,319,
327,319,328,
315,314,324,
302,300,301,
302,301,303,
320,311,292,
285,284,289,
310,307,288,
310,288,290,
321,350,281,
321,281,282,
423,448,367,
272,273,384,
272,384,274,
264,265,382,
264,382,383,
440,442,261,
440,261,263,
252,253,254,
252,254,251,
262,256,249,
262,249,248,
228,243,242,
228, 31,243,
213,215,238,
213,238,237,
19,212,230,
224,225,233,
224,233,231,
217,218, 56,
217, 56, 54,
217,216,239,
217,239,238,
217,238,215,
218,217,215,
218,215,214,
6,102,206,
186,199,200,
197,182,180,
170,171,157,
201,200,189,
170,190,191,
170,191,192,
175,174,178,
175,178,179,
168,167,155,
122,149,158,
122,158,159,
135,153,154,
135,154,118,
143,140,141,
143,141,144,
132,133,136,
130,126,133,
124,125,127,
122,101,100,
122,100,121,
110,108,107,
110,107,109,
98, 99, 97,
98, 97, 64,
98, 64, 66,
87, 55, 57,
83, 82, 79,
83, 79, 84,
78, 74, 50,
49, 71, 41,
49, 41, 37,
49, 37, 36,
58, 44, 60,
60, 59, 58,
51, 34, 33,
39, 40, 42,
39, 42, 38,
243,240, 33,
243, 33,229,
39, 38, 6,
44, 46, 40,
55, 56, 57,
64, 62, 65,
64, 65, 66,
41, 71, 45,
75, 50, 51,
81, 79, 82,
77, 88, 73,
93, 92, 94,
68, 47, 46,
96, 97, 99,
96, 99, 95,
110,109,111,
111,112,110,
114,113,123,
114,123,124,
132,131,129,
133,137,136,
135,142,145,
145,152,135,
149,147,157,
157,158,149,
164,150,151,
153,163,168,
153,168,154,
185,183,182,
185,182,184,
161,189,190,
200,199,191,
200,191,190,
180,178,195,
180,195,196,
102,101,204,
102,204,206,
43, 48,104,
43,104,103,
216,217, 54,
216, 54, 32,
207,224,231,
230,212,211,
230,211,231,
227,232,241,
227,241,242,
235,234,241,
235,241,244,
430,248,247,
272,274,253,
272,253,252,
439,260,275,
225,224,259,
225,259,257,
269,270,407,
269,407,405,
270,269,273,
270,273,272,
273,269,268,
273,268,267,
273,267,266,
273,266,265,
273,265,264,
448,279,367,
281,350,368,
285,286,301,
290,323,310,
290,311,323,
282,281,189,
292,311,290,
292,290,291,
307,306,302,
307,302,303,
316,315,324,
316,324,329,
331,351,350,
330,334,335,
330,335,328,
341,337,338,
344,355,354,
346,345,348,
346,348,347,
364,369,352,
364,352,353,
365,363,361,
365,361,362,
376,401,402,
373,372,397,
373,397,400,
376, 92,377,
381,378,387,
381,387,385,
386, 77, 80,
390,389,412,
416,417,401,
403,417,415,
408,429,430,
419,423,418,
427,428,444,
427,444,446,
437,436,441,
450,445, 11,
450, 11, 4,
447,449, 5,
447, 5, 8,
441,438,437,
425,426,451,
425,451,452,
417,421,415,
408,407,429,
399,403,400,
399,400,397,
394,393,416,
389,411,412,
386,383,385,
408,387,378,
408,378,406,
377,391,376,
94,375,415,
372,373,374,
372,374,370,
359,111,360,
359,112,111,
113,358,349,
113,349,123,
346,343,345,
343,340,342,
338,336,144,
338,144,141,
327,341,354,
327,354,326,
331,350,321,
331,321,322,
314,313,326,
314,326,325,
300,298,299,
300,299,301,
288,287,289,
189,292,282,
287,288,303,
284,285,297,
368,280,281,
448,447,279,
274,226,255,
267,268,404,
267,404,379,
429,262,430,
439,440,260,
257,258,249,
257,249,246,
430,262,248,
234,228,242,
234,242,241,
237,238,239,
237,239,236,
15, 18,227,
15,227,229,
222,223, 82,
222, 82, 83,
214,215,213,
214,213, 81,
38,102, 6,
122,159,200,
122,200,201,
174,171,192,
174,192,194,
197,193,198,
190,170,161,
181,179,178,
181,178,180,
166,156,155,
163,153,152,
163,152,162,
120,156,149,
120,149,121,
152,153,135,
140,143,142,
135,131,132,
135,132,136,
130,129,128,
130,128,127,
100,105,119,
100,119,120,
106,104,107,
106,107,108,
91, 95, 59,
93, 94, 68,
91, 89, 92,
76, 53, 55,
76, 55, 87,
81, 78, 79,
74, 73, 49,
69, 60, 45,
58, 62, 64,
58, 64, 61,
53, 31, 32,
32, 54, 53,
42, 43, 38,
35, 36, 0,
35, 0, 1,
34, 35, 1,
34, 1, 9,
44, 40, 41,
44, 41, 45,
33,240, 51,
63, 62, 58,
63, 58, 59,
45, 71, 70,
76, 75, 51,
76, 51, 52,
86, 85, 84,
86, 84, 87,
89, 72, 73,
89, 73, 88,
91, 92, 96,
91, 96, 95,
72, 91, 60,
72, 60, 69,
104,106,105,
119,105,117,
119,117,118,
124,127,128,
117,116,129,
117,129,131,
118,117,131,
135,140,142,
146,150,152,
146,152,145,
149,122,121,
166,165,151,
166,151,156,
158,172,173,
161,160,189,
199,198,193,
199,193,191,
204,201,202,
178,174,194,
200,159,186,
109, 48, 67,
48,107,104,
216, 32,236,
216,236,239,
223,214, 81,
223, 81, 82,
33, 12, 15,
32,228,234,
32,234,236,
240, 31, 52,
256,255,246,
256,246,249,
258,263,248,
258,248,249,
275,260,259,
275,259,276,
207,276,259,
270,271,429,
270,429,407,
413,418,366,
413,366,365,
368,367,279,
368,279,280,
303,301,286,
303,286,287,
283,282,292,
283,292,291,
320,292,189,
298,296,297,
298,297,299,
318,327,326,
318,326,313,
329,330,317,
336,333,320,
326,354,353,
334,332,333,
334,333,336,
342,339,139,
342,139,138,
345,342,126,
347,357,356,
369,368,351,
363,356,357,
363,357,361,
366,367,368,
366,368,369,
375,373,400,
92, 90,377,
409,387,408,
386,385,387,
386,387,388,
412,394,391,
396,398,399,
408,406,405,
415,421,419,
415,419,414,
425,452,448,
425,448,424,
444,441,443,
448,452,449,
448,449,447,
446,444,443,
446,443,445,
250,247,261,
250,261,428,
421,422,423,
421,423,419,
427,410,250,
417,403,401,
403,402,401,
420,392,412,
420,412,425,
420,425,424,
386,411,389,
383,382,381,
383,381,385,
378,379,404,
372,371,395,
372,395,397,
371,372,370,
361,359,360,
361,360,362,
368,350,351,
349,347,348,
356,355,344,
356,344,346,
344,341,340,
344,340,343,
338,337,336,
328,335,341,
324,352,351,
324,351,331,
320,144,336,
314,325,324,
322,308,309,
310,309,307,
287,286,289,
203,280,279,
203,279,205,
297,295,283,
297,283,284,
447,205,279,
274,384, 80,
274, 80,226,
266,267,379,
266,379,380,
225,257,246,
225,246,245,
256,254,253,
256,253,255,
430,247,250,
226,235,244,
226,244,245,
232,233,244,
232,244,241,
230, 18, 19,
32, 31,228,
219,220, 86,
219, 86, 57,
226,213,235,
206, 7, 6,
122,201,101,
201,204,101,
180,196,197,
170,192,171,
200,190,189,
194,193,195,
183,181,180,
183,180,182,
155,154,168,
149,156,151,
149,151,148,
155,156,120,
145,142,143,
145,143,146,
136,137,140,
133,132,130,
128,129,116,
100,120,121,
110,112,113,
110,113,114,
66, 65, 63,
66, 63, 99,
66, 99, 98,
96, 46, 61,
89, 88, 90,
86, 87, 57,
80, 78, 81,
72, 69, 49,
67, 48, 47,
67, 47, 68,
56, 55, 53,
50, 49, 36,
50, 36, 35,
40, 39, 41,
242,243,229,
242,229,227,
6, 37, 39,
42, 47, 48,
42, 48, 43,
61, 46, 44,
45, 70, 69,
69, 70, 71,
69, 71, 49,
74, 78, 77,
83, 84, 85,
73, 74, 77,
93, 96, 92,
68, 46, 93,
95, 99, 63,
95, 63, 59,
115,108,110,
115,110,114,
125,126,127,
129,130,132,
137,133,138,
137,138,139,
148,146,143,
148,143,147,
119,118,154,
161,147,143,
165,164,151,
158,157,171,
158,171,172,
159,158,187,
159,187,186,
194,192,191,
194,191,193,
189,202,201,
182,197,184,
205, 8, 7,
48,109,107,
218,219, 57,
218, 57, 56,
207,231,211,
232,230,231,
232,231,233,
53, 52, 31,
388,411,386,
409,430,250,
262,429,254,
262,254,256,
442,444,428,
273,264,383,
273,383,384,
429,271,251,
429,251,254,
413,365,362,
67,413,360,
282,283,295,
285,301,299,
202,281,280,
284,283,291,
284,291,289,
320,189,160,
308,306,307,
307,309,308,
319,317,330,
319,330,328,
353,352,324,
332,331,333,
340,341,338,
354,341,344,
349,358,357,
349,357,347,
364,355,356,
364,356,363,
364,365,366,
364,366,369,
374,376,402,
375, 92,373,
77,389,390,
382,380,381,
389, 77,386,
393,394,412,
393,412,392,
401,394,416,
415,400,403,
411,410,427,
411,427,426,
422,420,424,
247,248,263,
247,263,261,
445,443, 14,
445, 14, 11,
449,450, 4,
449, 4, 5,
443,441, 17,
443, 17, 14,
436, 23, 17,
436, 17,441,
424,448,422,
448,423,422,
414,419,418,
414,418,413,
406,404,405,
399,397,395,
399,395,396,
420,416,392,
388,410,411,
386,384,383,
390, 88, 77,
375, 94, 92,
415,414, 68,
415, 68, 94,
370,374,402,
370,402,398,
361,357,358,
361,358,359,
125,348,126,
346,344,343,
340,338,339,
337,335,334,
337,334,336,
325,353,324,
324,331,332,
324,332,329,
323,322,309,
323,309,310,
294,295,297,
294,297,296,
289,286,285,
202,280,203,
288,307,303,
282,295,321,
67,360,111,
418,423,367,
418,367,366,
272,252,251,
272,251,271,
272,271,270,
255,253,274,
265,266,380,
265,380,382,
442,428,261,
440,263,258,
440,258,260,
409,250,410,
255,226,245,
255,245,246,
31,240,243,
236,234,235,
236,235,237,
233,225,245,
233,245,244,
220,221, 85,
220, 85, 86,
81,213,226,
81,226, 80,
7,206,205,
186,184,198,
186,198,199,
204,203,205,
204,205,206,
195,193,196,
171,174,172,
173,174,175,
173,172,174,
155,167,166,
160,161,143,
160,143,144,
119,154,155,
148,151,150,
148,150,146,
140,137,139,
140,139,141,
127,126,130,
114,124,128,
114,128,115,
117,105,106,
117,106,116,
104,105,100,
104,100,103,
59, 60, 91,
97, 96, 61,
97, 61, 64,
91, 72, 89,
87, 84, 79,
87, 79, 76,
78, 80, 77,
49, 50, 74,
60, 44, 45,
61, 44, 58,
51, 50, 35,
51, 35, 34,
39, 37, 41,
33, 34, 9,
33, 9, 12,
0, 36, 37,
0, 37, 6,
40, 46, 47,
40, 47, 42,
53, 54, 56,
65, 62, 63,
72, 49, 73,
79, 78, 75,
79, 75, 76,
52, 53, 76,
92, 89, 90,
96, 93, 46,
102,103,100,
102,100,101,
116,106,108,
116,108,115,
123,125,124,
116,115,128,
118,131,135,
140,135,136,
148,147,149,
120,119,155,
164,162,152,
164,152,150,
157,147,161,
157,161,170,
186,187,185,
186,185,184,
193,197,196,
202,203,204,
194,195,178,
198,184,197,
67,111,109,
38, 43,103,
38,103,102,
214,223,222,
214,222,221,
214,221,220,
214,220,219,
214,219,218,
213,237,235,
221,222, 83,
221, 83, 85,
15,229, 33,
227, 18,230,
227,230,232,
52, 51,240,
75, 78, 50,
408,430,409,
260,258,257,
260,257,259,
224,207,259,
268,269,405,
268,405,404,
413,362,360,
447, 8,205,
299,297,285,
189,281,202,
290,288,289,
290,289,291,
322,321,295,
322,295,294,
333,323,311,
333,311,320,
317,316,329,
320,160,144,
353,325,326,
329,332,334,
329,334,330,
339,338,141,
339,141,139,
348,345,126,
347,356,346,
123,349,125,
364,353,354,
364,354,355,
365,364,363,
376,391,394,
376,394,401,
92,376,374,
92,374,373,
377, 90, 88,
380,379,378,
380,378,381,
388,387,409,
388,409,410,
416,393,392,
399,398,402,
399,402,403,
250,428,427,
421,417,416,
421,416,420,
426,427,446,
426,446,451,
444,442,441,
452,451,450,
452,450,449
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions.Compiler
{
internal partial class LambdaCompiler
{
private void EmitQuoteUnaryExpression(Expression expr)
{
EmitQuote((UnaryExpression)expr);
}
private void EmitQuote(UnaryExpression quote)
{
// emit the quoted expression as a runtime constant
EmitConstant(quote.Operand, quote.Type);
// Heuristic: only emit the tree rewrite logic if we have hoisted
// locals.
if (_scope.NearestHoistedLocals != null)
{
// HoistedLocals is internal so emit as System.Object
EmitConstant(_scope.NearestHoistedLocals, typeof(object));
_scope.EmitGet(_scope.NearestHoistedLocals.SelfVariable);
_ilg.Emit(OpCodes.Call, RuntimeOps_Quote);
Debug.Assert(typeof(LambdaExpression).IsAssignableFrom(quote.Type));
_ilg.Emit(OpCodes.Castclass, quote.Type);
}
}
private void EmitThrowUnaryExpression(Expression expr)
{
EmitThrow((UnaryExpression)expr, CompilationFlags.EmitAsDefaultType);
}
private void EmitThrow(UnaryExpression expr, CompilationFlags flags)
{
if (expr.Operand == null)
{
CheckRethrow();
_ilg.Emit(OpCodes.Rethrow);
}
else
{
EmitExpression(expr.Operand);
_ilg.Emit(OpCodes.Throw);
}
EmitUnreachable(expr, flags);
}
private void EmitUnaryExpression(Expression expr, CompilationFlags flags)
{
EmitUnary((UnaryExpression)expr, flags);
}
private void EmitUnary(UnaryExpression node, CompilationFlags flags)
{
if (node.Method != null)
{
EmitUnaryMethod(node, flags);
}
else if (node.NodeType == ExpressionType.NegateChecked && node.Operand.Type.IsInteger())
{
Type type = node.Type;
Debug.Assert(type == node.Operand.Type);
if (type.IsNullableType())
{
Label nullOrZero = _ilg.DefineLabel();
Label end = _ilg.DefineLabel();
EmitExpression(node.Operand);
LocalBuilder loc = GetLocal(type);
// check for null or zero
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Brfalse_S, nullOrZero);
// calculate 0 - operand
Type nnType = type.GetNonNullableType();
_ilg.EmitDefault(nnType, locals: null); // locals won't be used.
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitGetValueOrDefault(type);
EmitBinaryOperator(ExpressionType.SubtractChecked, nnType, nnType, nnType, liftedToNull: false);
// construct result
_ilg.Emit(OpCodes.Newobj, type.GetConstructor(new Type[] { nnType }));
_ilg.Emit(OpCodes.Br_S, end);
// if null then push back on stack
_ilg.MarkLabel(nullOrZero);
_ilg.Emit(OpCodes.Ldloc, loc);
FreeLocal(loc);
_ilg.MarkLabel(end);
}
else
{
_ilg.EmitDefault(type, locals: null); // locals won't be used.
EmitExpression(node.Operand);
EmitBinaryOperator(ExpressionType.SubtractChecked, type, type, type, liftedToNull: false);
}
}
else
{
EmitExpression(node.Operand);
EmitUnaryOperator(node.NodeType, node.Operand.Type, node.Type);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void EmitUnaryOperator(ExpressionType op, Type operandType, Type resultType)
{
bool operandIsNullable = operandType.IsNullableType();
if (op == ExpressionType.ArrayLength)
{
_ilg.Emit(OpCodes.Ldlen);
return;
}
if (operandIsNullable)
{
switch (op)
{
case ExpressionType.UnaryPlus:
return;
case ExpressionType.TypeAs:
if (operandType != resultType)
{
_ilg.Emit(OpCodes.Box, operandType);
_ilg.Emit(OpCodes.Isinst, resultType);
if (resultType.IsNullableType())
{
_ilg.Emit(OpCodes.Unbox_Any, resultType);
}
}
return;
default:
Debug.Assert(TypeUtils.AreEquivalent(operandType, resultType));
Label labIfNull = _ilg.DefineLabel();
Label labEnd = _ilg.DefineLabel();
LocalBuilder loc = GetLocal(operandType);
// check for null
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitHasValue(operandType);
_ilg.Emit(OpCodes.Brfalse_S, labIfNull);
// apply operator to non-null value
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitGetValueOrDefault(operandType);
Type nnOperandType = resultType.GetNonNullableType();
EmitUnaryOperator(op, nnOperandType, nnOperandType);
// construct result
ConstructorInfo ci = resultType.GetConstructor(new Type[] { nnOperandType });
_ilg.Emit(OpCodes.Newobj, ci);
_ilg.Emit(OpCodes.Br_S, labEnd);
// if null then push back on stack.
_ilg.MarkLabel(labIfNull);
_ilg.Emit(OpCodes.Ldloc, loc);
FreeLocal(loc);
_ilg.MarkLabel(labEnd);
return;
}
}
else
{
switch (op)
{
case ExpressionType.Not:
if (operandType == typeof(bool))
{
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
return;
}
goto case ExpressionType.OnesComplement;
case ExpressionType.OnesComplement:
_ilg.Emit(OpCodes.Not);
if (!operandType.IsUnsigned())
{
// Guaranteed to fit within result type: no conversion
return;
}
break;
case ExpressionType.IsFalse:
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
// Not an arithmetic operation -> no conversion
return;
case ExpressionType.IsTrue:
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.Emit(OpCodes.Ceq);
// Not an arithmetic operation -> no conversion
return;
case ExpressionType.UnaryPlus:
// Guaranteed to fit within result type: no conversion
return;
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
_ilg.Emit(OpCodes.Neg);
// Guaranteed to fit within result type: no conversion
// (integer NegateChecked was rewritten to 0 - operand and doesn't hit here).
return;
case ExpressionType.TypeAs:
if (operandType != resultType)
{
if (operandType.IsValueType)
{
_ilg.Emit(OpCodes.Box, operandType);
}
_ilg.Emit(OpCodes.Isinst, resultType);
if (resultType.IsNullableType())
{
_ilg.Emit(OpCodes.Unbox_Any, resultType);
}
}
// Not an arithmetic operation -> no conversion
return;
case ExpressionType.Increment:
EmitConstantOne(resultType);
_ilg.Emit(OpCodes.Add);
break;
case ExpressionType.Decrement:
EmitConstantOne(resultType);
_ilg.Emit(OpCodes.Sub);
break;
}
EmitConvertArithmeticResult(op, resultType);
}
}
private void EmitConstantOne(Type type)
{
switch (type.GetTypeCode())
{
case TypeCode.Int64:
case TypeCode.UInt64:
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.Emit(OpCodes.Conv_I8);
break;
case TypeCode.Single:
_ilg.Emit(OpCodes.Ldc_R4, 1.0f);
break;
case TypeCode.Double:
_ilg.Emit(OpCodes.Ldc_R8, 1.0d);
break;
default:
_ilg.Emit(OpCodes.Ldc_I4_1);
break;
}
}
private void EmitUnboxUnaryExpression(Expression expr)
{
var node = (UnaryExpression)expr;
Debug.Assert(node.Type.IsValueType);
// Unbox_Any leaves the value on the stack
EmitExpression(node.Operand);
_ilg.Emit(OpCodes.Unbox_Any, node.Type);
}
private void EmitConvertUnaryExpression(Expression expr, CompilationFlags flags)
{
EmitConvert((UnaryExpression)expr, flags);
}
private void EmitConvert(UnaryExpression node, CompilationFlags flags)
{
if (node.Method != null)
{
// User-defined conversions are only lifted if both source and
// destination types are value types. The C# compiler gets this wrong.
// In C#, if you have an implicit conversion from int->MyClass and you
// "lift" the conversion to int?->MyClass then a null int? goes to a
// null MyClass. This is contrary to the specification, which states
// that the correct behaviour is to unwrap the int?, throw an exception
// if it is null, and then call the conversion.
//
// We cannot fix this in C# but there is no reason why we need to
// propagate this behavior into the expression tree API. Unfortunately
// this means that when the C# compiler generates the lambda
// (int? i)=>(MyClass)i, we will get different results for converting
// that lambda to a delegate directly and converting that lambda to
// an expression tree and then compiling it. We can live with this
// discrepancy however.
if (node.IsLifted && (!node.Type.IsValueType || !node.Operand.Type.IsValueType))
{
ParameterInfo[] pis = node.Method.GetParametersCached();
Debug.Assert(pis != null && pis.Length == 1);
Type paramType = pis[0].ParameterType;
if (paramType.IsByRef)
{
paramType = paramType.GetElementType();
}
UnaryExpression operand = Expression.Convert(node.Operand, paramType);
Debug.Assert(operand.Method == null);
node = Expression.Convert(Expression.Call(node.Method, operand), node.Type);
Debug.Assert(node.Method == null);
}
else
{
EmitUnaryMethod(node, flags);
return;
}
}
if (node.Type == typeof(void))
{
EmitExpressionAsVoid(node.Operand, flags);
}
else
{
if (TypeUtils.AreEquivalent(node.Operand.Type, node.Type))
{
EmitExpression(node.Operand, flags);
}
else
{
// A conversion is emitted after emitting the operand, no tail call is emitted
EmitExpression(node.Operand);
_ilg.EmitConvertToType(node.Operand.Type, node.Type, node.NodeType == ExpressionType.ConvertChecked, this);
}
}
}
private void EmitUnaryMethod(UnaryExpression node, CompilationFlags flags)
{
if (node.IsLifted)
{
ParameterExpression v = Expression.Variable(node.Operand.Type.GetNonNullableType(), name: null);
MethodCallExpression mc = Expression.Call(node.Method, v);
Type resultType = mc.Type.GetNullableType();
EmitLift(node.NodeType, resultType, mc, new ParameterExpression[] { v }, new Expression[] { node.Operand });
_ilg.EmitConvertToType(resultType, node.Type, isChecked: false, locals: this);
}
else
{
EmitMethodCallExpression(Expression.Call(node.Method, node.Operand), flags);
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using Be.Windows.Forms;
using System.Collections.Generic;
using System.Text;
namespace Be.HexEditor
{
/// <summary>
/// Summary description for FormFind.
/// </summary>
public class FormFind : Core.FormEx
{
private Be.Windows.Forms.HexBox hexFind;
private System.Windows.Forms.TextBox txtFind;
private System.Windows.Forms.RadioButton rbString;
private System.Windows.Forms.RadioButton rbHex;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private Label lblPercent;
private Label lblFinding;
private CheckBox chkMatchCase;
private Timer timerPercent;
private Timer timer;
private FlowLayoutPanel flowLayoutPanel1;
private FlowLayoutPanel flowLayoutPanel2;
private Panel line;
private IContainer components;
public FormFind()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
rbString.CheckedChanged += new EventHandler(rb_CheckedChanged);
rbHex.CheckedChanged += new EventHandler(rb_CheckedChanged);
}
void ByteProvider_Changed(object sender, EventArgs e)
{
ValidateFind();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormFind));
this.txtFind = new System.Windows.Forms.TextBox();
this.rbString = new System.Windows.Forms.RadioButton();
this.rbHex = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.lblPercent = new System.Windows.Forms.Label();
this.lblFinding = new System.Windows.Forms.Label();
this.chkMatchCase = new System.Windows.Forms.CheckBox();
this.timerPercent = new System.Windows.Forms.Timer(this.components);
this.timer = new System.Windows.Forms.Timer(this.components);
this.hexFind = new Be.Windows.Forms.HexBox();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.line = new System.Windows.Forms.Panel();
this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel();
this.flowLayoutPanel1.SuspendLayout();
this.flowLayoutPanel2.SuspendLayout();
this.SuspendLayout();
//
// txtFind
//
resources.ApplyResources(this.txtFind, "txtFind");
this.txtFind.Name = "txtFind";
this.txtFind.TextChanged += new System.EventHandler(this.txtString_TextChanged);
//
// rbString
//
resources.ApplyResources(this.rbString, "rbString");
this.rbString.Checked = true;
this.rbString.Name = "rbString";
this.rbString.TabStop = true;
//
// rbHex
//
resources.ApplyResources(this.rbHex, "rbHex");
this.rbHex.Name = "rbHex";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.ForeColor = System.Drawing.Color.Blue;
this.label1.Name = "label1";
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Name = "btnCancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// lblPercent
//
resources.ApplyResources(this.lblPercent, "lblPercent");
this.lblPercent.Name = "lblPercent";
//
// lblFinding
//
this.lblFinding.ForeColor = System.Drawing.Color.Blue;
resources.ApplyResources(this.lblFinding, "lblFinding");
this.lblFinding.Name = "lblFinding";
//
// chkMatchCase
//
resources.ApplyResources(this.chkMatchCase, "chkMatchCase");
this.chkMatchCase.Name = "chkMatchCase";
this.chkMatchCase.UseVisualStyleBackColor = true;
//
// timerPercent
//
this.timerPercent.Tick += new System.EventHandler(this.timerPercent_Tick);
//
// timer
//
this.timer.Interval = 50;
this.timer.Tick += new System.EventHandler(this.timer_Tick);
//
// hexFind
//
resources.ApplyResources(this.hexFind, "hexFind");
//
//
//
this.hexFind.BuiltInContextMenu.CopyMenuItemImage = global::Be.HexEditor.images.CopyHS;
this.hexFind.BuiltInContextMenu.CopyMenuItemText = resources.GetString("hexFind.BuiltInContextMenu.CopyMenuItemText");
this.hexFind.BuiltInContextMenu.CutMenuItemImage = global::Be.HexEditor.images.CutHS;
this.hexFind.BuiltInContextMenu.CutMenuItemText = resources.GetString("hexFind.BuiltInContextMenu.CutMenuItemText");
this.hexFind.BuiltInContextMenu.PasteMenuItemImage = global::Be.HexEditor.images.PasteHS;
this.hexFind.BuiltInContextMenu.PasteMenuItemText = resources.GetString("hexFind.BuiltInContextMenu.PasteMenuItemText");
this.hexFind.BuiltInContextMenu.SelectAllMenuItemText = resources.GetString("hexFind.BuiltInContextMenu.SelectAllMenuItemText");
this.hexFind.InfoForeColor = System.Drawing.Color.Empty;
this.hexFind.Name = "hexFind";
this.hexFind.ShadowSelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(60)))), ((int)(((byte)(188)))), ((int)(((byte)(255)))));
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Controls.Add(this.label1);
this.flowLayoutPanel1.Controls.Add(this.line);
resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Paint += new System.Windows.Forms.PaintEventHandler(this.flowLayoutPanel1_Paint);
//
// line
//
resources.ApplyResources(this.line, "line");
this.line.BackColor = System.Drawing.Color.LightGray;
this.line.Name = "line";
//
// flowLayoutPanel2
//
resources.ApplyResources(this.flowLayoutPanel2, "flowLayoutPanel2");
this.flowLayoutPanel2.Controls.Add(this.btnCancel);
this.flowLayoutPanel2.Controls.Add(this.btnOK);
this.flowLayoutPanel2.Controls.Add(this.lblFinding);
this.flowLayoutPanel2.Controls.Add(this.lblPercent);
this.flowLayoutPanel2.Name = "flowLayoutPanel2";
//
// FormFind
//
this.AcceptButton = this.btnOK;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.SystemColors.Control;
this.CancelButton = this.btnCancel;
this.Controls.Add(this.flowLayoutPanel2);
this.Controls.Add(this.flowLayoutPanel1);
this.Controls.Add(this.chkMatchCase);
this.Controls.Add(this.rbHex);
this.Controls.Add(this.rbString);
this.Controls.Add(this.txtFind);
this.Controls.Add(this.hexFind);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FormFind";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Activated += new System.EventHandler(this.FormFind_Activated);
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.flowLayoutPanel2.ResumeLayout(false);
this.flowLayoutPanel2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private FindOptions _findOptions;
public FindOptions FindOptions
{
get
{
return _findOptions;
}
set
{
_findOptions = value;
Reinitialize();
}
}
public HexBox HexBox { get; set; }
private void Reinitialize()
{
rbString.Checked = _findOptions.Type == FindType.Text;
txtFind.Text = _findOptions.Text;
chkMatchCase.Checked = _findOptions.MatchCase;
rbHex.Checked = _findOptions.Type == FindType.Hex;
if (hexFind.ByteProvider != null)
hexFind.ByteProvider.Changed -= new EventHandler(ByteProvider_Changed);
var hex = this._findOptions.Hex != null ? _findOptions.Hex : new byte[0];
hexFind.ByteProvider = new DynamicByteProvider(hex);
hexFind.ByteProvider.Changed += new EventHandler(ByteProvider_Changed);
}
private void rb_CheckedChanged(object sender, System.EventArgs e)
{
txtFind.Enabled = rbString.Checked;
hexFind.Enabled = !txtFind.Enabled;
if(txtFind.Enabled)
txtFind.Focus();
else
hexFind.Focus();
}
private void rbString_Enter(object sender, EventArgs e)
{
txtFind.Focus();
}
private void rbHex_Enter(object sender, EventArgs e)
{
hexFind.Focus();
}
private void FormFind_Activated(object sender, System.EventArgs e)
{
if(rbString.Checked)
txtFind.Focus();
else
hexFind.Focus();
}
private void btnOK_Click(object sender, System.EventArgs e)
{
_findOptions.MatchCase = chkMatchCase.Checked;
var provider = this.hexFind.ByteProvider as DynamicByteProvider;
_findOptions.Hex = provider.Bytes.ToArray();
_findOptions.Text = txtFind.Text;
_findOptions.Type = rbHex.Checked ? FindType.Hex : FindType.Text;
_findOptions.MatchCase = chkMatchCase.Checked;
_findOptions.IsValid = true;
FindNext();
}
bool _finding;
public void FindNext()
{
if (!_findOptions.IsValid)
return;
UpdateUIToFindingState();
// start find process
long res = HexBox.Find(_findOptions);
UpdateUIToNormalState();
Application.DoEvents();
if (res == -1) // -1 = no match
{
MessageBox.Show(strings.FindOperationEndOfFile, Program.SoftwareName,
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (res == -2) // -2 = find was aborted
{
return;
}
else // something was found
{
this.Close();
Application.DoEvents();
if (!HexBox.Focused)
HexBox.Focus();
}
}
private void UpdateUIToNormalState()
{
timer.Stop();
timerPercent.Stop();
_finding = false;
txtFind.Enabled = chkMatchCase.Enabled = rbHex.Enabled = rbString.Enabled
= hexFind.Enabled = btnOK.Enabled = true;
}
private void UpdateUIToFindingState()
{
_finding = true;
timer.Start();
timerPercent.Start();
txtFind.Enabled = chkMatchCase.Enabled = rbHex.Enabled = rbString.Enabled
= hexFind.Enabled = btnOK.Enabled = false;
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
if (_finding)
this.HexBox.AbortFind();
else
this.Close();
}
private void txtString_TextChanged(object sender, EventArgs e)
{
ValidateFind();
}
private void ValidateFind()
{
var isValid = false;
if (rbString.Checked && txtFind.Text.Length > 0)
isValid = true;
if (rbHex.Checked && hexFind.ByteProvider.Length > 0)
isValid = true;
this.btnOK.Enabled = isValid;
}
private void timer_Tick(object sender, EventArgs e)
{
if (lblFinding.Text.Length == 13)
lblFinding.Text = "";
lblFinding.Text += ".";
}
private void timerPercent_Tick(object sender, EventArgs e)
{
long pos = this.HexBox.CurrentFindingPosition;
long length = HexBox.ByteProvider.Length;
double percent = (double)pos / (double)length * (double)100;
System.Globalization.NumberFormatInfo nfi =
new System.Globalization.CultureInfo("en-US").NumberFormat;
string text = percent.ToString("0.00", nfi) + " %";
lblPercent.Text = text;
}
private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Security.Policy;
using System.Reflection;
using System.Globalization;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Amib.Threading;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.EventQueue;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Interfaces;
namespace OpenSim.Region.ScriptEngine.XEngine
{
public class XEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SmartThreadPool m_ThreadPool;
private int m_MaxScriptQueue;
private Scene m_Scene;
private IConfig m_ScriptConfig = null;
private IConfigSource m_ConfigSource = null;
private ICompiler m_Compiler;
private int m_MinThreads;
private int m_MaxThreads ;
private int m_IdleTimeout;
private int m_StackSize;
private int m_SleepTime;
private int m_SaveTime;
private ThreadPriority m_Prio;
private bool m_Enabled = false;
private bool m_InitialStartup = true;
private int m_ScriptFailCount; // Number of script fails since compile queue was last empty
private string m_ScriptErrorMessage;
// disable warning: need to keep a reference to XEngine.EventManager
// alive to avoid it being garbage collected
#pragma warning disable 414
private EventManager m_EventManager;
#pragma warning restore 414
private IXmlRpcRouter m_XmlRpcRouter;
private int m_EventLimit;
private bool m_KillTimedOutScripts;
private static List<XEngine> m_ScriptEngines =
new List<XEngine>();
// Maps the local id to the script inventory items in it
private Dictionary<uint, List<UUID> > m_PrimObjects =
new Dictionary<uint, List<UUID> >();
// Maps the UUID above to the script instance
private Dictionary<UUID, IScriptInstance> m_Scripts =
new Dictionary<UUID, IScriptInstance>();
// Maps the asset ID to the assembly
private Dictionary<UUID, string> m_Assemblies =
new Dictionary<UUID, string>();
private Dictionary<string, int> m_AddingAssemblies =
new Dictionary<string, int>();
// This will list AppDomains by script asset
private Dictionary<UUID, AppDomain> m_AppDomains =
new Dictionary<UUID, AppDomain>();
// List the scripts running in each appdomain
private Dictionary<UUID, List<UUID> > m_DomainScripts =
new Dictionary<UUID, List<UUID> >();
private Queue m_CompileQueue = new Queue(100);
IWorkItemResult m_CurrentCompile = null;
public string ScriptEngineName
{
get { return "XEngine"; }
}
public Scene World
{
get { return m_Scene; }
}
public static List<XEngine> ScriptEngines
{
get { return m_ScriptEngines; }
}
public IScriptModule ScriptModule
{
get { return this; }
}
// private struct RezScriptParms
// {
// uint LocalID;
// UUID ItemID;
// string Script;
// }
public IConfig Config
{
get { return m_ScriptConfig; }
}
public IConfigSource ConfigSource
{
get { return m_ConfigSource; }
}
public event ScriptRemoved OnScriptRemoved;
public event ObjectRemoved OnObjectRemoved;
//
// IRegionModule functions
//
public void Initialise(IConfigSource configSource)
{
if (configSource.Configs["XEngine"] == null)
return;
m_ScriptConfig = configSource.Configs["XEngine"];
m_ConfigSource = configSource;
}
public void AddRegion(Scene scene)
{
if (m_ScriptConfig == null)
return;
m_ScriptFailCount = 0;
m_ScriptErrorMessage = String.Empty;
if (m_ScriptConfig == null)
{
// m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
return;
}
m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);
if (!m_Enabled)
return;
AppDomain.CurrentDomain.AssemblyResolve +=
OnAssemblyResolve;
m_log.InfoFormat("[XEngine] Initializing scripts in region {0}",
scene.RegionInfo.RegionName);
m_Scene = scene;
m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;
m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;
m_Prio = ThreadPriority.BelowNormal;
switch (priority)
{
case "Lowest":
m_Prio = ThreadPriority.Lowest;
break;
case "BelowNormal":
m_Prio = ThreadPriority.BelowNormal;
break;
case "Normal":
m_Prio = ThreadPriority.Normal;
break;
case "AboveNormal":
m_Prio = ThreadPriority.AboveNormal;
break;
case "Highest":
m_Prio = ThreadPriority.Highest;
break;
default:
m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
break;
}
lock (m_ScriptEngines)
{
m_ScriptEngines.Add(this);
}
// Needs to be here so we can queue the scripts that need starting
//
m_Scene.EventManager.OnRezScript += OnRezScript;
// Complete basic setup of the thread pool
//
SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
m_MaxScriptQueue, m_StackSize);
m_Scene.StackModuleInterface<IScriptModule>(this);
m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>();
if (m_XmlRpcRouter != null)
{
OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved;
OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved;
}
}
public void RemoveRegion(Scene scene)
{
lock (m_Scripts)
{
foreach (IScriptInstance instance in m_Scripts.Values)
{
// Force a final state save
//
if (m_Assemblies.ContainsKey(instance.AssetID))
{
string assembly = m_Assemblies[instance.AssetID];
instance.SaveState(assembly);
}
// Clear the event queue and abort the instance thread
//
instance.ClearQueue();
instance.Stop(0);
// Release events, timer, etc
//
instance.DestroyScriptInstance();
// Unload scripts and app domains
// Must be done explicitly because they have infinite
// lifetime
//
m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
if (m_DomainScripts[instance.AppDomain].Count == 0)
{
m_DomainScripts.Remove(instance.AppDomain);
UnloadAppDomain(instance.AppDomain);
}
}
m_Scripts.Clear();
m_PrimObjects.Clear();
m_Assemblies.Clear();
m_DomainScripts.Clear();
}
lock (m_ScriptEngines)
{
m_ScriptEngines.Remove(this);
}
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_EventManager = new EventManager(this);
m_Compiler = new Compiler(this);
m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
m_Scene.EventManager.OnScriptReset += OnScriptReset;
m_Scene.EventManager.OnStartScript += OnStartScript;
m_Scene.EventManager.OnStopScript += OnStopScript;
m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
m_Scene.EventManager.OnShutdown += OnShutdown;
if (m_SleepTime > 0)
{
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
new Object[]{ m_SleepTime });
}
if (m_SaveTime > 0)
{
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
new Object[] { m_SaveTime });
}
m_ThreadPool.Start();
}
public void Close()
{
lock (m_ScriptEngines)
{
if (m_ScriptEngines.Contains(this))
m_ScriptEngines.Remove(this);
}
}
public object DoBackup(object o)
{
Object[] p = (Object[])o;
int saveTime = (int)p[0];
if (saveTime > 0)
System.Threading.Thread.Sleep(saveTime);
// m_log.Debug("[XEngine] Backing up script states");
List<IScriptInstance> instances = new List<IScriptInstance>();
lock (m_Scripts)
{
foreach (IScriptInstance instance in m_Scripts.Values)
instances.Add(instance);
}
foreach (IScriptInstance i in instances)
{
string assembly = String.Empty;
lock (m_Scripts)
{
if (!m_Assemblies.ContainsKey(i.AssetID))
continue;
assembly = m_Assemblies[i.AssetID];
}
i.SaveState(assembly);
}
instances.Clear();
if (saveTime > 0)
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
new Object[] { saveTime });
return 0;
}
public object DoMaintenance(object p)
{
object[] parms = (object[])p;
int sleepTime = (int)parms[0];
foreach (IScriptInstance inst in m_Scripts.Values)
{
if (inst.EventTime() > m_EventLimit)
{
inst.Stop(100);
if (!m_KillTimedOutScripts)
inst.Start();
}
}
System.Threading.Thread.Sleep(sleepTime);
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
new Object[]{ sleepTime });
return 0;
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "XEngine"; }
}
public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
{
if (script.StartsWith("//MRM:"))
return;
List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());
List<string> names = new List<string>();
foreach (IScriptModule m in engines)
names.Add(m.ScriptEngineName);
int lineEnd = script.IndexOf('\n');
if (lineEnd > 1)
{
string firstline = script.Substring(0, lineEnd).Trim();
int colon = firstline.IndexOf(':');
if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
{
string engineName = firstline.Substring(2, colon-2);
if (names.Contains(engineName))
{
engine = engineName;
script = "//" + script.Substring(script.IndexOf(':')+1);
}
else
{
if (engine == ScriptEngineName)
{
SceneObjectPart part =
m_Scene.GetSceneObjectPart(
localID);
TaskInventoryItem item =
part.Inventory.GetInventoryItem(itemID);
ScenePresence presence =
m_Scene.GetScenePresence(
item.OwnerID);
if (presence != null)
{
presence.ControllingClient.SendAgentAlertMessage(
"Selected engine unavailable. "+
"Running script on "+
ScriptEngineName,
false);
}
}
}
}
}
if (engine != ScriptEngineName)
return;
Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};
if (stateSource == (int)StateSource.ScriptedRez)
{
DoOnRezScript(parms);
}
else
{
lock (m_CompileQueue)
{
m_CompileQueue.Enqueue(parms);
if (m_CurrentCompile == null)
{
m_CurrentCompile = m_ThreadPool.QueueWorkItem(
new WorkItemCallback(this.DoOnRezScriptQueue),
new Object[0]);
}
}
}
}
public Object DoOnRezScriptQueue(Object dummy)
{
if (m_InitialStartup)
{
m_InitialStartup = false;
System.Threading.Thread.Sleep(15000);
lock (m_CompileQueue)
{
if (m_CompileQueue.Count==0)
// No scripts on region, so won't get triggered later
// by the queue becoming empty so we trigger it here
m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty);
}
}
Object o;
lock (m_CompileQueue)
{
o = m_CompileQueue.Dequeue();
if (o == null)
{
m_CurrentCompile = null;
return null;
}
}
DoOnRezScript(o);
lock (m_CompileQueue)
{
if (m_CompileQueue.Count > 0)
{
m_CurrentCompile = m_ThreadPool.QueueWorkItem(
new WorkItemCallback(this.DoOnRezScriptQueue),
new Object[0]);
}
else
{
m_CurrentCompile = null;
m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
m_ScriptErrorMessage);
m_ScriptFailCount = 0;
}
}
return null;
}
private bool DoOnRezScript(object parm)
{
Object[] p = (Object[])parm;
uint localID = (uint)p[0];
UUID itemID = (UUID)p[1];
string script =(string)p[2];
int startParam = (int)p[3];
bool postOnRez = (bool)p[4];
StateSource stateSource = (StateSource)p[5];
// Get the asset ID of the script, so we can check if we
// already have it.
// We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
// m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock
// and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
if (part == null)
{
m_log.Error("[Script] SceneObjectPart unavailable. Script NOT started.");
m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
m_ScriptFailCount++;
return false;
}
TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
if (item == null)
{
m_ScriptErrorMessage += "Can't find script inventory item.\n";
m_ScriptFailCount++;
return false;
}
UUID assetID = item.AssetID;
//m_log.DebugFormat("[XEngine] Compiling script {0} ({1} on object {2})",
// item.Name, itemID.ToString(), part.ParentGroup.RootPart.Name);
ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);
string assembly = "";
CultureInfo USCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = USCulture;
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
try
{
lock (m_AddingAssemblies)
{
assembly = m_Compiler.PerformScriptCompile(script,
assetID.ToString(), item.OwnerID);
if (!m_AddingAssemblies.ContainsKey(assembly)) {
m_AddingAssemblies[assembly] = 1;
} else {
m_AddingAssemblies[assembly]++;
}
linemap = m_Compiler.LineMap();
}
string[] warnings = m_Compiler.GetWarnings();
if (warnings != null && warnings.Length != 0)
{
if (presence != null && (!postOnRez))
presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
foreach (string warning in warnings)
{
try
{
// DISPLAY WARNING INWORLD
string text = "Warning:\n" + warning;
if (text.Length > 1000)
text = text.Substring(0, 1000);
World.SimChat(Utils.StringToBytes(text),
ChatTypeEnum.DebugChannel, 2147483647,
part.AbsolutePosition,
part.Name, part.UUID, false);
}
catch (Exception e2) // LEGIT: User Scripting
{
m_log.Error("[XEngine]: " +
"Error displaying warning in-world: " +
e2.ToString());
m_log.Error("[XEngine]: " +
"Warning:\r\n" +
warning);
}
}
}
}
catch (Exception e)
{
if (presence != null && (!postOnRez))
presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
try
{
// DISPLAY ERROR INWORLD
m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();
m_ScriptFailCount++;
string text = "Error compiling script:\n" + e.Message.ToString();
if (text.Length > 1000)
text = text.Substring(0, 1000);
World.SimChat(Utils.StringToBytes(text),
ChatTypeEnum.DebugChannel, 2147483647,
part.AbsolutePosition,
part.Name, part.UUID, false);
}
catch (Exception e2) // LEGIT: User Scripting
{
m_log.Error("[XEngine]: "+
"Error displaying error in-world: " +
e2.ToString());
m_log.Error("[XEngine]: " +
"Errormessage: Error compiling script:\r\n" +
e.Message.ToString());
}
return false;
}
lock (m_Scripts)
{
ScriptInstance instance = null;
// Create the object record
if ((!m_Scripts.ContainsKey(itemID)) ||
(m_Scripts[itemID].AssetID != assetID))
{
UUID appDomain = assetID;
if (part.ParentGroup.IsAttachment)
appDomain = part.ParentGroup.RootPart.UUID;
if (!m_AppDomains.ContainsKey(appDomain))
{
try
{
AppDomainSetup appSetup = new AppDomainSetup();
// appSetup.ApplicationBase = Path.Combine(
// "ScriptEngines",
// m_Scene.RegionInfo.RegionID.ToString());
Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
Evidence evidence = new Evidence(baseEvidence);
AppDomain sandbox =
AppDomain.CreateDomain(
m_Scene.RegionInfo.RegionID.ToString(),
evidence, appSetup);
/*
PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
sandbox.SetAppDomainPolicy(sandboxPolicy);
*/
m_AppDomains[appDomain] = sandbox;
m_AppDomains[appDomain].AssemblyResolve +=
new ResolveEventHandler(
AssemblyResolver.OnAssemblyResolve);
m_DomainScripts[appDomain] = new List<UUID>();
}
catch (Exception e)
{
m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
m_ScriptErrorMessage += "Exception creating app domain:\n";
m_ScriptFailCount++;
lock (m_AddingAssemblies)
{
m_AddingAssemblies[assembly]--;
}
return false;
}
}
m_DomainScripts[appDomain].Add(itemID);
instance = new ScriptInstance(this, part,
itemID, assetID, assembly,
m_AppDomains[appDomain],
part.ParentGroup.RootPart.Name,
item.Name, startParam, postOnRez,
stateSource, m_MaxScriptQueue);
m_log.DebugFormat("[XEngine] Loaded script {0}.{1}, script UUID {2}, prim UUID {3} @ {4}",
part.ParentGroup.RootPart.Name, item.Name, assetID, part.UUID, part.ParentGroup.RootPart.AbsolutePosition.ToString());
instance.AppDomain = appDomain;
instance.LineMap = linemap;
m_Scripts[itemID] = instance;
}
lock (m_PrimObjects)
{
if (!m_PrimObjects.ContainsKey(localID))
m_PrimObjects[localID] = new List<UUID>();
if (!m_PrimObjects[localID].Contains(itemID))
m_PrimObjects[localID].Add(itemID);
}
if (!m_Assemblies.ContainsKey(assetID))
m_Assemblies[assetID] = assembly;
lock (m_AddingAssemblies)
{
m_AddingAssemblies[assembly]--;
}
if (instance!=null)
instance.Init();
}
return true;
}
public void OnRemoveScript(uint localID, UUID itemID)
{
lock (m_Scripts)
{
// Do we even have it?
if (!m_Scripts.ContainsKey(itemID))
return;
IScriptInstance instance=m_Scripts[itemID];
m_Scripts.Remove(itemID);
instance.ClearQueue();
instance.Stop(0);
SceneObjectPart part =
m_Scene.GetSceneObjectPart(localID);
if (part != null)
part.RemoveScriptEvents(itemID);
// bool objectRemoved = false;
lock (m_PrimObjects)
{
// Remove the script from it's prim
if (m_PrimObjects.ContainsKey(localID))
{
// Remove inventory item record
if (m_PrimObjects[localID].Contains(itemID))
m_PrimObjects[localID].Remove(itemID);
// If there are no more scripts, remove prim
if (m_PrimObjects[localID].Count == 0)
{
m_PrimObjects.Remove(localID);
// objectRemoved = true;
}
}
}
instance.RemoveState();
instance.DestroyScriptInstance();
m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
if (m_DomainScripts[instance.AppDomain].Count == 0)
{
m_DomainScripts.Remove(instance.AppDomain);
UnloadAppDomain(instance.AppDomain);
}
instance = null;
ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
if (handlerObjectRemoved != null)
handlerObjectRemoved(part.UUID);
CleanAssemblies();
}
ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
if (handlerScriptRemoved != null)
handlerScriptRemoved(itemID);
}
public void OnScriptReset(uint localID, UUID itemID)
{
ResetScript(itemID);
}
public void OnStartScript(uint localID, UUID itemID)
{
StartScript(itemID);
}
public void OnStopScript(uint localID, UUID itemID)
{
StopScript(itemID);
}
private void CleanAssemblies()
{
List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);
foreach (IScriptInstance i in m_Scripts.Values)
{
if (assetIDList.Contains(i.AssetID))
assetIDList.Remove(i.AssetID);
}
lock (m_AddingAssemblies)
{
foreach (UUID assetID in assetIDList)
{
// Do not remove assembly files if another instance of the script
// is currently initialising
if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
|| m_AddingAssemblies[m_Assemblies[assetID]] == 0)
{
// m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
try
{
if (File.Exists(m_Assemblies[assetID]))
File.Delete(m_Assemblies[assetID]);
if (File.Exists(m_Assemblies[assetID]+".text"))
File.Delete(m_Assemblies[assetID]+".text");
if (File.Exists(m_Assemblies[assetID]+".mdb"))
File.Delete(m_Assemblies[assetID]+".mdb");
if (File.Exists(m_Assemblies[assetID]+".map"))
File.Delete(m_Assemblies[assetID]+".map");
}
catch (Exception)
{
}
m_Assemblies.Remove(assetID);
}
}
}
}
private void UnloadAppDomain(UUID id)
{
if (m_AppDomains.ContainsKey(id))
{
AppDomain domain = m_AppDomains[id];
m_AppDomains.Remove(id);
AppDomain.Unload(domain);
domain = null;
// m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
}
}
//
// Start processing
//
private void SetupEngine(int minThreads, int maxThreads,
int idleTimeout, ThreadPriority threadPriority,
int maxScriptQueue, int stackSize)
{
m_MaxScriptQueue = maxScriptQueue;
STPStartInfo startInfo = new STPStartInfo();
startInfo.IdleTimeout = idleTimeout*1000; // convert to seconds as stated in .ini
startInfo.MaxWorkerThreads = maxThreads;
startInfo.MinWorkerThreads = minThreads;
startInfo.ThreadPriority = threadPriority;
startInfo.StackSize = stackSize;
startInfo.StartSuspended = true;
m_ThreadPool = new SmartThreadPool(startInfo);
}
//
// Used by script instances to queue event handler jobs
//
public IScriptWorkItem QueueEventHandler(object parms)
{
return new XWorkItem(m_ThreadPool.QueueWorkItem(
new WorkItemCallback(this.ProcessEventHandler),
parms));
}
/// <summary>
/// Process a previously posted script event.
/// </summary>
/// <param name="parms"></param>
/// <returns></returns>
private object ProcessEventHandler(object parms)
{
CultureInfo USCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = USCulture;
IScriptInstance instance = (ScriptInstance) parms;
//m_log.DebugFormat("[XENGINE]: Processing event for {0}", instance);
return instance.EventProcessor();
}
/// <summary>
/// Post event to an entire prim
/// </summary>
/// <param name="localID"></param>
/// <param name="p"></param>
/// <returns></returns>
public bool PostObjectEvent(uint localID, EventParams p)
{
bool result = false;
lock (m_PrimObjects)
{
if (!m_PrimObjects.ContainsKey(localID))
return false;
foreach (UUID itemID in m_PrimObjects[localID])
{
if (m_Scripts.ContainsKey(itemID))
{
IScriptInstance instance = m_Scripts[itemID];
if (instance != null)
{
instance.PostEvent(p);
result = true;
}
}
}
}
return result;
}
/// <summary>
/// Post an event to a single script
/// </summary>
/// <param name="itemID"></param>
/// <param name="p"></param>
/// <returns></returns>
public bool PostScriptEvent(UUID itemID, EventParams p)
{
if (m_Scripts.ContainsKey(itemID))
{
IScriptInstance instance = m_Scripts[itemID];
if (instance != null)
instance.PostEvent(p);
return true;
}
return false;
}
public bool PostScriptEvent(UUID itemID, string name, Object[] p)
{
Object[] lsl_p = new Object[p.Length];
for (int i = 0; i < p.Length ; i++)
{
if (p[i] is int)
lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
else if (p[i] is string)
lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
else if (p[i] is Vector3)
lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
else if (p[i] is Quaternion)
lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
else if (p[i] is float)
lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
else
lsl_p[i] = p[i];
}
return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
}
public bool PostObjectEvent(UUID itemID, string name, Object[] p)
{
SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
if (part == null)
return false;
Object[] lsl_p = new Object[p.Length];
for (int i = 0; i < p.Length ; i++)
{
if (p[i] is int)
lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
else if (p[i] is string)
lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
else if (p[i] is Vector3)
lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
else if (p[i] is Quaternion)
lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
else if (p[i] is float)
lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
else
lsl_p[i] = p[i];
}
return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
}
public Assembly OnAssemblyResolve(object sender,
ResolveEventArgs args)
{
if (!(sender is System.AppDomain))
return null;
string[] pathList = new string[] {"bin", "ScriptEngines",
Path.Combine("ScriptEngines",
m_Scene.RegionInfo.RegionID.ToString())};
string assemblyName = args.Name;
if (assemblyName.IndexOf(",") != -1)
assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
foreach (string s in pathList)
{
string path = Path.Combine(Directory.GetCurrentDirectory(),
Path.Combine(s, assemblyName))+".dll";
if (File.Exists(path))
return Assembly.LoadFrom(path);
}
return null;
}
private IScriptInstance GetInstance(UUID itemID)
{
IScriptInstance instance;
lock (m_Scripts)
{
if (!m_Scripts.ContainsKey(itemID))
return null;
instance = m_Scripts[itemID];
}
return instance;
}
public void SetScriptState(UUID itemID, bool running)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
{
if (running)
instance.Start();
else
instance.Stop(100);
}
}
public bool GetScriptState(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
return instance.Running;
return false;
}
public void ApiResetScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.ApiResetScript();
}
public void ResetScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.ResetScript();
}
public void StartScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.Start();
}
public void StopScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.Stop(0);
}
public DetectParams GetDetectParams(UUID itemID, int idx)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
return instance.GetDetectParams(idx);
return null;
}
public void SetMinEventDelay(UUID itemID, double delay)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.MinEventDelay = delay;
}
public UUID GetDetectID(UUID itemID, int idx)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
return instance.GetDetectID(idx);
return UUID.Zero;
}
public void SetState(UUID itemID, string newState)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return;
instance.SetState(newState);
}
public string GetState(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return "default";
return instance.State;
}
public int GetStartParameter(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return 0;
return instance.StartParam;
}
public void OnShutdown()
{
List<IScriptInstance> instances = new List<IScriptInstance>();
lock (m_Scripts)
{
foreach (IScriptInstance instance in m_Scripts.Values)
instances.Add(instance);
}
foreach (IScriptInstance i in instances)
{
// Stop the script, even forcibly if needed. Then flag
// it as shutting down and restore the previous run state
// for serialization, so the scripts don't come back
// dead after region restart
//
bool prevRunning = i.Running;
i.Stop(50);
i.ShuttingDown = true;
i.Running = prevRunning;
}
DoBackup(new Object[] {0});
}
public IScriptApi GetApi(UUID itemID, string name)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return null;
return instance.GetApi(name);
}
public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return;
IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
if (eq == null)
{
controllingClient.SendScriptRunningReply(objectID, itemID,
GetScriptState(itemID));
}
else
{
eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, GetScriptState(itemID), true),
controllingClient.AgentId);
}
}
public string GetAssemblyName(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return "";
return instance.GetAssemblyName();
}
public string GetXMLState(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return "";
return instance.GetXMLState();
}
public bool CanBeDeleted(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return true;
return instance.CanBeDeleted();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JoinRpg.DataModel;
namespace JoinRpg.Domain.CharacterFields
{
/// <summary>
/// Saves fields either to character or to claim
/// </summary>
//TODO That should be service with interface and costructed via DI container
public static class FieldSaveHelper
{
private abstract class FieldSaveStrategyBase
{
protected Claim? Claim { get; }
protected Character? Character { get; }
private int CurrentUserId { get; }
private IFieldDefaultValueGenerator Generator { get; }
protected Project Project { get; }
private List<FieldWithPreviousAndNewValue> UpdatedFields { get; } =
new List<FieldWithPreviousAndNewValue>();
protected FieldSaveStrategyBase(Claim? claim,
Character? character,
int currentUserId,
IFieldDefaultValueGenerator generator)
{
Claim = claim;
Character = character;
CurrentUserId = currentUserId;
Generator = generator;
Project = character?.Project ?? claim?.Project ?? throw new ArgumentNullException("",
"Either character or claim should be not null");
}
public IReadOnlyCollection<FieldWithPreviousAndNewValue> GetUpdatedFields() =>
UpdatedFields.Where(uf => uf.PreviousDisplayString != uf.DisplayString).ToList();
public abstract void Save(Dictionary<int, FieldWithValue> fields);
public Dictionary<int, FieldWithValue> LoadFields()
{
var fields =
Project.GetFieldsNotFilledWithoutOrder()
.ToList()
.FillIfEnabled(Claim, Character)
.ToDictionary(f => f.Field.ProjectFieldId);
return fields;
}
public void EnsureEditAccess(FieldWithValue field)
{
var accessArguments = Character != null
? new AccessArguments(Character, CurrentUserId)
: new AccessArguments(Claim!, CurrentUserId); // Either character or claim should be not null
var editAccess = field.HasEditAccess(accessArguments);
if (!editAccess)
{
throw new NoAccessToProjectException(Project, CurrentUserId);
}
}
/// <summary>
/// Returns true is the value has changed
/// </summary>
public bool AssignFieldValue(FieldWithValue field, string? newValue)
{
if (field.Value == newValue)
{
return false;
}
var existingField = UpdatedFields.FirstOrDefault(uf => uf.Field == field.Field);
if (existingField != null)
{
existingField.Value = newValue;
}
else
{
UpdatedFields.Add(
new FieldWithPreviousAndNewValue(field.Field, newValue, field.Value));
}
field.Value = newValue;
field.MarkUsed();
return true;
}
public string? GenerateDefaultValue(FieldWithValue field)
{
return field.Field.FieldBoundTo switch
{
FieldBoundTo.Character => Generator.CreateDefaultValue(Character, field),
FieldBoundTo.Claim => Generator.CreateDefaultValue(Claim, field),
_ => throw new ArgumentOutOfRangeException(),
};
}
protected abstract void SetCharacterNameFromPlayer();
}
private abstract class CharacterExistsStrategyBase : FieldSaveStrategyBase
{
protected new Character Character => base.Character!; //Character should always exists
protected CharacterExistsStrategyBase(Claim? claim, Character character, int currentUserId, IFieldDefaultValueGenerator generator)
: base(claim, character, currentUserId, generator)
{
}
protected void UpdateSpecialGroups(Dictionary<int, FieldWithValue> fields)
{
var ids = fields.Values.GenerateSpecialGroupsList();
var groupsToKeep = Character.Groups.Where(g => !g.IsSpecial)
.Select(g => g.CharacterGroupId);
Character.ParentCharacterGroupIds = groupsToKeep.Union(ids).ToArray();
}
protected void SetCharacterDescription(Dictionary<int, FieldWithValue> fields)
{
if (Project.Details.CharacterDescription != null)
{
Character.Description = new MarkdownString(
fields[Project.Details.CharacterDescription.ProjectFieldId].Value);
}
if (!Project.Details.CharacterNameLegacyMode)
{
if (Project.Details.CharacterNameField == null)
{
SetCharacterNameFromPlayer();
}
else
{
var name = fields[Project.Details.CharacterNameField.ProjectFieldId].Value;
Character.CharacterName = string.IsNullOrWhiteSpace(name) ?
Character.CharacterName = "CHAR" + Character.CharacterId
: name;
}
}
}
}
private class SaveToCharacterOnlyStrategy : CharacterExistsStrategyBase
{
public SaveToCharacterOnlyStrategy(
Character character,
int currentUserId,
IFieldDefaultValueGenerator generator)
: base(claim: null,
character,
currentUserId,
generator)
{
}
public override void Save(Dictionary<int, FieldWithValue> fields)
{
Character.JsonData = fields.Values
.Where(v => v.Field.FieldBoundTo == FieldBoundTo.Character).SerializeFields();
SetCharacterDescription(fields);
UpdateSpecialGroups(fields);
}
protected override void SetCharacterNameFromPlayer()
{
//TODO: we don't have player yet, but have to set player name from it.
//M.b. Disallow create characters in this scenarios?
Character.CharacterName = Character.CharacterName ?? "PLAYER_NAME";
}
}
private class SaveToClaimOnlyStrategy : FieldSaveStrategyBase
{
protected new Claim Claim => base.Claim!; //Claim should always exists
public SaveToClaimOnlyStrategy(Claim claim,
int currentUserId,
IFieldDefaultValueGenerator generator) : base(claim,
character: null,
currentUserId,
generator)
{
}
public override void Save(Dictionary<int, FieldWithValue> fields)
{
//TODO do not save fields that have values same as character's
Claim.JsonData = fields.Values.SerializeFields();
}
protected override void SetCharacterNameFromPlayer()
{
//Do nothing player could not change character yet
}
}
private class SaveToCharacterAndClaimStrategy : CharacterExistsStrategyBase
{
protected new Claim Claim => base.Claim!; //Claim should always exists
public SaveToCharacterAndClaimStrategy(Claim claim,
Character character,
int currentUserId,
IFieldDefaultValueGenerator generator) : base(claim,
character,
currentUserId,
generator)
{
}
public override void Save(Dictionary<int, FieldWithValue> fields)
{
Character.JsonData = fields.Values
.Where(v => v.Field.FieldBoundTo == FieldBoundTo.Character).SerializeFields();
Claim.JsonData = fields.Values
.Where(v => v.Field.FieldBoundTo == FieldBoundTo.Claim).SerializeFields();
SetCharacterDescription(fields);
UpdateSpecialGroups(fields);
}
protected override void SetCharacterNameFromPlayer() => Character.CharacterName = Claim.Player.GetDisplayName();
}
/// <summary>
/// Saves character fields
/// </summary>
/// <returns>Fields that have changed.</returns>
[MustUseReturnValue]
public static IReadOnlyCollection<FieldWithPreviousAndNewValue> SaveCharacterFields(
int currentUserId,
[NotNull]
Claim claim,
[NotNull]
IReadOnlyDictionary<int, string?> newFieldValue,
IFieldDefaultValueGenerator generator)
{
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
return SaveCharacterFieldsImpl(currentUserId,
claim.Character,
claim,
newFieldValue,
generator);
}
/// <summary>
/// Saves fields of a character
/// </summary>
/// <returns>The list of updated fields</returns>
[MustUseReturnValue]
public static IReadOnlyCollection<FieldWithPreviousAndNewValue> SaveCharacterFields(
int currentUserId,
[NotNull]
Character character,
IReadOnlyDictionary<int, string?> newFieldValue,
IFieldDefaultValueGenerator generator)
{
if (character == null)
{
throw new ArgumentNullException(nameof(character));
}
return SaveCharacterFieldsImpl(currentUserId,
character,
character.ApprovedClaim,
newFieldValue,
generator);
}
[MustUseReturnValue]
private static IReadOnlyCollection<FieldWithPreviousAndNewValue> SaveCharacterFieldsImpl(
int currentUserId,
Character? character,
Claim? claim,
[NotNull]
IReadOnlyDictionary<int, string?> newFieldValue,
IFieldDefaultValueGenerator generator)
{
if (newFieldValue == null)
{
throw new ArgumentNullException(nameof(newFieldValue));
}
var strategy = CreateStrategy(currentUserId, character, claim, generator);
var fields = strategy.LoadFields();
AssignValues(newFieldValue, fields, strategy);
GenerateDefaultValues(character, fields, strategy);
strategy.Save(fields);
return strategy.GetUpdatedFields();
}
private static FieldSaveStrategyBase CreateStrategy(int currentUserId, Character? character,
Claim? claim, IFieldDefaultValueGenerator generator)
{
return (claim, character) switch
{
(null, Character ch) => new SaveToCharacterOnlyStrategy(ch, currentUserId, generator),
({ IsApproved: true }, Character ch) => new SaveToCharacterAndClaimStrategy(claim!, ch, currentUserId, generator),
({ IsApproved: false }, _) => new SaveToClaimOnlyStrategy(claim!, currentUserId, generator),
_ => throw new InvalidOperationException("Either claim or character should be correct"),
};
}
private static void AssignValues(IReadOnlyDictionary<int, string?> newFieldValue, Dictionary<int, FieldWithValue> fields,
FieldSaveStrategyBase strategy)
{
foreach (var keyValuePair in newFieldValue)
{
var field = fields[keyValuePair.Key];
strategy.EnsureEditAccess(field);
var normalizedValue = NormalizeValueBeforeAssign(field, keyValuePair.Value);
if (normalizedValue is null && field.Field.MandatoryStatus == MandatoryStatus.Required)
{
throw new FieldRequiredException(field.Field.FieldName);
}
_ = strategy.AssignFieldValue(field, normalizedValue);
}
}
private static void GenerateDefaultValues(Character? character, Dictionary<int, FieldWithValue> fields,
FieldSaveStrategyBase strategy)
{
foreach (var field in fields.Values.Where(
f => !f.HasEditableValue && f.Field.CanHaveValue() &&
f.Field.IsAvailableForTarget(character)))
{
var newValue = strategy.GenerateDefaultValue(field);
var normalizedValue = NormalizeValueBeforeAssign(field, newValue);
_ = strategy.AssignFieldValue(field, normalizedValue);
}
}
private static string? NormalizeValueBeforeAssign(FieldWithValue field, string? toAssign)
{
switch (field.Field.FieldType)
{
case ProjectFieldType.Checkbox:
return toAssign?.StartsWith(FieldWithValue.CheckboxValueOn) == true
? FieldWithValue.CheckboxValueOn
: "";
default:
return string.IsNullOrEmpty(toAssign) ? null : toAssign;
}
}
}
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto;
using NBitcoin.BouncyCastle.Crypto.Parameters;
using NBitcoin.BouncyCastle.Math;
namespace NBitcoin.BouncyCastle.Crypto.Encodings
{
/**
* ISO 9796-1 padding. Note in the light of recent results you should
* only use this with RSA (rather than the "simpler" Rabin keys) and you
* should never use it with anything other than a hash (ie. even if the
* message is small don't sign the message, sign it's hash) or some "random"
* value. See your favorite search engine for details.
*/
public class ISO9796d1Encoding
: IAsymmetricBlockCipher
{
private static readonly BigInteger Sixteen = BigInteger.ValueOf(16);
private static readonly BigInteger Six = BigInteger.ValueOf(6);
private static readonly byte[] shadows = { 0xe, 0x3, 0x5, 0x8, 0x9, 0x4, 0x2, 0xf,
0x0, 0xd, 0xb, 0x6, 0x7, 0xa, 0xc, 0x1 };
private static readonly byte[] inverse = { 0x8, 0xf, 0x6, 0x1, 0x5, 0x2, 0xb, 0xc,
0x3, 0x4, 0xd, 0xa, 0xe, 0x9, 0x0, 0x7 };
private readonly IAsymmetricBlockCipher engine;
private bool forEncryption;
private int bitSize;
private int padBits = 0;
private BigInteger modulus;
public ISO9796d1Encoding(
IAsymmetricBlockCipher cipher)
{
this.engine = cipher;
}
public string AlgorithmName
{
get { return engine.AlgorithmName + "/ISO9796-1Padding"; }
}
public IAsymmetricBlockCipher GetUnderlyingCipher()
{
return engine;
}
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
RsaKeyParameters kParam;
if (parameters is ParametersWithRandom)
{
ParametersWithRandom rParam = (ParametersWithRandom)parameters;
kParam = (RsaKeyParameters)rParam.Parameters;
}
else
{
kParam = (RsaKeyParameters)parameters;
}
engine.Init(forEncryption, parameters);
modulus = kParam.Modulus;
bitSize = modulus.BitLength;
this.forEncryption = forEncryption;
}
/**
* return the input block size. The largest message we can process
* is (key_size_in_bits + 3)/16, which in our world comes to
* key_size_in_bytes / 2.
*/
public int GetInputBlockSize()
{
int baseBlockSize = engine.GetInputBlockSize();
if (forEncryption)
{
return (baseBlockSize + 1) / 2;
}
else
{
return baseBlockSize;
}
}
/**
* return the maximum possible size for the output.
*/
public int GetOutputBlockSize()
{
int baseBlockSize = engine.GetOutputBlockSize();
if (forEncryption)
{
return baseBlockSize;
}
else
{
return (baseBlockSize + 1) / 2;
}
}
/**
* set the number of bits in the next message to be treated as
* pad bits.
*/
public void SetPadBits(
int padBits)
{
if (padBits > 7)
{
throw new ArgumentException("padBits > 7");
}
this.padBits = padBits;
}
/**
* retrieve the number of pad bits in the last decoded message.
*/
public int GetPadBits()
{
return padBits;
}
public byte[] ProcessBlock(
byte[] input,
int inOff,
int length)
{
if (forEncryption)
{
return EncodeBlock(input, inOff, length);
}
else
{
return DecodeBlock(input, inOff, length);
}
}
private byte[] EncodeBlock(
byte[] input,
int inOff,
int inLen)
{
byte[] block = new byte[(bitSize + 7) / 8];
int r = padBits + 1;
int z = inLen;
int t = (bitSize + 13) / 16;
for (int i = 0; i < t; i += z)
{
if (i > t - z)
{
Array.Copy(input, inOff + inLen - (t - i),
block, block.Length - t, t - i);
}
else
{
Array.Copy(input, inOff, block, block.Length - (i + z), z);
}
}
for (int i = block.Length - 2 * t; i != block.Length; i += 2)
{
byte val = block[block.Length - t + i / 2];
block[i] = (byte)((shadows[(uint) (val & 0xff) >> 4] << 4)
| shadows[val & 0x0f]);
block[i + 1] = val;
}
block[block.Length - 2 * z] ^= (byte) r;
block[block.Length - 1] = (byte)((block[block.Length - 1] << 4) | 0x06);
int maxBit = (8 - (bitSize - 1) % 8);
int offSet = 0;
if (maxBit != 8)
{
block[0] &= (byte) ((ushort) 0xff >> maxBit);
block[0] |= (byte) ((ushort) 0x80 >> maxBit);
}
else
{
block[0] = 0x00;
block[1] |= 0x80;
offSet = 1;
}
return engine.ProcessBlock(block, offSet, block.Length - offSet);
}
/**
* @exception InvalidCipherTextException if the decrypted block is not a valid ISO 9796 bit string
*/
private byte[] DecodeBlock(
byte[] input,
int inOff,
int inLen)
{
byte[] block = engine.ProcessBlock(input, inOff, inLen);
int r = 1;
int t = (bitSize + 13) / 16;
BigInteger iS = new BigInteger(1, block);
BigInteger iR;
if (iS.Mod(Sixteen).Equals(Six))
{
iR = iS;
}
else
{
iR = modulus.Subtract(iS);
if (!iR.Mod(Sixteen).Equals(Six))
throw new InvalidCipherTextException("resulting integer iS or (modulus - iS) is not congruent to 6 mod 16");
}
block = iR.ToByteArrayUnsigned();
if ((block[block.Length - 1] & 0x0f) != 0x6)
throw new InvalidCipherTextException("invalid forcing byte in block");
block[block.Length - 1] =
(byte)(((ushort)(block[block.Length - 1] & 0xff) >> 4)
| ((inverse[(block[block.Length - 2] & 0xff) >> 4]) << 4));
block[0] = (byte)((shadows[(uint) (block[1] & 0xff) >> 4] << 4)
| shadows[block[1] & 0x0f]);
bool boundaryFound = false;
int boundary = 0;
for (int i = block.Length - 1; i >= block.Length - 2 * t; i -= 2)
{
int val = ((shadows[(uint) (block[i] & 0xff) >> 4] << 4)
| shadows[block[i] & 0x0f]);
if (((block[i - 1] ^ val) & 0xff) != 0)
{
if (!boundaryFound)
{
boundaryFound = true;
r = (block[i - 1] ^ val) & 0xff;
boundary = i - 1;
}
else
{
throw new InvalidCipherTextException("invalid tsums in block");
}
}
}
block[boundary] = 0;
byte[] nblock = new byte[(block.Length - boundary) / 2];
for (int i = 0; i < nblock.Length; i++)
{
nblock[i] = block[2 * i + boundary + 1];
}
padBits = r - 1;
return nblock;
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/control.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Api {
/// <summary>Holder for reflection information generated from google/api/control.proto</summary>
public static partial class ControlReflection {
#region Descriptor
/// <summary>File descriptor for google/api/control.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ControlReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chhnb29nbGUvYXBpL2NvbnRyb2wucHJvdG8SCmdvb2dsZS5hcGkiHgoHQ29u",
"dHJvbBITCgtlbnZpcm9ubWVudBgBIAEoCUJuCg5jb20uZ29vZ2xlLmFwaUIM",
"Q29udHJvbFByb3RvUAFaRWdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dv",
"b2dsZWFwaXMvYXBpL3NlcnZpY2Vjb25maWc7c2VydmljZWNvbmZpZ6ICBEdB",
"UEliBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Control), global::Google.Api.Control.Parser, new[]{ "Environment" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Selects and configures the service controller used by the service. The
/// service controller handles features like abuse, quota, billing, logging,
/// monitoring, etc.
/// </summary>
public sealed partial class Control : pb::IMessage<Control>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Control> _parser = new pb::MessageParser<Control>(() => new Control());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Control> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.ControlReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Control() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Control(Control other) : this() {
environment_ = other.environment_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Control Clone() {
return new Control(this);
}
/// <summary>Field number for the "environment" field.</summary>
public const int EnvironmentFieldNumber = 1;
private string environment_ = "";
/// <summary>
/// The service control environment to use. If empty, no control plane
/// feature (like quota and billing) will be enabled.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Environment {
get { return environment_; }
set {
environment_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Control);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Control other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Environment != other.Environment) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Environment.Length != 0) hash ^= Environment.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Environment.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Environment);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Environment.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Environment);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Environment.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Environment);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Control other) {
if (other == null) {
return;
}
if (other.Environment.Length != 0) {
Environment = other.Environment;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Environment = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Environment = input.ReadString();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Battleships.WebServices.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);
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// Reference.cs
//
// 21 [....] 2000
//
namespace System.Security.Cryptography.Xml
{
using System;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Xml;
using System.Globalization;
using System.Runtime.Versioning;
[Serializable]
internal enum ReferenceTargetType {
Stream,
XmlElement,
UriReference
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class Reference {
private string m_id;
private string m_uri;
private string m_type;
private TransformChain m_transformChain;
private string m_digestMethod;
private byte[] m_digestValue;
private HashAlgorithm m_hashAlgorithm;
private Object m_refTarget;
private ReferenceTargetType m_refTargetType;
private XmlElement m_cachedXml;
private SignedXml m_signedXml = null;
internal CanonicalXmlNodeList m_namespaces = null;
//
// public constructors
//
public Reference () {
m_transformChain = new TransformChain();
m_refTarget = null;
m_refTargetType = ReferenceTargetType.UriReference;
m_cachedXml = null;
m_digestMethod = SignedXml.XmlDsigSHA1Url;
}
public Reference (Stream stream) {
m_transformChain = new TransformChain();
m_refTarget = stream;
m_refTargetType = ReferenceTargetType.Stream;
m_cachedXml = null;
m_digestMethod = SignedXml.XmlDsigSHA1Url;
}
public Reference (string uri) {
m_transformChain = new TransformChain();
m_refTarget = uri;
m_uri = uri;
m_refTargetType = ReferenceTargetType.UriReference;
m_cachedXml = null;
m_digestMethod = SignedXml.XmlDsigSHA1Url;
}
internal Reference (XmlElement element) {
m_transformChain = new TransformChain();
m_refTarget = element;
m_refTargetType = ReferenceTargetType.XmlElement;
m_cachedXml = null;
m_digestMethod = SignedXml.XmlDsigSHA1Url;
}
//
// public properties
//
public string Id {
get { return m_id; }
set { m_id = value; }
}
public string Uri {
get { return m_uri; }
set {
m_uri = value;
m_cachedXml = null;
}
}
public string Type {
get { return m_type; }
set {
m_type = value;
m_cachedXml = null;
}
}
public string DigestMethod {
get { return m_digestMethod; }
set {
m_digestMethod = value;
m_cachedXml = null;
}
}
public byte[] DigestValue {
get { return m_digestValue; }
set {
m_digestValue = value;
m_cachedXml = null;
}
}
public TransformChain TransformChain {
get {
if (m_transformChain == null)
m_transformChain = new TransformChain();
return m_transformChain;
}
[ComVisible(false)]
set {
m_transformChain = value;
m_cachedXml = null;
}
}
internal bool CacheValid {
get {
return (m_cachedXml != null);
}
}
internal SignedXml SignedXml {
get { return m_signedXml; }
set { m_signedXml = value; }
}
internal ReferenceTargetType ReferenceTargetType {
get {
return m_refTargetType;
}
}
//
// public methods
//
public XmlElement GetXml() {
if (CacheValid) return(m_cachedXml);
XmlDocument document = new XmlDocument();
document.PreserveWhitespace = true;
return GetXml(document);
}
internal XmlElement GetXml (XmlDocument document) {
// Create the Reference
XmlElement referenceElement = document.CreateElement("Reference", SignedXml.XmlDsigNamespaceUrl);
if (!String.IsNullOrEmpty(m_id))
referenceElement.SetAttribute("Id", m_id);
if (m_uri != null)
referenceElement.SetAttribute("URI", m_uri);
if (!String.IsNullOrEmpty(m_type))
referenceElement.SetAttribute("Type", m_type);
// Add the transforms to the Reference
if (this.TransformChain.Count != 0)
referenceElement.AppendChild(this.TransformChain.GetXml(document, SignedXml.XmlDsigNamespaceUrl));
// Add the DigestMethod
if (String.IsNullOrEmpty(m_digestMethod))
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_DigestMethodRequired"));
XmlElement digestMethodElement = document.CreateElement("DigestMethod", SignedXml.XmlDsigNamespaceUrl);
digestMethodElement.SetAttribute("Algorithm",m_digestMethod);
referenceElement.AppendChild(digestMethodElement);
if (DigestValue == null) {
if (m_hashAlgorithm.Hash == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_DigestValueRequired"));
DigestValue = m_hashAlgorithm.Hash;
}
XmlElement digestValueElement = document.CreateElement("DigestValue", SignedXml.XmlDsigNamespaceUrl);
digestValueElement.AppendChild(document.CreateTextNode(Convert.ToBase64String(m_digestValue)));
referenceElement.AppendChild(digestValueElement);
return referenceElement;
}
public void LoadXml(XmlElement value) {
if (value == null)
throw new ArgumentNullException("value");
m_id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl);
m_uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl);
m_type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl);
XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);
nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
// Transforms
this.TransformChain = new TransformChain();
XmlElement transformsElement = value.SelectSingleNode("ds:Transforms", nsm) as XmlElement;
if (transformsElement != null) {
XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm);
if (transformNodes != null) {
foreach (XmlNode transformNode in transformNodes) {
XmlElement transformElement = transformNode as XmlElement;
string algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
Transform transform = CryptoConfig.CreateFromName(algorithm) as Transform;
if (transform == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UnknownTransform"));
AddTransform(transform);
// let the transform read the children of the transformElement for data
transform.LoadInnerXml(transformElement.ChildNodes);
// Hack! this is done to get around the lack of here() function support in XPath
if (transform is XmlDsigEnvelopedSignatureTransform) {
// Walk back to the Signature tag. Find the nearest signature ancestor
// Signature-->SignedInfo-->Reference-->Transforms-->Transform
XmlNode signatureTag = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm);
XmlNodeList signatureList = transformElement.SelectNodes("//ds:Signature", nsm);
if (signatureList != null) {
int position = 0;
foreach(XmlNode node in signatureList) {
position++;
if (node == signatureTag) {
((XmlDsigEnvelopedSignatureTransform)transform).SignaturePosition = position;
break;
}
}
}
}
}
}
}
// DigestMethod
XmlElement digestMethodElement = value.SelectSingleNode("ds:DigestMethod", nsm) as XmlElement;
if (digestMethodElement == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestMethod");
m_digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
// DigestValue
XmlElement digestValueElement = value.SelectSingleNode("ds:DigestValue", nsm) as XmlElement;
if (digestValueElement == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestValue");
m_digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText));
// cache the Xml
m_cachedXml = value;
}
public void AddTransform(Transform transform) {
if (transform == null)
throw new ArgumentNullException("transform");
transform.Reference = this;
this.TransformChain.Add(transform);
}
internal void UpdateHashValue(XmlDocument document, CanonicalXmlNodeList refList) {
DigestValue = CalculateHashValue(document, refList);
}
// What we want to do is pump the input throug the TransformChain and then
// hash the output of the chain document is the document context for resolving relative references
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) {
// refList is a list of elements that might be targets of references
// Now's the time to create our hashing algorithm
m_hashAlgorithm = CryptoConfig.CreateFromName(m_digestMethod) as HashAlgorithm;
if (m_hashAlgorithm == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));
// Let's go get the target.
string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI);
Stream hashInputStream = null;
WebRequest request = null;
WebResponse response = null;
Stream inputStream = null;
XmlResolver resolver = null;
byte[] hashval = null;
try {
switch (m_refTargetType) {
case ReferenceTargetType.Stream:
// This is the easiest case. We already have a stream, so just pump it through the TransformChain
resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
hashInputStream = this.TransformChain.TransformToOctetStream((Stream) m_refTarget, resolver, baseUri);
break;
case ReferenceTargetType.UriReference:
// Second-easiest case -- dereference the URI & pump through the TransformChain
// handle the special cases where the URI is null (meaning whole doc)
// or the URI is just a fragment (meaning a reference to an embedded Object)
if (m_uri == null) {
// We need to create a DocumentNavigator out of the XmlElement
resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
// In the case of a Uri-less reference, we will simply pass null to the transform chain.
// The first transform in the chain is expected to know how to retrieve the data to hash.
hashInputStream = this.TransformChain.TransformToOctetStream((Stream) null, resolver, baseUri);
} else if (m_uri.Length == 0) {
// This is the self-referential case. First, check that we have a document context.
// The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process
if (document == null)
throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), m_uri));
// Normalize the containing document
resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri));
hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri);
} else if (m_uri[0] == '#') {
// If we get here, then we are constructing a Reference to an embedded DataObject
// referenced by an Id = attribute. Go find the relevant object
bool discardComments = true;
string idref = Utils.GetIdFromLocalUri(m_uri, out discardComments);
if (idref == "xpointer(/)") {
// This is a self referencial case
if (document == null)
throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"),m_uri));
// We should not discard comments here!!!
resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri);
break;
}
XmlElement elem = this.SignedXml.GetIdElement(document, idref);
if (elem != null)
m_namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement);
if (elem == null) {
// Go throw the referenced items passed in
if (refList != null) {
foreach (XmlNode node in refList) {
XmlElement tempElem = node as XmlElement;
if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl))
&& (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref))) {
elem = tempElem;
if (this.m_signedXml.m_context != null)
m_namespaces = Utils.GetPropagatedAttributes(this.m_signedXml.m_context);
break;
}
}
}
}
if (elem == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidReference"));
XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri);
// Add the propagated attributes
Utils.AddNamespaces(normDocument.DocumentElement, m_namespaces);
resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
if (discardComments) {
// We should discard comments before going into the transform chain
XmlDocument docWithNoComments = Utils.DiscardComments(normDocument);
hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri);
} else {
// This is an XPointer reference, do not discard comments!!!
hashInputStream = this.TransformChain.TransformToOctetStream(normDocument, resolver, baseUri);
}
} else {
// WebRequest always expects an Absolute Uri, so try to resolve if we were passed a relative Uri.
System.Uri uri = new System.Uri(m_uri, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri) {
uri = new Uri(new Uri(baseUri), uri);
}
request = WebRequest.Create(uri);
if (request == null) goto default;
response = request.GetResponse();
if (response == null) goto default;
inputStream = response.GetResponseStream();
if (inputStream == null) goto default;
resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
hashInputStream = this.TransformChain.TransformToOctetStream(inputStream, resolver, m_uri);
}
break;
case ReferenceTargetType.XmlElement:
// We need to create a DocumentNavigator out of the XmlElement
resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement) m_refTarget, resolver, baseUri), resolver, baseUri);
break;
default:
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), m_uri);
}
// Compute the new hash value
hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream);
hashval = m_hashAlgorithm.ComputeHash(hashInputStream);
}
finally {
if (hashInputStream != null)
hashInputStream.Close();
if (response != null)
response.Close();
if (inputStream != null)
inputStream.Close();
}
return hashval;
}
}
}
| |
/*
* Vericred API
*
* Vericred's API allows you to search for Health Plans that a specific doctor
accepts.
## Getting Started
Visit our [Developer Portal](https://developers.vericred.com) to
create an account.
Once you have created an account, you can create one Application for
Production and another for our Sandbox (select the appropriate Plan when
you create the Application).
## SDKs
Our API follows standard REST conventions, so you can use any HTTP client
to integrate with us. You will likely find it easier to use one of our
[autogenerated SDKs](https://github.com/vericred/?query=vericred-),
which we make available for several common programming languages.
## Authentication
To authenticate, pass the API Key you created in the Developer Portal as
a `Vericred-Api-Key` header.
`curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Versioning
Vericred's API default to the latest version. However, if you need a specific
version, you can request it with an `Accept-Version` header.
The current version is `v3`. Previous versions are `v1` and `v2`.
`curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Pagination
Endpoints that accept `page` and `per_page` parameters are paginated. They expose
four additional fields that contain data about your position in the response,
namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988).
For example, to display 5 results per page and view the second page of a
`GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`.
## Sideloading
When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s
we sideload the associated data. In this example, we would provide an Array of
`State`s and a `state_id` for each provider. This is done primarily to reduce the
payload size since many of the `Provider`s will share a `State`
```
{
providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }],
states: [{ id: 1, code: 'NY' }]
}
```
If you need the second level of the object graph, you can just match the
corresponding id.
## Selecting specific data
All endpoints allow you to specify which fields you would like to return.
This allows you to limit the response to contain only the data you need.
For example, let's take a request that returns the following JSON by default
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890',
field_we_dont_care_about: 'value_we_dont_care_about'
},
states: [{
id: 1,
name: 'New York',
code: 'NY',
field_we_dont_care_about: 'value_we_dont_care_about'
}]
}
```
To limit our results to only return the fields we care about, we specify the
`select` query string parameter for the corresponding fields in the JSON
document.
In this case, we want to select `name` and `phone` from the `provider` key,
so we would add the parameters `select=provider.name,provider.phone`.
We also want the `name` and `code` from the `states` key, so we would
add the parameters `select=states.name,staes.code`. The id field of
each document is always returned whether or not it is requested.
Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code`
The response would be
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890'
},
states: [{
id: 1,
name: 'New York',
code: 'NY'
}]
}
```
## Benefits summary format
Benefit cost-share strings are formatted to capture:
* Network tiers
* Compound or conditional cost-share
* Limits on the cost-share
* Benefit-specific maximum out-of-pocket costs
**Example #1**
As an example, we would represent [this Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as:
* **Hospital stay facility fees**:
- Network Provider: `$400 copay/admit plus 20% coinsurance`
- Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance`
- Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible`
* **Rehabilitation services:**
- Network Provider: `20% coinsurance`
- Out-of-Network Provider: `50% coinsurance`
- Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.`
- Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period`
**Example #2**
In [this other Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies.
* **Specialty drugs:**
- Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply`
- Out-of-Network Provider `Not covered`
- Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%`
**BNF**
Here's a description of the benefits summary string, represented as a context-free grammar:
```
<cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit>
<tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:"
<opt-num-prefix> ::= "first" <num> <unit> | ""
<unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)"
<value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable"
<compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible>
<copay> ::= "$" <num>
<coinsurace> ::= <num> "%"
<ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited"
<opt-per-unit> ::= "per day" | "per visit" | "per stay" | ""
<deductible> ::= "before deductible" | "after deductible" | ""
<tier-limit> ::= ", " <limit> | ""
<benefit-limit> ::= <limit> | ""
```
*
* OpenAPI spec version: 1.0.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.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace IO.Vericred.Model
{
/// <summary>
/// State
/// </summary>
[DataContract]
public partial class State : IEquatable<State>
{
/// <summary>
/// Initializes a new instance of the <see cref="State" /> class.
/// </summary>
/// <param name="Id">Primary Key of State.</param>
/// <param name="Name">Name of state.</param>
/// <param name="Code">2 letter code for state.</param>
/// <param name="FipsNumber">National FIPs number.</param>
/// <param name="LastDateForIndividual">Last date this state is live for individuals.</param>
/// <param name="LastDateForShop">Last date this state is live for shop.</param>
/// <param name="LiveForBusiness">Is this State available for businesses.</param>
/// <param name="LiveForConsumers">Is this State available for individuals.</param>
public State(int? Id = null, string Name = null, string Code = null, string FipsNumber = null, DateTime? LastDateForIndividual = null, DateTime? LastDateForShop = null, bool? LiveForBusiness = null, bool? LiveForConsumers = null)
{
this.Id = Id;
this.Name = Name;
this.Code = Code;
this.FipsNumber = FipsNumber;
this.LastDateForIndividual = LastDateForIndividual;
this.LastDateForShop = LastDateForShop;
this.LiveForBusiness = LiveForBusiness;
this.LiveForConsumers = LiveForConsumers;
}
/// <summary>
/// Primary Key of State
/// </summary>
/// <value>Primary Key of State</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; set; }
/// <summary>
/// Name of state
/// </summary>
/// <value>Name of state</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// 2 letter code for state
/// </summary>
/// <value>2 letter code for state</value>
[DataMember(Name="code", EmitDefaultValue=false)]
public string Code { get; set; }
/// <summary>
/// National FIPs number
/// </summary>
/// <value>National FIPs number</value>
[DataMember(Name="fips_number", EmitDefaultValue=false)]
public string FipsNumber { get; set; }
/// <summary>
/// Last date this state is live for individuals
/// </summary>
/// <value>Last date this state is live for individuals</value>
[DataMember(Name="last_date_for_individual", EmitDefaultValue=false)]
public DateTime? LastDateForIndividual { get; set; }
/// <summary>
/// Last date this state is live for shop
/// </summary>
/// <value>Last date this state is live for shop</value>
[DataMember(Name="last_date_for_shop", EmitDefaultValue=false)]
public DateTime? LastDateForShop { get; set; }
/// <summary>
/// Is this State available for businesses
/// </summary>
/// <value>Is this State available for businesses</value>
[DataMember(Name="live_for_business", EmitDefaultValue=false)]
public bool? LiveForBusiness { get; set; }
/// <summary>
/// Is this State available for individuals
/// </summary>
/// <value>Is this State available for individuals</value>
[DataMember(Name="live_for_consumers", EmitDefaultValue=false)]
public bool? LiveForConsumers { 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 State {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Code: ").Append(Code).Append("\n");
sb.Append(" FipsNumber: ").Append(FipsNumber).Append("\n");
sb.Append(" LastDateForIndividual: ").Append(LastDateForIndividual).Append("\n");
sb.Append(" LastDateForShop: ").Append(LastDateForShop).Append("\n");
sb.Append(" LiveForBusiness: ").Append(LiveForBusiness).Append("\n");
sb.Append(" LiveForConsumers: ").Append(LiveForConsumers).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as State);
}
/// <summary>
/// Returns true if State instances are equal
/// </summary>
/// <param name="other">Instance of State to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(State other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Code == other.Code ||
this.Code != null &&
this.Code.Equals(other.Code)
) &&
(
this.FipsNumber == other.FipsNumber ||
this.FipsNumber != null &&
this.FipsNumber.Equals(other.FipsNumber)
) &&
(
this.LastDateForIndividual == other.LastDateForIndividual ||
this.LastDateForIndividual != null &&
this.LastDateForIndividual.Equals(other.LastDateForIndividual)
) &&
(
this.LastDateForShop == other.LastDateForShop ||
this.LastDateForShop != null &&
this.LastDateForShop.Equals(other.LastDateForShop)
) &&
(
this.LiveForBusiness == other.LiveForBusiness ||
this.LiveForBusiness != null &&
this.LiveForBusiness.Equals(other.LiveForBusiness)
) &&
(
this.LiveForConsumers == other.LiveForConsumers ||
this.LiveForConsumers != null &&
this.LiveForConsumers.Equals(other.LiveForConsumers)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Code != null)
hash = hash * 59 + this.Code.GetHashCode();
if (this.FipsNumber != null)
hash = hash * 59 + this.FipsNumber.GetHashCode();
if (this.LastDateForIndividual != null)
hash = hash * 59 + this.LastDateForIndividual.GetHashCode();
if (this.LastDateForShop != null)
hash = hash * 59 + this.LastDateForShop.GetHashCode();
if (this.LiveForBusiness != null)
hash = hash * 59 + this.LiveForBusiness.GetHashCode();
if (this.LiveForConsumers != null)
hash = hash * 59 + this.LiveForConsumers.GetHashCode();
return hash;
}
}
}
}
| |
using Aspose.Email.Live.Demos.UI.Controllers;
using Aspose.Email.Live.Demos.UI.Helpers;
using Aspose.Email.Live.Demos.UI.Models.Email;
using Aspose.Email.Live.Demos.UI.Services;
using System;
using System.Collections.Generic;
namespace Aspose.Email.Live.Demos.UI.Models
{
public partial class ViewModel
{
public const int MaximumUploadFiles = 10;
public BaseController Controller { get; }
public Uri RequestUri {get;}
public EmailApps AppType { get; }
public string Product => "email";
public string ProductAppName { get; }
public string DocumentNaming => this["Document"];
public string PageProductTitle => this["PageProductTitle", "Aspose.Email"];
public string AppName { get; }
public string AppURL { get; }
public string AppRoute { get; }
/// <summary>
/// File extension without dot received by "fileformat" value in RouteData (e.g. docx)
/// </summary>
public string Extension1 { get; }
/// <summary>
/// File extension without dot received by "fileformat" value in RouteData (e.g. docx)
/// </summary>
public string Extension2 { get; }
public bool IsCanonical => string.IsNullOrEmpty(Extension1) && string.IsNullOrEmpty(Extension2);
/// <summary>
/// Name of the partial View of controls (e.g. SignatureControls)
/// </summary>
public string ControlsView { get; set; }
public string AnotherFileText { get; set; }
public string UploadButtonText { get; set; }
public string ViewerButtonText { get; set; }
public bool ShowViewerButton { get; set; }
public string SuccessMessage { get; set; }
/// <summary>
/// List of app features for ul-list. E.g. Resources[app + "LiFeature1"]
/// </summary>
public List<string> AppFeatures { get; set; }
public string Title { get; set; }
public string TitleSub { get; set; }
public string PageTitle
{
get => Controller.ViewBag.PageTitle;
set => Controller.ViewBag.PageTitle = value;
}
public string MetaDescription
{
get => Controller.ViewBag.MetaDescription;
set => Controller.ViewBag.MetaDescription = value;
}
public string MetaKeywords
{
get => Controller.ViewBag.MetaKeywords;
set => Controller.ViewBag.MetaKeywords = value;
}
/// <summary>
/// If the application doesn't need to upload several files (e.g. Viewer, Editor). Start the processing instantly after the dropping a file
/// </summary>
public bool UploadAndRedirect { get; set; }
/// <summary>
/// If the application needs custom process button when enabled <see cref="UploadAndRedirect"/> option
/// </summary>
public bool NeedsProcessButton { get; set; }
/// <summary>
/// If the application needs download form when enabled <see cref="UploadAndRedirect"/> option
/// </summary>
public bool NeedsDownloadForm { get; set; }
protected string TitleCase(string value) => new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(value);
/// <summary>
/// e.g., .doc|.docx|.dot|.dotx|.rtf|.odt|.ott|.txt|.html|.xhtml|.mhtml
/// </summary>
public string ExtensionsString { get; set; }
#region SaveAs
protected bool _saveAsComponent;
public bool SaveAsComponent
{
get => _saveAsComponent;
set
{
_saveAsComponent = value;
Controller.ViewBag.SaveAsComponent = value;
if (_saveAsComponent)
{
SaveAsOptions = this["SaveAsOptions", ""].Split(',');
if (AppFeatures != null)
{
if (AppResources.ContainsResource("SaveAsLiFeature"))
AppFeatures.Add(this["SaveAsLiFeature"]);
}
}
}
}
/// <summary>
/// FileFormats in UpperCase
/// </summary>
public string[] SaveAsOptions { get; set; }
public Dictionary<string, string[]> SaveAsOptionsSpecific { get; set; }
/// <summary>
/// Original file format SaveAs option for multiple files uploading
/// </summary>
public bool SaveAsOriginal { get; set; }
#endregion
/// <summary>
/// The possibility of changing the order of uploaded files. It is actual for Merger App.
/// </summary>
public bool UseSorting { get; set; }
public bool ShowFileDropButtonBar { get; set; }
public bool HowToPanelEnabled { get; set; }
public bool ShowHowTo => HowToModel != null && HowToPanelEnabled;
public EmailHowToModel HowToModel { get; set; }
public bool FAQPagePanelEnabled { get; set; }
public bool ShowFAQPage => FAQPageModel != null && FAQPageModel.List.Count > 0 && FAQPagePanelEnabled;
public EmailFAQPageModel FAQPageModel { get; set; }
public IEnumerable<EmailAnotherApp> OtherApps { get; set; }
public string JSOptions { get; private set; }
/// <summary>
/// The possibility of main button working with no files uploaded
/// </summary>
public bool CanWorkWithoutFiles { get; set; }
public bool DefaultFileBlockDisabled { get; set; }
public IAppResources AppResources { get; }
public string PopularFeaturesTitle { get; private set; }
public string PopularFeaturesTitleSub { get; private set; }
public string OtherFeaturesTitle { get; private set; }
public string OtherFeaturesTitleSub { get; private set; }
public string VideoUrl { get; private set; }
public string VideoTitle { get; private set; }
public string Locale { get; private set; }
public string BaseUrl
{
get
{
var request = Controller.Request;
return $"{request.Scheme}://{request.Host}{request.PathBase}";
}
}
public bool IsDummyPage { get; set; }
public bool OverviewPanelEnabled { get; set; }
public bool AppFeaturesPanelEnabled { get; set; }
public bool AppFeaturesActionStringEnabled { get; set; }
public string AppFeaturesTitle => this["AppFeaturesTitle", "Aspose.Email " + AppName];
/// <summary>
/// Product, (AppName, AnotherApp)
/// </summary>
protected Dictionary<string, Dictionary<string, EmailAnotherApp>> OtherAppsStatic = new Dictionary<string, Dictionary<string, EmailAnotherApp>>();
public ViewModel(IAppResources resources, BaseController controller, Uri requestUri, EmailApps appType, string locale, string app, string extension1 = null, string extension2 = null)
{
Locale = locale;
Controller = controller;
Extension1 = extension1;
Extension2 = extension2;
RequestUri = requestUri;
AppResources = resources;
AppName = this[$"APPName", app];
ProductAppName = Product + app;
AppType = appType;
var url = requestUri.OriginalString;
AppURL = url.Substring(0, (url.IndexOf("?") > 0 ? url.IndexOf("?") : url.Length));
AppRoute = requestUri.GetLeftPart(UriPartial.Path);
InitOtherApps(Product.ToLower(), AppURL);
PrepareHowToModel();
SetTitles();
SetAppFeatures(app);
PrepareFAQPageModel();
if (OtherAppsStatic.ContainsKey(Product.ToLower()))
OtherApps = OtherAppsStatic[Product.ToLower()].Values;
ShowViewerButton = true;
SaveAsOriginal = true;
SaveAsComponent = false;
}
protected void PrepareHowToModel()
{
if (!string.IsNullOrEmpty(Extension1) || IsCanonical)
{
try
{
HowToModel = new EmailHowToModel(this);
}
catch
{
HowToModel = null;
}
}
}
protected void PrepareFAQPageModel()
{
FAQPageModel = new EmailFAQPageModel(this);
}
/// <summary>
/// Returns Word, OpenOffice, RTF or Text
/// </summary>
/// <param name="extension"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public string DesktopAppNameByExtension(string extension, string defaultValue = null)
{
if (!string.IsNullOrEmpty(extension))
{
switch (extension.ToLower())
{
case "docx":
case "doc":
case "dot":
case "dotx":
return "Word";
case "odt":
case "ott":
return "OpenOffice";
case "rtf":
return "RTF";
case "txt":
return this["Text"];
case "md":
return "Markdown";
case "ps":
return "PostScript";
case "tex":
return "LaTeX";
case "acroform":
return this["pdfXfaToAcroform"];
case "pdfa1a":
return "PDF/A-1A";
case "pdfa1b":
return "PDF/A-1B";
case "pdfa2a":
return "PDF/A-2A";
case "pdfa3a":
return "PDF/A-3A";
default:
return string.IsNullOrEmpty(defaultValue) ? extension.ToUpper() : defaultValue;
}
}
return defaultValue;
}
void SetTitles()
{
Title = this["H1"];
TitleSub = this["H4"];
VideoUrl = this["DefaultVideoUrl", null];
VideoTitle = this["DefaultVideoTitle", null];
PageTitle = this["PageTitle"];
MetaDescription = this["MetaDescription"];
MetaKeywords = this["MetaKeywords"];
ExtensionsString = this["ValidationExpression"];
OverviewPanelEnabled = this["OverviewPanelEnabled"].ParseToBoolOrDefault();
AppFeaturesPanelEnabled = this["AppFeaturesPanelEnabled"].ParseToBoolOrDefault();
FAQPagePanelEnabled = this["FAQPagePanelEnabled"].ParseToBoolOrDefault();
HowToPanelEnabled = this["HowToPanelEnabled"].ParseToBoolOrDefault();
AppFeaturesActionStringEnabled = this["AppFeaturesActionStringEnabled"].ParseToBoolOrDefault();
}
void SetAppFeatures(string app)
{
AppFeatures = new List<string>();
var i = 1;
string value;
while ((value = AppResources.GetResourceOrDefault($"LiFeature{i++}")) != null)
AppFeatures.Add(ResourceHelper.InjectFormatLinks(value));
// Stop other developers to add unnecessary features.
if (AppFeatures.Count == 0)
{
i = 1;
while ((value = AppResources.GetResourceOrDefault($"LiFeature{i}")) != null)
{
if (!value.Contains("Instantly download") || AppFeatures.Count == 0)
AppFeatures.Add(ResourceHelper.InjectFormatLinks(value));
i++;
}
}
}
void InitOtherApps(string product, string appUrl = null)
{
var appList = new Dictionary<string, EmailAnotherApp>();
var apps = new[]
{
"Conversion",
"Viewer",
"Headers",
"Metadata",
"Parser",
"Search",
"Merger",
"Signature",
"Watermark",
"Assembly",
"Redaction",
"Annotation",
"Editor",
"Comparison"
};
foreach (var appName in apps)
appList.Add(appName, new EmailAnotherApp(appName, Locale));
OtherAppsStatic[product] = appList;
}
public string this[string key] => AppResources.GetResourceOrDefault(key);
public string this[string key, string defaultValue]
{
get
{
var value = AppResources.GetResourceOrDefault(key);
if (value != null)
{
return value;
}
return defaultValue;
}
}
public void OnBeforeRendering()
{
JSOptions = new JSOptions(this).ToString();
// if the app has default process button
if (!UploadAndRedirect || NeedsProcessButton)
UploadButtonText = this["Button"];
// if the app has result downloading section
if (!UploadAndRedirect || NeedsDownloadForm)
{
ViewerButtonText = this["Viewer", "VIEW RESULTS"];
SuccessMessage = this["SuccessMessage", "Your file has been processed successfully"];
AnotherFileText = this["AnotherFile", "Process another file"];
}
}
}
}
| |
// Copyright 2020 The Tilt Brush 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.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using UnityEngine;
using NUnit.Framework;
namespace TiltBrush {
internal class TestListExtensions {
delegate float Thunk();
static bool sm_checkPerformance = true;
// Check that a is faster than b
static void SpeedTester(Thunk a, Thunk b, int iters, string label, int warmup = 20) {
// There is enough noise in this data that these asserts aren't reliable;
// so only do them when testing performance.
if (! sm_checkPerformance) { return; }
// warm up JIT
for (int i = 0; i < warmup; ++i) {
a(); b();
}
var watch = new System.Diagnostics.Stopwatch();
watch.Reset();
watch.Start();
for (int i = 0; i < iters; ++i) {
a();
}
watch.Stop();
var ta = watch.Elapsed;
watch.Reset();
watch.Start();
for (int i = 0; i < iters; ++i) {
b();
}
watch.Stop();
var tb = watch.Elapsed;
Debug.LogFormat("{0}: x{3:f4} {1:e5} vs {2:e5}", label,
ta.TotalSeconds,
tb.TotalSeconds,
ta.TotalSeconds / tb.TotalSeconds);
Assert.IsTrue(ta < tb, "{2}: Expected {0} < {1}", ta, tb, label);
}
[Test]
[Ignore("This crashes Unity")]
public void TestGetBackingArrayReferenceType() {
var elt = new object();
var list = new List<object> { elt };
var backing = list.GetBackingArray();
Assert.AreEqual(backing[0], elt);
}
[Test]
public void TestGetBackingArray() {
var list = new List<uint>();
for (uint i = 0; i < 10; ++i) {
list.Add(i * 3 + 2);
}
var backing = list.GetBackingArray();
backing[2] = 0xDB1F117E;
Assert.AreEqual(0xDB1F117E, list[2]);
list[2] = 0xF00D;
Assert.AreEqual(0xF00D, backing[2]);
}
[Test]
public void TestSetBackingArray() {
var array = new uint[] { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
var list = new List<uint>(array);
var list2 = new List<uint>();
list2.SetBackingArray(array);
Assert.AreEqual(list, list2);
}
[Test]
public void TestSetCountHigher() {
var list = new List<int>(5);
list.SetCount(3);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(5, list.Capacity);
}
[Test]
public void TestSetCountAboveCapacity() {
var list = new List<int>(5);
list.SetCount(7);
Assert.AreEqual(7, list.Count);
Assert.IsTrue(list.Capacity >= 7);
}
[Test]
public void TestSetCountLower() {
var list = new List<int>();
for (int i = 0; i < 10; ++i) list.Add(i);
list.SetCount(0);
Assert.AreEqual(0, list.Count);
Assert.IsTrue(list.Capacity > 0);
}
[Test]
public void TestAddRange() {
// The GetBackingArray() version
var list = new List<int>() { 0, 1, 2 };
var array = new int[100];
for (int i = 0; i < array.Length; ++i) array[i] = i + 100;
list.AddRange(array, 5, 95);
Assert.AreEqual(105, list[3]);
Assert.AreEqual(199, list[97]);
Assert.AreEqual(98, list.Count);
}
[Test]
public void TestAddRange2() {
// The fallback case
var list = new List<int>() { 0, 1, 2 };
var array = new int[10];
for (int i = 0; i < array.Length; ++i) array[i] = i + 100;
list.AddRange(array, 5, 1);
Assert.AreEqual(105, list[list.Count-1]);
list.AddRange(array, 0, 10);
Assert.AreEqual(14, list.Count);
}
[Test]
public void TestBadAddRange() {
var list = new List<int>() { 0, 1, 2 };
var array = new int[100];
for (int i = 0; i < array.Length; ++i) array[i] = i + 100;
Assert.That(() => list.AddRange(array, 50, 100), Throws.ArgumentException);
}
[Test]
public void TestBadAddRange2() {
// The fallback using .Skip().Take()
var list = new List<int>() { 0, 1, 2 };
var array = new int[10];
for (int i = 0; i < array.Length; ++i) array[i] = i + 100;
Assert.That(() => list.AddRange(array, 5, 10), Throws.ArgumentException);
}
[Test]
public void TestSpeed_GetBackingArray() {
var list = new List<Vector3>(100);
for (int i = 0; i < list.Capacity; ++i) {
list.Add(Vector3.one);
}
Thunk standard = () => {
Vector3 sum = Vector3.zero;
List<Vector3> mylist = list;
int n = mylist.Count;
for (int i = 0; i < n; ++i) {
sum += mylist[i] * Vector3.Dot(mylist[i], mylist[i]);
}
return sum.x;
};
Thunk backing = () => {
Vector3 sum = Vector3.zero;
Vector3[] mylist = list.GetBackingArray();
int n = mylist.Length;
for (int i = 0; i < n; ++i) {
sum += mylist[i] * Vector3.Dot(mylist[i], mylist[i]);
}
return sum.x;
};
SpeedTester(backing, standard, 20, "vs standard");
}
[Test]
public void TestSpeed_AddRange() {
// Break-even point is about 100
Vector3[] source = new Vector3[120];
List<Vector3> dest = new List<Vector3>(500);
// Our new overload, that internally uses GetBackingArray
Thunk backing = () => {
List<Vector3> mydest = dest;
mydest.Clear();
mydest.AddRange(source, 5, source.Length-10);
return 0;
};
// Uses linq (and internally optimized, maybe?)
Thunk linq = () => {
List<Vector3> mydest = dest;
mydest.Clear();
mydest.AddRange(source.Skip(5).Take(source.Length-10));
return 0;
};
// Write it out by hand
Thunk byhand = () => {
Vector3[] mysource = source;
List<Vector3> mydest = dest;
mydest.Clear();
int max = source.Length - 10;
for (int i = 5; i < max; ++i) {
mydest.Add(mysource[i]);
}
return 0;
};
int iters = 30;
SpeedTester(backing, linq, iters, "vs linq");
SpeedTester(backing, byhand, iters, "vs byhand");
}
[Test]
public void TestSpeed_SetCountUp() {
List<Vector3> list = new List<Vector3>(70);
Thunk setcount = () => {
list.SetCount(list.Capacity);
list.Clear();
return 0;
};
Thunk forloop = () => {
var mylist = list;
var num = mylist.Capacity;
for (int i = 0; i < num; ++i) mylist.Add(default(Vector3));
list.Clear();
return 0;
};
SpeedTester(setcount, forloop, 10, "vs forloop");
}
private void TestConvertHelperGeneric<T>() {
List<T> list = new List<T>(30);
for (int i=0; i<10; ++i) { list.Add(default(T)); }
Assert.AreEqual(list.Count, 10);
Assert.AreEqual(list.Capacity, 30);
var pub = ConvertHelper<List<T>, ListExtensions.PublicList<T>>.Convert(list);
Assert.IsTrue(pub != null);
Assert.IsTrue(ReferenceEquals(list.GetBackingArray(), pub.BackingArray));
Assert.AreEqual(pub.Count, list.Count);
Assert.AreEqual(pub.Capacity, list.Capacity);
}
[Test]
public void TestConvertHelper() {
TestConvertHelperGeneric<int>();
TestConvertHelperGeneric<Vector3>();
}
} // class TestListExtensions
} // namespace TiltBrush
| |
/*
* 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.Compute
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Synchronous Compute facade.
/// </summary>
internal class Compute : ICompute
{
/** */
private readonly ComputeImpl _compute;
/// <summary>
/// Initializes a new instance of the <see cref="Compute"/> class.
/// </summary>
/// <param name="computeImpl">The compute implementation.</param>
public Compute(ComputeImpl computeImpl)
{
Debug.Assert(computeImpl != null);
_compute = computeImpl;
}
/** <inheritDoc /> */
public IClusterGroup ClusterGroup
{
get { return _compute.ClusterGroup; }
}
/** <inheritDoc /> */
public ICompute WithNoFailover()
{
_compute.WithNoFailover();
return this;
}
/** <inheritDoc /> */
public ICompute WithNoResultCache()
{
_compute.WithNoResultCache();
return this;
}
/** <inheritDoc /> */
public ICompute WithTimeout(long timeout)
{
_compute.WithTimeout(timeout);
return this;
}
/** <inheritDoc /> */
public ICompute WithKeepBinary()
{
_compute.WithKeepBinary();
return this;
}
/** <inheritDoc /> */
public ICompute WithExecutor(string executorName)
{
var computeImpl = _compute.WithExecutor(executorName);
return new Compute(computeImpl);
}
/** <inheritDoc /> */
public TReduceRes ExecuteJavaTask<TReduceRes>(string taskName, object taskArg)
{
return _compute.ExecuteJavaTask<TReduceRes>(taskName, taskArg);
}
/** <inheritDoc /> */
public Task<TRes> ExecuteJavaTaskAsync<TRes>(string taskName, object taskArg)
{
return _compute.ExecuteJavaTaskAsync<TRes>(taskName, taskArg).Task;
}
/** <inheritDoc /> */
public Task<TRes> ExecuteJavaTaskAsync<TRes>(string taskName, object taskArg,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.ExecuteJavaTaskAsync<TRes>(taskName, taskArg).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TReduceRes Execute<TArg, TJobRes, TReduceRes>(IComputeTask<TArg, TJobRes, TReduceRes> task, TArg taskArg)
{
return _compute.Execute(task, taskArg).Get();
}
/** <inheritDoc /> */
public Task<TRes> ExecuteAsync<TArg, TJobRes, TRes>(IComputeTask<TArg, TJobRes, TRes> task, TArg taskArg)
{
return _compute.Execute(task, taskArg).Task;
}
/** <inheritDoc /> */
public Task<TRes> ExecuteAsync<TArg, TJobRes, TRes>(IComputeTask<TArg, TJobRes, TRes> task, TArg taskArg,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Execute(task, taskArg).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TJobRes Execute<TArg, TJobRes>(IComputeTask<TArg, TJobRes> task)
{
return _compute.Execute(task, null).Get();
}
/** <inheritDoc /> */
public Task<TRes> ExecuteAsync<TJobRes, TRes>(IComputeTask<TJobRes, TRes> task)
{
return _compute.Execute(task, null).Task;
}
/** <inheritDoc /> */
public Task<TRes> ExecuteAsync<TJobRes, TRes>(IComputeTask<TJobRes, TRes> task,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Execute(task, null).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TReduceRes Execute<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg)
{
return _compute.Execute<TArg, TJobRes, TReduceRes>(taskType, taskArg).Get();
}
/** <inheritDoc /> */
public Task<TReduceRes> ExecuteAsync<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg)
{
return _compute.Execute<TArg, TJobRes, TReduceRes>(taskType, taskArg).Task;
}
/** <inheritDoc /> */
public Task<TReduceRes> ExecuteAsync<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TReduceRes>(cancellationToken) ??
_compute.Execute<TArg, TJobRes, TReduceRes>(taskType, taskArg).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TReduceRes Execute<TArg, TReduceRes>(Type taskType)
{
return _compute.Execute<object, TArg, TReduceRes>(taskType, null).Get();
}
/** <inheritDoc /> */
public Task<TReduceRes> ExecuteAsync<TArg, TReduceRes>(Type taskType)
{
return _compute.Execute<object, TArg, TReduceRes>(taskType, null).Task;
}
/** <inheritDoc /> */
public Task<TReduceRes> ExecuteAsync<TArg, TReduceRes>(Type taskType, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TReduceRes>(cancellationToken) ??
_compute.Execute<object, TArg, TReduceRes>(taskType, null).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TJobRes Call<TJobRes>(IComputeFunc<TJobRes> clo)
{
return _compute.Execute(clo).Get();
}
/** <inheritDoc /> */
public Task<TRes> CallAsync<TRes>(IComputeFunc<TRes> clo)
{
return _compute.Execute(clo).Task;
}
/** <inheritDoc /> */
public Task<TRes> CallAsync<TRes>(IComputeFunc<TRes> clo, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Execute(clo).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TJobRes AffinityCall<TJobRes>(string cacheName, object affinityKey, IComputeFunc<TJobRes> clo)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return _compute.AffinityCall(cacheName, affinityKey, clo).Get();
}
/** <inheritDoc /> */
public Task<TRes> AffinityCallAsync<TRes>(string cacheName, object affinityKey, IComputeFunc<TRes> clo)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return _compute.AffinityCall(cacheName, affinityKey, clo).Task;
}
/** <inheritDoc /> */
public Task<TRes> AffinityCallAsync<TRes>(string cacheName, object affinityKey, IComputeFunc<TRes> clo,
CancellationToken cancellationToken)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.AffinityCall(cacheName, affinityKey, clo).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TJobRes Call<TJobRes>(Func<TJobRes> func)
{
return _compute.Execute(func).Get();
}
/** <inheritDoc /> */
public Task<TRes> CallAsync<TFuncRes, TRes>(IEnumerable<IComputeFunc<TFuncRes>> clos,
IComputeReducer<TFuncRes, TRes> reducer)
{
return _compute.Execute(clos, reducer).Task;
}
/** <inheritDoc /> */
public Task<TRes> CallAsync<TFuncRes, TRes>(IEnumerable<IComputeFunc<TFuncRes>> clos,
IComputeReducer<TFuncRes, TRes> reducer, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Execute(clos, reducer).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public ICollection<TJobRes> Call<TJobRes>(IEnumerable<IComputeFunc<TJobRes>> clos)
{
return _compute.Execute(clos).Get();
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> CallAsync<TRes>(IEnumerable<IComputeFunc<TRes>> clos)
{
return _compute.Execute(clos).Task;
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> CallAsync<TRes>(IEnumerable<IComputeFunc<TRes>> clos,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<ICollection<TRes>>(cancellationToken) ??
_compute.Execute(clos).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TReduceRes Call<TJobRes, TReduceRes>(IEnumerable<IComputeFunc<TJobRes>> clos,
IComputeReducer<TJobRes, TReduceRes> reducer)
{
return _compute.Execute(clos, reducer).Get();
}
/** <inheritDoc /> */
public ICollection<TJobRes> Broadcast<TJobRes>(IComputeFunc<TJobRes> clo)
{
return _compute.Broadcast(clo).Get();
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> BroadcastAsync<TRes>(IComputeFunc<TRes> clo)
{
return _compute.Broadcast(clo).Task;
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> BroadcastAsync<TRes>(IComputeFunc<TRes> clo, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<ICollection<TRes>>(cancellationToken) ??
_compute.Broadcast(clo).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public ICollection<TJobRes> Broadcast<T, TJobRes>(IComputeFunc<T, TJobRes> clo, T arg)
{
return _compute.Broadcast(clo, arg).Get();
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> BroadcastAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, TArg arg)
{
return _compute.Broadcast(clo, arg).Task;
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> BroadcastAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, TArg arg,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<ICollection<TRes>>(cancellationToken) ??
_compute.Broadcast(clo, arg).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public void Broadcast(IComputeAction action)
{
_compute.Broadcast(action).Get();
}
/** <inheritDoc /> */
public Task BroadcastAsync(IComputeAction action)
{
return _compute.Broadcast(action).Task;
}
/** <inheritDoc /> */
public Task BroadcastAsync(IComputeAction action, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<object>(cancellationToken) ??
_compute.Broadcast(action).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public void Run(IComputeAction action)
{
_compute.Run(action).Get();
}
/** <inheritDoc /> */
public Task RunAsync(IComputeAction action)
{
return _compute.Run(action).Task;
}
/** <inheritDoc /> */
public Task RunAsync(IComputeAction action, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<object>(cancellationToken) ??
_compute.Run(action).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public void AffinityRun(string cacheName, object affinityKey, IComputeAction action)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
_compute.AffinityRun(cacheName, affinityKey, action).Get();
}
/** <inheritDoc /> */
public Task AffinityRunAsync(string cacheName, object affinityKey, IComputeAction action)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return _compute.AffinityRun(cacheName, affinityKey, action).Task;
}
/** <inheritDoc /> */
public Task AffinityRunAsync(string cacheName, object affinityKey, IComputeAction action,
CancellationToken cancellationToken)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return GetTaskIfAlreadyCancelled<object>(cancellationToken) ??
_compute.AffinityRun(cacheName, affinityKey, action).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public void Run(IEnumerable<IComputeAction> actions)
{
_compute.Run(actions).Get();
}
/** <inheritDoc /> */
public Task RunAsync(IEnumerable<IComputeAction> actions)
{
return _compute.Run(actions).Task;
}
/** <inheritDoc /> */
public Task RunAsync(IEnumerable<IComputeAction> actions, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<object>(cancellationToken) ??
_compute.Run(actions).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TJobRes Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg)
{
return _compute.Apply(clo, arg).Get();
}
/** <inheritDoc /> */
public Task<TRes> ApplyAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, TArg arg)
{
return _compute.Apply(clo, arg).Task;
}
/** <inheritDoc /> */
public Task<TRes> ApplyAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, TArg arg,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Apply(clo, arg).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public ICollection<TJobRes> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, IEnumerable<TArg> args)
{
return _compute.Apply(clo, args).Get();
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> ApplyAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, IEnumerable<TArg> args)
{
return _compute.Apply(clo, args).Task;
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> ApplyAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, IEnumerable<TArg> args,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<ICollection<TRes>>(cancellationToken) ??
_compute.Apply(clo, args).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TReduceRes Apply<TArg, TJobRes, TReduceRes>(IComputeFunc<TArg, TJobRes> clo,
IEnumerable<TArg> args, IComputeReducer<TJobRes, TReduceRes> rdc)
{
return _compute.Apply(clo, args, rdc).Get();
}
/** <inheritDoc /> */
public Task<TRes> ApplyAsync<TArg, TFuncRes, TRes>(IComputeFunc<TArg, TFuncRes> clo, IEnumerable<TArg> args,
IComputeReducer<TFuncRes, TRes> rdc)
{
return _compute.Apply(clo, args, rdc).Task;
}
/** <inheritDoc /> */
public Task<TRes> ApplyAsync<TArg, TFuncRes, TRes>(IComputeFunc<TArg, TFuncRes> clo, IEnumerable<TArg> args,
IComputeReducer<TFuncRes, TRes> rdc, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Apply(clo, args, rdc).GetTask(cancellationToken);
}
/// <summary>
/// Gets the cancelled task if specified token is cancelled.
/// </summary>
private static Task<T> GetTaskIfAlreadyCancelled<T>(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return CancelledTask<T>.Instance;
return null;
}
/// <summary>
/// Determines whether specified exception should result in a job failover.
/// </summary>
internal static bool IsFailoverException(Exception err)
{
while (err != null)
{
if (err is ComputeExecutionRejectedException || err is ClusterTopologyException ||
err is ComputeJobFailoverException)
return true;
err = err.InnerException;
}
return false;
}
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.decoration
{
/// <summary>
/// <para>Abstract base class for the HBox and VBox decorators.
/// This decorator uses three images, which are positioned in a
/// vertical/horizontal line. The first and last image always keep their
/// original size. The center image is stretched.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.decoration.AbstractBox", OmitOptionalParameters = true, Export = false)]
public partial class AbstractBox : qx.ui.decoration.Abstract, qx.ui.decoration.IDecorator
{
#region Properties
/// <summary>
/// <para>Base image URL. All the different images needed are named by the default
/// naming scheme:</para>
/// <para>${baseImageWithoutExtension}-${imageName}.${baseImageExtension}</para>
/// <para>These image names are used:</para>
/// <list type="bullet">
/// <item>t: top side (vertical orientation)</item>
/// <item>b: bottom side (vertical orientation)</item>
/// </list>
/// <list type="bullet">
/// <item>l: left side (horizontal orientation)</item>
/// <item>r: right side (horizontal orientation)</item>
/// </list>
/// <list type="bullet">
/// <item>c: center image</item>
/// </list>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "baseImage", NativeField = true)]
public string BaseImage { get; set; }
/// <summary>
/// <para>Only used for the CSS3 implementation, see <see cref="qx.ui.decoration.css3.BorderImage.Fill"/> *</para>
/// </summary>
[JsProperty(Name = "fill", NativeField = true)]
public object Fill { get; set; }
/// <summary>
/// <para>Width of the bottom slice</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "sliceBottom", NativeField = true)]
public double SliceBottom { get; set; }
/// <summary>
/// <para>Width of the left slice</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "sliceLeft", NativeField = true)]
public double SliceLeft { get; set; }
/// <summary>
/// <para>Width of the right slice</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "sliceRight", NativeField = true)]
public double SliceRight { get; set; }
/// <summary>
/// <para>Property group for slices</para>
/// </summary>
[JsProperty(Name = "slices", NativeField = true)]
public object Slices { get; set; }
/// <summary>
/// <para>Width of the top slice</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "sliceTop", NativeField = true)]
public double SliceTop { get; set; }
#endregion Properties
#region Methods
public AbstractBox() { throw new NotImplementedException(); }
/// <param name="baseImage">Base image to use</param>
/// <param name="insets">Insets for the grid</param>
/// <param name="orientation">Vertical or horizontal orientation</param>
public AbstractBox(string baseImage, object insets, string orientation) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property baseImage.</para>
/// </summary>
[JsMethod(Name = "getBaseImage")]
public string GetBaseImage() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property fill.</para>
/// </summary>
[JsMethod(Name = "getFill")]
public object GetFill() { throw new NotImplementedException(); }
/// <summary>
/// <para>Get the amount of space, the decoration needs for its border on each
/// side.</para>
/// </summary>
/// <returns>the desired insed a map with the keys top, right, bottom, left.</returns>
[JsMethod(Name = "getInsets")]
public object GetInsets() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the basic markup structure used for this decoration.
/// This later updated on DOM to resize or tint the element.</para>
/// </summary>
/// <returns>Basic markup</returns>
[JsMethod(Name = "getMarkup")]
public string GetMarkup() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property sliceBottom.</para>
/// </summary>
[JsMethod(Name = "getSliceBottom")]
public double GetSliceBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property sliceLeft.</para>
/// </summary>
[JsMethod(Name = "getSliceLeft")]
public double GetSliceLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property sliceRight.</para>
/// </summary>
[JsMethod(Name = "getSliceRight")]
public double GetSliceRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property sliceTop.</para>
/// </summary>
[JsMethod(Name = "getSliceTop")]
public double GetSliceTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property baseImage
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property baseImage.</param>
[JsMethod(Name = "initBaseImage")]
public void InitBaseImage(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property fill
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property fill.</param>
[JsMethod(Name = "initFill")]
public void InitFill(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property sliceBottom
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property sliceBottom.</param>
[JsMethod(Name = "initSliceBottom")]
public void InitSliceBottom(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property sliceLeft
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property sliceLeft.</param>
[JsMethod(Name = "initSliceLeft")]
public void InitSliceLeft(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property sliceRight
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property sliceRight.</param>
[JsMethod(Name = "initSliceRight")]
public void InitSliceRight(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property sliceTop
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property sliceTop.</param>
[JsMethod(Name = "initSliceTop")]
public void InitSliceTop(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property baseImage.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetBaseImage")]
public void ResetBaseImage() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property fill.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetFill")]
public void ResetFill() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property sliceBottom.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetSliceBottom")]
public void ResetSliceBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property sliceLeft.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetSliceLeft")]
public void ResetSliceLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property sliceRight.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetSliceRight")]
public void ResetSliceRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property slices.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetSlices")]
public void ResetSlices() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property sliceTop.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetSliceTop")]
public void ResetSliceTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resizes the element respecting the configured borders
/// to the given width and height. Should automatically
/// respect the box model of the client to correctly
/// compute the dimensions.</para>
/// </summary>
/// <param name="element">The element to update</param>
/// <param name="width">Width of the element</param>
/// <param name="height">Height of the element</param>
[JsMethod(Name = "resize")]
public void Resize(qx.html.Element element, double width, double height) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property baseImage.</para>
/// </summary>
/// <param name="value">New value for property baseImage.</param>
[JsMethod(Name = "setBaseImage")]
public void SetBaseImage(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property fill.</para>
/// </summary>
/// <param name="value">New value for property fill.</param>
[JsMethod(Name = "setFill")]
public void SetFill(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property sliceBottom.</para>
/// </summary>
/// <param name="value">New value for property sliceBottom.</param>
[JsMethod(Name = "setSliceBottom")]
public void SetSliceBottom(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property sliceLeft.</para>
/// </summary>
/// <param name="value">New value for property sliceLeft.</param>
[JsMethod(Name = "setSliceLeft")]
public void SetSliceLeft(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property sliceRight.</para>
/// </summary>
/// <param name="value">New value for property sliceRight.</param>
[JsMethod(Name = "setSliceRight")]
public void SetSliceRight(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the values of the property group slices.</para>
/// <para>This setter supports a shorthand mode compatible with the way margins and paddins are set in CSS.</para>
/// </summary>
/// <param name="sliceTop">Sets the value of the property #sliceTop.</param>
/// <param name="sliceRight">Sets the value of the property #sliceRight.</param>
/// <param name="sliceBottom">Sets the value of the property #sliceBottom.</param>
/// <param name="sliceLeft">Sets the value of the property #sliceLeft.</param>
[JsMethod(Name = "setSlices")]
public void SetSlices(object sliceTop, object sliceRight, object sliceBottom, object sliceLeft) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property sliceTop.</para>
/// </summary>
/// <param name="value">New value for property sliceTop.</param>
[JsMethod(Name = "setSliceTop")]
public void SetSliceTop(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Applies the given background color to the element
/// or fallback to the background color defined
/// by the decoration itself.</para>
/// </summary>
/// <param name="element">The element to update</param>
/// <param name="bgcolor">The color to apply or null</param>
[JsMethod(Name = "tint")]
public void Tint(qx.html.Element element, string bgcolor) { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.DirectoryServices.ActiveDirectory.ActiveDirectorySchemaProperty.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.DirectoryServices.ActiveDirectory
{
public partial class ActiveDirectorySchemaProperty : IDisposable
{
#region Methods and constructors
public ActiveDirectorySchemaProperty(DirectoryContext context, string ldapDisplayName)
{
Contract.Requires(context != null);
Contract.Requires(!string.IsNullOrEmpty(ldapDisplayName));
}
protected virtual new void Dispose(bool disposing)
{
}
public void Dispose()
{
}
public static ActiveDirectorySchemaProperty FindByName(DirectoryContext context, string ldapDisplayName)
{
Contract.Requires(context != null);
Contract.Requires(!string.IsNullOrEmpty(ldapDisplayName));
Contract.Ensures(Contract.Result<ActiveDirectorySchemaProperty>() != null);
return default(System.DirectoryServices.ActiveDirectory.ActiveDirectorySchemaProperty);
}
public System.DirectoryServices.DirectoryEntry GetDirectoryEntry()
{
Contract.Ensures(Contract.Result<DirectoryEntry>() != null);
return default(System.DirectoryServices.DirectoryEntry);
}
public void Save()
{
}
#endregion
#region Properties and indexers
public string CommonName
{
get
{
return default(string);
}
set
{
}
}
public string Description
{
get
{
return default(string);
}
set
{
}
}
public bool IsDefunct
{
get
{
return default(bool);
}
set
{
}
}
public bool IsInAnr
{
get
{
return default(bool);
}
set
{
}
}
public bool IsIndexed
{
get
{
return default(bool);
}
set
{
}
}
public bool IsIndexedOverContainer
{
get
{
return default(bool);
}
set
{
}
}
public bool IsInGlobalCatalog
{
get
{
return default(bool);
}
set
{
}
}
public bool IsOnTombstonedObject
{
get
{
return default(bool);
}
set
{
}
}
public bool IsSingleValued
{
get
{
return default(bool);
}
set
{
}
}
public bool IsTupleIndexed
{
get
{
return default(bool);
}
set
{
}
}
public System.DirectoryServices.ActiveDirectory.ActiveDirectorySchemaProperty Link
{
get
{
return default(System.DirectoryServices.ActiveDirectory.ActiveDirectorySchemaProperty);
}
}
public Nullable<int> LinkId
{
get
{
return default(Nullable<int>);
}
set
{
}
}
public string Name
{
get
{
return default(string);
}
}
public string Oid
{
get
{
return default(string);
}
set
{
}
}
public Nullable<int> RangeLower
{
get
{
return default(Nullable<int>);
}
set
{
}
}
public Nullable<int> RangeUpper
{
get
{
return default(Nullable<int>);
}
set
{
}
}
public Guid SchemaGuid
{
get
{
return default(Guid);
}
set
{
}
}
public ActiveDirectorySyntax Syntax
{
get
{
return default(ActiveDirectorySyntax);
}
set
{
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal abstract partial class AbstractCodeGenerationService : ICodeGenerationService
{
private readonly ISymbolDeclarationService _symbolDeclarationService;
protected readonly Workspace Workspace;
protected AbstractCodeGenerationService(
ISymbolDeclarationService symbolDeclarationService,
Workspace workspace)
{
_symbolDeclarationService = symbolDeclarationService;
Workspace = workspace;
}
public TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode
{
return AddEvent(destination, @event, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken));
}
public TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode
{
return AddField(destination, field, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken));
}
public TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode
{
return AddMethod(destination, method, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken));
}
public TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode
{
return AddProperty(destination, property, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken));
}
public TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode
{
return AddNamedType(destination, namedType, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken), cancellationToken);
}
public TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode
{
return AddNamespace(destination, @namespace, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken), cancellationToken);
}
public TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<ISymbol> members, CodeGenerationOptions options, CancellationToken cancellationToken)
where TDeclarationNode : SyntaxNode
{
return AddMembers(destination, members, GetAvailableInsertionIndices(destination, cancellationToken), options ?? CodeGenerationOptions.Default, cancellationToken);
}
protected abstract TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) where TDeclarationNode : SyntaxNode;
protected abstract TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) where TDeclarationNode : SyntaxNode;
protected abstract TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) where TDeclarationNode : SyntaxNode;
protected abstract TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) where TDeclarationNode : SyntaxNode;
protected abstract TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
protected abstract TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
protected abstract TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members) where TDeclarationNode : SyntaxNode;
public abstract TDeclarationNode AddParameters<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
public abstract TDeclarationNode AddAttributes<TDeclarationNode>(TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
public abstract TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
public abstract TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
public abstract TDeclarationNode AddStatements<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
public abstract TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
public abstract TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
public abstract TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode;
public abstract TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) where TDeclarationNode : SyntaxNode;
public abstract CodeGenerationDestination GetDestination(SyntaxNode node);
public abstract SyntaxNode CreateEventDeclaration(IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options);
public abstract SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options);
public abstract SyntaxNode CreateMethodDeclaration(IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options);
public abstract SyntaxNode CreatePropertyDeclaration(IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options);
public abstract SyntaxNode CreateNamedTypeDeclaration(INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken);
public abstract SyntaxNode CreateNamespaceDeclaration(INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken);
protected abstract AbstractImportsAdder CreateImportsAdder(Document document);
protected static T Cast<T>(object value)
{
return (T)value;
}
protected static void CheckDeclarationNode<TDeclarationNode>(SyntaxNode destination) where TDeclarationNode : SyntaxNode
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
if (!(destination is TDeclarationNode))
{
throw new ArgumentException(
string.Format(WorkspacesResources.Destination_type_must_be_a_0_but_given_one_is_1, typeof(TDeclarationNode).Name, destination.GetType().Name),
nameof(destination));
}
}
protected static void CheckDeclarationNode<TDeclarationNode1, TDeclarationNode2>(SyntaxNode destination)
where TDeclarationNode1 : SyntaxNode
where TDeclarationNode2 : SyntaxNode
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
if (!(destination is TDeclarationNode1) &&
!(destination is TDeclarationNode2))
{
throw new ArgumentException(
string.Format(WorkspacesResources.Destination_type_must_be_a_0_or_a_1_but_given_one_is_2,
typeof(TDeclarationNode1).Name, typeof(TDeclarationNode2).Name, destination.GetType().Name),
nameof(destination));
}
}
protected static void CheckDeclarationNode<TDeclarationNode1, TDeclarationNode2, TDeclarationNode3>(SyntaxNode destination)
where TDeclarationNode1 : SyntaxNode
where TDeclarationNode2 : SyntaxNode
where TDeclarationNode3 : SyntaxNode
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
if (!(destination is TDeclarationNode1) &&
!(destination is TDeclarationNode2) &&
!(destination is TDeclarationNode3))
{
throw new ArgumentException(
string.Format(WorkspacesResources.Destination_type_must_be_a_0_1_or_2_but_given_one_is_3,
typeof(TDeclarationNode1).Name, typeof(TDeclarationNode2).Name, typeof(TDeclarationNode3).Name, destination.GetType().Name),
nameof(destination));
}
}
protected static void CheckDeclarationNode<TDeclarationNode1, TDeclarationNode2, TDeclarationNode3, TDeclarationNode4>(SyntaxNode destination)
where TDeclarationNode1 : SyntaxNode
where TDeclarationNode2 : SyntaxNode
where TDeclarationNode3 : SyntaxNode
where TDeclarationNode4 : SyntaxNode
{
if (!(destination is TDeclarationNode1) &&
!(destination is TDeclarationNode2) &&
!(destination is TDeclarationNode3) &&
!(destination is TDeclarationNode4))
{
throw new ArgumentException(
string.Format(WorkspacesResources.Destination_type_must_be_a_0_1_or_2_but_given_one_is_3,
typeof(TDeclarationNode1).Name, typeof(TDeclarationNode2).Name, typeof(TDeclarationNode3).Name, typeof(TDeclarationNode4).Name),
nameof(destination));
}
}
private async Task<Document> GetEditAsync(
Solution solution,
INamespaceOrTypeSymbol destination,
Func<SyntaxNode, CodeGenerationOptions, IList<bool>, CancellationToken, SyntaxNode> declarationTransform,
CodeGenerationOptions options,
IEnumerable<ISymbol> members,
CancellationToken cancellationToken)
{
options = options ?? CodeGenerationOptions.Default;
var (destinationDeclaration, availableIndices) =
await this.FindMostRelevantDeclarationAsync(solution, destination, options, cancellationToken).ConfigureAwait(false);
if (destinationDeclaration == null)
{
throw new ArgumentException(WorkspacesResources.Could_not_find_location_to_generation_symbol_into);
}
var transformedDeclaration = declarationTransform(destinationDeclaration, options, availableIndices, cancellationToken);
var destinationTree = destinationDeclaration.SyntaxTree;
var root = await destinationTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var currentRoot = root.ReplaceNode(destinationDeclaration, transformedDeclaration);
var oldDocument = solution.GetDocument(destinationTree);
var newDocument = oldDocument.WithSyntaxRoot(currentRoot);
if (options.AddImports)
{
newDocument = await AddImportsAsync(
newDocument, options, cancellationToken).ConfigureAwait(false);
}
return newDocument;
}
public async Task<Document> AddImportsAsync(Document document, CodeGenerationOptions options, CancellationToken cancellationToken)
{
options = options ?? CodeGenerationOptions.Default;
var adder = this.CreateImportsAdder(document);
var newDocument = await adder.AddAsync(options.PlaceSystemNamespaceFirst, options, cancellationToken).ConfigureAwait(false);
return newDocument;
}
protected TDeclarationNode AddMembers<TDeclarationNode>(
TDeclarationNode destination,
IEnumerable<ISymbol> members,
IList<bool> availableIndices,
CodeGenerationOptions options,
CancellationToken cancellationToken)
where TDeclarationNode : SyntaxNode
{
var membersList = members.ToList();
if (membersList.Count > 1)
{
options = CreateOptionsForMultipleMembers(options);
}
// Filter out the members that are implicitly declared. They're implicit, hence we do
// not want an explicit declaration.
var filteredMembers = membersList.Where(m => !m.IsImplicitlyDeclared);
return options.AutoInsertionLocation
? AddMembersToAppropiateLocationInDestination(destination, filteredMembers, availableIndices, options, cancellationToken)
: AddMembersToEndOfDestination(destination, filteredMembers, availableIndices, options, cancellationToken);
}
private TDeclarationSyntax AddMembersToEndOfDestination<TDeclarationSyntax>(
TDeclarationSyntax destination,
IEnumerable<ISymbol> members,
IList<bool> availableIndices,
CodeGenerationOptions options,
CancellationToken cancellationToken)
where TDeclarationSyntax : SyntaxNode
{
var newMembers = new List<SyntaxNode>();
var codeGenerationDestination = GetDestination(destination);
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
var newMember = GetNewMember(options, codeGenerationDestination, member, cancellationToken);
if (newMember != null)
{
newMembers.Add(newMember);
}
}
// Metadata as source generates complete declarations and doesn't modify
// existing ones. We can take the members to generate, sort them once,
// and then add them in that order to the end of the destination.
if (!GeneratingEnum(members) && options.SortMembers)
{
newMembers.Sort(GetMemberComparer());
}
return this.AddMembers(destination, newMembers);
}
private TDeclarationSyntax AddMembersToAppropiateLocationInDestination<TDeclarationSyntax>(
TDeclarationSyntax destination,
IEnumerable<ISymbol> members,
IList<bool> availableIndices,
CodeGenerationOptions options,
CancellationToken cancellationToken)
where TDeclarationSyntax : SyntaxNode
{
var currentDestination = destination;
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
currentDestination = UpdateDestination(availableIndices, options, currentDestination, member, cancellationToken);
}
return currentDestination;
}
private SyntaxNode GetNewMember(
CodeGenerationOptions options, CodeGenerationDestination codeGenerationDestination,
ISymbol member, CancellationToken cancellationToken)
{
switch (member)
{
case IEventSymbol @event: return this.CreateEventDeclaration(@event, codeGenerationDestination, options);
case IFieldSymbol field: return this.CreateFieldDeclaration(field, codeGenerationDestination, options);
case IPropertySymbol property: return this.CreatePropertyDeclaration(property, codeGenerationDestination, options);
case IMethodSymbol method: return this.CreateMethodDeclaration(method, codeGenerationDestination, options);
case INamedTypeSymbol namedType: return this.CreateNamedTypeDeclaration(namedType, codeGenerationDestination, options, cancellationToken);
case INamespaceSymbol @namespace: return this.CreateNamespaceDeclaration(@namespace, codeGenerationDestination, options, cancellationToken);
}
return null;
}
private TDeclarationNode UpdateDestination<TDeclarationNode>(
IList<bool> availableIndices,
CodeGenerationOptions options,
TDeclarationNode currentDestination,
ISymbol member,
CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode
{
switch (member)
{
case IEventSymbol @event: return this.AddEvent(currentDestination, @event, options, availableIndices);
case IFieldSymbol field: return this.AddField(currentDestination, field, options, availableIndices);
case IPropertySymbol property: return this.AddProperty(currentDestination, property, options, availableIndices);
case IMethodSymbol method: return this.AddMethod(currentDestination, method, options, availableIndices);
case INamedTypeSymbol namedType: return this.AddNamedType(currentDestination, namedType, options, availableIndices, cancellationToken);
case INamespaceSymbol @namespace: return this.AddNamespace(currentDestination, @namespace, options, availableIndices, cancellationToken);
}
return currentDestination;
}
private bool GeneratingEnum(IEnumerable<ISymbol> members)
{
var field = members.OfType<IFieldSymbol>().FirstOrDefault();
return field != null && field.ContainingType.IsEnumType();
}
protected abstract IComparer<SyntaxNode> GetMemberComparer();
protected static CodeGenerationOptions CreateOptionsForMultipleMembers(CodeGenerationOptions options)
{
// For now we ignore the afterThisLocation/beforeThisLocation if we're adding
// multiple members. In the future it would be nice to appropriately handle this.
// The difficulty lies with ensuring that we properly understand the position we're
// inserting into, even as we change the type by adding multiple members. Not
// impossible to figure out, but out of scope right now.
options = new CodeGenerationOptions(
options.ContextLocation,
addImports: options.AddImports,
placeSystemNamespaceFirst: options.PlaceSystemNamespaceFirst,
additionalImports: options.AdditionalImports,
generateMembers: options.GenerateMembers,
mergeNestedNamespaces: options.MergeNestedNamespaces,
mergeAttributes: options.MergeAttributes,
generateDefaultAccessibility: options.GenerateDefaultAccessibility,
generateMethodBodies: options.GenerateMethodBodies,
generateDocumentationComments: options.GenerateDocumentationComments,
autoInsertionLocation: options.AutoInsertionLocation,
reuseSyntax: options.ReuseSyntax,
sortMembers: options.SortMembers);
return options;
}
public virtual Task<Document> AddEventAsync(
Solution solution, INamedTypeSymbol destination, IEventSymbol @event,
CodeGenerationOptions options, CancellationToken cancellationToken)
{
return GetEditAsync(
solution,
destination,
(t, opts, ai, ct) => AddEvent(t, @event, opts, ai),
options,
new[] { @event },
cancellationToken);
}
public Task<Document> AddFieldAsync(Solution solution, INamedTypeSymbol destination, IFieldSymbol field, CodeGenerationOptions options, CancellationToken cancellationToken)
{
return GetEditAsync(
solution,
destination,
(t, opts, ai, ct) => AddField(t, field, opts, ai),
options,
new[] { field },
cancellationToken);
}
public Task<Document> AddPropertyAsync(Solution solution, INamedTypeSymbol destination, IPropertySymbol property, CodeGenerationOptions options, CancellationToken cancellationToken)
{
return GetEditAsync(
solution, destination,
(t, opts, ai, ct) => AddProperty(t, property, opts, ai),
options, new[] { property },
cancellationToken);
}
public Task<Document> AddNamedTypeAsync(Solution solution, INamedTypeSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions options, CancellationToken cancellationToken)
{
return GetEditAsync(
solution, destination,
(t, opts, ai, ct) => AddNamedType(t, namedType, opts, ai, ct),
options, new[] { namedType },
cancellationToken);
}
public Task<Document> AddNamedTypeAsync(Solution solution, INamespaceSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions options, CancellationToken cancellationToken)
{
return GetEditAsync(
solution, destination,
(t, opts, ai, ct) => AddNamedType(t, namedType, opts, ai, ct),
options, new[] { namedType }, cancellationToken);
}
public Task<Document> AddNamespaceAsync(Solution solution, INamespaceSymbol destination, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken)
{
return GetEditAsync(
solution, destination,
(t, opts, ai, ct) => AddNamespace(t, @namespace, opts, ai, ct),
options, new[] { @namespace }, cancellationToken);
}
public Task<Document> AddMethodAsync(Solution solution, INamedTypeSymbol destination, IMethodSymbol method, CodeGenerationOptions options, CancellationToken cancellationToken)
{
return GetEditAsync(
solution, destination,
(t, opts, ai, ct) => AddMethod(t, method, opts, ai),
options, new[] { method }, cancellationToken);
}
public Task<Document> AddMembersAsync(Solution solution, INamedTypeSymbol destination, IEnumerable<ISymbol> members, CodeGenerationOptions options, CancellationToken cancellationToken)
{
return GetEditAsync(
solution, destination,
(t, opts, ai, ct) => AddMembers(t, members, ai, opts, ct),
options, members, cancellationToken);
}
public Task<Document> AddNamespaceOrTypeAsync(Solution solution, INamespaceSymbol destination, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions options, CancellationToken cancellationToken)
{
if (namespaceOrType == null)
{
throw new ArgumentNullException(nameof(namespaceOrType));
}
if (namespaceOrType is INamespaceSymbol namespaceSymbol)
{
return AddNamespaceAsync(solution, destination, namespaceSymbol, options, cancellationToken);
}
else
{
return AddNamedTypeAsync(solution, destination, (INamedTypeSymbol)namespaceOrType, options, cancellationToken);
}
}
protected static void CheckLocation<TDeclarationNode>(
TDeclarationNode destinationMember, Location location) where TDeclarationNode : SyntaxNode
{
if (location == null)
{
throw new ArgumentException(WorkspacesResources.No_location_provided_to_add_statements_to);
}
if (!location.IsInSource)
{
throw new ArgumentException(WorkspacesResources.Destination_location_was_not_in_source);
}
if (location.SourceTree != destinationMember.SyntaxTree)
{
throw new ArgumentException(WorkspacesResources.Destination_location_was_from_a_different_tree);
}
}
protected static void ComputePositionAndTriviaForRemoveAttributeList(
SyntaxNode attributeList,
Func<SyntaxTrivia, bool> isEndOfLineTrivia,
out int positionOfRemovedNode,
out IEnumerable<SyntaxTrivia> triviaOfRemovedNode)
{
positionOfRemovedNode = attributeList.FullSpan.Start;
var leading = attributeList.GetLeadingTrivia();
var trailing = attributeList.GetTrailingTrivia();
if (trailing.Count >= 1 && isEndOfLineTrivia(trailing.Last()))
{
// Remove redundant trailing trivia as we are removing the entire attribute list.
triviaOfRemovedNode = leading;
}
else
{
triviaOfRemovedNode = leading.Concat(trailing);
}
}
protected static void ComputePositionAndTriviaForRemoveAttributeFromAttributeList(
SyntaxNode attributeToRemove,
Func<SyntaxToken, bool> isComma,
out int positionOfRemovedNode,
out IEnumerable<SyntaxTrivia> triviaOfRemovedNode)
{
positionOfRemovedNode = attributeToRemove.FullSpan.Start;
var root = attributeToRemove.SyntaxTree.GetRoot();
var previousToken = root.FindToken(attributeToRemove.FullSpan.Start - 1);
var leading = isComma(previousToken) ? previousToken.LeadingTrivia : attributeToRemove.GetLeadingTrivia();
var nextToken = root.FindToken(attributeToRemove.FullSpan.End + 1);
var trailing = isComma(nextToken) ? nextToken.TrailingTrivia : attributeToRemove.GetTrailingTrivia();
triviaOfRemovedNode = leading.Concat(trailing);
}
protected static T AppendTriviaAtPosition<T>(T node, int position, SyntaxTriviaList trivia)
where T : SyntaxNode
{
if (trivia.Any())
{
var tokenToInsertTrivia = node.FindToken(position);
var tokenWithInsertedTrivia = tokenToInsertTrivia.WithLeadingTrivia(trivia.Concat(tokenToInsertTrivia.LeadingTrivia));
return node.ReplaceToken(tokenToInsertTrivia, tokenWithInsertedTrivia);
}
return node;
}
protected static IList<SyntaxToken> GetUpdatedDeclarationAccessibilityModifiers(IList<SyntaxToken> newModifierTokens, SyntaxTokenList modifiersList, Func<SyntaxToken, bool> isAccessibilityModifier)
{
var updatedModifiersList = new List<SyntaxToken>();
var anyAccessModifierSeen = false;
foreach (var modifier in modifiersList)
{
SyntaxToken newModifier;
if (isAccessibilityModifier(modifier))
{
if (newModifierTokens.Count == 0)
{
continue;
}
newModifier = newModifierTokens[0]
.WithLeadingTrivia(modifier.LeadingTrivia)
.WithTrailingTrivia(modifier.TrailingTrivia);
newModifierTokens.RemoveAt(0);
anyAccessModifierSeen = true;
}
else
{
if (anyAccessModifierSeen && newModifierTokens.Any())
{
updatedModifiersList.AddRange(newModifierTokens);
newModifierTokens.Clear();
}
newModifier = modifier;
}
updatedModifiersList.Add(newModifier);
}
if (!anyAccessModifierSeen)
{
updatedModifiersList.InsertRange(0, newModifierTokens);
}
else
{
updatedModifiersList.AddRange(newModifierTokens);
}
return updatedModifiersList;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using DebuggerTests;
using Microsoft.PythonTools.Debugger;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
using TestUtilities;
using TestUtilities.Mocks;
using TestUtilities.Python;
namespace PythonToolsTests {
[TestClass]
public class DebugReplEvaluatorTests {
private PythonDebugReplEvaluator _evaluator;
private MockReplWindow _window;
private List<PythonProcess> _processes;
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal virtual string DebuggerTestPath {
get {
return TestData.GetPath(@"TestData\DebuggerProject\");
}
}
internal virtual PythonVersion Version {
get {
return PythonPaths.Python26 ?? PythonPaths.Python26_x64;
}
}
[TestInitialize]
public void TestInit() {
Version.AssertInstalled();
var serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();
_evaluator = new PythonDebugReplEvaluator(serviceProvider);
_window = new MockReplWindow(_evaluator);
_evaluator._Initialize(_window);
_processes = new List<PythonProcess>();
}
[TestCleanup]
public void TestClean() {
foreach (var proc in _processes) {
try {
proc.Continue();
} catch (Exception ex) {
Console.WriteLine("Failed to continue process");
Console.WriteLine(ex);
}
if (!proc.WaitForExit(5000)) {
try {
proc.Terminate();
} catch (Exception ex) {
Console.WriteLine("Failed to terminate process");
Console.WriteLine(ex);
}
}
}
if (_window != null) {
Console.WriteLine("Stdout:");
Console.Write(_window.Output);
Console.WriteLine("Stderr:");
Console.Write(_window.Error);
}
}
[TestMethod, Priority(1)]
public void DisplayVariables() {
Attach("DebugReplTest1.py", 3);
Assert.AreEqual("hello", ExecuteText("print(a)"));
Assert.AreEqual("'hello'", ExecuteText("a"));
}
[TestMethod, Priority(3)]
public void DisplayFunctionLocalsAndGlobals() {
Attach("DebugReplTest2.py", 13);
Assert.AreEqual("51", ExecuteText("print(innermost_val)"));
Assert.AreEqual("5", ExecuteText("print(global_val)"));
}
[TestMethod, Priority(3)]
public void ErrorInInput() {
Attach("DebugReplTest2.py", 13);
Assert.AreEqual("", ExecuteText("print(does_not_exist)", false));
Assert.AreEqual(@"Traceback (most recent call last):
File ""<debug input>"", line 1, in <module>
NameError: name 'does_not_exist' is not defined
", _window.Error);
}
[TestMethod, Priority(3)]
public void ChangeVariables() {
Attach("DebugReplTest2.py", 13);
Assert.AreEqual("", ExecuteText("innermost_val = 1"));
Assert.AreEqual("1", ExecuteText("print(innermost_val)"));
}
[TestMethod, Priority(1)]
public void ChangeModule() {
Attach("DebugReplTest1.py", 3);
Assert.AreEqual("'hello'", ExecuteText("a"));
// Change to the dis module
Assert.AreEqual("Current module changed to dis", ExecuteCommand(new SwitchModuleCommand(), "dis"));
Assert.AreEqual("", ExecuteText("test = 'world'"));
Assert.AreEqual("'world'", ExecuteText("test"));
// Change back to the current frame
Assert.AreEqual("Current module changed to <CurrentFrame>", ExecuteCommand(new SwitchModuleCommand(), "<CurrentFrame>"));
Assert.AreEqual("", ExecuteText("test", false));
Assert.IsTrue(_window.Error.Contains("NameError:"));
Assert.AreEqual("'hello'", ExecuteText("a"));
}
[TestMethod, Priority(2)]
public void ChangeFrame() {
Attach("DebugReplTest2.py", 13);
// We are broken in the innermost function
string stack;
stack = ExecuteCommand(new DebugReplFramesCommand(), "");
Assert.IsTrue(stack.StartsWith(@"=> Frame id=0, function=innermost
Frame id=1, function=inner
Frame id=2, function=outer
Frame id=3, function=<module>"));
Assert.AreEqual("0", ExecuteCommand(new DebugReplFrameCommand(), ""));
Assert.AreEqual("51", ExecuteText("print(innermost_val)"));
// Move up the stack to the inner function
Assert.AreEqual("Current frame changed to 1", ExecuteCommand(new DebugReplFrameUpCommand(), ""));
stack = ExecuteCommand(new DebugReplFramesCommand(), "");
Assert.IsTrue(stack.StartsWith(@" Frame id=0, function=innermost
=> Frame id=1, function=inner
Frame id=2, function=outer
Frame id=3, function=<module>"));
Assert.AreEqual("1", ExecuteCommand(new DebugReplFrameCommand(), ""));
Assert.AreEqual("50", ExecuteText("print(inner_val)"));
// Move to frame 2, the outer function
Assert.AreEqual("Current frame changed to 2", ExecuteCommand(new DebugReplFrameCommand(), "2"));
Assert.AreEqual("2", ExecuteCommand(new DebugReplFrameCommand(), ""));
Assert.AreEqual("10", ExecuteText("print(outer_val)"));
// Move down the stack, back to the inner function
Assert.AreEqual("Current frame changed to 1", ExecuteCommand(new DebugReplFrameDownCommand(), ""));
Assert.AreEqual("1", ExecuteCommand(new DebugReplFrameCommand(), ""));
}
[TestMethod, Priority(3)]
[TestCategory("10s")]
public void ChangeThread() {
Attach("DebugReplTest3.py", 39);
var threads = _processes[0].GetThreads();
PythonThread main = threads.SingleOrDefault(t => t.Frames[0].FunctionName == "threadmain");
PythonThread worker1 = threads.SingleOrDefault(t => t.Frames[0].FunctionName == "thread1");
PythonThread worker2 = threads.SingleOrDefault(t => t.Frames[0].FunctionName == "thread2");
// We are broken in the the main thread
string text;
text = ExecuteCommand(new DebugReplThreadsCommand(), "");
Assert.IsTrue(text.Contains(String.Format("=> Thread id={0}, name=", main.Id)));
Assert.IsTrue(text.Contains(String.Format(" Thread id={0}, name=", worker1.Id)));
Assert.IsTrue(text.Contains(String.Format(" Thread id={0}, name=", worker2.Id)));
Assert.AreEqual(main.Id.ToString(), ExecuteCommand(new DebugReplThreadCommand(), ""));
Assert.AreEqual("False", ExecuteText("t1_done"));
Assert.AreEqual("False", ExecuteText("t2_done"));
// Switch to worker thread 1
Assert.AreEqual(String.Format("Current thread changed to {0}, frame 0", worker1.Id), ExecuteCommand(new DebugReplThreadCommand(), worker1.Id.ToString()));
text = ExecuteCommand(new DebugReplThreadsCommand(), "");
Assert.IsTrue(text.Contains(String.Format(" Thread id={0}, name=", main.Id)));
Assert.IsTrue(text.Contains(String.Format("=> Thread id={0}, name=", worker1.Id)));
Assert.IsTrue(text.Contains(String.Format(" Thread id={0}, name=", worker2.Id)));
Assert.AreEqual(worker1.Id.ToString(), ExecuteCommand(new DebugReplThreadCommand(), ""));
Assert.AreEqual("'thread1'", ExecuteText("t1_val"));
}
[TestMethod, Priority(1)]
public void ChangeProcess() {
Attach("DebugReplTest4A.py", 3);
Attach("DebugReplTest4B.py", 3);
PythonProcess proc1 = _processes[0];
PythonProcess proc2 = _processes[1];
// We are broken in process 2 (the last one attached is the current one)
string text;
text = ExecuteCommand(new DebugReplProcessesCommand(), "");
Assert.AreEqual(String.Format(@" Process id={0}, Language version={2}
=> Process id={1}, Language version={2}", proc1.Id, proc2.Id, Version.Version), text);
// Switch to process 1
Assert.AreEqual(String.Format("Current process changed to {0}", proc1.Id), ExecuteCommand(new DebugReplProcessCommand(), proc1.Id.ToString()));
Assert.AreEqual(String.Format("{0}", proc1.Id), ExecuteCommand(new DebugReplProcessCommand(), String.Empty));
Assert.AreEqual("'hello'", ExecuteText("a1"));
Assert.AreEqual("30", ExecuteText("b1"));
// Switch to process 2
Assert.AreEqual(String.Format("Current process changed to {0}", proc2.Id), ExecuteCommand(new DebugReplProcessCommand(), proc2.Id.ToString()));
Assert.AreEqual(String.Format("{0}", proc2.Id), ExecuteCommand(new DebugReplProcessCommand(), String.Empty));
Assert.AreEqual("'world'", ExecuteText("a2"));
Assert.AreEqual("60", ExecuteText("b2"));
}
[TestMethod, Priority(3)]
[TestCategory("10s")]
public void Abort() {
Attach("DebugReplTest5.py", 3);
_window.ClearScreen();
var execute = _evaluator.ExecuteText("for i in range(0,20): time.sleep(0.5)");
_evaluator.AbortExecution();
execute.Wait();
Assert.IsTrue(execute.Result.IsSuccessful);
Assert.AreEqual("Abort is not supported.", _window.Error.TrimEnd());
}
[TestMethod, Priority(1)]
public void StepInto() {
// Make sure that we don't step into the internal repl code
// http://pytools.codeplex.com/workitem/777
Attach("DebugReplTest6.py", 2);
var thread = _processes[0].GetThreads()[0];
thread.StepInto();
// Result of step into is not immediate
Thread.Sleep(1000);
// We should still be in the <module>, not in the internals of print in repl code
foreach (var frame in thread.Frames) {
Console.WriteLine("{0}:{1} [{2}]", frame.FunctionName, frame.LineNo, frame.FileName);
}
Assert.AreEqual(1, thread.Frames.Count);
Assert.AreEqual("<module>", thread.Frames[0].FunctionName);
}
private string ExecuteCommand(IInteractiveWindowCommand cmd, string args) {
_window.ClearScreen();
var execute = cmd.Execute(_window, args);
execute.Wait();
Assert.IsTrue(execute.Result.IsSuccessful);
return _window.Output.TrimEnd();
}
private string ExecuteText(string executionText) {
return ExecuteText(executionText, true);
}
private string ExecuteText(string executionText, bool expectSuccess) {
_window.ClearScreen();
var execute = _evaluator.ExecuteText(executionText);
execute.Wait();
Assert.AreEqual(expectSuccess, execute.Result.IsSuccessful);
return _window.Output.TrimEnd();
}
private void SafeSetEvent(AutoResetEvent evt) {
try {
evt.Set();
} catch (ObjectDisposedException) {
}
}
private void Attach(string filename, int lineNo) {
var debugger = new PythonDebugger();
PythonProcess process = debugger.DebugProcess(Version, DebuggerTestPath + filename, (newproc, newthread) => {
var breakPoint = newproc.AddBreakPointByFileExtension(lineNo, filename);
breakPoint.Add();
_evaluator.AttachProcess(newproc, new MockThreadIdMapper());
},
debugOptions: PythonDebugOptions.CreateNoWindow);
_processes.Add(process);
using (var brkHit = new AutoResetEvent(false))
using (var procExited = new AutoResetEvent(false)) {
EventHandler<BreakpointHitEventArgs> breakpointHitHandler = (s, e) => SafeSetEvent(brkHit);
EventHandler<ProcessExitedEventArgs> processExitedHandler = (s, e) => SafeSetEvent(procExited);
process.BreakpointHit += breakpointHitHandler;
process.ProcessExited += processExitedHandler;
try {
process.Start();
} catch (Win32Exception ex) {
_processes.Remove(process);
if (ex.HResult == -2147467259 /*0x80004005*/) {
Assert.Inconclusive("Required Python interpreter is not installed");
} else {
Assert.Fail("Process start failed:\r\n" + ex.ToString());
}
}
var handles = new[] { brkHit, procExited };
if (WaitHandle.WaitAny(handles, 25000) != 0) {
Assert.Fail("Failed to wait on event");
}
process.BreakpointHit -= breakpointHitHandler;
process.ProcessExited -= processExitedHandler;
}
_evaluator.AttachProcess(process, new MockThreadIdMapper());
}
private class MockThreadIdMapper : IThreadIdMapper {
public long? GetPythonThreadId(uint vsThreadId) {
return vsThreadId;
}
}
}
[TestClass]
public class DebugReplEvaluatorTests30 : DebugReplEvaluatorTests {
[ClassInitialize]
public static new void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal override PythonVersion Version {
get {
return PythonPaths.Python30 ?? PythonPaths.Python30_x64;
}
}
}
[TestClass]
public class DebugReplEvaluatorTests31 : DebugReplEvaluatorTests {
[ClassInitialize]
public static new void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal override PythonVersion Version {
get {
return PythonPaths.Python31 ?? PythonPaths.Python31_x64;
}
}
}
[TestClass]
public class DebugReplEvaluatorTests32 : DebugReplEvaluatorTests {
[ClassInitialize]
public static new void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal override PythonVersion Version {
get {
return PythonPaths.Python32 ?? PythonPaths.Python32_x64;
}
}
}
[TestClass]
public class DebugReplEvaluatorTests33 : DebugReplEvaluatorTests {
[ClassInitialize]
public static new void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal override PythonVersion Version {
get {
return PythonPaths.Python33 ?? PythonPaths.Python33_x64;
}
}
}
[TestClass]
public class DebugReplEvaluatorTests34 : DebugReplEvaluatorTests {
[ClassInitialize]
public static new void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal override PythonVersion Version {
get {
return PythonPaths.Python34 ?? PythonPaths.Python34_x64;
}
}
}
[TestClass]
public class DebugReplEvaluatorTests35 : DebugReplEvaluatorTests {
[ClassInitialize]
public static new void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal override PythonVersion Version {
get {
return PythonPaths.Python35 ?? PythonPaths.Python35_x64;
}
}
}
[TestClass]
public class DebugReplEvaluatorTests27 : DebugReplEvaluatorTests {
[ClassInitialize]
public static new void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal override PythonVersion Version {
get {
return PythonPaths.Python27 ?? PythonPaths.Python27_x64;
}
}
}
[TestClass]
public class DebugReplEvaluatorTests25 : DebugReplEvaluatorTests {
[ClassInitialize]
public static new void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal override PythonVersion Version {
get {
return PythonPaths.Python25 ?? PythonPaths.Python25_x64;
}
}
}
[TestClass]
public class DebugReplEvaluatorTestsIPy : DebugReplEvaluatorTests {
[ClassInitialize]
public static new void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal override PythonVersion Version {
get {
return PythonPaths.IronPython27 ?? PythonPaths.IronPython27_x64;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using umbraco.interfaces;
namespace Umbraco.Core.Sync
{
[Serializable]
public class RefreshInstruction
{
// NOTE
// that class should be refactored
// but at the moment it is exposed in CacheRefresher webservice
// so for the time being we keep it as-is for backward compatibility reasons
// need this public, parameter-less constructor so the web service messenger
// can de-serialize the instructions it receives
public RefreshInstruction()
{
//set default - this value is not used for reading after it's been deserialized, it's only used for persisting the instruction to the db
JsonIdCount = 1;
}
// need this public one so it can be de-serialized - used by the Json thing
// otherwise, should use GetInstructions(...)
public RefreshInstruction(Guid refresherId, RefreshMethodType refreshType, Guid guidId, int intId, string jsonIds, string jsonPayload)
{
RefresherId = refresherId;
RefreshType = refreshType;
GuidId = guidId;
IntId = intId;
JsonIds = jsonIds;
JsonPayload = jsonPayload;
//set default - this value is not used for reading after it's been deserialized, it's only used for persisting the instruction to the db
JsonIdCount = 1;
}
private RefreshInstruction(ICacheRefresher refresher, RefreshMethodType refreshType)
{
RefresherId = refresher.UniqueIdentifier;
RefreshType = refreshType;
//set default - this value is not used for reading after it's been deserialized, it's only used for persisting the instruction to the db
JsonIdCount = 1;
}
private RefreshInstruction(ICacheRefresher refresher, RefreshMethodType refreshType, Guid guidId)
: this(refresher, refreshType)
{
GuidId = guidId;
}
private RefreshInstruction(ICacheRefresher refresher, RefreshMethodType refreshType, int intId)
: this(refresher, refreshType)
{
IntId = intId;
}
/// <summary>
/// A private constructor to create a new instance
/// </summary>
/// <param name="refresher"></param>
/// <param name="refreshType"></param>
/// <param name="json"></param>
/// <param name="idCount">
/// When the refresh method is <see cref="RefreshMethodType.RefreshByIds"/> we know how many Ids are being refreshed so we know the instruction
/// count which will be taken into account when we store this count in the database.
/// </param>
private RefreshInstruction(ICacheRefresher refresher, RefreshMethodType refreshType, string json, int idCount = 1)
: this(refresher, refreshType)
{
JsonIdCount = idCount;
if (refreshType == RefreshMethodType.RefreshByJson)
JsonPayload = json;
else
JsonIds = json;
}
public static IEnumerable<RefreshInstruction> GetInstructions(
ICacheRefresher refresher,
MessageType messageType,
IEnumerable<object> ids,
Type idType,
string json)
{
switch (messageType)
{
case MessageType.RefreshAll:
return new[] { new RefreshInstruction(refresher, RefreshMethodType.RefreshAll) };
case MessageType.RefreshByJson:
return new[] { new RefreshInstruction(refresher, RefreshMethodType.RefreshByJson, json) };
case MessageType.RefreshById:
if (idType == null)
throw new InvalidOperationException("Cannot refresh by id if idType is null.");
if (idType == typeof(int))
{
// bulk of ints is supported
var intIds = ids.Cast<int>().ToArray();
return new[] { new RefreshInstruction(refresher, RefreshMethodType.RefreshByIds, JsonConvert.SerializeObject(intIds), intIds.Length) };
}
// else must be guids, bulk of guids is not supported, iterate
return ids.Select(x => new RefreshInstruction(refresher, RefreshMethodType.RefreshByGuid, (Guid) x));
case MessageType.RemoveById:
if (idType == null)
throw new InvalidOperationException("Cannot remove by id if idType is null.");
// must be ints, bulk-remove is not supported, iterate
return ids.Select(x => new RefreshInstruction(refresher, RefreshMethodType.RemoveById, (int) x));
//return new[] { new RefreshInstruction(refresher, RefreshMethodType.RemoveByIds, JsonConvert.SerializeObject(ids.Cast<int>().ToArray())) };
default:
//case MessageType.RefreshByInstance:
//case MessageType.RemoveByInstance:
throw new ArgumentOutOfRangeException("messageType");
}
}
/// <summary>
/// Gets or sets the refresh action type.
/// </summary>
public RefreshMethodType RefreshType { get; set; }
/// <summary>
/// Gets or sets the refresher unique identifier.
/// </summary>
public Guid RefresherId { get; set; }
/// <summary>
/// Gets or sets the Guid data value.
/// </summary>
public Guid GuidId { get; set; }
/// <summary>
/// Gets or sets the int data value.
/// </summary>
public int IntId { get; set; }
/// <summary>
/// Gets or sets the ids data value.
/// </summary>
public string JsonIds { get; set; }
/// <summary>
/// Gets or sets the number of Ids contained in the JsonIds json value
/// </summary>
/// <remarks>
/// This is used to determine the instruction count per row
/// </remarks>
public int JsonIdCount { get; set; }
/// <summary>
/// Gets or sets the payload data value.
/// </summary>
public string JsonPayload { get; set; }
protected bool Equals(RefreshInstruction other)
{
return RefreshType == other.RefreshType
&& RefresherId.Equals(other.RefresherId)
&& GuidId.Equals(other.GuidId)
&& IntId == other.IntId
&& string.Equals(JsonIds, other.JsonIds)
&& string.Equals(JsonPayload, other.JsonPayload);
}
public override bool Equals(object other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (other.GetType() != this.GetType()) return false;
return Equals((RefreshInstruction) other);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (int) RefreshType;
hashCode = (hashCode*397) ^ RefresherId.GetHashCode();
hashCode = (hashCode*397) ^ GuidId.GetHashCode();
hashCode = (hashCode*397) ^ IntId;
hashCode = (hashCode*397) ^ (JsonIds != null ? JsonIds.GetHashCode() : 0);
hashCode = (hashCode*397) ^ (JsonPayload != null ? JsonPayload.GetHashCode() : 0);
return hashCode;
}
}
public static bool operator ==(RefreshInstruction left, RefreshInstruction right)
{
return Equals(left, right);
}
public static bool operator !=(RefreshInstruction left, RefreshInstruction right)
{
return Equals(left, right) == false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.VisualStudio.Text;
namespace VSConsole.PowerPack.Core
{
public class ConsoleDispatcher : IPrivateConsoleDispatcher, IConsoleDispatcher
{
private EventHandler _beforeStart;
private Dispatcher _dispatcher;
private EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> _executeInputLine;
public ConsoleDispatcher(IPrivateWpfConsole wpfConsole)
{
UtilityMethods.ThrowIfArgumentNull(wpfConsole);
WpfConsole = wpfConsole;
}
private IPrivateWpfConsole WpfConsole { get; set; }
public event EventHandler BeforeStart
{
add
{
EventHandler eventHandler = _beforeStart;
EventHandler comparand;
do
{
comparand = eventHandler;
eventHandler = Interlocked.CompareExchange(ref _beforeStart, comparand + value, comparand);
} while (eventHandler != comparand);
}
remove
{
EventHandler eventHandler = _beforeStart;
EventHandler comparand;
do
{
comparand = eventHandler;
eventHandler = Interlocked.CompareExchange(ref _beforeStart, comparand - value, comparand);
} while (eventHandler != comparand);
}
}
public event EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> ExecuteInputLine
{
add
{
EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> eventHandler = _executeInputLine;
EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> comparand;
do
{
comparand = eventHandler;
eventHandler = Interlocked.CompareExchange(ref _executeInputLine, comparand + value, comparand);
} while (eventHandler != comparand);
}
remove
{
EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> eventHandler = _executeInputLine;
EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> comparand;
do
{
comparand = eventHandler;
eventHandler = Interlocked.CompareExchange(ref _executeInputLine, comparand - value, comparand);
} while (eventHandler != comparand);
}
}
public void Start()
{
if (_dispatcher != null)
return;
IHost host = WpfConsole.Host;
if (host == null)
throw new InvalidOperationException("Can't start ConsoleDispatcher. Host is null.");
_dispatcher = !(host is IAsyncHost)
? new SyncHostConsoleDispatcher(this)
: (Dispatcher) new AsyncHostConsoleDispatcher(this);
_beforeStart.Raise(this, (EventArgs) null);
_dispatcher.Start();
}
public void ClearConsole()
{
if (_dispatcher == null)
return;
_dispatcher.ClearConsole();
}
public void PostInputLine(InputLine inputLine)
{
if (_dispatcher == null)
return;
_dispatcher.PostInputLine(inputLine);
}
private void OnExecute(SnapshotSpan inputLineSpan, bool isComplete)
{
_executeInputLine.Raise(this, Tuple.Create(inputLineSpan, isComplete));
}
private class AsyncHostConsoleDispatcher : Dispatcher
{
private readonly _Marshaler _marshaler;
private Queue<InputLine> _buffer;
private bool _isExecuting;
public AsyncHostConsoleDispatcher(ConsoleDispatcher parentDispatcher)
: base(parentDispatcher)
{
_marshaler = new _Marshaler(this);
}
private bool IsStarted
{
get { return _buffer != null; }
}
public override void Start()
{
if (IsStarted)
throw new InvalidOperationException();
_buffer = new Queue<InputLine>();
var asyncHost = WpfConsole.Host as IAsyncHost;
if (asyncHost == null)
throw new InvalidOperationException();
asyncHost.ExecuteEnd += _marshaler.AsyncHost_ExecuteEnd;
PromptNewLine();
}
public override void PostInputLine(InputLine inputLine)
{
if (!IsStarted)
return;
_buffer.Enqueue(inputLine);
ProcessInputs();
}
private void ProcessInputs()
{
if (_isExecuting || _buffer.Count <= 0)
return;
Tuple<bool, bool> tuple = Process(_buffer.Dequeue());
if (!tuple.Item1)
return;
_isExecuting = true;
if (tuple.Item2)
return;
OnExecuteEnd();
}
private void OnExecuteEnd()
{
if (!IsStarted)
return;
_isExecuting = false;
PromptNewLine();
ProcessInputs();
}
private class _Marshaler : Marshaler<AsyncHostConsoleDispatcher>
{
public _Marshaler(AsyncHostConsoleDispatcher impl)
: base(impl)
{
}
public void AsyncHost_ExecuteEnd(object sender, EventArgs e)
{
Invoke(() => _impl.OnExecuteEnd());
}
}
}
private abstract class Dispatcher
{
protected Dispatcher(ConsoleDispatcher parentDispatcher)
{
ParentDispatcher = parentDispatcher;
WpfConsole = parentDispatcher.WpfConsole;
}
protected ConsoleDispatcher ParentDispatcher { get; private set; }
protected IPrivateWpfConsole WpfConsole { get; private set; }
protected Tuple<bool, bool> Process(InputLine inputLine)
{
SnapshotSpan snapshotSpan = inputLine.SnapshotSpan;
if (inputLine.Flags.HasFlag(InputLineFlag.Echo))
{
WpfConsole.BeginInputLine();
if (inputLine.Flags.HasFlag(InputLineFlag.Execute))
{
WpfConsole.WriteLine(inputLine.Text);
snapshotSpan = WpfConsole.EndInputLine(true).Value;
}
else
WpfConsole.Write(inputLine.Text);
}
if (!inputLine.Flags.HasFlag(InputLineFlag.Execute))
return Tuple.Create(false, false);
string text = inputLine.Text;
bool isComplete = WpfConsole.Host.Execute(text);
WpfConsole.InputHistory.Add(text);
ParentDispatcher.OnExecute(snapshotSpan, isComplete);
return Tuple.Create(true, isComplete);
}
public void PromptNewLine()
{
WpfConsole.Write(WpfConsole.Host.Prompt + " ");
WpfConsole.BeginInputLine();
}
public void ClearConsole()
{
if (WpfConsole.InputLineStart.HasValue)
{
WpfConsole.Host.Abort();
WpfConsole.Clear();
PromptNewLine();
}
else
WpfConsole.Clear();
}
public abstract void Start();
public abstract void PostInputLine(InputLine inputLine);
}
private class SyncHostConsoleDispatcher : Dispatcher
{
public SyncHostConsoleDispatcher(ConsoleDispatcher parentDispatcher)
: base(parentDispatcher)
{
}
public override void Start()
{
PromptNewLine();
}
public override void PostInputLine(InputLine inputLine)
{
if (!Process(inputLine).Item1)
return;
PromptNewLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using gView.Framework.UI;
using gView.Framework.system;
using gView.Framework.IO;
using gView.Framework.Data;
using gView.Framework.Geometry;
using gView.Framework.system.UI;
using gView.Framework.FDB;
using gView.OGC;
using gView.Framework.Db.UI;
using gView.Framework.OGC.UI;
using gView.Framework.Globalisation;
using System.Windows.Forms;
namespace gView.DataSources.MSSqlSpatial.UI
{
[gView.Framework.system.RegisterPlugIn("BCD1A95C-CD4C-4EFA-B065-1A08B533CC4C")]
public class MsSql2008SpatialGeographyExplorerGroupObject : ExplorerParentObject, IOgcGroupExplorerObject
{
private IExplorerIcon _icon = new MsSql2008SpatialGeographyIcon();
public MsSql2008SpatialGeographyExplorerGroupObject()
: base(null,null, 0)
{
}
#region IExplorerGroupObject Members
public IExplorerIcon Icon
{
get { return _icon; }
}
#endregion
#region IExplorerObject Members
public string Name
{
get { return "MsSql 2008 Spatial Geography"; }
}
public string FullName
{
get { return @"OGC\MsSql2008SpatialGeography"; }
}
public string Type
{
get { return "MsSql Spatial Connection"; }
}
public new object Object
{
get { return null; }
}
public IExplorerObject CreateInstanceByFullName(string FullName)
{
return null;
}
#endregion
#region IExplorerParentObject Members
public override void Refresh()
{
base.Refresh();
base.AddChildObject(new MsSql2008SpatialGeographyNewConnectionObject(this));
ConfigTextStream stream = new ConfigTextStream("MsSql2008SpatialGeography_connections");
string connStr, id;
while ((connStr = stream.Read(out id)) != null)
{
base.AddChildObject(new MsSql2008SpatialGeographyExplorerObject(this, id, connStr));
}
stream.Close();
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
if (this.FullName == FullName)
{
MsSql2008SpatialGeographyExplorerGroupObject exObject = new MsSql2008SpatialGeographyExplorerGroupObject();
cache.Append(exObject);
return exObject;
}
return null;
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("2D95BCBD-B257-4162-8EB3-F5FED50A1F7A")]
public class MsSql2008SpatialGeographyNewConnectionObject : ExplorerObjectCls, IExplorerSimpleObject, IExplorerObjectDoubleClick, IExplorerObjectCreatable
{
private IExplorerIcon _icon = new MsSql2008SpatialGeographyNewConnectionIcon();
public MsSql2008SpatialGeographyNewConnectionObject()
: base(null,null, 0)
{
}
public MsSql2008SpatialGeographyNewConnectionObject(IExplorerObject parent)
: base(parent,null, 0)
{
}
#region IExplorerSimpleObject Members
public IExplorerIcon Icon
{
get { return _icon; }
}
#endregion
#region IExplorerObject Members
public string Name
{
get { return LocalizedResources.GetResString("String.NewConnection", "New Connection..."); }
}
public string FullName
{
get { return ""; }
}
public string Type
{
get { return "New MsSql 2008 Spatial Connection"; }
}
public void Dispose()
{
}
public new object Object
{
get { return null; }
}
public IExplorerObject CreateInstanceByFullName(string FullName)
{
return null;
}
#endregion
#region IExplorerObjectDoubleClick Members
public void ExplorerObjectDoubleClick(ExplorerObjectEventArgs e)
{
FormConnectionString dlg = new FormConnectionString();
dlg.ProviderID = "mssql";
dlg.UseProviderInConnectionString = false;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string connStr = dlg.ConnectionString;
ConfigTextStream stream = new ConfigTextStream("MsSql2008SpatialGeography_connections", true, true);
string id = ConfigTextStream.ExtractValue(connStr, "Database");
id += "@" + ConfigTextStream.ExtractValue(connStr, "Server");
if (id == "@") id = "MsSql 2008 Spatial Connection";
stream.Write(connStr, ref id);
stream.Close();
e.NewExplorerObject = new MsSql2008SpatialGeographyExplorerObject(this.ParentExplorerObject, id, dlg.ConnectionString);
}
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
return null;
}
#endregion
#region IExplorerObjectCreatable Member
public bool CanCreate(IExplorerObject parentExObject)
{
return (parentExObject is MsSql2008SpatialGeographyExplorerGroupObject);
}
public IExplorerObject CreateExplorerObject(IExplorerObject parentExObject)
{
ExplorerObjectEventArgs e = new ExplorerObjectEventArgs();
ExplorerObjectDoubleClick(e);
return e.NewExplorerObject;
}
#endregion
}
public class MsSql2008SpatialGeographyExplorerObject : gView.Framework.OGC.UI.ExplorerObjectFeatureClassImport, IExplorerSimpleObject, IExplorerObjectDeletable, IExplorerObjectRenamable, ISerializableExplorerObject
{
private MsSql2008SpatialGeographyIcon _icon = new MsSql2008SpatialGeographyIcon();
private string _server = "", _connectionString = "", _errMsg = "";
private IFeatureDataset _dataset;
public MsSql2008SpatialGeographyExplorerObject() : base(null,typeof(IFeatureDataset)) { }
public MsSql2008SpatialGeographyExplorerObject(IExplorerObject parent, string server, string connectionString)
: base(parent,typeof(IFeatureDataset))
{
_server = server;
_connectionString = connectionString;
}
internal string ConnectionString
{
get
{
return _connectionString;
}
}
#region IExplorerObject Members
public string Name
{
get
{
return _server;
}
}
public string FullName
{
get
{
return @"OGC\MsSql2008SpatialGeography\" + _server;
}
}
public string Type
{
get { return "MsSql2008SpatialGeography Database"; }
}
public IExplorerIcon Icon
{
get
{
return _icon;
}
}
public object Object
{
get
{
if (_dataset != null) _dataset.Dispose();
_dataset = new GeographyDataset();
_dataset.ConnectionString = _connectionString;
_dataset.Open();
return _dataset;
}
}
#endregion
#region IExplorerParentObject Members
public override void Refresh()
{
base.Refresh();
GeographyDataset dataset = new GeographyDataset();
dataset.ConnectionString = _connectionString;
dataset.Open();
List<IDatasetElement> elements = dataset.Elements;
if (elements == null) return;
foreach (IDatasetElement element in elements)
{
if (element.Class is IFeatureClass)
{
base.AddChildObject(new MsSql2008SpatialGeographyFeatureClassExplorerObject(this, element));
}
}
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
MsSql2008SpatialGeographyExplorerGroupObject group = new MsSql2008SpatialGeographyExplorerGroupObject();
if (FullName.IndexOf(group.FullName) != 0 || FullName.Length < group.FullName.Length + 2) return null;
group = (MsSql2008SpatialGeographyExplorerGroupObject)((cache.Contains(group.FullName)) ? cache[group.FullName] : group);
foreach (IExplorerObject exObject in group.ChildObjects)
{
if (exObject.FullName == FullName)
{
cache.Append(exObject);
return exObject;
}
}
return null;
}
#endregion
#region IExplorerObjectDeletable Member
public event ExplorerObjectDeletedEvent ExplorerObjectDeleted = null;
public bool DeleteExplorerObject(ExplorerObjectEventArgs e)
{
ConfigTextStream stream = new ConfigTextStream("MsSql2008SpatialGeography_connections", true, true);
stream.Remove(this.Name, _connectionString);
stream.Close();
if (ExplorerObjectDeleted != null) ExplorerObjectDeleted(this);
return true;
}
#endregion
#region IExplorerObjectRenamable Member
public event ExplorerObjectRenamedEvent ExplorerObjectRenamed = null;
public bool RenameExplorerObject(string newName)
{
bool ret = false;
ConfigTextStream stream = new ConfigTextStream("MsSql2008SpatialGeography_connections", true, true);
ret = stream.ReplaceHoleLine(ConfigTextStream.BuildLine(_server, _connectionString), ConfigTextStream.BuildLine(newName, _connectionString));
stream.Close();
if (ret == true)
{
_server = newName;
if (ExplorerObjectRenamed != null) ExplorerObjectRenamed(this);
}
return ret;
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("F600FA07-2DF7-478A-B683-E8B63D4A298D")]
public class MsSql2008SpatialGeographyFeatureClassExplorerObject : ExplorerObjectCls, IExplorerSimpleObject, ISerializableExplorerObject, IExplorerObjectDeletable
{
private string _fcname = "", _type = "";
private IExplorerIcon _icon = null;
private IFeatureClass _fc = null;
private MsSql2008SpatialGeographyExplorerObject _parent = null;
public MsSql2008SpatialGeographyFeatureClassExplorerObject() : base(null,typeof(IFeatureClass), 1) { }
public MsSql2008SpatialGeographyFeatureClassExplorerObject(MsSql2008SpatialGeographyExplorerObject parent, IDatasetElement element)
: base(parent,typeof(IFeatureClass), 1)
{
if (element == null || !(element.Class is IFeatureClass)) return;
_parent = parent;
_fcname = element.Title;
if (element.Class is IFeatureClass)
{
_fc = (IFeatureClass)element.Class;
switch (_fc.GeometryType)
{
case geometryType.Envelope:
case geometryType.Polygon:
_icon = new MsSql2008SpatialGeographyPolygonIcon();
_type = "Polygon Featureclass";
break;
case geometryType.Multipoint:
case geometryType.Point:
_icon = new MsSql2008SpatialGeographyPointIcon();
_type = "Point Featureclass";
break;
case geometryType.Polyline:
_icon = new MsSql2008SpatialGeographyLineIcon();
_type = "Polyline Featureclass";
break;
default:
_icon = new MsSql2008SpatialGeographyLineIcon();
_type = "Featureclass";
break;
}
}
}
internal string ConnectionString
{
get
{
if (_parent == null) return "";
return _parent.ConnectionString;
}
}
#region IExplorerObject Members
public string Name
{
get { return _fcname; }
}
public string FullName
{
get
{
if (_parent == null) return "";
return _parent.FullName + @"\" + this.Name;
}
}
public string Type
{
get { return _type; }
}
public IExplorerIcon Icon
{
get { return _icon; }
}
public void Dispose()
{
if (_fc != null)
{
_fc = null;
}
}
public object Object
{
get
{
return _fc;
}
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
FullName = FullName.Replace("/", @"\");
int lastIndex = FullName.LastIndexOf(@"\");
if (lastIndex == -1) return null;
string dsName = FullName.Substring(0, lastIndex);
string fcName = FullName.Substring(lastIndex + 1, FullName.Length - lastIndex - 1);
MsSql2008SpatialGeographyExplorerObject dsObject = new MsSql2008SpatialGeographyExplorerObject();
dsObject = dsObject.CreateInstanceByFullName(dsName, cache) as MsSql2008SpatialGeographyExplorerObject;
if (dsObject == null || dsObject.ChildObjects == null) return null;
foreach (IExplorerObject exObject in dsObject.ChildObjects)
{
if (exObject.Name == fcName)
{
cache.Append(exObject);
return exObject;
}
}
return null;
}
#endregion
#region IExplorerObjectDeletable Member
public event ExplorerObjectDeletedEvent ExplorerObjectDeleted;
public bool DeleteExplorerObject(ExplorerObjectEventArgs e)
{
if (_parent.Object is IFeatureDatabase)
{
if (((IFeatureDatabase)_parent.Object).DeleteFeatureClass(this.Name))
{
if (ExplorerObjectDeleted != null) ExplorerObjectDeleted(this);
return true;
}
else
{
MessageBox.Show("ERROR: " + ((IFeatureDatabase)_parent.Object).lastErrorMsg);
return false;
}
}
return false;
}
#endregion
}
class MsSql2008SpatialGeographyIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get
{
return new Guid("B22782D4-59D2-448a-A531-DE29B0067DE6");
}
}
public System.Drawing.Image Image
{
get
{
return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.cat6;
}
}
#endregion
}
class MsSql2008SpatialGeographyNewConnectionIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get
{
return new Guid("56943EE9-DCE8-4ad9-9F13-D306A8A9210E");
}
}
public System.Drawing.Image Image
{
get
{
return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.gps_point;
}
}
#endregion
}
public class MsSql2008SpatialGeographyPointIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get { return new Guid("372EBA30-1F19-4109-B476-8B158CAA6360"); }
}
public System.Drawing.Image Image
{
get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.img_32; }
}
#endregion
}
public class MsSql2008SpatialGeographyLineIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get { return new Guid("5EA3477F-7616-4775-B233-72C94BE055CA"); }
}
public System.Drawing.Image Image
{
get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.img_33; }
}
#endregion
}
public class MsSql2008SpatialGeographyPolygonIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get { return new Guid("D1297B06-4306-4d5d-BBC6-10E26792CE5F"); }
}
public System.Drawing.Image Image
{
get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.img_34; }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
/*
// ===========================================================================
Defines structs that package an aggregate member together with
generic type argument information.
// ===========================================================================*/
/******************************************************************************
SymWithType and its cousins. These package an aggregate member (field,
prop, event, or meth) together with the particular instantiation of the
aggregate (the AggregateType).
The default constructor does nothing so these are not safe to use
uninitialized. Note that when they are used as member of an EXPR they
are automatically zero filled by newExpr.
******************************************************************************/
internal class SymWithType
{
private AggregateType _ats;
private Symbol _sym;
public SymWithType()
{
}
public SymWithType(Symbol sym, AggregateType ats)
{
Set(sym, ats);
}
public virtual void Clear()
{
_sym = null;
_ats = null;
}
public AggregateType Ats
{
get { return _ats; }
}
public Symbol Sym
{
get { return _sym; }
}
public new AggregateType GetType()
{
// This conflicts with object.GetType. Turn every usage of this
// into a get on Ats.
return Ats;
}
public static bool operator ==(SymWithType swt1, SymWithType swt2)
{
if (ReferenceEquals(swt1, swt2))
{
return true;
}
else if (ReferenceEquals(swt1, null))
{
return swt2._sym == null;
}
else if (ReferenceEquals(swt2, null))
{
return swt1._sym == null;
}
return swt1.Sym == swt2.Sym && swt1.Ats == swt2.Ats;
}
public static bool operator !=(SymWithType swt1, SymWithType swt2) => !(swt1 == swt2);
[ExcludeFromCodeCoverage] // == overload should always be the method called.
public override bool Equals(object obj)
{
Debug.Fail("Sub-optimal equality called. Check if this is correct.");
SymWithType other = obj as SymWithType;
if (other == null) return false;
return Sym == other.Sym && Ats == other.Ats;
}
[ExcludeFromCodeCoverage] // Never used as a key.
public override int GetHashCode()
{
Debug.Fail("If using this as a key, implement IEquatable<SymWithType>");
return (Sym?.GetHashCode() ?? 0) + (Ats?.GetHashCode() ?? 0);
}
// The SymWithType is considered NULL iff the Symbol is NULL.
public static implicit operator bool (SymWithType swt)
{
return swt != null;
}
// These assert that the Symbol is of the correct type.
public MethodOrPropertySymbol MethProp()
{
return Sym as MethodOrPropertySymbol;
}
public MethodSymbol Meth()
{
return Sym as MethodSymbol;
}
public PropertySymbol Prop()
{
return Sym as PropertySymbol;
}
public FieldSymbol Field()
{
return Sym as FieldSymbol;
}
public EventSymbol Event()
{
return Sym as EventSymbol;
}
public void Set(Symbol sym, AggregateType ats)
{
if (sym == null)
ats = null;
Debug.Assert(ats == null || sym.parent == ats.getAggregate());
_sym = sym;
_ats = ats;
}
}
internal class MethPropWithType : SymWithType
{
public MethPropWithType()
{
}
public MethPropWithType(MethodOrPropertySymbol mps, AggregateType ats)
{
Set(mps, ats);
}
}
internal sealed class MethWithType : MethPropWithType
{
public MethWithType()
{
}
public MethWithType(MethodSymbol meth, AggregateType ats)
{
Set(meth, ats);
}
}
internal sealed class PropWithType : MethPropWithType
{
public PropWithType(PropertySymbol prop, AggregateType ats)
{
Set(prop, ats);
}
public PropWithType(SymWithType swt)
{
Set(swt.Sym as PropertySymbol, swt.Ats);
}
}
internal sealed class EventWithType : SymWithType
{
public EventWithType(EventSymbol @event, AggregateType ats)
{
Set(@event, ats);
}
}
internal sealed class FieldWithType : SymWithType
{
public FieldWithType(FieldSymbol field, AggregateType ats)
{
Set(field, ats);
}
}
/******************************************************************************
MethPropWithInst and MethWithInst. These extend MethPropWithType with
the method type arguments. Properties will never have type args, but
methods and properties share a lot of code so it's convenient to allow
both here.
The default constructor does nothing so these are not safe to use
uninitialized. Note that when they are used as member of an EXPR they
are automatically zero filled by newExpr.
******************************************************************************/
internal class MethPropWithInst : MethPropWithType
{
public TypeArray TypeArgs { get; private set; }
public MethPropWithInst()
{
Set(null, null, null);
}
public MethPropWithInst(MethodOrPropertySymbol mps, AggregateType ats)
: this(mps, ats, null)
{
}
public MethPropWithInst(MethodOrPropertySymbol mps, AggregateType ats, TypeArray typeArgs)
{
Set(mps, ats, typeArgs);
}
public override void Clear()
{
base.Clear();
TypeArgs = null;
}
public void Set(MethodOrPropertySymbol mps, AggregateType ats, TypeArray typeArgs)
{
if (mps == null)
{
ats = null;
typeArgs = null;
}
Debug.Assert(ats == null || mps != null && mps.getClass() == ats.getAggregate());
base.Set(mps, ats);
TypeArgs = typeArgs;
}
}
internal sealed class MethWithInst : MethPropWithInst
{
public MethWithInst(MethodSymbol meth, AggregateType ats)
: this(meth, ats, null)
{
}
public MethWithInst(MethodSymbol meth, AggregateType ats, TypeArray typeArgs)
{
Set(meth, ats, typeArgs);
}
public MethWithInst(MethPropWithInst mpwi)
{
Set(mpwi.Sym as MethodSymbol, mpwi.Ats, mpwi.TypeArgs);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Json;
using System.Security.Claims;
using System.Text;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Moq;
using Schokotaler.Api.Common;
using Schokotaler.Api.Controllers;
using Schokotaler.Api.Models;
using Schokotaler.Api.Models.Controllers.Tokens;
using Schokotaler.Api.Repository;
using Schokotaler.Api.Tests.Common;
using Xunit;
using Microsoft.Extensions.Logging;
namespace Schokotaler.Api.Tests
{
public class TokensControllerTest : IDisposable {
private Mock<IUserRepository> mockUserRepo;
private Mock<IConfiguration> mockConfig;
private Utility utility;
private ILogger<TokenController> logger;
public TokensControllerTest() {
mockUserRepo = new Mock<IUserRepository>();
mockConfig = new Mock<IConfiguration>();
utility = new Utility();
logger = new Mock<ILogger<TokenController>>().Object;
}
[Fact]
public void GenerateTokenPassTest() {
//Given
var role1 = new Role{Id = 1, Name = "admin"};
var role2 = new Role{Id = 2, Name = "user"};
var model = new TokenCreate();
model.Email = "test_email";
model.Password = "test_pw";
var modelRet = new User();
modelRet.Id = 1;
modelRet.Email = "test_email";
modelRet.Active = true;
modelRet.Name = "test Name";
modelRet.Password = utility.HashPassword(model.Password);
var ru1 = new RolesUsers{RoleId = 1, Role = role1, UserId = 1, User = modelRet};
var ru2 = new RolesUsers{RoleId = 2, Role = role2, UserId = 1, User = modelRet};
modelRet.RolesUsers = new List<RolesUsers>();
modelRet.RolesUsers.Add(ru1);
modelRet.RolesUsers.Add(ru2);
mockUserRepo.Setup(r => r.GetUserWithEmail("test_email", true)).Returns(modelRet);
mockConfig.Setup(c => c["Token:Key"]).Returns("secretsecretsecret");
mockConfig.Setup(c => c["Token:Issuer"]).Returns("unittest");
var controller = new TokenController(mockUserRepo.Object, mockConfig.Object, utility, logger);
//When
var res = controller.GenerateToken(model);
//Then
var okResult = res.Should().BeOfType<JsonResult>().Subject;
string token = TestUtility.GetProperty<string>("token", okResult.Value);
token.Should().NotBeNull();
string[] splitToken = token.Split('.');
string headerS = Encoding.UTF8.GetString(Convert.FromBase64String(TestUtility.ExtendBase64Padding(splitToken[0])));
string bodyS = Encoding.UTF8.GetString(Convert.FromBase64String(TestUtility.ExtendBase64Padding(splitToken[1])));
JsonObject header = (JsonObject)JsonValue.Parse(headerS);
JsonObject body = (JsonObject)JsonValue.Parse(bodyS);
string alg = (string)header["alg"];
alg.ShouldBeEquivalentTo("HS256");
string typ = (string)header["typ"];
typ.ShouldBeEquivalentTo("JWT");
string email = (string)body["email"];
email.ShouldBeEquivalentTo("test_email");
string sub = (string)body["sub"];
sub.ShouldBeEquivalentTo("1");
JsonArray roles = (JsonArray)body[ClaimTypes.Role];
roles.Count.Should().Be(2);
List<string> l = new List<string>();
l.Add((string)roles[0]);
l.Add((string)roles[1]);
l.Should().OnlyContain(s => s.Equals("user") || s.Equals("admin"));
}
[Fact]
public void GenerateTokenMissingPwTest() {
//Given
var model = new TokenCreate{Email = "test_email"};
var controller = new TokenController(mockUserRepo.Object, mockConfig.Object, utility, logger);
//When
var res = controller.GenerateToken(model);
//Then
res.Should().NotBeNull();
var resUnauthorized = res.Should().BeOfType<UnauthorizedResult>().Subject;
resUnauthorized.StatusCode.Should().Be(401);
}
[Fact]
public void GenerateTokenMissingEmailTest() {
//Given
var model = new TokenCreate{ Password = "test_pw" };
var controller = new TokenController(mockUserRepo.Object, mockConfig.Object, utility, logger);
//When
var res = controller.GenerateToken(model);
//Then
res.Should().NotBeNull();
var resUnauthorized = res.Should().BeOfType<UnauthorizedResult>().Subject;
resUnauthorized.StatusCode.Should().Be(401);
}
[Fact]
public void GenerateTokenMissingModelTest() {
//Given
var controller = new TokenController(mockUserRepo.Object, mockConfig.Object, utility, logger);
//When
var res = controller.GenerateToken(null);
//Then
res.Should().NotBeNull();
var resUnauthorized = res.Should().BeOfType<UnauthorizedResult>().Subject;
resUnauthorized.StatusCode.Should().Be(401);
}
[Fact]
public void GenerateTokenWrongEmailTest() {
//Given
User wrongUser = null;
mockUserRepo.Setup(r => r.GetUserWithEmail("wrong_email", true)).Returns(wrongUser);
TokenCreate model = new TokenCreate{Email = "wrong_email", Password = "pass"};
var controller = new TokenController(mockUserRepo.Object, mockConfig.Object, utility, logger);
//When
var res = controller.GenerateToken(model);
//Then
res.Should().NotBeNull();
var resUnauthorized = res.Should().BeOfType<UnauthorizedResult>().Subject;
resUnauthorized.StatusCode.Should().Be(401);
}
[Fact]
public void GenerateTokenWrongPwTest() {
//Given
var loginModel = new TokenCreate{Email = "test_email_2", Password = "wrong_pass"};
var model = new User{
Id = 2,
Email = "test_email_2",
Active = true,
Name = "test_name_2",
Password = utility.HashPassword("correct_pass")
};
mockUserRepo.Setup(r => r.GetUserWithEmail("test_email_2", true)).Returns(model);
var controller = new TokenController(mockUserRepo.Object, mockConfig.Object, utility, logger);
//When
var res = controller.GenerateToken(loginModel);
//Then
res.Should().NotBeNull();
var resUnauthorized = res.Should().BeOfType<UnauthorizedResult>().Subject;
resUnauthorized.StatusCode.Should().Be(401);
}
[Fact]
public void GenerateTokenInactiveTest() {
//Given
var loginModel = new TokenCreate{Email = "test_email_3", Password = "correct_pass"};
var model = new User{
Id = 3,
Name = "test_user_3",
Email = "test_email_3",
Active = false,
Password = utility.HashPassword("correct_pass")
};
mockUserRepo.Setup(r => r.GetUserWithEmail("test_email_3", true)).Returns(model);
var controller = new TokenController(mockUserRepo.Object, mockConfig.Object, utility, logger);
//When
var res = controller.GenerateToken(loginModel);
//Then
res.Should().NotBeNull();
var resBadRequest = res.Should().BeOfType<BadRequestObjectResult>().Subject;
resBadRequest.StatusCode.Should().Be(400);
int errno = TestUtility.GetProperty<int>("Errno", resBadRequest.Value);
errno.Should().Be(3);
}
public void Dispose()
{
}
}
}
| |
namespace android.util
{
[global::MonoJavaBridge.JavaClass()]
public partial class TypedValue : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static TypedValue()
{
InitJNI();
}
protected TypedValue(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _toString8635;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.util.TypedValue._toString8635)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.util.TypedValue.staticClass, global::android.util.TypedValue._toString8635)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getFloat8636;
public virtual float getFloat()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.util.TypedValue._getFloat8636);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.util.TypedValue.staticClass, global::android.util.TypedValue._getFloat8636);
}
internal static global::MonoJavaBridge.MethodId _setTo8637;
public virtual void setTo(android.util.TypedValue arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.util.TypedValue._setTo8637, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.util.TypedValue.staticClass, global::android.util.TypedValue._setTo8637, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getDimension8638;
public virtual float getDimension(android.util.DisplayMetrics arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.util.TypedValue._getDimension8638, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.util.TypedValue.staticClass, global::android.util.TypedValue._getDimension8638, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getFraction8639;
public virtual float getFraction(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.util.TypedValue._getFraction8639, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.util.TypedValue.staticClass, global::android.util.TypedValue._getFraction8639, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _complexToFloat8640;
public static float complexToFloat(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticFloatMethod(android.util.TypedValue.staticClass, global::android.util.TypedValue._complexToFloat8640, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _complexToDimension8641;
public static float complexToDimension(int arg0, android.util.DisplayMetrics arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticFloatMethod(android.util.TypedValue.staticClass, global::android.util.TypedValue._complexToDimension8641, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _complexToDimensionPixelOffset8642;
public static int complexToDimensionPixelOffset(int arg0, android.util.DisplayMetrics arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.util.TypedValue.staticClass, global::android.util.TypedValue._complexToDimensionPixelOffset8642, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _complexToDimensionPixelSize8643;
public static int complexToDimensionPixelSize(int arg0, android.util.DisplayMetrics arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.util.TypedValue.staticClass, global::android.util.TypedValue._complexToDimensionPixelSize8643, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _complexToDimensionNoisy8644;
public static float complexToDimensionNoisy(int arg0, android.util.DisplayMetrics arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticFloatMethod(android.util.TypedValue.staticClass, global::android.util.TypedValue._complexToDimensionNoisy8644, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _applyDimension8645;
public static float applyDimension(int arg0, float arg1, android.util.DisplayMetrics arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticFloatMethod(android.util.TypedValue.staticClass, global::android.util.TypedValue._applyDimension8645, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _complexToFraction8646;
public static float complexToFraction(int arg0, float arg1, float arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticFloatMethod(android.util.TypedValue.staticClass, global::android.util.TypedValue._complexToFraction8646, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _coerceToString8647;
public virtual global::java.lang.CharSequence coerceToString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.util.TypedValue._coerceToString8647)) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.util.TypedValue.staticClass, global::android.util.TypedValue._coerceToString8647)) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _coerceToString8648;
public static global::java.lang.String coerceToString(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.util.TypedValue.staticClass, global::android.util.TypedValue._coerceToString8648, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _TypedValue8649;
public TypedValue() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.util.TypedValue.staticClass, global::android.util.TypedValue._TypedValue8649);
Init(@__env, handle);
}
public static int TYPE_NULL
{
get
{
return 0;
}
}
public static int TYPE_REFERENCE
{
get
{
return 1;
}
}
public static int TYPE_ATTRIBUTE
{
get
{
return 2;
}
}
public static int TYPE_STRING
{
get
{
return 3;
}
}
public static int TYPE_FLOAT
{
get
{
return 4;
}
}
public static int TYPE_DIMENSION
{
get
{
return 5;
}
}
public static int TYPE_FRACTION
{
get
{
return 6;
}
}
public static int TYPE_FIRST_INT
{
get
{
return 16;
}
}
public static int TYPE_INT_DEC
{
get
{
return 16;
}
}
public static int TYPE_INT_HEX
{
get
{
return 17;
}
}
public static int TYPE_INT_BOOLEAN
{
get
{
return 18;
}
}
public static int TYPE_FIRST_COLOR_INT
{
get
{
return 28;
}
}
public static int TYPE_INT_COLOR_ARGB8
{
get
{
return 28;
}
}
public static int TYPE_INT_COLOR_RGB8
{
get
{
return 29;
}
}
public static int TYPE_INT_COLOR_ARGB4
{
get
{
return 30;
}
}
public static int TYPE_INT_COLOR_RGB4
{
get
{
return 31;
}
}
public static int TYPE_LAST_COLOR_INT
{
get
{
return 31;
}
}
public static int TYPE_LAST_INT
{
get
{
return 31;
}
}
public static int COMPLEX_UNIT_SHIFT
{
get
{
return 0;
}
}
public static int COMPLEX_UNIT_MASK
{
get
{
return 15;
}
}
public static int COMPLEX_UNIT_PX
{
get
{
return 0;
}
}
public static int COMPLEX_UNIT_DIP
{
get
{
return 1;
}
}
public static int COMPLEX_UNIT_SP
{
get
{
return 2;
}
}
public static int COMPLEX_UNIT_PT
{
get
{
return 3;
}
}
public static int COMPLEX_UNIT_IN
{
get
{
return 4;
}
}
public static int COMPLEX_UNIT_MM
{
get
{
return 5;
}
}
public static int COMPLEX_UNIT_FRACTION
{
get
{
return 0;
}
}
public static int COMPLEX_UNIT_FRACTION_PARENT
{
get
{
return 1;
}
}
public static int COMPLEX_RADIX_SHIFT
{
get
{
return 4;
}
}
public static int COMPLEX_RADIX_MASK
{
get
{
return 3;
}
}
public static int COMPLEX_RADIX_23p0
{
get
{
return 0;
}
}
public static int COMPLEX_RADIX_16p7
{
get
{
return 1;
}
}
public static int COMPLEX_RADIX_8p15
{
get
{
return 2;
}
}
public static int COMPLEX_RADIX_0p23
{
get
{
return 3;
}
}
public static int COMPLEX_MANTISSA_SHIFT
{
get
{
return 8;
}
}
public static int COMPLEX_MANTISSA_MASK
{
get
{
return 16777215;
}
}
public static int DENSITY_DEFAULT
{
get
{
return 0;
}
}
public static int DENSITY_NONE
{
get
{
return 65535;
}
}
internal static global::MonoJavaBridge.FieldId _type8650;
public int type
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _string8651;
public global::java.lang.CharSequence @string
{
get
{
return default(global::java.lang.CharSequence);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _data8652;
public int data
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _assetCookie8653;
public int assetCookie
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _resourceId8654;
public int resourceId
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _changingConfigurations8655;
public int changingConfigurations
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _density8656;
public int density
{
get
{
return default(int);
}
set
{
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.util.TypedValue.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/util/TypedValue"));
global::android.util.TypedValue._toString8635 = @__env.GetMethodIDNoThrow(global::android.util.TypedValue.staticClass, "toString", "()Ljava/lang/String;");
global::android.util.TypedValue._getFloat8636 = @__env.GetMethodIDNoThrow(global::android.util.TypedValue.staticClass, "getFloat", "()F");
global::android.util.TypedValue._setTo8637 = @__env.GetMethodIDNoThrow(global::android.util.TypedValue.staticClass, "setTo", "(Landroid/util/TypedValue;)V");
global::android.util.TypedValue._getDimension8638 = @__env.GetMethodIDNoThrow(global::android.util.TypedValue.staticClass, "getDimension", "(Landroid/util/DisplayMetrics;)F");
global::android.util.TypedValue._getFraction8639 = @__env.GetMethodIDNoThrow(global::android.util.TypedValue.staticClass, "getFraction", "(FF)F");
global::android.util.TypedValue._complexToFloat8640 = @__env.GetStaticMethodIDNoThrow(global::android.util.TypedValue.staticClass, "complexToFloat", "(I)F");
global::android.util.TypedValue._complexToDimension8641 = @__env.GetStaticMethodIDNoThrow(global::android.util.TypedValue.staticClass, "complexToDimension", "(ILandroid/util/DisplayMetrics;)F");
global::android.util.TypedValue._complexToDimensionPixelOffset8642 = @__env.GetStaticMethodIDNoThrow(global::android.util.TypedValue.staticClass, "complexToDimensionPixelOffset", "(ILandroid/util/DisplayMetrics;)I");
global::android.util.TypedValue._complexToDimensionPixelSize8643 = @__env.GetStaticMethodIDNoThrow(global::android.util.TypedValue.staticClass, "complexToDimensionPixelSize", "(ILandroid/util/DisplayMetrics;)I");
global::android.util.TypedValue._complexToDimensionNoisy8644 = @__env.GetStaticMethodIDNoThrow(global::android.util.TypedValue.staticClass, "complexToDimensionNoisy", "(ILandroid/util/DisplayMetrics;)F");
global::android.util.TypedValue._applyDimension8645 = @__env.GetStaticMethodIDNoThrow(global::android.util.TypedValue.staticClass, "applyDimension", "(IFLandroid/util/DisplayMetrics;)F");
global::android.util.TypedValue._complexToFraction8646 = @__env.GetStaticMethodIDNoThrow(global::android.util.TypedValue.staticClass, "complexToFraction", "(IFF)F");
global::android.util.TypedValue._coerceToString8647 = @__env.GetMethodIDNoThrow(global::android.util.TypedValue.staticClass, "coerceToString", "()Ljava/lang/CharSequence;");
global::android.util.TypedValue._coerceToString8648 = @__env.GetStaticMethodIDNoThrow(global::android.util.TypedValue.staticClass, "coerceToString", "(II)Ljava/lang/String;");
global::android.util.TypedValue._TypedValue8649 = @__env.GetMethodIDNoThrow(global::android.util.TypedValue.staticClass, "<init>", "()V");
}
}
}
| |
using System;
using System.Linq;
using Autofac;
using FluentAssertions;
using Moq;
using Xunit;
namespace DotNetDesign.Substrate.Tests
{
public class BaseEntityTests
{
private IPerson _person;
private IPersonData _personData;
private IContainer _container;
#region Setup
public BaseEntityTests()
{
var builder = new ContainerBuilder();
builder.RegisterModule(new TestModule());
_container = builder.Build();
_person = _container.Resolve<IPerson>();
_personData = _container.Resolve<IPersonData>();
_personData.FirstName = "John";
_personData.LastName = "Doe";
_personData.Version = 1;
}
~BaseEntityTests()
{
_container.Dispose();
}
#endregion
[Fact]
public void PersonPropertyValuesShouldMatchDataPropertyValuesAfterInitialization()
{
_person.Initialize(_personData);
_person.FirstName.Should().Be(_personData.FirstName);
_person.LastName.Should().Be(_personData.LastName);
_person.IsDirty.Should().BeFalse();
}
[Fact]
public void Person_NotInitialized_ShouldThrowExceptionWhenPropertyGetSet()
{
Assert.Throws<InvalidOperationException>(() => { var firstName = _person.FirstName; });
Assert.Throws<InvalidOperationException>(() => { _person.FirstName = "First Name"; });
}
[Fact]
public void GetPropertyDisplayName_Should_Return_Value_In_Attribute()
{
_person.GetPropertyDisplayName(e => e.FirstName).Should().Be("First Name");
_person.GetPropertyDisplayName("FirstName").Should().Be("First Name");
}
[Fact]
public void GetPropertyDisplayName_Should_Return_StringEmpty_If_Attribute_Is_Missing()
{
_person.GetPropertyDisplayName(e => e.LastName).Should().Be(string.Empty);
_person.GetPropertyDisplayName("LastName").Should().Be(string.Empty);
}
[Fact]
public void PersonShouldNotBeDirtyAfterInitializeAndAfterPropertySetToSameValue()
{
_person.Initialize(_personData);
_person.IsDirty.Should().BeFalse();
_person.FirstName = _personData.FirstName;
_person.IsDirty.Should().BeFalse();
}
[Fact]
public void PersonShouldNotBeDirtyAfterInitializeAndShouldBeAfterPropertySetToDifferentValue()
{
_person.Initialize(_personData);
_person.IsDirty.Should().BeFalse();
var newFirstName = _personData.FirstName + " additional characters";
_person.FirstName = newFirstName;
_person.FirstName.Should().Be(newFirstName);
_person.IsDirty.Should().BeTrue();
}
[Fact]
public void ValidPersonShouldCallSaveOnRepository()
{
_person.Initialize(_personData);
var personRepositoryMock = new Mock<IPersonRepository>(MockBehavior.Strict);
_person.EntityRepositoryFactory = () => personRepositoryMock.Object;
personRepositoryMock.Setup(x => x.Save(_person)).Returns(_person);
_person.Save();
}
[Fact]
public void InvalidPersonShouldNotCallSaveOnRepository()
{
_person.Initialize(_personData);
var personRepositoryMock = new Mock<IPersonRepository>(MockBehavior.Strict);
_person.EntityRepositoryFactory = () => personRepositoryMock.Object;
_person.FirstName = null;
_person.Save();
}
[Fact]
public void VersionShouldNotIncrementIfNoChangesMade()
{
_person.Initialize(_personData);
var expectedVersion = _person.Version;
IPerson returnedPerson;
_person.Save(out returnedPerson);
returnedPerson.Version.Should().Be(expectedVersion);
}
[Fact]
public void VersionShouldIncrementIfChangesMade()
{
_person.Initialize(_personData);
_person.FirstName = _person.FirstName + " more info";
var expectedVersion = _person.Version + 1;
var newPerson = _container.Resolve<IPerson>();
var newEntityData = _person.EntityData;
var personRepositoryMock = new Mock<IPersonRepository>(MockBehavior.Strict);
_person.EntityRepositoryFactory = () => personRepositoryMock.Object;
personRepositoryMock.Setup(x => x.Save(_person)).Returns(() =>
{
newPerson.Initialize(newEntityData);
return newPerson;
});
var concurrencyManagerMock = new Mock<IConcurrencyManager<IPerson, IPersonData, IPersonRepository>>(MockBehavior.Strict);
_person.EntityConcurrencyManagerFactory = () => concurrencyManagerMock.Object;
concurrencyManagerMock.Setup(x => x.Verify(_person));
IPerson returnedPerson;
_person.Save(out returnedPerson);
returnedPerson.Version.Should().Be(expectedVersion);
}
[Fact]
public void HasPropertyChangedShouldReturnFalseIfNotChanged()
{
_person.Initialize(_personData);
_person.HasPropertyChanged(x => x.FirstName).Should().BeFalse();
_person.HasPropertyChanged(x => x.LastName).Should().BeFalse();
}
[Fact]
public void HasPropertyChangedShouldReturnTrueIfChanged()
{
_person.Initialize(_personData);
_person.FirstName = _person.FirstName + " more info";
_person.HasPropertyChanged(x => x.FirstName).Should().BeTrue();
_person.HasPropertyChanged(x => x.LastName).Should().BeFalse();
}
[Fact]
public void InvalidOperationExceptionShouldBeThrownIfInitializeIsCalledTwice()
{
_person.Initialize(_personData);
Assert.Throws(typeof (InvalidOperationException), () => _person.Initialize(_personData));
}
[Fact]
public void CallToGetVersionShouldPassInstanceAndVersionToEntityRepository()
{
_person.Initialize(_personData);
var personRepositoryMock = new Mock<IPersonRepository>(MockBehavior.Strict);
_person.EntityRepositoryFactory = () => personRepositoryMock.Object;
const int version = 1;
personRepositoryMock.Setup(x => x.GetVersion(_person.Id, version, false)).Returns(_person);
_person.GetVersion(version);
}
[Fact]
public void CallToDeleteShouldPassInstanceToEntityRepository()
{
_person.Initialize(_personData);
var personRepositoryMock = new Mock<IPersonRepository>(MockBehavior.Strict);
_person.EntityRepositoryFactory = () => personRepositoryMock.Object;
personRepositoryMock.Setup(x => x.Delete(_person));
_person.Delete();
}
[Fact]
public void CallToRevertChangesShouldResetValuesAndSetIsDirtyToFalse()
{
_person.Initialize(_personData);
var originalFirstName = _person.FirstName;
var newFirstName = "NewFirstName";
var originalLastName = _person.LastName;
var newLastName = "NewLastName";
_person.IsDirty.Should().BeFalse();
var originalValidationResults = _person.Validate();
_person.FirstName = newFirstName;
_person.LastName = newLastName;
_person.IsDirty.Should().BeTrue();
_person.FirstName.Should().Be(newFirstName);
_person.LastName.Should().Be(newLastName);
_person.RevertChanges();
_person.IsDirty.Should().BeFalse();
_person.FirstName.Should().Be(originalFirstName);
_person.LastName.Should().Be(originalLastName);
_person.Validate().Count().Should().Be(originalValidationResults.Count());
}
[Fact]
public void CallToInitializeShouldCallInitializingAndInitializeOnceEach()
{
var initializingCallCount = 0;
var initializedCallCount = 0;
_person.Initializing += (sender, e) => initializingCallCount++;
_person.Initialized += (sender, e) => initializedCallCount++;
_person.Initialize(_personData);
initializingCallCount.Should().Be(1);
initializedCallCount.Should().Be(1);
}
[Fact]
public void WhenPropertyValueChangesPropertyChangingAndPropertyChangedEventsShouldBeTriggered()
{
var propertyChangingCallCount = 0;
var propertyChangedCallCount = 0;
var propertyChangingPropertyName = string.Empty;
var propertyChangedPropertyName = string.Empty;
_person.PropertyChanging +=
(sender, e) =>
{
propertyChangingCallCount++;
propertyChangingPropertyName = e.PropertyName;
};
_person.PropertyChanged +=
(sender, e) =>
{
propertyChangedCallCount++;
propertyChangedPropertyName = e.PropertyName;
};
_person.Initialize(_personData);
_person.FirstName = _personData.FirstName;
propertyChangingCallCount.Should().Be(0);
propertyChangedCallCount.Should().Be(0);
propertyChangingPropertyName.Should().BeEmpty();
propertyChangedPropertyName.Should().BeEmpty();
_person.FirstName = _personData.FirstName + " more info";
propertyChangingCallCount.Should().Be(1);
propertyChangedCallCount.Should().Be(1);
propertyChangingPropertyName.Should().Be("FirstName");
propertyChangedPropertyName.Should().Be("FirstName");
}
}
}
| |
using UnityEngine.Rendering;
using Unity.Collections;
using System.Collections.Generic;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
#if ENABLE_RAYTRACING
public class RayCountManager
{
// Indices of the values that we can query
public enum RayCountValues
{
AmbientOcclusion = 0,
Reflection = 1,
AreaShadow = 2,
Total = 3
}
// Texture that keeps track of the ray count per pixel
public RTHandleSystem.RTHandle rayCountTexture { get { return m_RayCountTexture; } }
RTHandleSystem.RTHandle m_RayCountTexture = null;
// Buffer that holds the reductions of the ray count
ComputeBuffer m_ReducedRayCountBuffer0 = null;
ComputeBuffer m_ReducedRayCountBuffer1 = null;
ComputeBuffer m_ReducedRayCountBuffer2 = null;
// CPU Buffer that holds the current values
uint[] m_ReducedRayCountValues = new uint[4];
// HDRP Resources
DebugDisplaySettings m_DebugDisplaySettings;
RenderPipelineResources m_PipelineResources;
// Given that the requests are guaranteed to be executed in order we use a queue to store it
Queue<AsyncGPUReadbackRequest> rayCountReadbacks = new Queue<AsyncGPUReadbackRequest>();
public void Init(RenderPipelineResources renderPipelineResources, DebugDisplaySettings currentDebugDisplaySettings)
{
// Keep track of the external resources
m_DebugDisplaySettings = currentDebugDisplaySettings;
m_PipelineResources = renderPipelineResources;
m_RayCountTexture = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R32G32B32A32_UInt, enableRandomWrite: true, useMipMap: false, name: "RayCountTexture");
// We only require 3 buffers (this supports a maximal size of 8192x8192)
m_ReducedRayCountBuffer0 = new ComputeBuffer(4 * 256 * 256, sizeof(uint));
m_ReducedRayCountBuffer1 = new ComputeBuffer(4 * 32 * 32, sizeof(uint));
m_ReducedRayCountBuffer2 = new ComputeBuffer(4, sizeof(uint));
// Initialize the cpu ray count (Optional)
for(int i = 0; i < 4; ++i)
{
m_ReducedRayCountValues[i] = 0;
}
}
public void Release()
{
RTHandles.Release(m_RayCountTexture);
CoreUtils.SafeRelease(m_ReducedRayCountBuffer0);
CoreUtils.SafeRelease(m_ReducedRayCountBuffer1);
CoreUtils.SafeRelease(m_ReducedRayCountBuffer2);
}
public void ClearRayCount(CommandBuffer cmd, HDCamera camera)
{
// We only want to do the clears only if the debug display is active
if (m_DebugDisplaySettings.data.countRays)
{
// Get the compute shader to use
ComputeShader countCompute = m_PipelineResources.shaders.countTracedRays;
// Grab the kernel that we will be using for the clear
int currentKenel = countCompute.FindKernel("ClearBuffer");
// We only clear the 256x256 texture, the clear will then implicitly propagate to the lower resolutions
cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer0);
cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 256);
int tileSize = 256 / 32;
cmd.DispatchCompute(countCompute, currentKenel, tileSize, tileSize, 1);
// Clear the ray count texture (that ensures that we don't have to check what we are reading while we reduce)
HDUtils.SetRenderTarget(cmd, m_RayCountTexture, ClearFlag.Color);
}
}
public int RayCountIsEnabled()
{
return m_DebugDisplaySettings.data.countRays ? 1 : 0;
}
public void EvaluateRayCount(CommandBuffer cmd, HDCamera camera)
{
if (m_DebugDisplaySettings.data.countRays)
{
using (new ProfilingSample(cmd, "Raytracing Debug Overlay", CustomSamplerId.RaytracingDebug.GetSampler()))
{
// Get the size of the viewport to process
int currentWidth = camera.actualWidth;
int currentHeight = camera.actualHeight;
// Get the compute shader
ComputeShader countCompute = m_PipelineResources.shaders.countTracedRays;
// Grab the kernel that we will be using for the reduction
int currentKenel = countCompute.FindKernel("TextureReduction");
// Compute the dispatch dimensions
int areaTileSize = 32;
int dispatchWidth = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
int dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);
// Do we need three passes
if (dispatchHeight > 32 || dispatchWidth > 32)
{
// Bind the texture and the 256x256 buffer
cmd.SetComputeTextureParam(countCompute, currentKenel, HDShaderIDs._InputRayCountTexture, m_RayCountTexture);
cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer0);
cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 256);
cmd.DispatchCompute(countCompute, currentKenel, dispatchWidth, dispatchHeight, 1);
// Let's move to the next reduction pass
currentWidth /= 32;
currentHeight /= 32;
// Grab the kernel that we will be using for the reduction
currentKenel = countCompute.FindKernel("BufferReduction");
// Compute the dispatch dimensions
dispatchWidth = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);
cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._InputRayCountBuffer, m_ReducedRayCountBuffer0);
cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer1);
cmd.SetComputeIntParam(countCompute, HDShaderIDs._InputBufferDimension, 256);
cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 32);
cmd.DispatchCompute(countCompute, currentKenel, dispatchWidth, dispatchHeight, 1);
// Let's move to the next reduction pass
currentWidth /= 32;
currentHeight /= 32;
// Compute the dispatch dimensions
dispatchWidth = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);
cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._InputRayCountBuffer, m_ReducedRayCountBuffer1);
cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer2);
cmd.SetComputeIntParam(countCompute, HDShaderIDs._InputBufferDimension, 32);
cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 1);
cmd.DispatchCompute(countCompute, currentKenel, dispatchWidth, dispatchHeight, 1);
}
else
{
cmd.SetComputeTextureParam(countCompute, currentKenel, HDShaderIDs._InputRayCountTexture, m_RayCountTexture);
cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer1);
cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 32);
cmd.DispatchCompute(countCompute, currentKenel, dispatchWidth, dispatchHeight, 1);
// Let's move to the next reduction pass
currentWidth /= 32;
currentHeight /= 32;
// Grab the kernel that we will be using for the reduction
currentKenel = countCompute.FindKernel("BufferReduction");
// Compute the dispatch dimensions
dispatchWidth = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);
cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._InputRayCountBuffer, m_ReducedRayCountBuffer1);
cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer2);
cmd.SetComputeIntParam(countCompute, HDShaderIDs._InputBufferDimension, 32);
cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 1);
cmd.DispatchCompute(countCompute, currentKenel, dispatchWidth, dispatchHeight, 1);
}
// Enqueue an Async read-back for the single value
AsyncGPUReadbackRequest singleReadBack = AsyncGPUReadback.Request(m_ReducedRayCountBuffer2, 4 * sizeof(uint), 0);
rayCountReadbacks.Enqueue(singleReadBack);
}
}
}
public float GetRaysPerFrame(RayCountValues rayCountValue)
{
if (!m_DebugDisplaySettings.data.countRays)
{
return 0.0f;
}
else
{
while(rayCountReadbacks.Peek().done || rayCountReadbacks.Peek().hasError == true)
{
if (rayCountReadbacks.Peek().done)
{
// Grab the native array from this readback
NativeArray<uint> sampleCount = rayCountReadbacks.Peek().GetData<uint>();
for(int i = 0; i < 4; ++i)
{
m_ReducedRayCountValues[i] = sampleCount[i];
}
}
rayCountReadbacks.Dequeue();
}
return m_ReducedRayCountValues[(int)rayCountValue];
}
}
}
#endif
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security.AccessControl;
using System.ServiceModel;
using System.ServiceModel.Activation.Diagnostics;
using System.ServiceModel.Channels;
using System.Threading;
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
abstract class WorkerProcess : IConnectionRegister
{
int isUnregistered;
int processId;
MessageQueue queue;
int queueId;
IConnectionDuplicator connectionDuplicator;
EventTraceActivity eventTraceActivity;
public bool IsRegistered
{
get { return isUnregistered == 0; }
}
public MessageQueue Queue
{
get
{
return this.queue;
}
set
{
this.queue = value;
}
}
public int ProcessId
{
get
{
return this.processId;
}
}
#if DEBUG
public int QueueId
{
get
{
return this.queueId;
}
}
#endif
internal void Close()
{
if (Interlocked.Increment(ref isUnregistered) == 1)
{
if (this.queue != null)
{
this.queue.Unregister(this);
}
}
}
protected EventTraceActivity EventTraceActivity
{
get
{
if (this.eventTraceActivity == null)
{
this.eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate();
}
return this.eventTraceActivity;
}
}
protected abstract DuplicateContext DuplicateConnection(ListenerSessionConnection session);
protected abstract void OnDispatchSuccess();
protected abstract TransportType TransportType { get; }
internal IAsyncResult BeginDispatchSession(ListenerSessionConnection session, AsyncCallback callback, object state)
{
return new DispatchSessionAsyncResult(session, callback, state);
}
internal bool EndDispatchSession(IAsyncResult result)
{
try
{
DispatchSessionAsyncResult dispatchAsyncResult = DispatchSessionAsyncResult.End(result);
if (dispatchAsyncResult.DuplicateSucceeded)
{
OnDispatchSuccess();
return true;
}
}
catch (Exception exception)
{
EventLogEventId logEventId = EventLogEventId.MessageQueueDuplicatedSocketLeak;
if (this.TransportType == TransportType.NamedPipe)
{
logEventId = EventLogEventId.MessageQueueDuplicatedPipeLeak;
}
Debug.Print("WorkerProcess.DispatchSession() failed sending duplicated socket to processId: " + this.ProcessId + " exception:" + exception);
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)EventLogCategory.SharingService,
(uint)logEventId,
this.ProcessId.ToString(NumberFormatInfo.InvariantInfo),
ListenerTraceUtility.CreateSourceString(this),
exception.ToString());
if (Fx.IsFatal(exception))
{
throw;
}
Close();
// make sure we close the connection to the SharedConnectionListener
// so it knows we've unregistered it
((IChannel)connectionDuplicator).Abort();
if (!ShouldRecoverFromProxyCall(exception))
{
throw;
}
}
return false;
}
internal IConnectionDuplicator ConnectionDuplicator
{
get
{
return this.connectionDuplicator;
}
}
void WorkerProcess_Closed(object sender, EventArgs e)
{
Debug.Print("WorkerProcess.WorkerProcess_Closed() worker leaving: " + processId + " State: " + ((IDuplexContextChannel)sender).State);
Close();
}
void WorkerProcess_Faulted(object sender, EventArgs e)
{
Debug.Print("WorkerProcess.WorkerProcess_Faulted() worker leaving: " + processId + " State: " + ((IDuplexContextChannel)sender).State);
Close();
}
ListenerExceptionStatus IConnectionRegister.Register(Version version, int processId, BaseUriWithWildcard path, int queueId, Guid token, string eventName)
{
if (TD.MessageQueueRegisterStartIsEnabled())
{
TD.MessageQueueRegisterStart(this.EventTraceActivity);
}
Debug.Print("WorkerProcess.Register() version: " + version + " processId: " + processId + " path: " + path + " queueId: " + queueId + " token: " + token + " eventName: " + eventName);
if (DiagnosticUtility.ShouldTraceInformation)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Information, ListenerTraceCode.MessageQueueRegisterCalled, SR.GetString(SR.TraceCodeMessageQueueRegisterCalled), new StringTraceRecord("Path", path.ToString()), this, null);
}
// Get the callback channel
this.connectionDuplicator = OperationContext.Current.GetCallbackChannel<IConnectionDuplicator>();
// Prevent this duplicate operation from timing out, faulting the pipe, and stopping any further communication with w3wp
// we're gated by MaxPendingAccepts + MaxPendingConnection. see CSD Main bug 193390 for details
((IContextChannel)this.connectionDuplicator).OperationTimeout = TimeSpan.MaxValue;
ListenerExceptionStatus status = ListenerExceptionStatus.Success;
bool abortInstance = false;
if (path == null || eventName == null)
{
status = ListenerExceptionStatus.InvalidArgument;
abortInstance = true;
goto FAILED;
}
// Vista only: validate remote process ID
if (OSEnvironmentHelper.IsVistaOrGreater)
{
status = ListenerExceptionStatus.InvalidArgument;
object property = OperationContext.Current.IncomingMessage.Properties[ConnectionMessageProperty.Name];
Fx.Assert(property != null, "WorkerProcess.Register() ConnectionMessageProperty not found!");
IConnection connection = property as IConnection;
Fx.Assert(connection != null, "WorkerProcess.Register() ConnectionMessageProperty is not IConnection!");
PipeHandle pipe = connection.GetCoreTransport() as PipeHandle;
Fx.Assert(pipe != null, "WorkerProcess.Register() CoreTransport is not PipeHandle!");
if (processId != pipe.GetClientPid())
{
status = ListenerExceptionStatus.InvalidArgument;
abortInstance = true;
goto FAILED;
}
}
// validate version
Version ourVersion = Assembly.GetExecutingAssembly().GetName().Version;
if (version > ourVersion)
{
// VERSIONING
// in V1 we assume that we can handle earlier versions
// this might not be true when we ship later releases.
Debug.Print("WorkerProcess.Register() unsupported version ourVersion: " + ourVersion + " version: " + version);
status = ListenerExceptionStatus.VersionUnsupported;
goto FAILED;
}
if (queueId == 0 && path == null)
{
status = ListenerExceptionStatus.InvalidArgument;
abortInstance = true;
goto FAILED;
}
this.processId = processId;
this.queueId = 0;
if (queueId != 0)
{
this.queueId = queueId;
status = ActivatedMessageQueue.Register(queueId, token, this);
}
else
{
status = MessageQueue.Register(path, this);
}
if (status == ListenerExceptionStatus.Success)
{
foreach (IChannel channel in OperationContext.Current.InstanceContext.IncomingChannels)
{
channel.Faulted += new EventHandler(WorkerProcess_Faulted);
channel.Closed += new EventHandler(WorkerProcess_Closed);
}
try
{
using (EventWaitHandle securityEvent = EventWaitHandle.OpenExisting(ListenerConstants.GlobalPrefix + eventName, EventWaitHandleRights.Modify))
{
securityEvent.Set();
}
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Error);
status = ListenerExceptionStatus.InvalidArgument;
abortInstance = true;
}
}
if (status != ListenerExceptionStatus.Success)
{
goto FAILED;
}
if (DiagnosticUtility.ShouldTraceInformation)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Information, ListenerTraceCode.MessageQueueRegisterSucceeded, SR.GetString(SR.TraceCodeMessageQueueRegisterSucceeded), new StringTraceRecord("Path", path.ToString()), this, null);
}
if (TD.MessageQueueRegisterCompletedIsEnabled())
{
TD.MessageQueueRegisterCompleted(this.EventTraceActivity, path.ToString());
}
FAILED:
if (abortInstance)
{
if (DiagnosticUtility.ShouldTraceError)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Error, ListenerTraceCode.MessageQueueRegisterFailed, SR.GetString(SR.TraceCodeMessageQueueRegisterFailed),
new StringTraceRecord("Register", SR.GetString(SR.SharingRegistrationFailedAndAbort, status.ToString())), this, null);
}
if (TD.MessageQueueRegisterAbortIsEnabled())
{
TD.MessageQueueRegisterAbort(this.EventTraceActivity,
status.ToString(),
(path != null) ? path.ToString() : string.Empty);
}
AbortServiceInstance();
}
else if (status != ListenerExceptionStatus.Success)
{
if (DiagnosticUtility.ShouldTraceError)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Error, ListenerTraceCode.MessageQueueRegisterFailed, SR.GetString(SR.TraceCodeMessageQueueRegisterFailed),
new StringTraceRecord("Register", SR.GetString(SR.SharingRegistrationFailed, status.ToString())), this, null);
}
if (TD.MessageQueueRegisterFailedIsEnabled())
{
TD.MessageQueueRegisterFailed(this.EventTraceActivity,
(path != null) ? path.ToString() : string.Empty,
status.ToString());
}
InitiateClosingServiceInstance();
}
return status;
}
bool IConnectionRegister.ValidateUriRoute(Uri uri, System.Net.IPAddress address, int port)
{
if (this.queue == null)
{
AbortServiceInstance();
return false;
}
MessageQueue destinationQueue = RoutingTable.Lookup(uri, address, port);
return object.ReferenceEquals(destinationQueue, this.queue);
}
void IConnectionRegister.Unregister()
{
Debug.Print("WorkerProcess.Unregister() processId: " + processId);
Close();
}
static bool ShouldRecoverFromProxyCall(Exception exception)
{
return (
(exception is CommunicationException) ||
(exception is ObjectDisposedException) ||
(exception is TimeoutException)
);
}
void AbortServiceInstance()
{
OperationContext.Current.InstanceContext.Abort();
}
void InitiateClosingServiceInstance()
{
InstanceContext serviceInstance = OperationContext.Current.InstanceContext;
serviceInstance.BeginClose(ListenerConstants.RegistrationCloseTimeout,
Fx.ThunkCallback(new AsyncCallback(CloseCallback)), serviceInstance);
}
static void CloseCallback(IAsyncResult asyncResult)
{
InstanceContext serviceInstance = asyncResult.AsyncState as InstanceContext;
try
{
serviceInstance.EndClose(asyncResult);
}
catch (CommunicationException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
catch (TimeoutException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
}
class DispatchSessionAsyncResult : AsyncResult
{
ListenerSessionConnection session;
bool duplicateSucceeded;
static AsyncCallback dispatchSessionCallback = Fx.ThunkCallback(new AsyncCallback(DispatchSessionCompletedCallback));
public DispatchSessionAsyncResult(ListenerSessionConnection session, AsyncCallback callback, object state)
: base(callback, state)
{
this.session = session;
DuplicateContext duplicateContext = null;
try
{
duplicateContext = session.WorkerProcess.DuplicateConnection(session);
}
catch (ServiceActivationException e)
{
int traceCode;
string traceDescription;
if (session.WorkerProcess is TcpWorkerProcess)
{
traceCode = ListenerTraceCode.MessageQueueDuplicatedSocketError;
traceDescription = SR.GetString(SR.TraceCodeMessageQueueDuplicatedSocketError);
}
else
{
traceCode = ListenerTraceCode.MessageQueueDuplicatedPipeError;
traceDescription = SR.GetString(SR.TraceCodeMessageQueueDuplicatedPipeError);
}
if (DiagnosticUtility.ShouldTraceError)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Error, traceCode, traceDescription, this, e);
}
this.Complete(true, e);
return;
}
IAsyncResult result = this.session.WorkerProcess.ConnectionDuplicator.BeginDuplicate(duplicateContext,
dispatchSessionCallback, this);
if (result.CompletedSynchronously)
{
CompleteDuplicateSession(result);
this.Complete(true);
}
}
static void DispatchSessionCompletedCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
return;
DispatchSessionAsyncResult thisPtr = (DispatchSessionAsyncResult)result.AsyncState;
Exception completeException = null;
try
{
thisPtr.CompleteDuplicateSession(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
completeException = exception;
}
thisPtr.Complete(false, completeException);
}
void CompleteDuplicateSession(IAsyncResult result)
{
this.session.WorkerProcess.ConnectionDuplicator.EndDuplicate(result);
// Successfully duplicated the session.
duplicateSucceeded = true;
}
public bool DuplicateSucceeded
{
get
{
return duplicateSucceeded;
}
}
public static DispatchSessionAsyncResult End(IAsyncResult result)
{
return AsyncResult.End<DispatchSessionAsyncResult>(result);
}
}
}
}
| |
/********************************************************************
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.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Multiverse.Tools.WorldEditor
{
public partial class NameValueDialog : Form
{
NameValueObject nameValueCollecton = new NameValueObject();
NameValueTemplateCollection temColl;
public NameValueDialog(NameValueObject obj, string type, NameValueTemplateCollection temCol)
{
InitializeComponent();
temColl = temCol;
NameValueCollection.SetNameValueObject(obj.nameValuePairs);
loadTemplateListBox(temCol.List(type));
loadNameListBox();
}
public NameValueObject NameValueCollection
{
get
{
return nameValueCollecton;
}
}
private void loadNameListBox()
{
valueItem item;
nameListBox.Items.Clear();
foreach(string Name in NameValueCollection.NameValuePairKeyList())
{
string value;
valueItem valItem = NameValueCollection.LookUp(Name);
nameListBox.Items.Add(String.Format("{0}={1}", Name, (NameValueCollection.LookUp(Name) as valueItem).value));
}
}
private void loadTemplateListBox(List<string> name)
{
foreach(string template in name)
{
templatesListBox.Items.Add(template);
}
}
public void addNVPButton_click(object obj, EventArgs e)
{
bool showAgain = false;
using (NameValueAddEdit_Dialog dlg = new NameValueAddEdit_Dialog("", "", "", null))
{
DialogResult dlgResult = dlg.ShowDialog();
do{
if (dlgResult == DialogResult.OK)
{
showAgain = false;
if (dlgResult == DialogResult.OK)
{
// do validation here
// if validation fails, set showAgain to true
showAgain = ((dlgResult == DialogResult.OK) && (!dlg.okButton_validating()));
}
}
}while (showAgain);
if (dlgResult == DialogResult.OK)
{
NameValueCollection.AddNameValuePair(dlg.NameTextBoxText, dlg.ValueTextBoxText);
nameListBox.Items.Add(String.Format("{0}={1}", dlg.NameTextBoxText, dlg.ValueTextBoxText));
return;
}
else if (dlgResult == DialogResult.Cancel)
{
return;
}
}
}
public void editNVPButton_click(object obj, EventArgs e)
{
valueItem value;
if (nameListBox.Items.Count > 0 && nameListBox.SelectedItem != null)
{
string name = nameListBox.SelectedItem.ToString();
value = NameValueCollection.LookUp(name);
NameValueAddEdit_Dialog dlg;
if (value == null)
{
return;
}
if (String.Equals(value.type, "enum"))
{
dlg = new NameValueAddEdit_Dialog(name, value.value, value.type, value.enumList);
}
else
{
dlg = new NameValueAddEdit_Dialog(name, value.value, value.type, null);
}
DialogResult dlgResult = dlg.ShowDialog();
if (dlgResult == DialogResult.OK)
{
NameValueCollection.EditNameValuePair(nameListBox.SelectedItem.ToString(), dlg.NameTextBoxText, dlg.ValueTextBoxText, value.type);
}
dlg.ValueTextbox.Visible = true;
dlg.ValueTextbox.Visible = false;
}
}
public void deleteNVPButton_click(object obj, EventArgs e)
{
if (nameListBox.SelectedItem != null)
{
NameValueCollection.RemoveNameValuePair(nameListBox.SelectedItem.ToString());
nameListBox.Items.Remove(nameListBox.SelectedItem);
}
}
public void templatesListBox_selectedIndexChanged(object obj, EventArgs e)
{
if (templatesListBox.SelectedIndex != -1)
{
string templateName = templatesListBox.SelectedItem.ToString();
nameListBox.Items.Clear();
List<string> list = temColl.NameValuePropertiesList(templateName);
foreach (string name in list)
{
nameListBox.Items.Add(name);
}
}
else
{
nameListBox.Items.Clear();
foreach (string name in NameValueCollection.NameValuePairKeyList())
{
nameListBox.Items.Add(name);
}
}
}
private void addTemplateButton_clicked(object sender, EventArgs e)
{
if (templatesListBox.SelectedItem != null)
{
string tempName = templatesListBox.SelectedItem.ToString();
List<string> propList = temColl.NameValuePropertiesList(tempName);
foreach (string prop in propList)
{
string type = temColl.PropertyType(tempName, prop);
string def = temColl.DefaultValue(tempName, prop);
if (def == "")
{
switch (type)
{
case "float":
case "int":
case "uint":
def = "0";
break;
case "string":
case "enum":
def = "";
break;
}
}
temColl.Enum(tempName, prop);
if (String.Equals(type, "Enum"))
{
NameValueCollection.AddNameValuePair(prop, def, temColl.Enum(tempName, prop));
nameListBox.Items.Add(prop);
}
else
{
nameListBox.Items.Add(prop);
NameValueCollection.AddNameValuePair(prop, def);
}
}
}
}
private void addNVPButton_clicked(object sender, EventArgs e)
{
using (NameValueAddEdit_Dialog dlg = new NameValueAddEdit_Dialog("", "", "", null))
{
dlg.Text = "Name Value Pair Add Dialog";
if (dlg.ShowDialog() == DialogResult.OK)
{
nameListBox.Items.Add(dlg.NameTextBoxText);
NameValueCollection.AddNameValuePair(dlg.NameTextBoxText, dlg.ValueTextBoxText);
}
}
}
private void editNVPButton_clicked(object sender, EventArgs e)
{
valueItem val;
string oldName = nameListBox.SelectedItem.ToString();
val = NameValueCollection.LookUp(oldName);
using (NameValueAddEdit_Dialog dlg = new NameValueAddEdit_Dialog(nameListBox.SelectedItem.ToString(), val.value, val.type,null))
{
dlg.Text = "Name Value Pair Edit Dialog";
if (dlg.ShowDialog() == DialogResult.OK)
{
NameValueCollection.EditNameValuePair(oldName, dlg.NameTextBoxText, dlg.NameTextBoxText, val.type);
}
}
}
private void deleteNVButton_clicked(object sender, EventArgs e)
{
string name = nameListBox.SelectedItem.ToString();
nameListBox.Items.Remove(nameListBox.SelectedItem);
NameValueCollection.RemoveNameValuePair(name);
}
private void helpButton_clicked(object sender, EventArgs e)
{
Button but = sender as Button;
WorldEditor.LaunchDoc(but.Tag as string);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NBitcoin;
using WalletWasabi.Blockchain.Analysis;
using WalletWasabi.Blockchain.Analysis.Clustering;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Blockchain.TransactionOutputs;
using WalletWasabi.Blockchain.Transactions;
using WalletWasabi.Helpers;
using WalletWasabi.Models;
namespace WalletWasabi.Blockchain.TransactionProcessing
{
public class TransactionProcessor
{
public TransactionProcessor(
AllTransactionStore transactionStore,
KeyManager keyManager,
Money dustThreshold,
int privacyLevelThreshold)
{
TransactionStore = Guard.NotNull(nameof(transactionStore), transactionStore);
KeyManager = Guard.NotNull(nameof(keyManager), keyManager);
DustThreshold = Guard.NotNull(nameof(dustThreshold), dustThreshold);
Coins = new CoinsRegistry();
BlockchainAnalyzer = new BlockchainAnalyzer(privacyLevelThreshold);
}
public event EventHandler<ProcessedResult>? WalletRelevantTransactionProcessed;
private static object Lock { get; } = new object();
public AllTransactionStore TransactionStore { get; }
public KeyManager KeyManager { get; }
public CoinsRegistry Coins { get; }
public BlockchainAnalyzer BlockchainAnalyzer { get; }
public Money DustThreshold { get; }
#region Progress
public int QueuedTxCount { get; private set; }
public int QueuedProcessedTxCount { get; private set; }
#endregion Progress
public IEnumerable<ProcessedResult> Process(IEnumerable<SmartTransaction> txs)
{
var rets = new List<ProcessedResult>();
lock (Lock)
{
try
{
QueuedTxCount = txs.Count();
foreach (var tx in txs)
{
rets.Add(ProcessNoLock(tx));
QueuedProcessedTxCount++;
}
}
finally
{
QueuedTxCount = 0;
QueuedProcessedTxCount = 0;
}
}
foreach (var ret in rets.Where(x => x.IsNews))
{
WalletRelevantTransactionProcessed?.Invoke(this, ret);
}
return rets;
}
public IEnumerable<ProcessedResult> Process(params SmartTransaction[] txs)
=> Process(txs as IEnumerable<SmartTransaction>);
public ProcessedResult Process(SmartTransaction tx)
{
ProcessedResult ret;
lock (Lock)
{
try
{
QueuedTxCount = 1;
ret = ProcessNoLock(tx);
}
finally
{
QueuedTxCount = 0;
}
}
if (ret.IsNews)
{
WalletRelevantTransactionProcessed?.Invoke(this, ret);
}
return ret;
}
private ProcessedResult ProcessNoLock(SmartTransaction tx)
{
var result = new ProcessedResult(tx);
// We do not care about non-witness transactions for other than mempool cleanup.
if (!tx.Transaction.PossiblyP2WPKHInvolved())
{
return result;
}
uint256 txId = tx.GetHash();
// Performance ToDo: txids could be cached in a hashset here by the AllCoinsView and then the contains would be fast.
if (!tx.Transaction.IsCoinBase && !Coins.AsAllCoinsView().CreatedBy(txId).Any()) // Transactions we already have and processed would be "double spends" but they shouldn't.
{
var doubleSpends = new List<SmartCoin>();
foreach (var txin in tx.Transaction.Inputs)
{
if (Coins.TryGetSpenderSmartCoinsByOutPoint(txin.PrevOut, out var coins))
{
doubleSpends.AddRange(coins);
}
}
if (doubleSpends.Any())
{
if (tx.Height == Height.Mempool)
{
// if the received transaction is spending at least one input already
// spent by a previous unconfirmed transaction signaling RBF then it is not a double
// spending transaction but a replacement transaction.
var isReplacementTx = doubleSpends.Any(x => x.IsReplaceable());
if (isReplacementTx)
{
// Undo the replaced transaction by removing the coins it created (if other coin
// spends it, remove that too and so on) and restoring those that it replaced.
// After undoing the replaced transaction it will process the replacement transaction.
var replacedTxId = doubleSpends.First().TransactionId;
var (replaced, restored) = Coins.Undo(replacedTxId);
result.ReplacedCoins.AddRange(replaced);
result.RestoredCoins.AddRange(restored);
foreach (var replacedTransactionId in replaced.Select(coin => coin.TransactionId))
{
TransactionStore.MempoolStore.TryRemove(replacedTransactionId, out _);
}
tx.SetReplacement();
}
else
{
return result;
}
}
else // new confirmation always enjoys priority
{
// remove double spent coins recursively (if other coin spends it, remove that too and so on), will add later if they came to our keys
foreach (SmartCoin doubleSpentCoin in doubleSpends)
{
Coins.Remove(doubleSpentCoin);
}
result.SuccessfullyDoubleSpentCoins.AddRange(doubleSpends);
var unconfirmedDoubleSpentTxId = doubleSpends.First().TransactionId;
TransactionStore.MempoolStore.TryRemove(unconfirmedDoubleSpentTxId, out _);
}
}
}
for (var i = 0U; i < tx.Transaction.Outputs.Count; i++)
{
// If transaction received to any of the wallet keys:
var output = tx.Transaction.Outputs[i];
HdPubKey foundKey = KeyManager.GetKeyForScriptPubKey(output.ScriptPubKey);
if (foundKey is { })
{
if (!foundKey.IsInternal)
{
tx.Label = SmartLabel.Merge(tx.Label, foundKey.Label);
}
foundKey.SetKeyState(KeyState.Used, KeyManager);
if (output.Value <= DustThreshold)
{
result.ReceivedDusts.Add(output);
continue;
}
SmartCoin newCoin = new SmartCoin(tx, i, foundKey);
result.ReceivedCoins.Add(newCoin);
// If we did not have it.
if (Coins.TryAdd(newCoin))
{
result.NewlyReceivedCoins.Add(newCoin);
// Make sure there's always 21 clean keys generated and indexed.
KeyManager.AssertCleanKeysIndexed(isInternal: foundKey.IsInternal);
if (foundKey.IsInternal)
{
// Make sure there's always 14 internal locked keys generated and indexed.
KeyManager.AssertLockedInternalKeysIndexed(14);
}
}
else // If we had this coin already.
{
if (newCoin.Height != Height.Mempool) // Update the height of this old coin we already had.
{
SmartCoin oldCoin = Coins.AsAllCoinsView().GetByOutPoint(new OutPoint(txId, i));
if (oldCoin is { }) // Just to be sure, it is a concurrent collection.
{
result.NewlyConfirmedReceivedCoins.Add(newCoin);
oldCoin.Height = newCoin.Height;
}
}
}
}
}
// If spends any of our coin
foreach (var coin in Coins.AsAllCoinsView().OutPoints(tx.Transaction.Inputs.Select(x => x.PrevOut).ToHashSet()))
{
var alreadyKnown = coin.SpenderTransaction == tx;
result.SpentCoins.Add(coin);
if (!alreadyKnown)
{
Coins.Spend(coin, tx);
result.NewlySpentCoins.Add(coin);
}
if (tx.Confirmed)
{
result.NewlyConfirmedSpentCoins.Add(coin);
}
}
if (result.IsNews)
{
TransactionStore.AddOrUpdate(tx);
}
BlockchainAnalyzer.Analyze(result.Transaction);
return result;
}
public void UndoBlock(Height blockHeight)
{
Coins.SwitchToUnconfirmFromBlock(blockHeight);
}
}
}
| |
// Copyright 2021 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 gcsv = Google.Cloud.SecurityCenter.V1P1Beta1;
using sys = System;
namespace Google.Cloud.SecurityCenter.V1P1Beta1
{
/// <summary>Resource name for the <c>Source</c> resource.</summary>
public sealed partial class SourceName : gax::IResourceName, sys::IEquatable<SourceName>
{
/// <summary>The possible contents of <see cref="SourceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>organizations/{organization}/sources/{source}</c>.</summary>
OrganizationSource = 1,
/// <summary>A resource name with pattern <c>folders/{folder}/sources/{source}</c>.</summary>
FolderSource = 2,
/// <summary>A resource name with pattern <c>projects/{project}/sources/{source}</c>.</summary>
ProjectSource = 3,
}
private static gax::PathTemplate s_organizationSource = new gax::PathTemplate("organizations/{organization}/sources/{source}");
private static gax::PathTemplate s_folderSource = new gax::PathTemplate("folders/{folder}/sources/{source}");
private static gax::PathTemplate s_projectSource = new gax::PathTemplate("projects/{project}/sources/{source}");
/// <summary>Creates a <see cref="SourceName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="SourceName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static SourceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SourceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SourceName"/> with the pattern <c>organizations/{organization}/sources/{source}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SourceName"/> constructed from the provided ids.</returns>
public static SourceName FromOrganizationSource(string organizationId, string sourceId) =>
new SourceName(ResourceNameType.OrganizationSource, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Creates a <see cref="SourceName"/> with the pattern <c>folders/{folder}/sources/{source}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SourceName"/> constructed from the provided ids.</returns>
public static SourceName FromFolderSource(string folderId, string sourceId) =>
new SourceName(ResourceNameType.FolderSource, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Creates a <see cref="SourceName"/> with the pattern <c>projects/{project}/sources/{source}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SourceName"/> constructed from the provided ids.</returns>
public static SourceName FromProjectSource(string projectId, string sourceId) =>
new SourceName(ResourceNameType.ProjectSource, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern
/// <c>organizations/{organization}/sources/{source}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SourceName"/> with pattern
/// <c>organizations/{organization}/sources/{source}</c>.
/// </returns>
public static string Format(string organizationId, string sourceId) =>
FormatOrganizationSource(organizationId, sourceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern
/// <c>organizations/{organization}/sources/{source}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SourceName"/> with pattern
/// <c>organizations/{organization}/sources/{source}</c>.
/// </returns>
public static string FormatOrganizationSource(string organizationId, string sourceId) =>
s_organizationSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern
/// <c>folders/{folder}/sources/{source}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SourceName"/> with pattern <c>folders/{folder}/sources/{source}</c>
/// .
/// </returns>
public static string FormatFolderSource(string folderId, string sourceId) =>
s_folderSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern
/// <c>projects/{project}/sources/{source}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SourceName"/> with pattern
/// <c>projects/{project}/sources/{source}</c>.
/// </returns>
public static string FormatProjectSource(string projectId, string sourceId) =>
s_projectSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>Parses the given resource name string into a new <see cref="SourceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/sources/{source}</c></description></item>
/// <item><description><c>folders/{folder}/sources/{source}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}</c></description></item>
/// </list>
/// </remarks>
/// <param name="sourceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SourceName"/> if successful.</returns>
public static SourceName Parse(string sourceName) => Parse(sourceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SourceName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/sources/{source}</c></description></item>
/// <item><description><c>folders/{folder}/sources/{source}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sourceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="SourceName"/> if successful.</returns>
public static SourceName Parse(string sourceName, bool allowUnparsed) =>
TryParse(sourceName, allowUnparsed, out SourceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SourceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/sources/{source}</c></description></item>
/// <item><description><c>folders/{folder}/sources/{source}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}</c></description></item>
/// </list>
/// </remarks>
/// <param name="sourceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SourceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sourceName, out SourceName result) => TryParse(sourceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SourceName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/sources/{source}</c></description></item>
/// <item><description><c>folders/{folder}/sources/{source}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sourceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SourceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sourceName, bool allowUnparsed, out SourceName result)
{
gax::GaxPreconditions.CheckNotNull(sourceName, nameof(sourceName));
gax::TemplatedResourceName resourceName;
if (s_organizationSource.TryParseName(sourceName, out resourceName))
{
result = FromOrganizationSource(resourceName[0], resourceName[1]);
return true;
}
if (s_folderSource.TryParseName(sourceName, out resourceName))
{
result = FromFolderSource(resourceName[0], resourceName[1]);
return true;
}
if (s_projectSource.TryParseName(sourceName, out resourceName))
{
result = FromProjectSource(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(sourceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SourceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string folderId = null, string organizationId = null, string projectId = null, string sourceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
SourceId = sourceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SourceName"/> class from the component parts of pattern
/// <c>organizations/{organization}/sources/{source}</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
public SourceName(string organizationId, string sourceId) : this(ResourceNameType.OrganizationSource, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Source</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string SourceId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.OrganizationSource: return s_organizationSource.Expand(OrganizationId, SourceId);
case ResourceNameType.FolderSource: return s_folderSource.Expand(FolderId, SourceId);
case ResourceNameType.ProjectSource: return s_projectSource.Expand(ProjectId, SourceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as SourceName);
/// <inheritdoc/>
public bool Equals(SourceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SourceName a, SourceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SourceName a, SourceName b) => !(a == b);
}
public partial class Source
{
/// <summary>
/// <see cref="gcsv::SourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::SourceName SourceName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::SourceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using CSJ2K;
using Nini.Config;
using log4net;
using Rednettle.Warp3D;
using Mono.Addins;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenMetaverse.Rendering;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Physics.Manager;
using OpenSim.Services.Interfaces;
using WarpRenderer = global::Warp3D.Warp3D;
namespace OpenSim.Region.CoreModules.World.Warp3DMap
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DImageModule")]
public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule
{
private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3");
private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216);
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
private IRendering m_primMesher;
private IConfigSource m_config;
private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>();
private bool m_useAntiAliasing = false; // TODO: Make this a config option
private bool m_Enabled = false;
#region Region Module interface
public void Initialise(IConfigSource source)
{
m_config = source;
if (Util.GetConfigVarFromSections<string>(
m_config, "MapImageModule", new string[] { "Startup", "Map" }, "MapImageModule") != "Warp3DImageModule")
return;
m_Enabled = true;
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_scene = scene;
List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
if (renderers.Count > 0)
{
m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
m_log.DebugFormat("[WARP 3D IMAGE MODULE]: Loaded prim mesher {0}", m_primMesher);
}
else
{
m_log.Debug("[WARP 3D IMAGE MODULE]: No prim mesher loaded, prim rendering will be disabled");
}
m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "Warp3DImageModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
#region IMapImageGenerator Members
public Bitmap CreateMapTile()
{
Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f);
Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f, (int)Constants.RegionSize, (int)Constants.RegionSize, (float)Constants.RegionSize, (float)Constants.RegionSize);
return CreateMapTile(viewport, false);
}
public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
{
Viewport viewport = new Viewport(camPos, camDir, fov, (float)Constants.RegionSize, 0.1f, width, height);
return CreateMapTile(viewport, useTextures);
}
public Bitmap CreateMapTile(Viewport viewport, bool useTextures)
{
bool drawPrimVolume = true;
bool textureTerrain = true;
string[] configSections = new string[] { "Map", "Startup" };
drawPrimVolume
= Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, drawPrimVolume);
textureTerrain
= Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, textureTerrain);
m_colors.Clear();
int width = viewport.Width;
int height = viewport.Height;
if (m_useAntiAliasing)
{
width *= 2;
height *= 2;
}
WarpRenderer renderer = new WarpRenderer();
renderer.CreateScene(width, height);
renderer.Scene.autoCalcNormals = false;
#region Camera
warp_Vector pos = ConvertVector(viewport.Position);
pos.z -= 0.001f; // Works around an issue with the Warp3D camera
warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
renderer.Scene.defaultCamera.setPos(pos);
renderer.Scene.defaultCamera.lookAt(lookat);
if (viewport.Orthographic)
{
renderer.Scene.defaultCamera.isOrthographic = true;
renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth;
renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight;
}
else
{
float fov = viewport.FieldOfView;
fov *= 1.75f; // FIXME: ???
renderer.Scene.defaultCamera.setFov(fov);
}
#endregion Camera
renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40));
renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40));
CreateWater(renderer);
CreateTerrain(renderer, textureTerrain);
if (drawPrimVolume)
CreateAllPrims(renderer, useTextures);
renderer.Render();
Bitmap bitmap = renderer.Scene.getImage();
if (m_useAntiAliasing)
{
using (Bitmap origBitmap = bitmap)
bitmap = ImageUtils.ResizeImage(origBitmap, viewport.Width, viewport.Height);
}
// XXX: It shouldn't really be necesary to force a GC here as one should occur anyway pretty shortly
// afterwards. It's generally regarded as a bad idea to manually GC. If Warp3D is using lots of memory
// then this may be some issue with the Warp3D code itself, though it's also quite possible that generating
// this map tile simply takes a lot of memory.
GC.Collect();
m_log.Debug("[WARP 3D IMAGE MODULE]: GC.Collect()");
return bitmap;
}
public byte[] WriteJpeg2000Image()
{
try
{
using (Bitmap mapbmp = CreateMapTile())
return OpenJPEG.EncodeFromImage(mapbmp, true);
}
catch (Exception e)
{
// JPEG2000 encoder failed
m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
}
return null;
}
#endregion
#region Rendering Methods
private void CreateWater(WarpRenderer renderer)
{
float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
renderer.AddPlane("Water", 256f * 0.5f);
renderer.Scene.sceneobject("Water").setPos(127.5f, waterHeight, 127.5f);
renderer.AddMaterial("WaterColor", ConvertColor(WATER_COLOR));
renderer.Scene.material("WaterColor").setReflectivity(0); // match water color with standard map module thanks lkalif
renderer.Scene.material("WaterColor").setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
renderer.SetObjectMaterial("Water", "WaterColor");
}
private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
{
ITerrainChannel terrain = m_scene.Heightmap;
float[] heightmap = terrain.GetFloatsSerialised();
warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2);
for (int y = 0; y < 256; y++)
{
for (int x = 0; x < 256; x++)
{
int v = y * 256 + x;
float height = heightmap[v];
warp_Vector pos = ConvertVector(new Vector3(x, y, height));
obj.addVertex(new warp_Vertex(pos, (float)x / 255f, (float)(255 - y) / 255f));
}
}
for (int y = 0; y < 256; y++)
{
for (int x = 0; x < 256; x++)
{
if (x < 255 && y < 255)
{
int v = y * 256 + x;
// Normal
Vector3 v1 = new Vector3(x, y, heightmap[y * 256 + x]);
Vector3 v2 = new Vector3(x + 1, y, heightmap[y * 256 + x + 1]);
Vector3 v3 = new Vector3(x, y + 1, heightmap[(y + 1) * 256 + x]);
warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3));
norm = norm.reverse();
obj.vertex(v).n = norm;
// Triangle 1
obj.addTriangle(
v,
v + 1,
v + 256);
// Triangle 2
obj.addTriangle(
v + 256 + 1,
v + 256,
v + 1);
}
}
}
renderer.Scene.addObject("Terrain", obj);
UUID[] textureIDs = new UUID[4];
float[] startHeights = new float[4];
float[] heightRanges = new float[4];
RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings;
textureIDs[0] = regionInfo.TerrainTexture1;
textureIDs[1] = regionInfo.TerrainTexture2;
textureIDs[2] = regionInfo.TerrainTexture3;
textureIDs[3] = regionInfo.TerrainTexture4;
startHeights[0] = (float)regionInfo.Elevation1SW;
startHeights[1] = (float)regionInfo.Elevation1NW;
startHeights[2] = (float)regionInfo.Elevation1SE;
startHeights[3] = (float)regionInfo.Elevation1NE;
heightRanges[0] = (float)regionInfo.Elevation2SW;
heightRanges[1] = (float)regionInfo.Elevation2NW;
heightRanges[2] = (float)regionInfo.Elevation2SE;
heightRanges[3] = (float)regionInfo.Elevation2NE;
uint globalX, globalY;
Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
warp_Texture texture;
using (
Bitmap image
= TerrainSplat.Splat(
heightmap, textureIDs, startHeights, heightRanges,
new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain))
{
texture = new warp_Texture(image);
}
warp_Material material = new warp_Material(texture);
material.setReflectivity(50);
renderer.Scene.addMaterial("TerrainColor", material);
renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif
renderer.SetObjectMaterial("Terrain", "TerrainColor");
}
private void CreateAllPrims(WarpRenderer renderer, bool useTextures)
{
if (m_primMesher == null)
return;
m_scene.ForEachSOG(
delegate(SceneObjectGroup group)
{
CreatePrim(renderer, group.RootPart, useTextures);
foreach (SceneObjectPart child in group.Parts)
CreatePrim(renderer, child, useTextures);
}
);
}
private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
bool useTextures)
{
const float MIN_SIZE = 2f;
if ((PCode)prim.Shape.PCode != PCode.Prim)
return;
if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE)
return;
Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
FacetedMesh renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
if (renderMesh == null)
return;
warp_Vector primPos = ConvertVector(prim.GetWorldPosition());
warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset);
warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
if (prim.ParentID != 0)
{
SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId);
if (group != null)
m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset)));
}
warp_Vector primScale = ConvertVector(prim.Scale);
string primID = prim.UUID.ToString();
// Create the prim faces
// TODO: Implement the useTextures flag behavior
for (int i = 0; i < renderMesh.Faces.Count; i++)
{
Face face = renderMesh.Faces[i];
string meshName = primID + "-Face-" + i.ToString();
// Avoid adding duplicate meshes to the scene
if (renderer.Scene.objectData.ContainsKey(meshName))
{
continue;
}
warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3);
for (int j = 0; j < face.Vertices.Count; j++)
{
Vertex v = face.Vertices[j];
warp_Vector pos = ConvertVector(v.Position);
warp_Vector norm = ConvertVector(v.Normal);
if (prim.Shape.SculptTexture == UUID.Zero)
norm = norm.reverse();
warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);
faceObj.addVertex(vert);
}
for (int j = 0; j < face.Indices.Count; j += 3)
{
faceObj.addTriangle(
face.Indices[j + 0],
face.Indices[j + 1],
face.Indices[j + 2]);
}
Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
Color4 faceColor = GetFaceColor(teFace);
string materialName = GetOrCreateMaterial(renderer, faceColor);
faceObj.transform(m);
faceObj.setPos(primPos);
faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);
renderer.Scene.addObject(meshName, faceObj);
renderer.SetObjectMaterial(meshName, materialName);
}
}
private Color4 GetFaceColor(Primitive.TextureEntryFace face)
{
Color4 color;
if (face.TextureID == UUID.Zero)
return face.RGBA;
if (!m_colors.TryGetValue(face.TextureID, out color))
{
bool fetched = false;
// Attempt to fetch the texture metadata
UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
if (metadata != null)
{
OSDMap map = null;
try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }
if (map != null)
{
color = map["X-JPEG2000-RGBA"].AsColor4();
fetched = true;
}
}
if (!fetched)
{
// Fetch the texture, decode and get the average color,
// then save it to a temporary metadata asset
AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
if (textureAsset != null)
{
int width, height;
color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
metadata = new AssetBase
{
Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
Flags = AssetFlags.Collectable,
FullID = metadataID,
ID = metadataID.ToString(),
Local = true,
Temporary = true,
Name = String.Empty,
Type = (sbyte)AssetType.Unknown
};
m_scene.AssetService.Store(metadata);
}
else
{
color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
}
}
m_colors[face.TextureID] = color;
}
return color * face.RGBA;
}
private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
{
string name = color.ToString();
warp_Material material = renderer.Scene.material(name);
if (material != null)
return name;
renderer.AddMaterial(name, ConvertColor(color));
if (color.A < 1f)
renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
return name;
}
#endregion Rendering Methods
#region Static Helpers
private static warp_Vector ConvertVector(Vector3 vector)
{
return new warp_Vector(vector.X, vector.Z, vector.Y);
}
private static warp_Quaternion ConvertQuaternion(Quaternion quat)
{
return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W);
}
private static int ConvertColor(Color4 color)
{
int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
if (color.A < 1f)
c |= (byte)(color.A * 255f) << 24;
return c;
}
private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3)
{
Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z);
Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z);
Vector3 normal = Vector3.Cross(edge1, edge2);
normal.Normalize();
return normal;
}
public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
{
ulong r = 0;
ulong g = 0;
ulong b = 0;
ulong a = 0;
using (MemoryStream stream = new MemoryStream(j2kData))
{
try
{
int pixelBytes;
using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream))
{
width = bitmap.Width;
height = bitmap.Height;
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
// Sum up the individual channels
unsafe
{
if (pixelBytes == 4)
{
for (int y = 0; y < height; y++)
{
byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
for (int x = 0; x < width; x++)
{
b += row[x * pixelBytes + 0];
g += row[x * pixelBytes + 1];
r += row[x * pixelBytes + 2];
a += row[x * pixelBytes + 3];
}
}
}
else
{
for (int y = 0; y < height; y++)
{
byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
for (int x = 0; x < width; x++)
{
b += row[x * pixelBytes + 0];
g += row[x * pixelBytes + 1];
r += row[x * pixelBytes + 2];
}
}
}
}
}
// Get the averages for each channel
const decimal OO_255 = 1m / 255m;
decimal totalPixels = (decimal)(width * height);
decimal rm = ((decimal)r / totalPixels) * OO_255;
decimal gm = ((decimal)g / totalPixels) * OO_255;
decimal bm = ((decimal)b / totalPixels) * OO_255;
decimal am = ((decimal)a / totalPixels) * OO_255;
if (pixelBytes == 3)
am = 1m;
return new Color4((float)rm, (float)gm, (float)bm, (float)am);
}
catch (Exception ex)
{
m_log.WarnFormat(
"[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}",
textureID, j2kData.Length, ex.Message);
width = 0;
height = 0;
return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
}
}
}
#endregion Static Helpers
}
public static class ImageUtils
{
/// <summary>
/// Performs bilinear interpolation between four values
/// </summary>
/// <param name="v00">First, or top left value</param>
/// <param name="v01">Second, or top right value</param>
/// <param name="v10">Third, or bottom left value</param>
/// <param name="v11">Fourth, or bottom right value</param>
/// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param>
/// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param>
/// <returns>The bilinearly interpolated result</returns>
public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent)
{
return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
}
/// <summary>
/// Performs a high quality image resize
/// </summary>
/// <param name="image">Image to resize</param>
/// <param name="width">New width</param>
/// <param name="height">New height</param>
/// <returns>Resized image</returns>
public static Bitmap ResizeImage(Image image, int width, int height)
{
Bitmap result = new Bitmap(width, height);
using (Graphics graphics = Graphics.FromImage(result))
{
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
}
return result;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// TenantAccessOperations operations.
/// </summary>
internal partial class TenantAccessOperations : IServiceOperations<ApiManagementClient>, ITenantAccessOperations
{
/// <summary>
/// Initializes a new instance of the TenantAccessOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal TenantAccessOperations(ApiManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ApiManagementClient
/// </summary>
public ApiManagementClient Client { get; private set; }
/// <summary>
/// Get tenant access information details.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<AccessInformationContract,TenantAccessGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string accessName = "access";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("accessName", accessName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{accessName}", System.Uri.EscapeDataString(accessName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<AccessInformationContract,TenantAccessGetHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AccessInformationContract>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<TenantAccessGetHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Update tenant access information details.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to retrieve the Tenant Access Information.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the property to update. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, AccessInformationUpdateParameters parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (ifMatch == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string accessName = "access";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("accessName", accessName);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{accessName}", System.Uri.EscapeDataString(accessName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Regenerate primary access key.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> RegeneratePrimaryKeyWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string accessName = "access";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("accessName", accessName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "RegeneratePrimaryKey", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}/regeneratePrimaryKey").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{accessName}", System.Uri.EscapeDataString(accessName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Regenerate secondary access key.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> RegenerateSecondaryKeyWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string accessName = "access";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("accessName", accessName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "RegenerateSecondaryKey", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}/regenerateSecondaryKey").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{accessName}", System.Uri.EscapeDataString(accessName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
[assembly: PythonModule("time", typeof(IronPython.Modules.PythonTime))]
namespace IronPython.Modules {
public static class PythonTime {
private const int YearIndex = 0;
private const int MonthIndex = 1;
private const int DayIndex = 2;
private const int HourIndex = 3;
private const int MinuteIndex = 4;
private const int SecondIndex = 5;
private const int WeekdayIndex = 6;
private const int DayOfYearIndex = 7;
private const int IsDaylightSavingsIndex = 8;
private const int MaxIndex = 9;
private const int minYear = 1900; // minimum year for python dates (CLS dates are bigger)
private const double epochDifferenceDouble = 62135596800.0; // Difference between CLS epoch and UNIX epoch, == System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc).Ticks / TimeSpan.TicksPerSecond
private const long epochDifferenceLong = 62135596800;
private const double ticksPerSecond = (double)TimeSpan.TicksPerSecond;
public static readonly int altzone;
public static readonly int daylight;
public static readonly int timezone;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PythonTuple tzname;
public const int _STRUCT_TM_ITEMS = 9;
[MultiRuntimeAware]
private static Stopwatch sw;
public const string __doc__ = "This module provides various functions to manipulate time values.";
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
// we depend on locale, it needs to be initialized
PythonLocale.EnsureLocaleInitialized(context);
}
static PythonTime() {
// altzone, timezone are offsets from UTC in seconds, so they always fit in the
// -13*3600 to 13*3600 range and are safe to cast to ints
daylight = TimeZoneInfo.Local.SupportsDaylightSavingTime ? 1 : 0;
tzname = PythonTuple.MakeTuple(TimeZoneInfo.Local.StandardName, TimeZoneInfo.Local.DaylightName);
timezone = (int)-TimeZoneInfo.Local.BaseUtcOffset.TotalSeconds;
altzone = timezone;
if (TimeZoneInfo.Local.SupportsDaylightSavingTime) {
var now = DateTime.Now;
var rule = TimeZoneInfo.Local.GetAdjustmentRules().Where(x => x.DateStart <= now && x.DateEnd >= now).FirstOrDefault();
if (rule != null) {
altzone = timezone + ((int)-rule.DaylightDelta.TotalSeconds);
}
}
}
internal static long TimestampToTicks(double seconds) {
// If everything is converted in one shot, the rounding error surface at
// microsecond level.
// e.g: 5399410716.777882 --> 2141-02-06 05:18:36.777881
// 1399410716.123 --> 2014-05-06 23:11:56.122995
// To work around it, second and microseconds are converted
// separately
return (((long)seconds) + epochDifferenceLong) * TimeSpan.TicksPerSecond + // seconds
(long)(Math.Round(seconds % 1, 6) * TimeSpan.TicksPerSecond); // micro seconds
}
internal static double TicksToTimestamp(long ticks) {
return (ticks / ticksPerSecond) - epochDifferenceDouble;
}
public static string asctime(CodeContext/*!*/ context) {
return asctime(context, null);
}
public static string asctime(CodeContext/*!*/ context, object time) {
DateTime dt;
if (time is PythonTuple) {
// docs say locale information is not used by asctime, so ignore DST here
dt = GetDateTimeFromTupleNoDst(context, (PythonTuple)time);
} else if (time == null) {
dt = DateTime.Now;
} else {
throw PythonOps.TypeError("expected struct_time or None");
}
return $"{dt.ToString("ddd MMM", CultureInfo.InvariantCulture)} {dt.Day,2} {dt.ToString("HH:mm:ss yyyy", CultureInfo.InvariantCulture)}";
}
public static double clock() {
InitStopWatch();
return ((double)sw.ElapsedTicks) / Stopwatch.Frequency;
}
public static double perf_counter() => clock();
public static string ctime(CodeContext/*!*/ context) {
return asctime(context, localtime());
}
public static string ctime(CodeContext/*!*/ context, object seconds) {
if (seconds == null)
return ctime(context);
return asctime(context, localtime(seconds));
}
public static object get_clock_info(string name) {
// TODO: Fill with correct values
if (name == "monotonic")
return new SimpleNamespace(new Dictionary<string, object> { { "adjustable", false }, { "implementation", "Stopwatch.GetTimestamp" }, { "monotonic", true }, { "resolution", 0.015625 } });
throw new NotImplementedException();
}
public static void sleep(double tm) {
Thread.Sleep((int)(tm * 1000));
}
public static double monotonic()
=> (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency;
// new in Python 3.7
public static BigInteger monotonic_ns()
=> (BigInteger)Stopwatch.GetTimestamp() * 1000000000 / Stopwatch.Frequency;
public static double time() {
return TicksToTimestamp(DateTime.Now.ToUniversalTime().Ticks);
}
public static PythonTuple localtime() {
return GetDateTimeTuple(DateTime.Now, DateTime.Now.IsDaylightSavingTime());
}
public static PythonTuple localtime(object seconds) {
if (seconds == null) return localtime();
DateTime dt = TimestampToDateTime(GetTimestampFromObject(seconds));
dt = dt.AddSeconds(-timezone);
return GetDateTimeTuple(dt, dt.IsDaylightSavingTime());
}
public static PythonTuple gmtime() {
return GetDateTimeTuple(DateTime.Now.ToUniversalTime(), false);
}
public static PythonTuple gmtime(object seconds) {
if (seconds == null) return gmtime();
DateTime dt = new DateTime(TimestampToTicks(GetTimestampFromObject(seconds)), DateTimeKind.Unspecified);
return GetDateTimeTuple(dt, false);
}
public static double mktime(CodeContext/*!*/ context, PythonTuple localTime) {
return TicksToTimestamp(GetDateTimeFromTuple(context, localTime).AddSeconds(timezone).Ticks);
}
public static string strftime(CodeContext/*!*/ context, string format) {
return strftime(context, format, DateTime.Now, null);
}
public static string strftime(CodeContext/*!*/ context, string format, PythonTuple dateTime) {
return strftime(context, format, GetDateTimeFromTupleNoDst(context, dateTime), null);
}
public static object strptime(CodeContext/*!*/ context, string @string) {
return DateTime.Parse(@string, PythonLocale.GetLocaleInfo(context).Time.DateTimeFormat);
}
public static object strptime(CodeContext/*!*/ context, string @string, string format) {
var packed = _strptime(context, @string, format);
return GetDateTimeTuple(packed.Item1, packed.Item2);
}
// returns object array containing 2 elements: DateTime and DayOfWeek
internal static Tuple<DateTime, DayOfWeek?> _strptime(CodeContext/*!*/ context, string @string, string format) {
bool postProc;
FoundDateComponents foundDateComp;
List<FormatInfo> formatInfo = PythonFormatToCLIFormat(format, true, out postProc, out foundDateComp);
DateTime res;
if (postProc) {
int doyIndex = FindFormat(formatInfo, "\\%j");
int dowMIndex = FindFormat(formatInfo, "\\%W");
int dowSIndex = FindFormat(formatInfo, "\\%U");
if (doyIndex != -1 && dowMIndex == -1 && dowSIndex == -1) {
res = new DateTime(1900, 1, 1);
res = res.AddDays(int.Parse(@string));
} else if (dowMIndex != -1 && doyIndex == -1 && dowSIndex == -1) {
res = new DateTime(1900, 1, 1);
res = res.AddDays(int.Parse(@string) * 7);
} else if (dowSIndex != -1 && doyIndex == -1 && dowMIndex == -1) {
res = new DateTime(1900, 1, 1);
res = res.AddDays(int.Parse(@string) * 7);
} else {
throw PythonOps.ValueError("cannot parse %j, %W, or %U w/ other values");
}
} else {
var fIdx = -1;
string[] formatParts = new string[formatInfo.Count];
for (int i = 0; i < formatInfo.Count; i++) {
switch (formatInfo[i].Type) {
case FormatInfoType.UserText: formatParts[i] = "'" + formatInfo[i].Text + "'"; break;
case FormatInfoType.SimpleFormat: formatParts[i] = formatInfo[i].Text; break;
case FormatInfoType.CustomFormat:
if (formatInfo[i].Text == "f") {
fIdx = i;
}
// include % if we only have one specifier to mark that it's a custom
// specifier
if (formatInfo.Count == 1 && formatInfo[i].Text.Length == 1) {
formatParts[i] = "%" + formatInfo[i].Text;
} else {
formatParts[i] = formatInfo[i].Text;
}
break;
}
}
var formats =
fIdx == -1 ? new [] { string.Join("", formatParts) } : ExpandMicrosecondFormat(fIdx, formatParts);
try {
if (!DateTime.TryParseExact(@string,
formats,
PythonLocale.GetLocaleInfo(context).Time.DateTimeFormat,
DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault,
out res)) {
throw PythonOps.ValueError("time data does not match format" + Environment.NewLine +
"data=" + @string + ", fmt=" + format + ", to: " + formats[0]);
}
} catch (FormatException e) {
throw PythonOps.ValueError(e.Message + Environment.NewLine +
"data=" + @string + ", fmt=" + format + ", to: " + formats[0]);
}
}
DayOfWeek? dayOfWeek = null;
if ((foundDateComp & FoundDateComponents.DayOfWeek) != 0) {
dayOfWeek = res.DayOfWeek;
}
if ((foundDateComp & FoundDateComponents.Year) == 0) {
res = new DateTime(1900, res.Month, res.Day, res.Hour, res.Minute, res.Second, res.Millisecond, res.Kind);
}
return Tuple.Create(res, dayOfWeek);
}
private static string[] ExpandMicrosecondFormat(int fIdx, string [] formatParts) {
// for %f number of digits can be anything between 1 and 6
string[] formats = new string[6];
formats[0] = string.Join("", formatParts);
for (var i = 1; i < 6; i++) {
formatParts[fIdx] = new string('f', i+1);
formats[i] = string.Join("", formatParts);
}
return formats;
}
internal static string strftime(CodeContext/*!*/ context, string format, DateTime dt, int? microseconds) {
bool postProc;
List<FormatInfo> formatInfoList = PythonFormatToCLIFormat(format, false, out postProc, out _);
StringBuilder res = new StringBuilder();
foreach (FormatInfo formatInfo in formatInfoList) {
switch (formatInfo.Type) {
case FormatInfoType.UserText: res.Append(formatInfo.Text); break;
case FormatInfoType.SimpleFormat: res.Append(dt.ToString(formatInfo.Text, PythonLocale.GetLocaleInfo(context).Time.DateTimeFormat)); break;
case FormatInfoType.CustomFormat:
// custom format strings need to be at least 2 characters long
res.Append(dt.ToString("%" + formatInfo.Text, PythonLocale.GetLocaleInfo(context).Time.DateTimeFormat));
break;
}
}
if (postProc) {
res = res.Replace("%f", microseconds != null ? string.Format("{0:D6}", microseconds) : "");
res = res.Replace("%j", dt.DayOfYear.ToString("D03")); // day of the year (001 - 366)
// figure out first day of the year...
DateTime first = new DateTime(dt.Year, 1, 1);
int weekOneSunday = (7 - (int)first.DayOfWeek) % 7;
int dayOffset = (8 - (int)first.DayOfWeek) % 7;
// week of year (sunday first day, 0-53), all days before Sunday are 0
res = res.Replace("%U", (((dt.DayOfYear + 6 - weekOneSunday) / 7)).ToString());
// week number of year (monday first day, 0-53), all days before Monday are 0
res = res.Replace("%W", (((dt.DayOfYear + 6 - dayOffset) / 7)).ToString());
res = res.Replace("%w", ((int)dt.DayOfWeek).ToString());
}
return res.ToString();
}
internal static double DateTimeToTimestamp(DateTime dateTime) {
return TicksToTimestamp(RemoveDst(dateTime).Ticks);
}
internal static DateTime TimestampToDateTime(double timeStamp) {
return AddDst(new DateTime(TimestampToTicks(timeStamp)));
}
private static DateTime RemoveDst(DateTime dt) {
return RemoveDst(dt, false);
}
private static DateTime RemoveDst(DateTime dt, bool always) {
if (always || TimeZoneInfo.Local.IsDaylightSavingTime(dt)) {
dt = dt - (TimeZoneInfo.Local.GetUtcOffset(dt) - TimeZoneInfo.Local.BaseUtcOffset);
}
return dt;
}
private static DateTime AddDst(DateTime dt) {
if (TimeZoneInfo.Local.IsDaylightSavingTime(dt)) {
dt = dt + (TimeZoneInfo.Local.GetUtcOffset(dt) - TimeZoneInfo.Local.BaseUtcOffset);
}
return dt;
}
private static double GetTimestampFromObject(object seconds) {
if (Converter.TryConvertToInt32(seconds, out int intSeconds)) {
return intSeconds;
}
double dblVal;
if (Converter.TryConvertToDouble(seconds, out dblVal)) {
if (dblVal > long.MaxValue || dblVal < long.MinValue) throw PythonOps.ValueError("unreasonable date/time");
return dblVal;
}
throw PythonOps.TypeError("expected int, got {0}", DynamicHelpers.GetPythonType(seconds));
}
private enum FormatInfoType {
UserText,
SimpleFormat,
CustomFormat,
}
private class FormatInfo {
public FormatInfo(string text) {
Type = FormatInfoType.SimpleFormat;
Text = text;
}
public FormatInfo(FormatInfoType type, string text) {
Type = type;
Text = text;
}
public FormatInfoType Type;
public string Text;
public override string ToString() {
return string.Format("{0}:{1}", Type, Text);
}
}
// temporary solution
private static void AddTime(List<FormatInfo> newFormat) {
newFormat.Add(new FormatInfo("HH"));
newFormat.Add(new FormatInfo(FormatInfoType.UserText, ":"));
newFormat.Add(new FormatInfo("mm"));
newFormat.Add(new FormatInfo(FormatInfoType.UserText, ":"));
newFormat.Add(new FormatInfo("ss"));
}
private static void AddDate(List<FormatInfo> newFormat) {
newFormat.Add(new FormatInfo("MM"));
newFormat.Add(new FormatInfo(FormatInfoType.UserText, "/"));
newFormat.Add(new FormatInfo("dd"));
newFormat.Add(new FormatInfo(FormatInfoType.UserText, "/"));
newFormat.Add(new FormatInfo("yy"));
}
/// <summary>
/// Represents the date components that we found while parsing the date. Used for zeroing out values
/// which have different defaults from CPython. Currently we only know that we need to do this for
/// the year.
/// </summary>
[Flags]
private enum FoundDateComponents {
None,
Year = 0x01,
Date = (Year),
DayOfWeek = 0x02,
}
private static List<FormatInfo> PythonFormatToCLIFormat(string format, bool forParse, out bool postProcess, out FoundDateComponents found) {
postProcess = false;
found = FoundDateComponents.None;
List<FormatInfo> newFormat = new List<FormatInfo>();
for (int i = 0; i < format.Length; i++) {
if (format[i] == '%') {
if (i + 1 == format.Length) throw PythonOps.ValueError("badly formatted string");
switch (format[++i]) {
case 'a':
found |= FoundDateComponents.DayOfWeek;
newFormat.Add(new FormatInfo("ddd")); break;
case 'A':
found |= FoundDateComponents.DayOfWeek;
newFormat.Add(new FormatInfo("dddd")); break;
case 'b':
newFormat.Add(new FormatInfo("MMM"));
break;
case 'B':
newFormat.Add(new FormatInfo("MMMM"));
break;
case 'c':
found |= FoundDateComponents.Date;
AddDate(newFormat);
newFormat.Add(new FormatInfo(FormatInfoType.UserText, " "));
AddTime(newFormat);
break;
case 'd':
// if we're parsing we want to use the less-strict
// d format and which doesn't require both digits.
if (forParse) newFormat.Add(new FormatInfo(FormatInfoType.CustomFormat, "d"));
else newFormat.Add(new FormatInfo("dd"));
break;
case 'H': newFormat.Add(new FormatInfo(forParse ? "H" : "HH")); break;
case 'I': newFormat.Add(new FormatInfo(forParse ? "h" : "hh")); break;
case 'm':
newFormat.Add(new FormatInfo(forParse ? "M" : "MM"));
break;
case 'M': newFormat.Add(new FormatInfo(forParse ? "m" : "mm")); break;
case 'p':
newFormat.Add(new FormatInfo(FormatInfoType.CustomFormat, "t"));
newFormat.Add(new FormatInfo(FormatInfoType.UserText, "M"));
break;
case 'S': newFormat.Add(new FormatInfo("ss")); break;
case 'x':
found |= FoundDateComponents.Date;
AddDate(newFormat); break;
case 'X':
AddTime(newFormat);
break;
case 'y':
found |= FoundDateComponents.Year;
newFormat.Add(new FormatInfo("yy"));
break;
case 'Y':
found |= FoundDateComponents.Year;
newFormat.Add(new FormatInfo("yyyy"));
break;
case '%': newFormat.Add(new FormatInfo("\\%")); break;
// format conversions not defined by the CLR. We leave
// them as \\% and then replace them by hand later
case 'j': // day of year
newFormat.Add(new FormatInfo("\\%j"));
postProcess = true;
break;
case 'f':
if (forParse) {
newFormat.Add(new FormatInfo(FormatInfoType.CustomFormat, "f"));
} else {
postProcess = true;
newFormat.Add(new FormatInfo(FormatInfoType.UserText, "%f"));
}
break;
case 'W': newFormat.Add(new FormatInfo("\\%W")); postProcess = true; break;
case 'U': newFormat.Add(new FormatInfo("\\%U")); postProcess = true; break; // week number
case 'w': newFormat.Add(new FormatInfo("\\%w")); postProcess = true; break; // weekday number
case 'z':
case 'Z':
// !!!TODO:
// 'z' for offset
// 'Z' for time zone name; could be from PythonTimeZoneInformation
newFormat.Add(new FormatInfo(FormatInfoType.UserText, ""));
break;
default:
newFormat.Add(new FormatInfo(FormatInfoType.UserText, "")); break;
}
} else {
if (newFormat.Count == 0 || newFormat[newFormat.Count - 1].Type != FormatInfoType.UserText)
newFormat.Add(new FormatInfo(FormatInfoType.UserText, format[i].ToString()));
else
newFormat[newFormat.Count - 1].Text = newFormat[newFormat.Count - 1].Text + format[i];
}
}
return newFormat;
}
// weekday: Monday is 0, Sunday is 6
internal static int Weekday(DateTime dt) {
return Weekday(dt.DayOfWeek);
}
internal static int Weekday(DayOfWeek dayOfWeek) {
if (dayOfWeek == DayOfWeek.Sunday) return 6;
else return (int)dayOfWeek - 1;
}
// isoweekday: Monday is 1, Sunday is 7
internal static int IsoWeekday(DateTime dt) {
if (dt.DayOfWeek == DayOfWeek.Sunday) return 7;
else return (int)dt.DayOfWeek;
}
internal static PythonTuple GetDateTimeTuple(DateTime dt) {
return GetDateTimeTuple(dt, null);
}
internal static PythonTuple GetDateTimeTuple(DateTime dt, DayOfWeek? dayOfWeek) {
return GetDateTimeTuple(dt, dayOfWeek, null);
}
internal static PythonTuple GetDateTimeTuple(DateTime dt, DayOfWeek? dayOfWeek, PythonDateTime.tzinfo tz) {
int last = -1;
if (tz != null) {
PythonDateTime.timedelta delta = tz.dst(dt);
PythonDateTime.ThrowIfInvalid(delta, "dst");
if (delta == null) {
last = -1;
} else {
last = delta.__bool__() ? 1 : 0;
}
}
return new struct_time(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, Weekday(dayOfWeek ?? dt.DayOfWeek), dt.DayOfYear, last);
}
internal static struct_time GetDateTimeTuple(DateTime dt, bool dstMode) {
return new struct_time(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, Weekday(dt), dt.DayOfYear, dstMode ? 1 : 0);
}
private static DateTime GetDateTimeFromTuple(CodeContext/*!*/ context, PythonTuple t) {
int[] ints;
DateTime res = GetDateTimeFromTupleNoDst(context, t, out ints);
if (ints != null) {
switch (ints[IsDaylightSavingsIndex]) {
// automatic detection
case -1: res = RemoveDst(res); break;
// is daylight savings time, force adjustment
case 1: res = RemoveDst(res, true); break;
}
}
return res;
}
private static DateTime GetDateTimeFromTupleNoDst(CodeContext context, PythonTuple t) {
return GetDateTimeFromTupleNoDst(context, t, out _);
}
private static DateTime GetDateTimeFromTupleNoDst(CodeContext context, PythonTuple t, out int[] ints) {
if (t == null) {
ints = null;
return DateTime.Now;
}
ints = ValidateDateTimeTuple(context, t);
var month = ints[MonthIndex];
if (month == 0) month = 1;
var day = ints[DayIndex];
if (day == 0) day = 1;
return new DateTime(ints[YearIndex], month, day, ints[HourIndex], ints[MinuteIndex], ints[SecondIndex]);
}
private static int[] ValidateDateTimeTuple(CodeContext/*!*/ context, PythonTuple t) {
if (t.__len__() != MaxIndex) throw PythonOps.TypeError("expected tuple of length {0}", MaxIndex);
int[] ints = new int[MaxIndex];
for (int i = 0; i < MaxIndex; i++) {
ints[i] = context.LanguageContext.ConvertToInt32(t[i]);
}
int year = ints[YearIndex];
if (year >= 0 && year <= 99) {
if (year > 68) {
year += 1900;
} else {
year += 2000;
}
}
if (year < DateTime.MinValue.Year || year <= minYear) throw PythonOps.ValueError("year is too low");
if (year > DateTime.MaxValue.Year) throw PythonOps.ValueError("year is too high");
if (ints[WeekdayIndex] < 0 || ints[WeekdayIndex] >= 7) throw PythonOps.ValueError("day of week is outside of 0-6 range");
return ints;
}
private static int FindFormat(List<FormatInfo> formatInfo, string format) {
for (int i = 0; i < formatInfo.Count; i++) {
if (formatInfo[i].Text == format) return i;
}
return -1;
}
private static void InitStopWatch() {
if (sw == null) {
sw = new Stopwatch();
sw.Start();
}
}
[PythonType]
public class struct_time : PythonTuple {
private static readonly PythonType _StructTimeType = DynamicHelpers.GetPythonTypeFromType(typeof(struct_time));
public object tm_year => _data[0];
public object tm_mon => _data[1];
public object tm_mday => _data[2];
public object tm_hour => _data[3];
public object tm_min => _data[4];
public object tm_sec => _data[5];
public object tm_wday => _data[6];
public object tm_yday => _data[7];
public object tm_isdst => _data[8];
public int n_fields => _data.Length;
public int n_sequence_fields => _data.Length;
public int n_unnamed_fields => 0;
internal struct_time(int year, int month, int day, int hour, int minute, int second, int dayOfWeek, int dayOfYear, int isDst)
: base(new object[] { year, month, day, hour, minute, second, dayOfWeek, dayOfYear, isDst }) {
}
internal struct_time(PythonTuple sequence)
: base(sequence) {
}
public static struct_time __new__(CodeContext context, PythonType cls, int year, int month, int day, int hour, int minute, int second, int dayOfWeek, int dayOfYear, int isDst) {
if (cls == _StructTimeType) {
return new struct_time(year, month, day, hour, minute, second, dayOfWeek, dayOfYear, isDst);
}
if (cls.CreateInstance(context, year, month, day, hour, minute, second, dayOfWeek, dayOfYear, isDst) is struct_time st) {
return st;
}
throw PythonOps.TypeError("{0} is not a subclass of time.struct_time", cls);
}
public static struct_time __new__(CodeContext context, PythonType cls, [NotNull]PythonTuple sequence) {
if (sequence.__len__() != 9) {
throw PythonOps.TypeError("time.struct_time() takes a 9-sequence ({0}-sequence given)", sequence.__len__());
}
if (cls == _StructTimeType) {
return new struct_time(sequence);
}
if (cls.CreateInstance(context, sequence) is struct_time st) {
return st;
}
throw PythonOps.TypeError("{0} is not a subclass of time.struct_time", cls);
}
public static struct_time __new__(CodeContext context, PythonType cls, [NotNull]IEnumerable sequence) {
return __new__(context, cls, PythonTuple.Make(sequence));
}
public PythonTuple __reduce__() {
return PythonTuple.MakeTuple(_StructTimeType, PythonTuple.MakeTuple(tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst));
}
public static object __getnewargs__(CodeContext context, int year, int month, int day, int hour, int minute, int second, int dayOfWeek, int dayOfYear, int isDst) {
return PythonTuple.MakeTuple(struct_time.__new__(context, _StructTimeType, year, month, day, hour, minute, second, dayOfWeek, dayOfYear, isDst));
}
public override string ToString() {
return string.Format(
"time.struct_time(tm_year={0}, tm_mon={1}, tm_mday={2}, tm_hour={3}, tm_min={4}, tm_sec={5}, tm_wday={6}, tm_yday={7}, tm_isdst={8})",
//this.tm_year, this.tm_mon, this.tm_mday, this.tm_hour, this.tm_min, this.tm_sec, this.tm_wday, this.tm_yday, this.tm_isdst
_data);
}
public override string __repr__(CodeContext context) {
return this.ToString();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.IO
{
partial class FileSystemInfo : IFileSystemObject
{
/// <summary>The last cached stat information about the file.</summary>
private Interop.Sys.FileStatus _fileStatus;
/// <summary>true if <see cref="_fileStatus"/> represents a symlink and the target of that symlink is a directory.</summary>
private bool _targetOfSymlinkIsDirectory;
/// <summary>
/// Whether we've successfully cached a stat structure.
/// -1 if we need to refresh _fileStatus, 0 if we've successfully cached one,
/// or any other value that serves as an errno error code from the
/// last time we tried and failed to refresh _fileStatus.
/// </summary>
private int _fileStatusInitialized = -1;
internal IFileSystemObject FileSystemObject
{
get { return this; }
}
internal void Invalidate()
{
_fileStatusInitialized = -1;
}
FileAttributes IFileSystemObject.Attributes
{
get
{
EnsureStatInitialized();
FileAttributes attrs = default(FileAttributes);
if (IsDirectoryAssumesInitialized) // this is the one attribute where we follow symlinks
{
attrs |= FileAttributes.Directory;
}
if (IsReadOnlyAssumesInitialized)
{
attrs |= FileAttributes.ReadOnly;
}
if (IsSymlinkAssumesInitialized)
{
attrs |= FileAttributes.ReparsePoint;
}
// If the filename starts with a period, it's hidden. Or if this is a directory ending in a slash,
// if the directory name starts with a period, it's hidden.
string fileName = Path.GetFileName(FullPath);
if (string.IsNullOrEmpty(fileName))
{
fileName = Path.GetFileName(Path.GetDirectoryName(FullPath));
}
if (!string.IsNullOrEmpty(fileName) && fileName[0] == '.')
{
attrs |= FileAttributes.Hidden;
}
return attrs != default(FileAttributes) ?
attrs :
FileAttributes.Normal;
}
set
{
// Validate that only flags from the attribute are being provided. This is an
// approximation for the validation done by the Win32 function.
const FileAttributes allValidFlags =
FileAttributes.Archive | FileAttributes.Compressed | FileAttributes.Device |
FileAttributes.Directory | FileAttributes.Encrypted | FileAttributes.Hidden |
FileAttributes.Hidden | FileAttributes.IntegrityStream | FileAttributes.Normal |
FileAttributes.NoScrubData | FileAttributes.NotContentIndexed | FileAttributes.Offline |
FileAttributes.ReadOnly | FileAttributes.ReparsePoint | FileAttributes.SparseFile |
FileAttributes.System | FileAttributes.Temporary;
if ((value & ~allValidFlags) != 0)
{
throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(value));
}
// The only thing we can reasonably change is whether the file object is readonly,
// just changing its permissions accordingly.
EnsureStatInitialized();
IsReadOnlyAssumesInitialized = (value & FileAttributes.ReadOnly) != 0;
_fileStatusInitialized = -1;
}
}
/// <summary>Gets whether stat reported this system object as a directory.</summary>
private bool IsDirectoryAssumesInitialized =>
(_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR ||
(IsSymlinkAssumesInitialized && _targetOfSymlinkIsDirectory);
/// <summary>Gets whether stat reported this system object as a symlink.</summary>
private bool IsSymlinkAssumesInitialized =>
(_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFLNK;
/// <summary>
/// Gets or sets whether the file is read-only. This is based on the read/write/execute
/// permissions of the object.
/// </summary>
private bool IsReadOnlyAssumesInitialized
{
get
{
Interop.Sys.Permissions readBit, writeBit;
if (_fileStatus.Uid == Interop.Sys.GetEUid()) // does the user effectively own the file?
{
readBit = Interop.Sys.Permissions.S_IRUSR;
writeBit = Interop.Sys.Permissions.S_IWUSR;
}
else if (_fileStatus.Gid == Interop.Sys.GetEGid()) // does the user belong to a group that effectively owns the file?
{
readBit = Interop.Sys.Permissions.S_IRGRP;
writeBit = Interop.Sys.Permissions.S_IWGRP;
}
else // everyone else
{
readBit = Interop.Sys.Permissions.S_IROTH;
writeBit = Interop.Sys.Permissions.S_IWOTH;
}
return
(_fileStatus.Mode & (int)readBit) != 0 && // has read permission
(_fileStatus.Mode & (int)writeBit) == 0; // but not write permission
}
set
{
int newMode = _fileStatus.Mode;
if (value) // true if going from writable to readable, false if going from readable to writable
{
// Take away all write permissions from user/group/everyone
newMode &= ~(int)(Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IWOTH);
}
else if ((newMode & (int)Interop.Sys.Permissions.S_IRUSR) != 0)
{
// Give write permission to the owner if the owner has read permission
newMode |= (int)Interop.Sys.Permissions.S_IWUSR;
}
// Change the permissions on the file
if (newMode != _fileStatus.Mode)
{
bool isDirectory = this is DirectoryInfo;
Interop.CheckIo(Interop.Sys.ChMod(FullPath, newMode), FullPath, isDirectory);
}
}
}
bool IFileSystemObject.Exists
{
get
{
if (_fileStatusInitialized == -1)
{
Refresh();
}
return
_fileStatusInitialized == 0 && // avoid throwing if Refresh failed; instead just return false
(this is DirectoryInfo) == IsDirectoryAssumesInitialized;
}
}
DateTimeOffset IFileSystemObject.CreationTime
{
get
{
EnsureStatInitialized();
long rawTime = (_fileStatus.Flags & Interop.Sys.FileStatusFlags.HasBirthTime) != 0 ?
_fileStatus.BirthTime :
Math.Min(_fileStatus.CTime, _fileStatus.MTime); // fall back to the oldest time we have in between change and modify time
return DateTimeOffset.FromUnixTimeSeconds(rawTime).ToLocalTime();
}
set
{
// There isn't a reliable way to set this; however, we can't just do nothing since the
// FileSystemWatcher specifically looks for this call to make a Metatdata Change, so we
// should set the LastAccessTime of the file to cause the metadata change we need.
LastAccessTime = LastAccessTime;
}
}
DateTimeOffset IFileSystemObject.LastAccessTime
{
get
{
EnsureStatInitialized();
return DateTimeOffset.FromUnixTimeSeconds(_fileStatus.ATime).ToLocalTime();
}
set { SetAccessWriteTimes(value.ToUnixTimeSeconds(), null); }
}
DateTimeOffset IFileSystemObject.LastWriteTime
{
get
{
EnsureStatInitialized();
return DateTimeOffset.FromUnixTimeSeconds(_fileStatus.MTime).ToLocalTime();
}
set { SetAccessWriteTimes(null, value.ToUnixTimeSeconds()); }
}
private void SetAccessWriteTimes(long? accessTime, long? writeTime)
{
_fileStatusInitialized = -1; // force a refresh so that we have an up-to-date times for values not being overwritten
EnsureStatInitialized();
Interop.Sys.UTimBuf buf;
buf.AcTime = accessTime ?? _fileStatus.ATime;
buf.ModTime = writeTime ?? _fileStatus.MTime;
bool isDirectory = this is DirectoryInfo;
Interop.CheckIo(Interop.Sys.UTime(FullPath, ref buf), FullPath, isDirectory);
_fileStatusInitialized = -1;
}
long IFileSystemObject.Length
{
get
{
EnsureStatInitialized();
return _fileStatus.Size;
}
}
void IFileSystemObject.Refresh()
{
// This should not throw, instead we store the result so that we can throw it
// when someone actually accesses a property.
// Use lstat to get the details on the object, without following symlinks.
// If it is a symlink, then subsequently get details on the target of the symlink,
// storing those results separately. We only report failure if the initial
// lstat fails, as a broken symlink should still report info on exists, attributes, etc.
_targetOfSymlinkIsDirectory = false;
int result = Interop.Sys.LStat(FullPath, out _fileStatus);
if (result < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
_fileStatusInitialized = errorInfo.RawErrno;
return;
}
Interop.Sys.FileStatus targetStatus;
if ((_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFLNK &&
Interop.Sys.Stat(FullPath, out targetStatus) >= 0)
{
_targetOfSymlinkIsDirectory = (targetStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR;
}
_fileStatusInitialized = 0;
}
private void EnsureStatInitialized()
{
if (_fileStatusInitialized == -1)
{
Refresh();
}
if (_fileStatusInitialized != 0)
{
int errno = _fileStatusInitialized;
_fileStatusInitialized = -1;
var errorInfo = new Interop.ErrorInfo(errno);
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
// directoryError is true only if a FileNotExists error was provided and the parent
// directory of the file represented by _fullPath is nonexistent
bool directoryError = (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(PathHelpers.TrimEndingDirectorySeparator(FullPath)))); // The destFile's path is invalid
throw Interop.GetExceptionForIoErrno(errorInfo, FullPath, directoryError);
}
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using Orleans.Runtime.Configuration;
using Orleans.Messaging;
namespace Orleans.Runtime.Messaging
{
internal class MessageCenter : ISiloMessageCenter, IDisposable
{
private Gateway Gateway { get; set; }
private IncomingMessageAcceptor ima;
private static readonly TraceLogger log = TraceLogger.GetLogger("Orleans.Messaging.MessageCenter");
private Action<Message> rerouteHandler;
private Action<List<GrainId>> clientDropHandler;
// ReSharper disable UnaccessedField.Local
private IntValueStatistic sendQueueLengthCounter;
private IntValueStatistic receiveQueueLengthCounter;
// ReSharper restore UnaccessedField.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(IPEndPoint here, int generation, IMessagingConfiguration config, ISiloPerformanceMetrics metrics = null)
{
Initialize(here, generation, config, metrics);
}
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 RecordProxiedGrain(GrainId grainId, Guid clientId)
{
if (Gateway != null)
Gateway.RecordProxiedGrain(grainId, clientId);
}
public void RecordUnproxiedGrain(GrainId grainId)
{
if (Gateway != null)
Gateway.RecordUnproxiedGrain(grainId);
}
public void Start()
{
IsBlockingApplicationMessages = false;
ima.Start();
OutboundQueue.Start();
}
public void StartGateway()
{
if (Gateway != null)
Gateway.Start();
}
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)
&& (msg.TargetGrain != Constants.SystemMembershipTableId))
{
// 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);
}
}
public Action<List<GrainId>> ClientDropHandler
{
set
{
if (clientDropHandler != null)
throw new InvalidOperationException("MessageCenter ClientDropHandler already set");
clientDropHandler = value;
}
}
internal void RecordClientDrop(List<GrainId> client)
{
if (clientDropHandler != null && client != null)
clientDropHandler(client);
}
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;
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace Dynastream.Fit
{
// Define our necessary event types (EventArgs and the delegate)
public delegate void MesgEventHandler(object sender, MesgEventArgs e);
public delegate void MesgDefinitionEventHandler(object sender, MesgDefinitionEventArgs e);
public class MesgEventArgs : EventArgs
{
public Mesg mesg = null;
public MesgEventArgs()
{
}
public MesgEventArgs(Mesg newMesg)
{
mesg = new Mesg(newMesg);
}
}
public class MesgDefinitionEventArgs : EventArgs
{
public MesgDefinition mesgDef = null;
public MesgDefinitionEventArgs()
{
}
public MesgDefinitionEventArgs(MesgDefinition newDefn)
{
mesgDef = new MesgDefinition(newDefn);
}
}
/// <summary>
/// The MesgBroadcaster manages Mesg and MesgDefinition events. Its
/// handlers should be connected to the source of Mesg and MesgDef events
/// (such as a file decoder).
/// Clients may subscribe to the Broadcasters events (Mesg, Mesg Def
/// or specofic Profile Mesg)
/// </summary>
public class MesgBroadcaster
{
#region Methods & Events
public event MesgDefinitionEventHandler MesgDefinitionEvent;
public event MesgEventHandler MesgEvent;
// One event for every Profile Mesg
public event MesgEventHandler FileIdMesgEvent;
public event MesgEventHandler FileCreatorMesgEvent;
public event MesgEventHandler TimestampCorrelationMesgEvent;
public event MesgEventHandler SoftwareMesgEvent;
public event MesgEventHandler SlaveDeviceMesgEvent;
public event MesgEventHandler CapabilitiesMesgEvent;
public event MesgEventHandler FileCapabilitiesMesgEvent;
public event MesgEventHandler MesgCapabilitiesMesgEvent;
public event MesgEventHandler FieldCapabilitiesMesgEvent;
public event MesgEventHandler DeviceSettingsMesgEvent;
public event MesgEventHandler UserProfileMesgEvent;
public event MesgEventHandler HrmProfileMesgEvent;
public event MesgEventHandler SdmProfileMesgEvent;
public event MesgEventHandler BikeProfileMesgEvent;
public event MesgEventHandler ZonesTargetMesgEvent;
public event MesgEventHandler SportMesgEvent;
public event MesgEventHandler HrZoneMesgEvent;
public event MesgEventHandler SpeedZoneMesgEvent;
public event MesgEventHandler CadenceZoneMesgEvent;
public event MesgEventHandler PowerZoneMesgEvent;
public event MesgEventHandler MetZoneMesgEvent;
public event MesgEventHandler GoalMesgEvent;
public event MesgEventHandler ActivityMesgEvent;
public event MesgEventHandler SessionMesgEvent;
public event MesgEventHandler LapMesgEvent;
public event MesgEventHandler LengthMesgEvent;
public event MesgEventHandler RecordMesgEvent;
public event MesgEventHandler EventMesgEvent;
public event MesgEventHandler DeviceInfoMesgEvent;
public event MesgEventHandler TrainingFileMesgEvent;
public event MesgEventHandler HrvMesgEvent;
public event MesgEventHandler CameraEventMesgEvent;
public event MesgEventHandler GyroscopeDataMesgEvent;
public event MesgEventHandler AccelerometerDataMesgEvent;
public event MesgEventHandler ThreeDSensorCalibrationMesgEvent;
public event MesgEventHandler VideoFrameMesgEvent;
public event MesgEventHandler ObdiiDataMesgEvent;
public event MesgEventHandler NmeaSentenceMesgEvent;
public event MesgEventHandler AviationAttitudeMesgEvent;
public event MesgEventHandler VideoMesgEvent;
public event MesgEventHandler VideoTitleMesgEvent;
public event MesgEventHandler VideoDescriptionMesgEvent;
public event MesgEventHandler VideoClipMesgEvent;
public event MesgEventHandler CourseMesgEvent;
public event MesgEventHandler CoursePointMesgEvent;
public event MesgEventHandler SegmentIdMesgEvent;
public event MesgEventHandler SegmentLeaderboardEntryMesgEvent;
public event MesgEventHandler SegmentPointMesgEvent;
public event MesgEventHandler SegmentLapMesgEvent;
public event MesgEventHandler SegmentFileMesgEvent;
public event MesgEventHandler WorkoutMesgEvent;
public event MesgEventHandler WorkoutStepMesgEvent;
public event MesgEventHandler ScheduleMesgEvent;
public event MesgEventHandler TotalsMesgEvent;
public event MesgEventHandler WeightScaleMesgEvent;
public event MesgEventHandler BloodPressureMesgEvent;
public event MesgEventHandler MonitoringInfoMesgEvent;
public event MesgEventHandler MonitoringMesgEvent;
public event MesgEventHandler MemoGlobMesgEvent;
public event MesgEventHandler PadMesgEvent;
public void OnMesg(object sender, MesgEventArgs e)
{
// Notify any subscribers of either our general mesg event or specific profile mesg event
if (MesgEvent != null)
{
MesgEvent(sender, e);
}
switch (e.mesg.Num)
{
case (ushort)MesgNum.FileId:
if (FileIdMesgEvent != null)
{
FileIdMesg fileIdMesg = new FileIdMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = fileIdMesg;
FileIdMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.FileCreator:
if (FileCreatorMesgEvent != null)
{
FileCreatorMesg fileCreatorMesg = new FileCreatorMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = fileCreatorMesg;
FileCreatorMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.TimestampCorrelation:
if (TimestampCorrelationMesgEvent != null)
{
TimestampCorrelationMesg timestampCorrelationMesg = new TimestampCorrelationMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = timestampCorrelationMesg;
TimestampCorrelationMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Software:
if (SoftwareMesgEvent != null)
{
SoftwareMesg softwareMesg = new SoftwareMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = softwareMesg;
SoftwareMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.SlaveDevice:
if (SlaveDeviceMesgEvent != null)
{
SlaveDeviceMesg slaveDeviceMesg = new SlaveDeviceMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = slaveDeviceMesg;
SlaveDeviceMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Capabilities:
if (CapabilitiesMesgEvent != null)
{
CapabilitiesMesg capabilitiesMesg = new CapabilitiesMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = capabilitiesMesg;
CapabilitiesMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.FileCapabilities:
if (FileCapabilitiesMesgEvent != null)
{
FileCapabilitiesMesg fileCapabilitiesMesg = new FileCapabilitiesMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = fileCapabilitiesMesg;
FileCapabilitiesMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.MesgCapabilities:
if (MesgCapabilitiesMesgEvent != null)
{
MesgCapabilitiesMesg mesgCapabilitiesMesg = new MesgCapabilitiesMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = mesgCapabilitiesMesg;
MesgCapabilitiesMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.FieldCapabilities:
if (FieldCapabilitiesMesgEvent != null)
{
FieldCapabilitiesMesg fieldCapabilitiesMesg = new FieldCapabilitiesMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = fieldCapabilitiesMesg;
FieldCapabilitiesMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.DeviceSettings:
if (DeviceSettingsMesgEvent != null)
{
DeviceSettingsMesg deviceSettingsMesg = new DeviceSettingsMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = deviceSettingsMesg;
DeviceSettingsMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.UserProfile:
if (UserProfileMesgEvent != null)
{
UserProfileMesg userProfileMesg = new UserProfileMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = userProfileMesg;
UserProfileMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.HrmProfile:
if (HrmProfileMesgEvent != null)
{
HrmProfileMesg hrmProfileMesg = new HrmProfileMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = hrmProfileMesg;
HrmProfileMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.SdmProfile:
if (SdmProfileMesgEvent != null)
{
SdmProfileMesg sdmProfileMesg = new SdmProfileMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = sdmProfileMesg;
SdmProfileMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.BikeProfile:
if (BikeProfileMesgEvent != null)
{
BikeProfileMesg bikeProfileMesg = new BikeProfileMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = bikeProfileMesg;
BikeProfileMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.ZonesTarget:
if (ZonesTargetMesgEvent != null)
{
ZonesTargetMesg zonesTargetMesg = new ZonesTargetMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = zonesTargetMesg;
ZonesTargetMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Sport:
if (SportMesgEvent != null)
{
SportMesg sportMesg = new SportMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = sportMesg;
SportMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.HrZone:
if (HrZoneMesgEvent != null)
{
HrZoneMesg hrZoneMesg = new HrZoneMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = hrZoneMesg;
HrZoneMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.SpeedZone:
if (SpeedZoneMesgEvent != null)
{
SpeedZoneMesg speedZoneMesg = new SpeedZoneMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = speedZoneMesg;
SpeedZoneMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.CadenceZone:
if (CadenceZoneMesgEvent != null)
{
CadenceZoneMesg cadenceZoneMesg = new CadenceZoneMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = cadenceZoneMesg;
CadenceZoneMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.PowerZone:
if (PowerZoneMesgEvent != null)
{
PowerZoneMesg powerZoneMesg = new PowerZoneMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = powerZoneMesg;
PowerZoneMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.MetZone:
if (MetZoneMesgEvent != null)
{
MetZoneMesg metZoneMesg = new MetZoneMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = metZoneMesg;
MetZoneMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Goal:
if (GoalMesgEvent != null)
{
GoalMesg goalMesg = new GoalMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = goalMesg;
GoalMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Activity:
if (ActivityMesgEvent != null)
{
ActivityMesg activityMesg = new ActivityMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = activityMesg;
ActivityMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Session:
if (SessionMesgEvent != null)
{
SessionMesg sessionMesg = new SessionMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = sessionMesg;
SessionMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Lap:
if (LapMesgEvent != null)
{
LapMesg lapMesg = new LapMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = lapMesg;
LapMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Length:
if (LengthMesgEvent != null)
{
LengthMesg lengthMesg = new LengthMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = lengthMesg;
LengthMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Record:
if (RecordMesgEvent != null)
{
RecordMesg recordMesg = new RecordMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = recordMesg;
RecordMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Event:
if (EventMesgEvent != null)
{
EventMesg eventMesg = new EventMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = eventMesg;
EventMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.DeviceInfo:
if (DeviceInfoMesgEvent != null)
{
DeviceInfoMesg deviceInfoMesg = new DeviceInfoMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = deviceInfoMesg;
DeviceInfoMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.TrainingFile:
if (TrainingFileMesgEvent != null)
{
TrainingFileMesg trainingFileMesg = new TrainingFileMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = trainingFileMesg;
TrainingFileMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Hrv:
if (HrvMesgEvent != null)
{
HrvMesg hrvMesg = new HrvMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = hrvMesg;
HrvMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.CameraEvent:
if (CameraEventMesgEvent != null)
{
CameraEventMesg cameraEventMesg = new CameraEventMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = cameraEventMesg;
CameraEventMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.GyroscopeData:
if (GyroscopeDataMesgEvent != null)
{
GyroscopeDataMesg gyroscopeDataMesg = new GyroscopeDataMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = gyroscopeDataMesg;
GyroscopeDataMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.AccelerometerData:
if (AccelerometerDataMesgEvent != null)
{
AccelerometerDataMesg accelerometerDataMesg = new AccelerometerDataMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = accelerometerDataMesg;
AccelerometerDataMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.ThreeDSensorCalibration:
if (ThreeDSensorCalibrationMesgEvent != null)
{
ThreeDSensorCalibrationMesg threeDSensorCalibrationMesg = new ThreeDSensorCalibrationMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = threeDSensorCalibrationMesg;
ThreeDSensorCalibrationMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.VideoFrame:
if (VideoFrameMesgEvent != null)
{
VideoFrameMesg videoFrameMesg = new VideoFrameMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = videoFrameMesg;
VideoFrameMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.ObdiiData:
if (ObdiiDataMesgEvent != null)
{
ObdiiDataMesg obdiiDataMesg = new ObdiiDataMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = obdiiDataMesg;
ObdiiDataMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.NmeaSentence:
if (NmeaSentenceMesgEvent != null)
{
NmeaSentenceMesg nmeaSentenceMesg = new NmeaSentenceMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = nmeaSentenceMesg;
NmeaSentenceMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.AviationAttitude:
if (AviationAttitudeMesgEvent != null)
{
AviationAttitudeMesg aviationAttitudeMesg = new AviationAttitudeMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = aviationAttitudeMesg;
AviationAttitudeMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Video:
if (VideoMesgEvent != null)
{
VideoMesg videoMesg = new VideoMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = videoMesg;
VideoMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.VideoTitle:
if (VideoTitleMesgEvent != null)
{
VideoTitleMesg videoTitleMesg = new VideoTitleMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = videoTitleMesg;
VideoTitleMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.VideoDescription:
if (VideoDescriptionMesgEvent != null)
{
VideoDescriptionMesg videoDescriptionMesg = new VideoDescriptionMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = videoDescriptionMesg;
VideoDescriptionMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.VideoClip:
if (VideoClipMesgEvent != null)
{
VideoClipMesg videoClipMesg = new VideoClipMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = videoClipMesg;
VideoClipMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Course:
if (CourseMesgEvent != null)
{
CourseMesg courseMesg = new CourseMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = courseMesg;
CourseMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.CoursePoint:
if (CoursePointMesgEvent != null)
{
CoursePointMesg coursePointMesg = new CoursePointMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = coursePointMesg;
CoursePointMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.SegmentId:
if (SegmentIdMesgEvent != null)
{
SegmentIdMesg segmentIdMesg = new SegmentIdMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = segmentIdMesg;
SegmentIdMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.SegmentLeaderboardEntry:
if (SegmentLeaderboardEntryMesgEvent != null)
{
SegmentLeaderboardEntryMesg segmentLeaderboardEntryMesg = new SegmentLeaderboardEntryMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = segmentLeaderboardEntryMesg;
SegmentLeaderboardEntryMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.SegmentPoint:
if (SegmentPointMesgEvent != null)
{
SegmentPointMesg segmentPointMesg = new SegmentPointMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = segmentPointMesg;
SegmentPointMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.SegmentLap:
if (SegmentLapMesgEvent != null)
{
SegmentLapMesg segmentLapMesg = new SegmentLapMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = segmentLapMesg;
SegmentLapMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.SegmentFile:
if (SegmentFileMesgEvent != null)
{
SegmentFileMesg segmentFileMesg = new SegmentFileMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = segmentFileMesg;
SegmentFileMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Workout:
if (WorkoutMesgEvent != null)
{
WorkoutMesg workoutMesg = new WorkoutMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = workoutMesg;
WorkoutMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.WorkoutStep:
if (WorkoutStepMesgEvent != null)
{
WorkoutStepMesg workoutStepMesg = new WorkoutStepMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = workoutStepMesg;
WorkoutStepMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Schedule:
if (ScheduleMesgEvent != null)
{
ScheduleMesg scheduleMesg = new ScheduleMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = scheduleMesg;
ScheduleMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Totals:
if (TotalsMesgEvent != null)
{
TotalsMesg totalsMesg = new TotalsMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = totalsMesg;
TotalsMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.WeightScale:
if (WeightScaleMesgEvent != null)
{
WeightScaleMesg weightScaleMesg = new WeightScaleMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = weightScaleMesg;
WeightScaleMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.BloodPressure:
if (BloodPressureMesgEvent != null)
{
BloodPressureMesg bloodPressureMesg = new BloodPressureMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = bloodPressureMesg;
BloodPressureMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.MonitoringInfo:
if (MonitoringInfoMesgEvent != null)
{
MonitoringInfoMesg monitoringInfoMesg = new MonitoringInfoMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = monitoringInfoMesg;
MonitoringInfoMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Monitoring:
if (MonitoringMesgEvent != null)
{
MonitoringMesg monitoringMesg = new MonitoringMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = monitoringMesg;
MonitoringMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.MemoGlob:
if (MemoGlobMesgEvent != null)
{
MemoGlobMesg memoGlobMesg = new MemoGlobMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = memoGlobMesg;
MemoGlobMesgEvent(sender, mesgEventArgs);
}
break;
case (ushort)MesgNum.Pad:
if (PadMesgEvent != null)
{
PadMesg padMesg = new PadMesg(e.mesg);
MesgEventArgs mesgEventArgs = new MesgEventArgs();
mesgEventArgs.mesg = padMesg;
PadMesgEvent(sender, mesgEventArgs);
}
break;
}
}
public void OnMesgDefinition(object sender, MesgDefinitionEventArgs e)
{
// Notify any subscribers
if (MesgDefinitionEvent != null)
{
MesgDefinitionEvent(sender, e);
}
}
#endregion // Methods
} // Class
} // namespace
| |
// 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.Xml;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.Text;
using System.Xml.Linq;
using OLEDB.Test.ModuleCore;
namespace System.Xml.XmlDiff
{
public enum NodePosition
{
Before = 0,
After = 1,
Unknown = 2,
Same = 3
}
public enum XmlDiffNodeType
{
Element = 0,
Attribute = 1,
ER = 2,
Text = 3,
CData = 4,
Comment = 5,
PI = 6,
WS = 7,
Document = 8
}
internal class PositionInfo : IXmlLineInfo
{
public virtual bool HasLineInfo() { return false; }
public virtual int LineNumber { get { return 0; } }
public virtual int LinePosition { get { return 0; } }
public static PositionInfo GetPositionInfo(Object o)
{
IXmlLineInfo lineInfo = o as IXmlLineInfo;
if (lineInfo != null && lineInfo.HasLineInfo())
{
return new ReaderPositionInfo(lineInfo);
}
else
{
return new PositionInfo();
}
}
}
internal class ReaderPositionInfo : PositionInfo
{
private IXmlLineInfo _mlineInfo;
public ReaderPositionInfo(IXmlLineInfo lineInfo)
{
_mlineInfo = lineInfo;
}
public override bool HasLineInfo() { return true; }
public override int LineNumber { get { return _mlineInfo.LineNumber; } }
public override int LinePosition
{
get { return _mlineInfo.LinePosition; }
}
}
public class XmlDiffDocument : XmlDiffNode
{
private bool _bLoaded;
private bool _bIgnoreAttributeOrder;
private bool _bIgnoreChildOrder;
private bool _bIgnoreComments;
private bool _bIgnoreWhitespace;
private bool _bIgnoreDTD;
private bool _bIgnoreNS;
private bool _bIgnorePrefix;
private bool _bCDataAsText;
private bool _bNormalizeNewline;
public XmlNameTable nameTable;
public XmlDiffDocument()
: base()
{
_bLoaded = false;
_bIgnoreAttributeOrder = false;
_bIgnoreChildOrder = false;
_bIgnoreComments = false;
_bIgnoreWhitespace = false;
_bIgnoreDTD = false;
_bCDataAsText = false;
}
public XmlDiffOption Option
{
set
{
this.IgnoreAttributeOrder = (((int)value & (int)(XmlDiffOption.IgnoreAttributeOrder)) > 0);
this.IgnoreChildOrder = (((int)value & (int)(XmlDiffOption.IgnoreChildOrder)) > 0);
this.IgnoreComments = (((int)value & (int)(XmlDiffOption.IgnoreComments)) > 0);
this.IgnoreWhitespace = (((int)value & (int)(XmlDiffOption.IgnoreWhitespace)) > 0);
this.IgnoreDTD = (((int)value & (int)(XmlDiffOption.IgnoreDTD)) > 0);
this.IgnoreNS = (((int)value & (int)(XmlDiffOption.IgnoreNS)) > 0);
this.IgnorePrefix = (((int)value & (int)(XmlDiffOption.IgnorePrefix)) > 0);
this.CDataAsText = (((int)value & (int)(XmlDiffOption.CDataAsText)) > 0);
this.NormalizeNewline = (((int)value & (int)(XmlDiffOption.NormalizeNewline)) > 0);
}
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Document; } }
public bool IgnoreAttributeOrder
{
get { return this._bIgnoreAttributeOrder; }
set { this._bIgnoreAttributeOrder = value; }
}
public bool IgnoreChildOrder
{
get { return this._bIgnoreChildOrder; }
set { this._bIgnoreChildOrder = value; }
}
public bool IgnoreComments
{
get { return this._bIgnoreComments; }
set { this._bIgnoreComments = value; }
}
public bool IgnoreWhitespace
{
get { return this._bIgnoreWhitespace; }
set { this._bIgnoreWhitespace = value; }
}
public bool IgnoreDTD
{
get { return this._bIgnoreDTD; }
set { this._bIgnoreDTD = value; }
}
public bool IgnoreNS
{
get { return this._bIgnoreNS; }
set { this._bIgnoreNS = value; }
}
public bool IgnorePrefix
{
get { return this._bIgnorePrefix; }
set { this._bIgnorePrefix = value; }
}
public bool CDataAsText
{
get { return this._bCDataAsText; }
set { this._bCDataAsText = value; }
}
public bool NormalizeNewline
{
get { return this._bNormalizeNewline; }
set { this._bNormalizeNewline = value; }
}
//NodePosition.Before is returned if node2 should be before node1;
//NodePosition.After is returned if node2 should be after node1;
//In any case, NodePosition.Unknown should never be returned.
internal NodePosition ComparePosition(XmlDiffNode node1, XmlDiffNode node2)
{
int nt1 = (int)(node1.NodeType);
int nt2 = (int)(node2.NodeType);
if (nt2 > nt1)
return NodePosition.After;
if (nt2 < nt1)
return NodePosition.Before;
//now nt1 == nt2
if (nt1 == (int)XmlDiffNodeType.Element)
{
return CompareElements(node1 as XmlDiffElement, node2 as XmlDiffElement);
}
else if (nt1 == (int)XmlDiffNodeType.Attribute)
{
return CompareAttributes(node1 as XmlDiffAttribute, node2 as XmlDiffAttribute);
}
else if (nt1 == (int)XmlDiffNodeType.ER)
{
return CompareERs(node1 as XmlDiffEntityReference, node2 as XmlDiffEntityReference);
}
else if (nt1 == (int)XmlDiffNodeType.PI)
{
return ComparePIs(node1 as XmlDiffProcessingInstruction, node2 as XmlDiffProcessingInstruction);
}
else if (node1 is XmlDiffCharacterData)
{
return CompareTextLikeNodes(node1 as XmlDiffCharacterData, node2 as XmlDiffCharacterData);
}
else
{
//something really wrong here, what should we do???
Debug.Assert(false, "ComparePosition meets an undecision situation.");
return NodePosition.Unknown;
}
}
private NodePosition CompareElements(XmlDiffElement elem1, XmlDiffElement elem2)
{
Debug.Assert(elem1 != null);
Debug.Assert(elem2 != null);
int nCompare = 0;
if ((nCompare = CompareText(elem2.LocalName, elem1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(elem2.NamespaceURI, elem1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(elem2.Prefix, elem1.Prefix)) == 0)
{
if ((nCompare = CompareText(elem2.Value, elem1.Value)) == 0)
{
if ((nCompare = CompareAttributes(elem2, elem1)) == 0)
{
return NodePosition.After;
}
}
}
}
}
if (nCompare > 0)
//elem2 > elem1
return NodePosition.After;
else
//elem2 < elem1
return NodePosition.Before;
}
private int CompareAttributes(XmlDiffElement elem1, XmlDiffElement elem2)
{
int count1 = elem1.AttributeCount;
int count2 = elem2.AttributeCount;
if (count1 > count2)
return 1;
else if (count1 < count2)
return -1;
else
{
XmlDiffAttribute current1 = elem1.FirstAttribute;
XmlDiffAttribute current2 = elem2.FirstAttribute;
// NodePosition result = 0;
int nCompare = 0;
while (current1 != null && current2 != null && nCompare == 0)
{
if ((nCompare = CompareText(current2.LocalName, current1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(current2.NamespaceURI, current1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(current2.Prefix, current1.Prefix)) == 0)
{
if ((nCompare = CompareText(current2.Value, current1.Value)) == 0)
{
//do nothing!
}
}
}
}
current1 = (XmlDiffAttribute)current1._next;
current2 = (XmlDiffAttribute)current2._next;
}
if (nCompare > 0)
//elem1 > attr2
return 1;
else
//elem1 < elem2
return -1;
}
}
private NodePosition CompareAttributes(XmlDiffAttribute attr1, XmlDiffAttribute attr2)
{
Debug.Assert(attr1 != null);
Debug.Assert(attr2 != null);
int nCompare = 0;
if ((nCompare = CompareText(attr2.LocalName, attr1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(attr2.NamespaceURI, attr1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(attr2.Prefix, attr1.Prefix)) == 0)
{
if ((nCompare = CompareText(attr2.Value, attr1.Value)) == 0)
{
return NodePosition.After;
}
}
}
}
if (nCompare > 0)
//attr2 > attr1
return NodePosition.After;
else
//attr2 < attr1
return NodePosition.Before;
}
private NodePosition CompareERs(XmlDiffEntityReference er1, XmlDiffEntityReference er2)
{
Debug.Assert(er1 != null);
Debug.Assert(er2 != null);
int nCompare = CompareText(er2.Name, er1.Name);
if (nCompare >= 0)
return NodePosition.After;
else
return NodePosition.Before;
}
private NodePosition ComparePIs(XmlDiffProcessingInstruction pi1, XmlDiffProcessingInstruction pi2)
{
Debug.Assert(pi1 != null);
Debug.Assert(pi2 != null);
int nCompare = 0;
if ((nCompare = CompareText(pi2.Name, pi1.Name)) == 0)
{
if ((nCompare = CompareText(pi2.Value, pi1.Value)) == 0)
{
return NodePosition.After;
}
}
if (nCompare > 0)
//pi2 > pi1
return NodePosition.After;
else
//pi2 < pi1
return NodePosition.Before;
}
private NodePosition CompareTextLikeNodes(XmlDiffCharacterData t1, XmlDiffCharacterData t2)
{
Debug.Assert(t1 != null);
Debug.Assert(t2 != null);
int nCompare = CompareText(t2.Value, t1.Value);
if (nCompare >= 0)
return NodePosition.After;
else
return NodePosition.Before;
}
//returns 0 if the same string; 1 if s1 > s1 and -1 if s1 < s2
private int CompareText(string s1, string s2)
{
int len = s1.Length;
//len becomes the smaller of the two
if (len > s2.Length)
len = s2.Length;
int nInd = 0;
char c1 = (char)0x0;
char c2 = (char)0x0;
while (nInd < len)
{
c1 = s1[nInd];
c2 = s2[nInd];
if (c1 < c2)
return -1; //s1 < s2
else if (c1 > c2)
return 1; //s1 > s2
nInd++;
}
if (s2.Length > s1.Length)
return -1; //s1 < s2
else if (s2.Length < s1.Length)
return 1; //s1 > s2
else return 0;
}
public virtual void Load(XmlReader reader)
{
if (_bLoaded)
throw new InvalidOperationException("The document already contains data and should not be used again.");
if (reader.ReadState == ReadState.Initial)
{
if (!reader.Read())
return;
}
PositionInfo pInfo = PositionInfo.GetPositionInfo(reader);
ReadChildNodes(this, reader, pInfo);
this._bLoaded = true;
this.nameTable = reader.NameTable;
}
internal void ReadChildNodes(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
bool lookAhead = false;
do
{
lookAhead = false;
switch (reader.NodeType)
{
case XmlNodeType.Element:
LoadElement(parent, reader, pInfo);
break;
case XmlNodeType.Comment:
if (!IgnoreComments)
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.Comment);
break;
case XmlNodeType.ProcessingInstruction:
LoadPI(parent, reader, pInfo);
break;
case XmlNodeType.SignificantWhitespace:
if (reader.XmlSpace == XmlSpace.Preserve)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.WS);
}
break;
case XmlNodeType.CDATA:
if (!CDataAsText)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.CData);
}
else //merge with adjacent text/CDATA nodes
{
StringBuilder text = new StringBuilder();
text.Append(reader.Value);
while ((lookAhead = reader.Read()) && (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA))
{
text.Append(reader.Value);
}
LoadTextNode(parent, text.ToString(), pInfo, XmlDiffNodeType.Text);
}
break;
case XmlNodeType.Text:
if (!CDataAsText)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.Text);
}
else //megre with adjacent text/CDATA nodes
{
StringBuilder text = new StringBuilder();
text.Append(reader.Value);
while ((lookAhead = reader.Read()) && (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA))
{
text.Append(reader.Value);
}
LoadTextNode(parent, text.ToString(), pInfo, XmlDiffNodeType.Text);
}
break;
case XmlNodeType.EntityReference:
LoadEntityReference(parent, reader, pInfo);
break;
case XmlNodeType.EndElement:
SetElementEndPosition(parent as XmlDiffElement, pInfo);
return;
case XmlNodeType.Attribute: //attribute at top level
string attrVal = reader.Name + "=\"" + reader.Value + "\"";
LoadTopLevelAttribute(parent, attrVal, pInfo, XmlDiffNodeType.Text);
break;
default:
break;
}
} while (lookAhead || reader.Read());
}
private void LoadElement(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffElement elem = null;
bool bEmptyElement = reader.IsEmptyElement;
if (bEmptyElement)
elem = new XmlDiffEmptyElement(reader.LocalName, reader.Prefix, reader.NamespaceURI);
else
elem = new XmlDiffElement(reader.LocalName, reader.Prefix, reader.NamespaceURI);
elem.LineNumber = pInfo.LineNumber;
elem.LinePosition = pInfo.LinePosition;
ReadAttributes(elem, reader, pInfo);
if (!bEmptyElement)
{
reader.Read(); //move to child
ReadChildNodes(elem, reader, pInfo);
}
InsertChild(parent, elem);
}
private void ReadAttributes(XmlDiffElement parent, XmlReader reader, PositionInfo pInfo)
{
if (reader.MoveToFirstAttribute())
{
XmlDiffAttribute attr = new XmlDiffAttribute(reader.LocalName, reader.Prefix, reader.NamespaceURI, reader.Value);
attr.LineNumber = pInfo.LineNumber;
attr.LinePosition = pInfo.LinePosition;
InsertAttribute(parent, attr);
while (reader.MoveToNextAttribute())
{
attr = new XmlDiffAttribute(reader.LocalName, reader.Prefix, reader.NamespaceURI, reader.Value);
attr.LineNumber = pInfo.LineNumber;
attr.LinePosition = pInfo.LinePosition;
InsertAttribute(parent, attr);
}
}
}
private void LoadTextNode(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo, XmlDiffNodeType nt)
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(reader.Value, nt, this.NormalizeNewline);
textNode.LineNumber = pInfo.LineNumber;
textNode.LinePosition = pInfo.LinePosition;
InsertChild(parent, textNode);
}
private void LoadTextNode(XmlDiffNode parent, string text, PositionInfo pInfo, XmlDiffNodeType nt)
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(text, nt, this.NormalizeNewline);
textNode.LineNumber = pInfo.LineNumber;
textNode.LinePosition = pInfo.LinePosition;
InsertChild(parent, textNode);
}
private void LoadTopLevelAttribute(XmlDiffNode parent, string text, PositionInfo pInfo, XmlDiffNodeType nt)
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(text, nt, this.NormalizeNewline);
textNode.LineNumber = pInfo.LineNumber;
textNode.LinePosition = pInfo.LinePosition;
InsertTopLevelAttributeAsText(parent, textNode);
}
private void LoadPI(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffProcessingInstruction pi = new XmlDiffProcessingInstruction(reader.Name, reader.Value);
pi.LineNumber = pInfo.LineNumber;
pi.LinePosition = pInfo.LinePosition;
InsertChild(parent, pi);
}
private void LoadEntityReference(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffEntityReference er = new XmlDiffEntityReference(reader.Name);
er.LineNumber = pInfo.LineNumber;
er.LinePosition = pInfo.LinePosition;
InsertChild(parent, er);
}
private void SetElementEndPosition(XmlDiffElement elem, PositionInfo pInfo)
{
Debug.Assert(elem != null);
elem.EndLineNumber = pInfo.LineNumber;
elem.EndLinePosition = pInfo.LinePosition;
}
private void InsertChild(XmlDiffNode parent, XmlDiffNode newChild)
{
if (IgnoreChildOrder)
{
XmlDiffNode child = parent.FirstChild;
XmlDiffNode prevChild = null;
while (child != null && (ComparePosition(child, newChild) == NodePosition.After))
{
prevChild = child;
child = child.NextSibling;
}
parent.InsertChildAfter(prevChild, newChild);
}
else
parent.InsertChildAfter(parent.LastChild, newChild);
}
private void InsertTopLevelAttributeAsText(XmlDiffNode parent, XmlDiffCharacterData newChild)
{
if (parent.LastChild != null && (parent.LastChild.NodeType == XmlDiffNodeType.Text || parent.LastChild.NodeType == XmlDiffNodeType.WS))
{
((XmlDiffCharacterData)parent.LastChild).Value = ((XmlDiffCharacterData)parent.LastChild).Value + " " + newChild.Value;
}
else
{
parent.InsertChildAfter(parent.LastChild, newChild);
}
}
private void InsertAttribute(XmlDiffElement parent, XmlDiffAttribute newAttr)
{
Debug.Assert(parent != null);
Debug.Assert(newAttr != null);
newAttr._parent = parent;
if (IgnoreAttributeOrder)
{
XmlDiffAttribute attr = parent.FirstAttribute;
XmlDiffAttribute prevAttr = null;
while (attr != null && (CompareAttributes(attr, newAttr) == NodePosition.After))
{
prevAttr = attr;
attr = (XmlDiffAttribute)(attr.NextSibling);
}
parent.InsertAttributeAfter(prevAttr, newAttr);
}
else
parent.InsertAttributeAfter(parent.LastAttribute, newAttr);
}
public override void WriteTo(XmlWriter w)
{
WriteContentTo(w);
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
public XmlDiffNavigator CreateNavigator()
{
return new XmlDiffNavigator(this);
}
public void SortChildren()
{
if (this.FirstChild != null)
{
XmlDiffNode _first = this.FirstChild;
XmlDiffNode _current = this.FirstChild;
XmlDiffNode _last = this.LastChild;
this._firstChild = null;
this._lastChild = null;
//set flag to ignore child order
bool temp = IgnoreChildOrder;
IgnoreChildOrder = true;
XmlDiffNode _next = null;
do
{
if (_current is XmlDiffElement)
_next = _current._next;
_current._next = null;
InsertChild(this, _current);
if (_current == _last)
break;
_current = _next;
}
while (true);
//restore flag for ignoring child order
IgnoreChildOrder = temp;
}
}
void SortChildren(XmlDiffElement elem)
{
if (elem.FirstChild != null)
{
XmlDiffNode _first = elem.FirstChild;
XmlDiffNode _current = elem.FirstChild;
XmlDiffNode _last = elem.LastChild;
elem._firstChild = null;
elem._lastChild = null;
//set flag to ignore child order
bool temp = IgnoreChildOrder;
IgnoreChildOrder = true;
XmlDiffNode _next = null;
do
{
if (_current is XmlDiffElement)
_next = _current._next;
_current._next = null;
InsertChild(elem, _current);
if (_current == _last)
break;
_current = _next;
}
while (true);
//restore flag for ignoring child order
IgnoreChildOrder = temp;
}
}
}
//navgator over the xmldiffdocument
public class XmlDiffNavigator
{
private XmlDiffDocument _document;
private XmlDiffNode _currentNode;
public XmlDiffNavigator(XmlDiffDocument doc)
{
_document = doc;
_currentNode = _document;
}
public XmlDiffNavigator Clone()
{
XmlDiffNavigator _clone = new XmlDiffNavigator(_document);
if (!_clone.MoveTo(this))
throw new Exception("Cannot clone");
return _clone;
}
public NodePosition ComparePosition(XmlDiffNavigator nav)
{
XmlDiffNode targetNode = ((XmlDiffNavigator)nav).CurrentNode;
if (!(nav is XmlDiffNavigator))
{
return NodePosition.Unknown;
}
if (targetNode == this.CurrentNode)
{
return NodePosition.Same;
}
else
{
if (this.CurrentNode.ParentNode == null) //this is root
{
return NodePosition.After;
}
else if (targetNode.ParentNode == null) //this is root
{
return NodePosition.Before;
}
else //look in the following nodes
{
if (targetNode.LineNumber != 0 && this.CurrentNode.LineNumber != 0)
{
if (targetNode.LineNumber > this.CurrentNode.LineNumber)
{
return NodePosition.Before;
}
else if (targetNode.LineNumber == this.CurrentNode.LineNumber && targetNode.LinePosition > this.CurrentNode.LinePosition)
{
return NodePosition.Before;
}
else
return NodePosition.After;
}
return NodePosition.Before;
}
}
}
public String GetAttribute(String localName, String namespaceURI)
{
if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).GetAttributeValue(localName, namespaceURI);
}
return "";
}
public String GetNamespace(String name)
{
Debug.Assert(false, "GetNamespace is NYI");
return "";
}
public bool IsSamePosition(XmlDiffNavigator other)
{
if (other is XmlDiffNavigator)
{
if (_currentNode == ((XmlDiffNavigator)other).CurrentNode)
return true;
}
return false;
}
public bool MoveTo(XmlDiffNavigator other)
{
if (other is XmlDiffNavigator)
{
_currentNode = ((XmlDiffNavigator)other).CurrentNode;
return true;
}
return false;
}
public bool MoveToAttribute(String localName, String namespaceURI)
{
if (_currentNode is XmlDiffElement)
{
XmlDiffAttribute _attr = ((XmlDiffElement)_currentNode).GetAttribute(localName, namespaceURI);
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
return false;
}
public bool MoveToFirst()
{
if (!(_currentNode is XmlDiffAttribute))
{
if (_currentNode.ParentNode.FirstChild == _currentNode)
{
if (_currentNode.ParentNode.FirstChild._next != null)
{
_currentNode = _currentNode.ParentNode.FirstChild._next;
return true;
}
}
else
{
_currentNode = _currentNode.ParentNode.FirstChild;
return true;
}
}
return false;
}
public bool MoveToFirstAttribute()
{
if (_currentNode is XmlDiffElement)
{
if (((XmlDiffElement)_currentNode).FirstAttribute != null)
{
XmlDiffAttribute _attr = ((XmlDiffElement)_currentNode).FirstAttribute;
while (_attr != null && IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
}
return false;
}
public bool MoveToFirstChild()
{
if ((_currentNode is XmlDiffDocument || _currentNode is XmlDiffElement) && _currentNode.FirstChild != null)
{
_currentNode = _currentNode.FirstChild;
return true;
}
return false;
}
public bool MoveToFirstNamespace(XNamespace namespaceScope)
{
if (_currentNode is XmlDiffElement)
{
if (((XmlDiffElement)_currentNode).FirstAttribute != null)
{
XmlDiffAttribute _attr = ((XmlDiffElement)_currentNode).FirstAttribute;
while (_attr != null && !IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
}
return false;
}
public bool MoveToId(String id)
{
Debug.Assert(false, "MoveToId is NYI");
return false;
}
public bool MoveToNamespace(String name)
{
Debug.Assert(false, "MoveToNamespace is NYI");
return false;
}
public bool MoveToNext()
{
if (!(_currentNode is XmlDiffAttribute) && _currentNode._next != null)
{
_currentNode = _currentNode._next;
return true;
}
return false;
}
public bool MoveToNextAttribute()
{
if (_currentNode is XmlDiffAttribute)
{
XmlDiffAttribute _attr = (XmlDiffAttribute)_currentNode._next;
while (_attr != null && IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
return false;
}
private bool IsNamespaceNode(XmlDiffAttribute attr)
{
return attr.LocalName.ToLower() == "xmlns" ||
attr.Prefix.ToLower() == "xmlns";
}
public bool MoveToNextNamespace(XNamespace namespaceScope)
{
if (_currentNode is XmlDiffAttribute)
{
XmlDiffAttribute _attr = (XmlDiffAttribute)_currentNode._next;
while (_attr != null && !IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
return false;
}
public bool MoveToParent()
{
if (!(_currentNode is XmlDiffDocument))
{
_currentNode = _currentNode.ParentNode;
return true;
}
return false;
}
public bool MoveToPrevious()
{
if (_currentNode != _currentNode.ParentNode.FirstChild)
{
XmlDiffNode _current = _currentNode.ParentNode.FirstChild;
XmlDiffNode _prev = _currentNode.ParentNode.FirstChild;
while (_current != _currentNode)
{
_prev = _current;
_current = _current._next;
}
_currentNode = _prev;
return true;
}
return false;
}
public void MoveToRoot()
{
_currentNode = _document;
}
public string LocalName
{
get
{
if (_currentNode.NodeType == XmlDiffNodeType.Element)
{
return ((XmlDiffElement)_currentNode).LocalName;
}
else if (_currentNode.NodeType == XmlDiffNodeType.Attribute)
{
return ((XmlDiffAttribute)_currentNode).LocalName;
}
else if (_currentNode.NodeType == XmlDiffNodeType.PI)
{
return ((XmlDiffProcessingInstruction)_currentNode).Name;
}
return "";
}
}
public string Name
{
get
{
if (_currentNode.NodeType == XmlDiffNodeType.Element)
{
return _document.nameTable.Get(((XmlDiffElement)_currentNode).Name);
}
else if (_currentNode.NodeType == XmlDiffNodeType.Attribute)
{
return ((XmlDiffAttribute)_currentNode).Name;
}
else if (_currentNode.NodeType == XmlDiffNodeType.PI)
{
return ((XmlDiffProcessingInstruction)_currentNode).Name;
}
return "";
}
}
public string NamespaceURI
{
get
{
if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).NamespaceURI;
}
else if (_currentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)_currentNode).NamespaceURI;
}
return "";
}
}
public string Value
{
get
{
if (_currentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)_currentNode).Value;
}
else if (_currentNode is XmlDiffCharacterData)
{
return ((XmlDiffCharacterData)_currentNode).Value;
}
else if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).Value;
}
return "";
}
}
public string Prefix
{
get
{
if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).Prefix;
}
else if (_currentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)_currentNode).Prefix;
}
return "";
}
}
public string BaseURI
{
get
{
Debug.Assert(false, "BaseURI is NYI");
return "";
}
}
public string XmlLang
{
get
{
Debug.Assert(false, "XmlLang not supported");
return "";
}
}
public bool HasAttributes
{
get
{
return (_currentNode is XmlDiffElement && ((XmlDiffElement)_currentNode).FirstAttribute != null) ? true : false;
}
}
public bool HasChildren
{
get
{
return _currentNode._next != null ? true : false;
}
}
public bool IsEmptyElement
{
get
{
return _currentNode is XmlDiffEmptyElement ? true : false;
}
}
public XmlNameTable NameTable
{
get
{
return _document.nameTable;
}
}
public XmlDiffNode CurrentNode
{
get
{
return _currentNode;
}
}
public bool IsOnRoot()
{
return _currentNode == null ? true : false;
}
}
public class PropertyCollection : MyDict<string, object> { }
public abstract class XmlDiffNode
{
internal XmlDiffNode _next;
internal XmlDiffNode _firstChild;
internal XmlDiffNode _lastChild;
internal XmlDiffNode _parent;
internal int _lineNumber, _linePosition;
internal bool _bIgnoreValue;
private PropertyCollection _extendedProperties;
public XmlDiffNode()
{
this._next = null;
this._firstChild = null;
this._lastChild = null;
this._parent = null;
_lineNumber = 0;
_linePosition = 0;
}
public XmlDiffNode FirstChild
{
get
{
return this._firstChild;
}
}
public XmlDiffNode LastChild
{
get
{
return this._lastChild;
}
}
public XmlDiffNode NextSibling
{
get
{
return this._next;
}
}
public XmlDiffNode ParentNode
{
get
{
return this._parent;
}
}
public virtual bool IgnoreValue
{
get
{
return _bIgnoreValue;
}
set
{
_bIgnoreValue = value;
XmlDiffNode current = this._firstChild;
while (current != null)
{
current.IgnoreValue = value;
current = current._next;
}
}
}
public abstract XmlDiffNodeType NodeType { get; }
public virtual string OuterXml
{
get
{
StringWriter sw = new StringWriter();
XmlWriterSettings xws = new XmlWriterSettings();
xws.ConformanceLevel = ConformanceLevel.Auto;
xws.CheckCharacters = false;
XmlWriter xw = XmlWriter.Create(sw, xws);
WriteTo(xw);
xw.Dispose();
return sw.ToString();
}
}
public virtual string InnerXml
{
get
{
StringWriter sw = new StringWriter();
XmlWriterSettings xws = new XmlWriterSettings();
xws.ConformanceLevel = ConformanceLevel.Auto;
xws.CheckCharacters = false;
XmlWriter xw = XmlWriter.Create(sw, xws);
WriteTo(xw);
xw.Dispose();
return sw.ToString();
}
}
public abstract void WriteTo(XmlWriter w);
public abstract void WriteContentTo(XmlWriter w);
public PropertyCollection ExtendedProperties
{
get
{
if (_extendedProperties == null)
_extendedProperties = new PropertyCollection();
return _extendedProperties;
}
}
public virtual void InsertChildAfter(XmlDiffNode child, XmlDiffNode newChild)
{
Debug.Assert(newChild != null);
newChild._parent = this;
if (child == null)
{
newChild._next = this._firstChild;
this._firstChild = newChild;
}
else
{
Debug.Assert(child._parent == this);
newChild._next = child._next;
child._next = newChild;
}
if (newChild._next == null)
this._lastChild = newChild;
}
public virtual void DeleteChild(XmlDiffNode child)
{
if (child == this.FirstChild)//delete head
{
_firstChild = this.FirstChild.NextSibling;
}
else
{
XmlDiffNode current = this.FirstChild;
XmlDiffNode previous = null;
while (current != child)
{
previous = current;
current = current.NextSibling;
}
Debug.Assert(current != null);
if (current == this.LastChild) //tail being deleted
{
this._lastChild = current.NextSibling;
}
previous._next = current.NextSibling;
}
}
public int LineNumber
{
get { return this._lineNumber; }
set { this._lineNumber = value; }
}
public int LinePosition
{
get { return this._linePosition; }
set { this._linePosition = value; }
}
}
public class XmlDiffElement : XmlDiffNode
{
private string _lName;
private string _prefix;
private string _ns;
private XmlDiffAttribute _firstAttribute;
private XmlDiffAttribute _lastAttribute;
private int _attrC;
private int _endLineNumber, _endLinePosition;
public XmlDiffElement(string localName, string prefix, string ns)
: base()
{
this._lName = localName;
this._prefix = prefix;
this._ns = ns;
this._firstAttribute = null;
this._lastAttribute = null;
this._attrC = -1;
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Element; } }
public string LocalName { get { return this._lName; } }
public string NamespaceURI { get { return this._ns; } }
public string Prefix { get { return this._prefix; } }
public string Name
{
get
{
if (this._prefix.Length > 0)
return Prefix + ":" + LocalName;
else
return LocalName;
}
}
public XmlDiffAttribute FirstAttribute
{
get
{
return this._firstAttribute;
}
}
public XmlDiffAttribute LastAttribute
{
get
{
return this._lastAttribute;
}
}
public string GetAttributeValue(string LocalName, string NamespaceUri)
{
if (_firstAttribute != null)
{
XmlDiffAttribute _current = _firstAttribute;
do
{
if (_current.LocalName == LocalName && _current.NamespaceURI == NamespaceURI)
{
return _current.Value;
}
_current = (XmlDiffAttribute)_current._next;
}
while (_current != _lastAttribute);
}
return "";
}
public XmlDiffAttribute GetAttribute(string LocalName, string NamespaceUri)
{
if (_firstAttribute != null)
{
XmlDiffAttribute _current = _firstAttribute;
do
{
if (_current.LocalName == LocalName && _current.NamespaceURI == NamespaceURI)
{
return _current;
}
_current = (XmlDiffAttribute)_current._next;
}
while (_current != _lastAttribute);
}
return null;
}
internal void InsertAttributeAfter(XmlDiffAttribute attr, XmlDiffAttribute newAttr)
{
Debug.Assert(newAttr != null);
newAttr._ownerElement = this;
if (attr == null)
{
newAttr._next = this._firstAttribute;
this._firstAttribute = newAttr;
}
else
{
Debug.Assert(attr._ownerElement == this);
newAttr._next = attr._next;
attr._next = newAttr;
}
if (newAttr._next == null)
this._lastAttribute = newAttr;
}
internal void DeleteAttribute(XmlDiffAttribute attr)
{
if (attr == this.FirstAttribute)//delete head
{
if (attr == this.LastAttribute) //tail being deleted
{
this._lastAttribute = (XmlDiffAttribute)attr.NextSibling;
}
_firstAttribute = (XmlDiffAttribute)this.FirstAttribute.NextSibling;
}
else
{
XmlDiffAttribute current = this.FirstAttribute;
XmlDiffAttribute previous = null;
while (current != attr)
{
previous = current;
current = (XmlDiffAttribute)current.NextSibling;
}
Debug.Assert(current != null);
if (current == this.LastAttribute) //tail being deleted
{
this._lastAttribute = (XmlDiffAttribute)current.NextSibling;
}
previous._next = current.NextSibling;
}
}
public int AttributeCount
{
get
{
if (this._attrC != -1)
return this._attrC;
XmlDiffAttribute attr = this._firstAttribute;
this._attrC = 0;
while (attr != null)
{
this._attrC++;
attr = (XmlDiffAttribute)attr.NextSibling;
}
return this._attrC;
}
}
public override bool IgnoreValue
{
set
{
base.IgnoreValue = value;
XmlDiffAttribute current = this._firstAttribute;
while (current != null)
{
current.IgnoreValue = value;
current = (XmlDiffAttribute)current._next;
}
}
}
public int EndLineNumber
{
get { return this._endLineNumber; }
set { this._endLineNumber = value; }
}
public int EndLinePosition
{
get { return this._endLinePosition; }
set { this._endLinePosition = value; }
}
public override void WriteTo(XmlWriter w)
{
w.WriteStartElement(Prefix, LocalName, NamespaceURI);
XmlDiffAttribute attr = this._firstAttribute;
while (attr != null)
{
attr.WriteTo(w);
attr = (XmlDiffAttribute)(attr.NextSibling);
}
WriteContentTo(w);
w.WriteFullEndElement();
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
public string Value
{
get
{
if (this.IgnoreValue)
{
return "";
}
if (_firstChild != null)
{
StringBuilder _bldr = new StringBuilder();
XmlDiffNode _current = _firstChild;
do
{
if (_current is XmlDiffCharacterData && _current.NodeType != XmlDiffNodeType.Comment && _current.NodeType != XmlDiffNodeType.PI)
{
_bldr.Append(((XmlDiffCharacterData)_current).Value);
}
else if (_current is XmlDiffElement)
{
_bldr.Append(((XmlDiffElement)_current).Value);
}
_current = _current._next;
}
while (_current != null);
return _bldr.ToString();
}
return "";
}
}
}
public class XmlDiffEmptyElement : XmlDiffElement
{
public XmlDiffEmptyElement(string localName, string prefix, string ns) : base(localName, prefix, ns) { }
}
public class XmlDiffAttribute : XmlDiffNode
{
internal XmlDiffElement _ownerElement;
private string _lName;
private string _prefix;
private string _ns;
private string _value;
public XmlDiffAttribute(string localName, string prefix, string ns, string value)
: base()
{
this._lName = localName;
this._prefix = prefix;
this._ns = ns;
this._value = value;
}
public string Value
{
get
{
if (this.IgnoreValue)
{
return "";
}
return this._value;
}
}
public string LocalName { get { return this._lName; } }
public string NamespaceURI { get { return this._ns; } }
public string Prefix { get { return this._prefix; } }
public string Name
{
get
{
if (this._prefix.Length > 0)
return this._prefix + ":" + this._lName;
else
return this._lName;
}
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Attribute; } }
public override void WriteTo(XmlWriter w)
{
w.WriteStartAttribute(Prefix, LocalName, NamespaceURI);
WriteContentTo(w);
w.WriteEndAttribute();
}
public override void WriteContentTo(XmlWriter w)
{
w.WriteString(Value);
}
}
public class XmlDiffEntityReference : XmlDiffNode
{
private string _name;
public XmlDiffEntityReference(string name)
: base()
{
this._name = name;
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.ER; } }
public string Name { get { return this._name; } }
public override void WriteTo(XmlWriter w)
{
w.WriteEntityRef(this._name);
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = this.FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
}
public class XmlDiffCharacterData : XmlDiffNode
{
private string _value;
private XmlDiffNodeType _nodetype;
public XmlDiffCharacterData(string value, XmlDiffNodeType nt, bool NormalizeNewline)
: base()
{
this._value = value;
if (NormalizeNewline)
{
this._value = this._value.Replace("\n", "");
this._value = this._value.Replace("\r", "");
}
this._nodetype = nt;
}
public string Value
{
get
{
if (this.IgnoreValue)
{
return "";
}
return this._value;
}
set
{
_value = value;
}
}
public override XmlDiffNodeType NodeType { get { return _nodetype; } }
public override void WriteTo(XmlWriter w)
{
switch (this._nodetype)
{
case XmlDiffNodeType.Comment:
w.WriteComment(Value);
break;
case XmlDiffNodeType.CData:
w.WriteCData(Value);
break;
case XmlDiffNodeType.WS:
case XmlDiffNodeType.Text:
w.WriteString(Value);
break;
default:
Debug.Assert(false, "Wrong type for text-like node : " + this._nodetype.ToString());
break;
}
}
public override void WriteContentTo(XmlWriter w) { }
}
public class XmlDiffProcessingInstruction : XmlDiffCharacterData
{
private string _name;
public XmlDiffProcessingInstruction(string name, string value)
: base(value, XmlDiffNodeType.PI, false)
{
this._name = name;
}
public string Name { get { return this._name; } }
public override void WriteTo(XmlWriter w)
{
w.WriteProcessingInstruction(this._name, Value);
}
public override void WriteContentTo(XmlWriter w) { }
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copysecond (c) 2017 Atif Aziz. All seconds 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.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Linq;
static partial class MoreEnumerable
{
/// <summary>
/// Performs a full outer join on two homogeneous sequences.
/// Additional arguments specify key selection functions and result
/// projection functions.
/// </summary>
/// <typeparam name="TSource">
/// The type of elements in the source sequence.</typeparam>
/// <typeparam name="TKey">
/// The type of the key returned by the key selector function.</typeparam>
/// <typeparam name="TResult">
/// The type of the result elements.</typeparam>
/// <param name="first">
/// The first sequence to join fully.</param>
/// <param name="second">
/// The second sequence to join fully.</param>
/// <param name="keySelector">
/// Function that projects the key given an element of one of the
/// sequences to join.</param>
/// <param name="firstSelector">
/// Function that projects the result given just an element from
/// <paramref name="first"/> where there is no corresponding element
/// in <paramref name="second"/>.</param>
/// <param name="secondSelector">
/// Function that projects the result given just an element from
/// <paramref name="second"/> where there is no corresponding element
/// in <paramref name="first"/>.</param>
/// <param name="bothSelector">
/// Function that projects the result given an element from
/// <paramref name="first"/> and an element from <paramref name="second"/>
/// that match on a common key.</param>
/// <returns>A sequence containing results projected from a full
/// outer join of the two input sequences.</returns>
public static IEnumerable<TResult> FullJoin<TSource, TKey, TResult>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector,
Func<TSource, TResult> firstSelector,
Func<TSource, TResult> secondSelector,
Func<TSource, TSource, TResult> bothSelector)
{
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
return first.FullJoin(second, keySelector,
firstSelector, secondSelector, bothSelector,
null);
}
/// <summary>
/// Performs a full outer join on two homogeneous sequences.
/// Additional arguments specify key selection functions, result
/// projection functions and a key comparer.
/// </summary>
/// <typeparam name="TSource">
/// The type of elements in the source sequence.</typeparam>
/// <typeparam name="TKey">
/// The type of the key returned by the key selector function.</typeparam>
/// <typeparam name="TResult">
/// The type of the result elements.</typeparam>
/// <param name="first">
/// The first sequence to join fully.</param>
/// <param name="second">
/// The second sequence to join fully.</param>
/// <param name="keySelector">
/// Function that projects the key given an element of one of the
/// sequences to join.</param>
/// <param name="firstSelector">
/// Function that projects the result given just an element from
/// <paramref name="first"/> where there is no corresponding element
/// in <paramref name="second"/>.</param>
/// <param name="secondSelector">
/// Function that projects the result given just an element from
/// <paramref name="second"/> where there is no corresponding element
/// in <paramref name="first"/>.</param>
/// <param name="bothSelector">
/// Function that projects the result given an element from
/// <paramref name="first"/> and an element from <paramref name="second"/>
/// that match on a common key.</param>
/// <param name="comparer">
/// The <see cref="IEqualityComparer{T}"/> instance used to compare
/// keys for equality.</param>
/// <returns>A sequence containing results projected from a full
/// outer join of the two input sequences.</returns>
public static IEnumerable<TResult> FullJoin<TSource, TKey, TResult>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector,
Func<TSource, TResult> firstSelector,
Func<TSource, TResult> secondSelector,
Func<TSource, TSource, TResult> bothSelector,
IEqualityComparer<TKey>? comparer)
{
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
return first.FullJoin(second,
keySelector, keySelector,
firstSelector, secondSelector, bothSelector,
comparer);
}
/// <summary>
/// Performs a full outer join on two heterogeneous sequences.
/// Additional arguments specify key selection functions and result
/// projection functions.
/// </summary>
/// <typeparam name="TFirst">
/// The type of elements in the first sequence.</typeparam>
/// <typeparam name="TSecond">
/// The type of elements in the second sequence.</typeparam>
/// <typeparam name="TKey">
/// The type of the key returned by the key selector functions.</typeparam>
/// <typeparam name="TResult">
/// The type of the result elements.</typeparam>
/// <param name="first">
/// The first sequence to join fully.</param>
/// <param name="second">
/// The second sequence to join fully.</param>
/// <param name="firstKeySelector">
/// Function that projects the key given an element from <paramref name="first"/>.</param>
/// <param name="secondKeySelector">
/// Function that projects the key given an element from <paramref name="second"/>.</param>
/// <param name="firstSelector">
/// Function that projects the result given just an element from
/// <paramref name="first"/> where there is no corresponding element
/// in <paramref name="second"/>.</param>
/// <param name="secondSelector">
/// Function that projects the result given just an element from
/// <paramref name="second"/> where there is no corresponding element
/// in <paramref name="first"/>.</param>
/// <param name="bothSelector">
/// Function that projects the result given an element from
/// <paramref name="first"/> and an element from <paramref name="second"/>
/// that match on a common key.</param>
/// <returns>A sequence containing results projected from a full
/// outer join of the two input sequences.</returns>
public static IEnumerable<TResult> FullJoin<TFirst, TSecond, TKey, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TKey> firstKeySelector,
Func<TSecond, TKey> secondKeySelector,
Func<TFirst, TResult> firstSelector,
Func<TSecond, TResult> secondSelector,
Func<TFirst, TSecond, TResult> bothSelector) =>
first.FullJoin(second,
firstKeySelector, secondKeySelector,
firstSelector, secondSelector, bothSelector,
null);
/// <summary>
/// Performs a full outer join on two heterogeneous sequences.
/// Additional arguments specify key selection functions, result
/// projection functions and a key comparer.
/// </summary>
/// <typeparam name="TFirst">
/// The type of elements in the first sequence.</typeparam>
/// <typeparam name="TSecond">
/// The type of elements in the second sequence.</typeparam>
/// <typeparam name="TKey">
/// The type of the key returned by the key selector functions.</typeparam>
/// <typeparam name="TResult">
/// The type of the result elements.</typeparam>
/// <param name="first">
/// The first sequence to join fully.</param>
/// <param name="second">
/// The second sequence to join fully.</param>
/// <param name="firstKeySelector">
/// Function that projects the key given an element from <paramref name="first"/>.</param>
/// <param name="secondKeySelector">
/// Function that projects the key given an element from <paramref name="second"/>.</param>
/// <param name="firstSelector">
/// Function that projects the result given just an element from
/// <paramref name="first"/> where there is no corresponding element
/// in <paramref name="second"/>.</param>
/// <param name="secondSelector">
/// Function that projects the result given just an element from
/// <paramref name="second"/> where there is no corresponding element
/// in <paramref name="first"/>.</param>
/// <param name="bothSelector">
/// Function that projects the result given an element from
/// <paramref name="first"/> and an element from <paramref name="second"/>
/// that match on a common key.</param>
/// <param name="comparer">
/// The <see cref="IEqualityComparer{T}"/> instance used to compare
/// keys for equality.</param>
/// <returns>A sequence containing results projected from a full
/// outer join of the two input sequences.</returns>
public static IEnumerable<TResult> FullJoin<TFirst, TSecond, TKey, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TKey> firstKeySelector,
Func<TSecond, TKey> secondKeySelector,
Func<TFirst, TResult> firstSelector,
Func<TSecond, TResult> secondSelector,
Func<TFirst, TSecond, TResult> bothSelector,
IEqualityComparer<TKey>? comparer)
{
if (first == null) throw new ArgumentNullException(nameof(first));
if (second == null) throw new ArgumentNullException(nameof(second));
if (firstKeySelector == null) throw new ArgumentNullException(nameof(firstKeySelector));
if (secondKeySelector == null) throw new ArgumentNullException(nameof(secondKeySelector));
if (firstSelector == null) throw new ArgumentNullException(nameof(firstSelector));
if (secondSelector == null) throw new ArgumentNullException(nameof(secondSelector));
if (bothSelector == null) throw new ArgumentNullException(nameof(bothSelector));
return _(); IEnumerable<TResult> _()
{
var seconds = second.Select(e => new KeyValuePair<TKey, TSecond>(secondKeySelector(e), e)).ToArray();
var secondLookup = seconds.ToLookup(e => e.Key, e => e.Value, comparer);
var firstKeys = new HashSet<TKey>(comparer);
foreach (var fe in first)
{
var key = firstKeySelector(fe);
firstKeys.Add(key);
using var se = secondLookup[key].GetEnumerator();
if (se.MoveNext())
{
do { yield return bothSelector(fe, se.Current); }
while (se.MoveNext());
}
else
{
se.Dispose();
yield return firstSelector(fe);
}
}
foreach (var se in seconds)
{
if (!firstKeys.Contains(se.Key))
yield return secondSelector(se.Value);
}
}
}
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:41 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.grid.feature
{
#region Summary
/// <summary>
/// <p>This feature is used to place a summary row at the bottom of the grid. If using a grouping,
/// see <see cref="Ext.grid.feature.GroupingSummary">Ext.grid.feature.GroupingSummary</see>. There are 2 aspects to calculating the summaries,
/// calculation and rendering.</p>
/// <h2>Calculation</h2>
/// <p>The summary value needs to be calculated for each column in the grid. This is controlled
/// by the summaryType option specified on the column. There are several built in summary types,
/// which can be specified as a string on the column configuration. These call underlying methods
/// on the store:</p>
/// <ul>
/// <li><see cref="Ext.data.Store.count">count</see></li>
/// <li><see cref="Ext.data.Store.sum">sum</see></li>
/// <li><see cref="Ext.data.Store.min">min</see></li>
/// <li><see cref="Ext.data.Store.max">max</see></li>
/// <li><see cref="Ext.data.Store.average">average</see></li>
/// </ul>
/// <p>Alternatively, the summaryType can be a function definition. If this is the case,
/// the function is called with an array of records to calculate the summary value.</p>
/// <h2>Rendering</h2>
/// <p>Similar to a column, the summary also supports a summaryRenderer function. This
/// summaryRenderer is called before displaying a value. The function is optional, if
/// not specified the default calculated value is shown. The summaryRenderer is called with:</p>
/// <ul>
/// <li>value {Object} - The calculated value.</li>
/// <li>summaryData {Object} - Contains all raw summary values for the row.</li>
/// <li>field {String} - The name of the field we are calculating</li>
/// </ul>
/// <h2>Example Usage</h2>
/// <pre><code><see cref="Ext.ExtContext.define">Ext.define</see>('TestResult', {
/// extend: '<see cref="Ext.data.Model">Ext.data.Model</see>',
/// fields: ['student', {
/// name: 'mark',
/// type: 'int'
/// }]
/// });
/// <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.grid.Panel">Ext.grid.Panel</see>', {
/// width: 200,
/// height: 140,
/// renderTo: document.body,
/// features: [{
/// ftype: 'summary'
/// }],
/// store: {
/// model: 'TestResult',
/// data: [{
/// student: 'Student 1',
/// mark: 84
/// },{
/// student: 'Student 2',
/// mark: 72
/// },{
/// student: 'Student 3',
/// mark: 96
/// },{
/// student: 'Student 4',
/// mark: 68
/// }]
/// },
/// columns: [{
/// dataIndex: 'student',
/// text: 'Name',
/// summaryType: 'count',
/// summaryRenderer: function(value, summaryData, dataIndex) {
/// return <see cref="Ext.String.format">Ext.String.format</see>('{0} student{1}', value, value !== 1 ? 's' : '');
/// }
/// }, {
/// dataIndex: 'mark',
/// text: 'Mark',
/// summaryType: 'average'
/// }]
/// });
/// </code></pre>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class Summary : AbstractSummary
{
/// <summary>
/// A config object containing one or more event handlers to be added to this object during initialization. This
/// should be a valid listeners config object as specified in the addListener example for attaching multiple
/// handlers at once.
/// <strong>DOM events from Ext JS <see cref="Ext.Component">Components</see></strong>
/// While <em>some</em> Ext JS Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually
/// only done when extra value can be added. For example the <see cref="Ext.view.View">DataView</see>'s <strong><c><see cref="Ext.view.ViewEvents.itemclick">itemclick</see></c></strong> event passing the node clicked on. To access DOM events directly from a
/// child element of a Component, we need to specify the <c>element</c> option to identify the Component property to add a
/// DOM listener to:
/// <code>new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({
/// width: 400,
/// height: 200,
/// dockedItems: [{
/// xtype: 'toolbar'
/// }],
/// listeners: {
/// click: {
/// element: 'el', //bind to the underlying el property on the panel
/// fn: function(){ console.log('click el'); }
/// },
/// dblclick: {
/// element: 'body', //bind to the underlying body property on the panel
/// fn: function(){ console.log('dblclick body'); }
/// }
/// }
/// });
/// </code>
/// </summary>
public JsObject listeners;
/// <summary>
/// True to show the summary row.
/// Defaults to: <c>true</c>
/// </summary>
public bool showSummaryRow;
/// <summary>
/// Defaults to: <c>"Ext.Base"</c>
/// </summary>
[JsProperty(Name="$className")]
public JsString @className{get;set;}
/// <summary>
/// Most features will not modify the data returned to the view.
/// This is limited to one feature that manipulates the data per grid view.
/// Defaults to: <c>false</c>
/// </summary>
public bool collectData{get;set;}
/// <summary>
/// Defaults to: <c>{}</c>
/// </summary>
public JsObject configMap{get;set;}
/// <summary>
/// True when feature is disabled.
/// Defaults to: <c>false</c>
/// </summary>
public bool disabled{get;set;}
/// <summary>
/// Prefix to use when firing events on the view.
/// For example a prefix of group would expose "groupclick", "groupcontextmenu", "groupdblclick".
/// Defaults to: <c>null</c>
/// </summary>
public JsString eventPrefix{get;set;}
/// <summary>
/// Selector used to determine when to fire the event with the eventPrefix.
/// Defaults to: <c>null</c>
/// </summary>
public JsString eventSelector{get;set;}
/// <summary>
/// Initial suspended call count. Incremented when suspendEvents is called, decremented when resumeEvents is called.
/// Defaults to: <c>0</c>
/// </summary>
private JsNumber eventsSuspended{get;set;}
/// <summary>
/// Reference to the grid panel
/// Defaults to: <c>null</c>
/// </summary>
public Ext.grid.Panel grid{get;set;}
/// <summary>
/// Most features will expose additional events, some may not and will
/// need to change this to false.
/// Defaults to: <c>true</c>
/// </summary>
public bool hasFeatureEvent{get;set;}
/// <summary>
/// This object holds a key for any event that has a listener. The listener may be set
/// directly on the instance, or on its class or a super class (via observe) or
/// on the MVC EventBus. The values of this object are truthy
/// (a non-zero number) and falsy (0 or undefined). They do not represent an exact count
/// of listeners. The value for an event is truthy if the event must be fired and is
/// falsy if there is no need to fire the event.
/// The intended use of this property is to avoid the expense of fireEvent calls when
/// there are no listeners. This can be particularly helpful when one would otherwise
/// have to call fireEvent hundreds or thousands of times. It is used like this:
/// <code> if (this.hasListeners.foo) {
/// this.fireEvent('foo', this, arg1);
/// }
/// </code>
/// </summary>
public JsObject hasListeners{get;set;}
/// <summary>
/// Defaults to: <c>[]</c>
/// </summary>
public JsArray initConfigList{get;set;}
/// <summary>
/// Defaults to: <c>{}</c>
/// </summary>
public JsObject initConfigMap{get;set;}
/// <summary>
/// Defaults to: <c>true</c>
/// </summary>
public bool isInstance{get;set;}
/// <summary>
/// true in this class to identify an object as an instantiated Observable, or subclass thereof.
/// Defaults to: <c>true</c>
/// </summary>
public bool isObservable{get;set;}
/// <summary>
/// Get the reference to the current class from which this object was instantiated. Unlike statics,
/// this.self is scope-dependent and it's meant to be used for dynamic inheritance. See statics
/// for a detailed comparison
/// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.Cat', {
/// statics: {
/// speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
/// },
/// constructor: function() {
/// alert(this.self.speciesName); // dependent on 'this'
/// },
/// clone: function() {
/// return new this.self();
/// }
/// });
/// <see cref="Ext.ExtContext.define">Ext.define</see>('My.SnowLeopard', {
/// extend: 'My.Cat',
/// statics: {
/// speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
/// }
/// });
/// var cat = new My.Cat(); // alerts 'Cat'
/// var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
/// var clone = snowLeopard.clone();
/// alert(<see cref="Ext.ExtContext.getClassName">Ext.getClassName</see>(clone)); // alerts 'My.SnowLeopard'
/// </code>
/// </summary>
public Class self{get;set;}
/// <summary>
/// Reference to the TableView.
/// Defaults to: <c>null</c>
/// </summary>
public Ext.view.Table view{get;set;}
/// <summary>
/// Adds the specified events to the list of events which this Observable may fire.
/// </summary>
/// <param name="eventNames"><p>Either an object with event names as properties with
/// a value of <c>true</c>. For example:</p>
/// <pre><code>this.addEvents({
/// storeloaded: true,
/// storecleared: true
/// });
/// </code></pre>
/// <p>Or any number of event names as separate parameters. For example:</p>
/// <pre><code>this.addEvents('storeloaded', 'storecleared');
/// </code></pre>
/// </param>
public void addEvents(object eventNames){}
/// <summary>
/// Appends an event handler to this object. For example:
/// <code>myGridPanel.on("mouseover", this.onMouseOver, this);
/// </code>
/// The method also allows for a single argument to be passed which is a config object
/// containing properties which specify multiple events. For example:
/// <code>myGridPanel.on({
/// cellClick: this.onCellClick,
/// mouseover: this.onMouseOver,
/// mouseout: this.onMouseOut,
/// scope: this // Important. Ensure "this" is correct during handler execution
/// });
/// </code>
/// One can also specify options for each event handler separately:
/// <code>myGridPanel.on({
/// cellClick: {fn: this.onCellClick, scope: this, single: true},
/// mouseover: {fn: panel.onMouseOver, scope: panel}
/// });
/// </code>
/// <em>Names</em> of methods in a specified scope may also be used. Note that
/// <c>scope</c> MUST be specified to use this option:
/// <code>myGridPanel.on({
/// cellClick: {fn: 'onCellClick', scope: this, single: true},
/// mouseover: {fn: 'onMouseOver', scope: panel}
/// });
/// </code>
/// </summary>
/// <param name="eventName"><p>The name of the event to listen for.
/// May also be an object who's property names are event names.</p>
/// </param>
/// <param name="fn"><p>The method the event invokes, or <em>if <c>scope</c> is specified, the </em>name* of the method within
/// the specified <c>scope</c>. Will be called with arguments
/// given to <see cref="Ext.util.Observable.fireEvent">fireEvent</see> plus the <c>options</c> parameter described below.</p>
/// </param>
/// <param name="scope"><p>The scope (<c>this</c> reference) in which the handler function is
/// executed. <strong>If omitted, defaults to the object which fired the event.</strong></p>
/// </param>
/// <param name="options"><p>An object containing handler configuration.</p>
/// <p><strong>Note:</strong> Unlike in ExtJS 3.x, the options object will also be passed as the last
/// argument to every event handler.</p>
/// <p>This object may contain any of the following properties:</p>
/// <ul><li><span>scope</span> : <see cref="Object">Object</see><div><p>The scope (<c>this</c> reference) in which the handler function is executed. <strong>If omitted,
/// defaults to the object which fired the event.</strong></p>
/// </div></li><li><span>delay</span> : <see cref="Number">Number</see><div><p>The number of milliseconds to delay the invocation of the handler after the event fires.</p>
/// </div></li><li><span>single</span> : <see cref="bool">Boolean</see><div><p>True to add a handler to handle just the next firing of the event, and then remove itself.</p>
/// </div></li><li><span>buffer</span> : <see cref="Number">Number</see><div><p>Causes the handler to be scheduled to run in an <see cref="Ext.util.DelayedTask">Ext.util.DelayedTask</see> delayed
/// by the specified number of milliseconds. If the event fires again within that time,
/// the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</p>
/// </div></li><li><span>target</span> : <see cref="Ext.util.Observable">Ext.util.Observable</see><div><p>Only call the handler if the event was fired on the target Observable, <em>not</em> if the event
/// was bubbled up from a child Observable.</p>
/// </div></li><li><span>element</span> : <see cref="String">String</see><div><p><strong>This option is only valid for listeners bound to <see cref="Ext.Component">Components</see>.</strong>
/// The name of a Component property which references an element to add a listener to.</p>
/// <p> This option is useful during Component construction to add DOM event listeners to elements of
/// <see cref="Ext.Component">Components</see> which will exist only after the Component is rendered.
/// For example, to add a click listener to a Panel's body:</p>
/// <pre><code> new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({
/// title: 'The title',
/// listeners: {
/// click: this.handlePanelClick,
/// element: 'body'
/// }
/// });
/// </code></pre>
/// <p><strong>Combining Options</strong></p>
/// <p>Using the options argument, it is possible to combine different types of listeners:</p>
/// <p>A delayed, one-time listener.</p>
/// <pre><code>myPanel.on('hide', this.handleClick, this, {
/// single: true,
/// delay: 100
/// });
/// </code></pre>
/// </div></li></ul></param>
public void addListener(object eventName, System.Delegate fn=null, object scope=null, object options=null){}
/// <summary>
/// Adds listeners to any Observable object (or Ext.Element) which are automatically removed when this Component is
/// destroyed.
/// </summary>
/// <param name="item"><p>The item to which to add a listener/listeners.</p>
/// </param>
/// <param name="ename"><p>The event name, or an object containing event name properties.</p>
/// </param>
/// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p>
/// </param>
/// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference)
/// in which the handler function is executed.</p>
/// </param>
/// <param name="opt"><p>If the <c>ename</c> parameter was an event name, this is the
/// <see cref="Ext.util.Observable.addListener">addListener</see> options.</p>
/// </param>
public void addManagedListener(object item, object ename, System.Delegate fn=null, object scope=null, object opt=null){}
/// <summary>
/// Removes all listeners for this object including the managed listeners
/// </summary>
public void clearListeners(){}
/// <summary>
/// Removes all managed listeners for this object.
/// </summary>
public void clearManagedListeners(){}
/// <summary>
/// Provide our own custom footer for the grid.
/// </summary>
/// <returns>
/// <span><see cref="String">String</see></span><div><p>The custom footer</p>
/// </div>
/// </returns>
private JsString closeRows(){return null;}
/// <summary>
/// Continue to fire event.
/// </summary>
/// <param name="eventName">
/// </param>
/// <param name="args">
/// </param>
/// <param name="bubbles">
/// </param>
private void continueFireEvent(JsString eventName, object args=null, object bubbles=null){}
/// <summary>
/// Creates an event handling function which refires the event from this object as the passed event name.
/// </summary>
/// <param name="newName">
/// </param>
/// <param name="beginEnd"><p>The caller can specify on which indices to slice</p>
/// </param>
/// <returns>
/// <span><see cref="Function">Function</see></span><div>
/// </div>
/// </returns>
private System.Delegate createRelayer(object newName, object beginEnd=null){return null;}
/// <summary>
/// Enables events fired by this Observable to bubble up an owner hierarchy by calling this.getBubbleTarget() if
/// present. There is no implementation in the Observable base class.
/// This is commonly used by Ext.Components to bubble events to owner Containers.
/// See <see cref="Ext.Component.getBubbleTarget">Ext.Component.getBubbleTarget</see>. The default implementation in <see cref="Ext.Component">Ext.Component</see> returns the
/// Component's immediate owner. But if a known target is required, this can be overridden to access the
/// required target more quickly.
/// Example:
/// <code><see cref="Ext.ExtContext.override">Ext.override</see>(<see cref="Ext.form.field.Base">Ext.form.field.Base</see>, {
/// // Add functionality to Field's initComponent to enable the change event to bubble
/// initComponent : <see cref="Ext.Function.createSequence">Ext.Function.createSequence</see>(Ext.form.field.Base.prototype.initComponent, function() {
/// this.enableBubble('change');
/// }),
/// // We know that we want Field's events to bubble directly to the FormPanel.
/// getBubbleTarget : function() {
/// if (!this.formPanel) {
/// this.formPanel = this.findParentByType('form');
/// }
/// return this.formPanel;
/// }
/// });
/// var myForm = new Ext.formPanel({
/// title: 'User Details',
/// items: [{
/// ...
/// }],
/// listeners: {
/// change: function() {
/// // Title goes red if form has been modified.
/// myForm.header.setStyle('color', 'red');
/// }
/// }
/// });
/// </code>
/// </summary>
/// <param name="eventNames"><p>The event name to bubble, or an Array of event names.</p>
/// </param>
public void enableBubble(object eventNames){}
/// <summary>
/// Fires the specified event with the passed parameters (minus the event name, plus the options object passed
/// to addListener).
/// An event may be set to bubble up an Observable parent hierarchy (See <see cref="Ext.Component.getBubbleTarget">Ext.Component.getBubbleTarget</see>) by
/// calling <see cref="Ext.util.Observable.enableBubble">enableBubble</see>.
/// </summary>
/// <param name="eventName"><p>The name of the event to fire.</p>
/// </param>
/// <param name="args"><p>Variable number of parameters are passed to handlers.</p>
/// </param>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p>returns false if any of the handlers return false otherwise it returns true.</p>
/// </div>
/// </returns>
public bool fireEvent(JsString eventName, params object[] args){return false;}
/// <summary>
/// Generates all of the summary data to be used when processing the template
/// </summary>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>The summary data</p>
/// </div>
/// </returns>
private object generateSummaryData(){return null;}
/// <summary>
/// Gets the bubbling parent for an Observable
/// </summary>
/// <returns>
/// <span><see cref="Ext.util.Observable">Ext.util.Observable</see></span><div><p>The bubble parent. null is returned if no bubble target exists</p>
/// </div>
/// </returns>
private Ext.util.Observable getBubbleParent(){return null;}
/// <summary>
/// Gets the value for the column from the attached data.
/// </summary>
/// <param name="column"><p>The header</p>
/// </param>
/// <param name="data"><p>The current data</p>
/// </param>
/// <returns>
/// <span><see cref="String">String</see></span><div><p>The value to be rendered</p>
/// </div>
/// </returns>
public virtual JsString getColumnValue(Ext.grid.column.Column column, object data){return null;}
/// <summary>
/// Gets any fragments needed for the template.
/// </summary>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>The fragments</p>
/// </div>
/// </returns>
private object getFragmentTpl(){return null;}
/// <summary>
/// Gets the data for printing a template row
/// </summary>
/// <param name="index"><p>The index in the template</p>
/// </param>
/// <returns>
/// <span><see cref="Array">Array</see></span><div><p>The template values</p>
/// </div>
/// </returns>
private JsArray getPrintData(JsNumber index){return null;}
/// <summary>
/// Get the summary data for a field.
/// </summary>
/// <param name="store"><p>The store to get the data from</p>
/// </param>
/// <param name="type"><p>The type of aggregation. If a function is specified it will
/// be passed to the stores aggregate function.</p>
/// </param>
/// <param name="field"><p>The field to aggregate on</p>
/// </param>
/// <param name="group"><p>True to aggregate in grouped mode</p>
/// </param>
/// <returns>
/// <span><see cref="Number">Number</see>/<see cref="String">String</see>/<see cref="Object">Object</see></span><div><p>See the return type for the store functions.</p>
/// </div>
/// </returns>
public virtual object getSummary(Ext.data.Store store, object type, JsString field, bool group){return null;}
/// <summary>
/// Gets any fragments to be used in the tpl
/// </summary>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>The fragments</p>
/// </div>
/// </returns>
public virtual object getSummaryFragments(){return null;}
/// <summary>
/// Overrides the closeRows method on the template so we can include our own custom
/// footer.
/// </summary>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>The custom fragments</p>
/// </div>
/// </returns>
private object getTableFragments(){return null;}
/// <summary>
/// Checks to see if this object has any listeners for a specified event, or whether the event bubbles. The answer
/// indicates whether the event needs firing or not.
/// </summary>
/// <param name="eventName"><p>The name of the event to check for</p>
/// </param>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p><c>true</c> if the event is being listened for or bubbles, else <c>false</c></p>
/// </div>
/// </returns>
public bool hasListener(JsString eventName){return false;}
/// <summary>
/// Shorthand for addManagedListener.
/// Adds listeners to any Observable object (or <see cref="Ext.dom.Element">Ext.Element</see>) which are automatically removed when this Component is
/// destroyed.
/// </summary>
/// <param name="item"><p>The item to which to add a listener/listeners.</p>
/// </param>
/// <param name="ename"><p>The event name, or an object containing event name properties.</p>
/// </param>
/// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p>
/// </param>
/// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference)
/// in which the handler function is executed.</p>
/// </param>
/// <param name="opt"><p>If the <c>ename</c> parameter was an event name, this is the
/// <see cref="Ext.util.Observable.addListener">addListener</see> options.</p>
/// </param>
public void mon(object item, object ename, System.Delegate fn=null, object scope=null, object opt=null){}
/// <summary>
/// Shorthand for removeManagedListener.
/// Removes listeners that were added by the <see cref="Ext.util.Observable.mon">mon</see> method.
/// </summary>
/// <param name="item"><p>The item from which to remove a listener/listeners.</p>
/// </param>
/// <param name="ename"><p>The event name, or an object containing event name properties.</p>
/// </param>
/// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p>
/// </param>
/// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference)
/// in which the handler function is executed.</p>
/// </param>
public void mun(object item, object ename, System.Delegate fn=null, object scope=null){}
/// <summary>
/// Shorthand for addListener.
/// Appends an event handler to this object. For example:
/// <code>myGridPanel.on("mouseover", this.onMouseOver, this);
/// </code>
/// The method also allows for a single argument to be passed which is a config object
/// containing properties which specify multiple events. For example:
/// <code>myGridPanel.on({
/// cellClick: this.onCellClick,
/// mouseover: this.onMouseOver,
/// mouseout: this.onMouseOut,
/// scope: this // Important. Ensure "this" is correct during handler execution
/// });
/// </code>
/// One can also specify options for each event handler separately:
/// <code>myGridPanel.on({
/// cellClick: {fn: this.onCellClick, scope: this, single: true},
/// mouseover: {fn: panel.onMouseOver, scope: panel}
/// });
/// </code>
/// <em>Names</em> of methods in a specified scope may also be used. Note that
/// <c>scope</c> MUST be specified to use this option:
/// <code>myGridPanel.on({
/// cellClick: {fn: 'onCellClick', scope: this, single: true},
/// mouseover: {fn: 'onMouseOver', scope: panel}
/// });
/// </code>
/// </summary>
/// <param name="eventName"><p>The name of the event to listen for.
/// May also be an object who's property names are event names.</p>
/// </param>
/// <param name="fn"><p>The method the event invokes, or <em>if <c>scope</c> is specified, the </em>name* of the method within
/// the specified <c>scope</c>. Will be called with arguments
/// given to <see cref="Ext.util.Observable.fireEvent">fireEvent</see> plus the <c>options</c> parameter described below.</p>
/// </param>
/// <param name="scope"><p>The scope (<c>this</c> reference) in which the handler function is
/// executed. <strong>If omitted, defaults to the object which fired the event.</strong></p>
/// </param>
/// <param name="options"><p>An object containing handler configuration.</p>
/// <p><strong>Note:</strong> Unlike in ExtJS 3.x, the options object will also be passed as the last
/// argument to every event handler.</p>
/// <p>This object may contain any of the following properties:</p>
/// <ul><li><span>scope</span> : <see cref="Object">Object</see><div><p>The scope (<c>this</c> reference) in which the handler function is executed. <strong>If omitted,
/// defaults to the object which fired the event.</strong></p>
/// </div></li><li><span>delay</span> : <see cref="Number">Number</see><div><p>The number of milliseconds to delay the invocation of the handler after the event fires.</p>
/// </div></li><li><span>single</span> : <see cref="bool">Boolean</see><div><p>True to add a handler to handle just the next firing of the event, and then remove itself.</p>
/// </div></li><li><span>buffer</span> : <see cref="Number">Number</see><div><p>Causes the handler to be scheduled to run in an <see cref="Ext.util.DelayedTask">Ext.util.DelayedTask</see> delayed
/// by the specified number of milliseconds. If the event fires again within that time,
/// the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</p>
/// </div></li><li><span>target</span> : <see cref="Ext.util.Observable">Ext.util.Observable</see><div><p>Only call the handler if the event was fired on the target Observable, <em>not</em> if the event
/// was bubbled up from a child Observable.</p>
/// </div></li><li><span>element</span> : <see cref="String">String</see><div><p><strong>This option is only valid for listeners bound to <see cref="Ext.Component">Components</see>.</strong>
/// The name of a Component property which references an element to add a listener to.</p>
/// <p> This option is useful during Component construction to add DOM event listeners to elements of
/// <see cref="Ext.Component">Components</see> which will exist only after the Component is rendered.
/// For example, to add a click listener to a Panel's body:</p>
/// <pre><code> new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({
/// title: 'The title',
/// listeners: {
/// click: this.handlePanelClick,
/// element: 'body'
/// }
/// });
/// </code></pre>
/// <p><strong>Combining Options</strong></p>
/// <p>Using the options argument, it is possible to combine different types of listeners:</p>
/// <p>A delayed, one-time listener.</p>
/// <pre><code>myPanel.on('hide', this.handleClick, this, {
/// single: true,
/// delay: 100
/// });
/// </code></pre>
/// </div></li></ul></param>
public void on(object eventName, System.Delegate fn=null, object scope=null, object options=null){}
/// <summary>
/// Prepares a given class for observable instances. This method is called when a
/// class derives from this class or uses this class as a mixin.
/// </summary>
/// <param name="T"><p>The class constructor to prepare.</p>
/// </param>
private void prepareClass(System.Delegate T){}
/// <summary>
/// Prints a summary row
/// </summary>
/// <param name="index"><p>The index in the template</p>
/// </param>
/// <returns>
/// <span><see cref="String">String</see></span><div><p>The value of the summary row</p>
/// </div>
/// </returns>
public virtual JsString printSummaryRow(object index){return null;}
/// <summary>
/// Relays selected events from the specified Observable as if the events were fired by this.
/// For example if you are extending Grid, you might decide to forward some events from store.
/// So you can do this inside your initComponent:
/// <code>this.relayEvents(this.getStore(), ['load']);
/// </code>
/// The grid instance will then have an observable 'load' event which will be passed the
/// parameters of the store's load event and any function fired with the grid's load event
/// would have access to the grid using the <c>this</c> keyword.
/// </summary>
/// <param name="origin"><p>The Observable whose events this object is to relay.</p>
/// </param>
/// <param name="events"><p>Array of event names to relay.</p>
/// </param>
/// <param name="prefix"><p>A common prefix to prepend to the event names. For example:</p>
/// <pre><code>this.relayEvents(this.getStore(), ['load', 'clear'], 'store');
/// </code></pre>
/// <p>Now the grid will forward 'load' and 'clear' events of store as 'storeload' and 'storeclear'.</p>
/// </param>
public void relayEvents(object origin, JsArray<String> events, object prefix=null){}
/// <summary>
/// Removes an event handler.
/// </summary>
/// <param name="eventName"><p>The type of event the handler was associated with.</p>
/// </param>
/// <param name="fn"><p>The handler to remove. <strong>This must be a reference to the function passed into the
/// <see cref="Ext.util.Observable.addListener">addListener</see> call.</strong></p>
/// </param>
/// <param name="scope"><p>The scope originally specified for the handler. It must be the same as the
/// scope argument specified in the original call to <see cref="Ext.util.Observable.addListener">addListener</see> or the listener will not be removed.</p>
/// </param>
public void removeListener(JsString eventName, System.Delegate fn, object scope=null){}
/// <summary>
/// Removes listeners that were added by the mon method.
/// </summary>
/// <param name="item"><p>The item from which to remove a listener/listeners.</p>
/// </param>
/// <param name="ename"><p>The event name, or an object containing event name properties.</p>
/// </param>
/// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p>
/// </param>
/// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference)
/// in which the handler function is executed.</p>
/// </param>
public void removeManagedListener(object item, object ename, System.Delegate fn=null, object scope=null){}
/// <summary>
/// Remove a single managed listener item
/// </summary>
/// <param name="isClear"><p>True if this is being called during a clear</p>
/// </param>
/// <param name="managedListener"><p>The managed listener item
/// See removeManagedListener for other args</p>
/// </param>
private void removeManagedListenerItem(bool isClear, object managedListener){}
/// <summary>
/// Resumes firing events (see suspendEvents).
/// If events were suspended using the <c>queueSuspended</c> parameter, then all events fired
/// during event suspension will be sent to any listeners now.
/// </summary>
public void resumeEvents(){}
/// <summary>
/// Suspends the firing of all events. (see resumeEvents)
/// </summary>
/// <param name="queueSuspended"><p>Pass as true to queue up suspended events to be fired
/// after the <see cref="Ext.util.Observable.resumeEvents">resumeEvents</see> call instead of discarding all suspended events.</p>
/// </param>
public void suspendEvents(bool queueSuspended){}
/// <summary>
/// Toggle whether or not to show the summary row.
/// </summary>
/// <param name="visible"><p>True to show the summary row</p>
/// </param>
public virtual void toggleSummaryRow(bool visible){}
/// <summary>
/// Shorthand for removeListener.
/// Removes an event handler.
/// </summary>
/// <param name="eventName"><p>The type of event the handler was associated with.</p>
/// </param>
/// <param name="fn"><p>The handler to remove. <strong>This must be a reference to the function passed into the
/// <see cref="Ext.util.Observable.addListener">addListener</see> call.</strong></p>
/// </param>
/// <param name="scope"><p>The scope originally specified for the handler. It must be the same as the
/// scope argument specified in the original call to <see cref="Ext.util.Observable.addListener">addListener</see> or the listener will not be removed.</p>
/// </param>
public void un(JsString eventName, System.Delegate fn, object scope=null){}
/// <summary>
/// Defaults to: <c>[]</c>
/// </summary>
[JsProperty(Name="$onExtended")]
private static JsArray @onExtended{get;set;}
public Summary(SummaryConfig config){}
public Summary(){}
public Summary(params object[] args){}
}
#endregion
#region SummaryConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class SummaryConfig : AbstractSummaryConfig
{
public SummaryConfig(params object[] args){}
}
#endregion
#region SummaryEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class SummaryEvents : AbstractSummaryEvents
{
public SummaryEvents(params object[] args){}
}
#endregion
}
| |
namespace RJP.MultiUrlPicker
{
using System;
using System.Collections.Generic;
using System.Linq;
using ClientDependency.Core;
using Newtonsoft.Json;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Services;
using Umbraco.Web;
using Umbraco.Web.PropertyEditors;
using Models;
using Constants = Umbraco.Core.Constants;
using Umbraco.Core.Configuration;
[PropertyEditorAsset(ClientDependencyType.Javascript, "~/App_Plugins/RJP.MultiUrlPicker/MultiUrlPicker.js")]
[PropertyEditor("RJP.MultiUrlPicker", "Multi Url Picker", "JSON",
"~/App_Plugins/RJP.MultiUrlPicker/MultiUrlPicker.html",
Group = "pickers", Icon = "icon-link", IsParameterEditor = true)]
public class MultiUrlPickerPropertyEditor : PropertyEditor
{
private IDictionary<string, object> _defaultPreValues;
public MultiUrlPickerPropertyEditor()
{
_defaultPreValues = new Dictionary<string, object>
{
{"minNumberOfItems", null},
{"maxNumberOfItems", null},
{"hideQuerystring", "0"},
{"hideTarget", "0"},
{"version", Information.Version.ToString(3)},
};
}
public override IDictionary<string, object> DefaultPreValues
{
get { return _defaultPreValues; }
set { _defaultPreValues = value; }
}
protected override PreValueEditor CreatePreValueEditor()
{
return new MultiUrlPickerPreValueEditor();
}
protected override PropertyValueEditor CreateValueEditor()
{
return new MultiUrlPickerPropertyValueEditor(base.CreateValueEditor());
}
private class MultiUrlPickerPreValueEditor : PreValueEditor
{
public MultiUrlPickerPreValueEditor()
{
Fields.AddRange(new[]
{
new PreValueField
{
Key = "minNumberOfItems",
Name = "Min number of items",
View = "number"
},
new PreValueField
{
Key = "maxNumberOfItems",
Name = "Max number of items",
View = "number"
},
new PreValueField
{
Key = "hideTarget",
Name = "Hide target/open in new window or tab checkbox",
View = "boolean"
},
new PreValueField
{
Key = "version",
Name = "Multi Url Picker version",
View = "hidden",
HideLabel = true
}
});
if (UmbracoVersion.Current < new Version(7, 12, 0))
{
// Umbraco 7.12 has it's own query string field which is not possible to hide at the time of writing
// so only add the field in older versions
Fields.Insert(2, new PreValueField
{
Key = "hideQuerystring",
Name = "Hide query string input",
View = "boolean"
});
}
}
public override IDictionary<string, object> ConvertDbToEditor(IDictionary<string, object> defaultPreVals, PreValueCollection persistedPreVals)
{
// if there isn't a version stored set it to 0 for backwards compatibility
if (!persistedPreVals.PreValuesAsDictionary.ContainsKey("version"))
{
persistedPreVals.PreValuesAsDictionary["version"] = new PreValue("0");
}
return base.ConvertDbToEditor(defaultPreVals, persistedPreVals);
}
}
private class MultiUrlPickerPropertyValueEditor : PropertyValueEditorWrapper
{
public MultiUrlPickerPropertyValueEditor(PropertyValueEditor wrapped) : base(wrapped)
{
}
public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
{
string value = property.Value?.ToString();
if (string.IsNullOrEmpty(value))
{
return Enumerable.Empty<object>();
}
try
{
ServiceContext services = ApplicationContext.Current.Services;
IEntityService entityService = services.EntityService;
IContentTypeService contentTypeService = services.ContentTypeService;
var links = JsonConvert.DeserializeObject<List<LinkDto>>(value);
var documentLinks = links.FindAll(link =>
link.Id.HasValue && false == link.IsMedia.GetValueOrDefault() ||
link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Document
);
var mediaLinks = links.FindAll(link =>
link.Id.HasValue && true == link.IsMedia.GetValueOrDefault() ||
link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Media
);
List<IUmbracoEntity> entities = new List<IUmbracoEntity>();
if (documentLinks.Count > 0)
{
if (documentLinks[0].Id.HasValue)
{
entities.AddRange(
entityService.GetAll(UmbracoObjectTypes.Document, documentLinks.Select(link => link.Id.Value).ToArray())
);
}
else
{
entities.AddRange(
entityService.GetAll(UmbracoObjectTypes.Document, documentLinks.Select(link => link.Udi.Guid).ToArray())
);
}
}
if (mediaLinks.Count > 0)
{
if (mediaLinks[0].Id.HasValue)
{
entities.AddRange(
entityService.GetAll(UmbracoObjectTypes.Media, mediaLinks.Select(link => link.Id.Value).ToArray())
);
}
else
{
entities.AddRange(
entityService.GetAll(UmbracoObjectTypes.Media, mediaLinks.Select(link => link.Udi.Guid).ToArray())
);
}
}
var result = new List<LinkDisplay>();
foreach (LinkDto dto in links)
{
if (dto.Id.HasValue || dto.Udi != null)
{
IUmbracoEntity entity = entities.Find(e => e.Key == dto.Udi?.Guid || e.Id == dto.Id);
if (entity == null)
{
continue;
}
string entityType = Equals(entity.AdditionalData["NodeObjectTypeId"], Constants.ObjectTypes.MediaGuid) ?
Constants.UdiEntityType.Media :
Constants.UdiEntityType.Document;
var udi = new GuidUdi(entityType, entity.Key);
string contentTypeAlias = entity.AdditionalData["ContentTypeAlias"] as string;
string icon;
bool isMedia = false;
bool published = Equals(entity.AdditionalData["IsPublished"], true);
string url = dto.Url;
if (string.IsNullOrEmpty(contentTypeAlias))
{
continue;
}
if (udi.EntityType == Constants.UdiEntityType.Document)
{
IContentType contentType = contentTypeService.GetContentType(contentTypeAlias);
if (contentType == null)
{
continue;
}
icon = contentType.Icon;
if (UmbracoContext.Current != null)
{
url = UmbracoContext.Current.UrlProvider.GetUrl(entity.Id);
}
}
else
{
IMediaType mediaType = contentTypeService.GetMediaType(contentTypeAlias);
if (mediaType == null)
{
continue;
}
icon = mediaType.Icon;
isMedia = true;
published = true;
if (UmbracoContext.Current != null)
{
url = UmbracoContext.Current.MediaCache.GetById(entity.Id)?.Url;
}
}
result.Add(new LinkDisplay
{
Icon = icon,
Id = entity.Id,
IsMedia = isMedia,
Name = dto.Name,
Target = dto.Target,
Published = published,
Udi = udi,
Url = url,
Querystring = dto.Querystring
});
}
else
{
result.Add(new LinkDisplay
{
Icon = "icon-link",
Name = dto.Name,
Published = true,
Target = dto.Target,
Url = dto.Url,
Querystring = dto.Querystring
});
}
}
return result;
}
catch (Exception ex)
{
ApplicationContext.Current.ProfilingLogger.Logger.Error<MultiUrlPickerPropertyValueEditor>("Error getting links", ex);
}
return base.ConvertDbToEditor(property, propertyType, dataTypeService);
}
public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue)
{
string value = editorValue.Value?.ToString();
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
try
{
return JsonConvert.SerializeObject(
from link in JsonConvert.DeserializeObject<List<LinkDisplay>>(value)
select new LinkDto
{
Name = link.Name,
Target = link.Target,
Udi = link.Udi,
Url = link.Udi == null ? link.Url : null, // only save the url for external links
Querystring = link.Querystring
},
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
}
catch (Exception ex)
{
ApplicationContext.Current.ProfilingLogger.Logger.Error<MultiUrlPickerPropertyValueEditor>("Error saving links", ex);
}
return base.ConvertEditorToDb(editorValue, currentValue);
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Brown Univerity" file="FileOperation.cs">
// Public Domain
// </copyright>
// <summary>
// The file operation.
// </summary>
//
// --------------------------------------------------------------------------------------------------------------------
namespace FileOperation
{
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Windows.Forms;
/// <summary>
/// The file operation.
/// </summary>
public class FileOperation : IDisposable
{
/// <summary>
/// The file operation.
/// </summary>
private readonly IFileOperation fileOperation;
/// <summary>
/// The callback sink.
/// </summary>
private readonly FileOperationProgressSink callbackSink;
/// <summary>
/// The sink cookie.
/// </summary>
private readonly uint sinkCookie;
/// <summary>
/// The COM GUID for file operation
/// </summary>
private static readonly Guid ClsidFileOperation = new Guid("3ad05575-8857-4850-9277-11b85bdb8e09");
/// <summary>
/// The file operation type.
/// </summary>
private static readonly Type FileOperationType = Type.GetTypeFromCLSID(ClsidFileOperation);
/// <summary>
/// The shell item guid.
/// </summary>
private static Guid shellItemGuid = typeof(IShellItem).GUID;
/// <summary>
/// The _disposed.
/// </summary>
private bool disposed;
/// <summary>
/// Initializes a new instance of the <see cref="FileOperation"/> class.
/// </summary>
public FileOperation()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FileOperation"/> class.
/// </summary>
/// <param name="callbackSink">
/// The callback sink.
/// </param>
public FileOperation(FileOperationProgressSink callbackSink)
: this(callbackSink, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FileOperation"/> class.
/// </summary>
/// <param name="callbackSink">
/// The callback sink.
/// </param>
/// <param name="owner">
/// The owner.
/// </param>
public FileOperation(FileOperationProgressSink callbackSink, IWin32Window owner)
{
this.callbackSink = callbackSink;
this.fileOperation = (IFileOperation)Activator.CreateInstance(FileOperationType);
this.fileOperation.SetOperationFlags(FileOperationFlags.FOF_NOCONFIRMMKDIR | FileOperationFlags.FOF_SILENT | FileOperationFlags.FOFX_SHOWELEVATIONPROMPT | FileOperationFlags.FOFX_NOCOPYHOOKS | FileOperationFlags.FOFX_REQUIREELEVATION);
if (this.callbackSink != null)
{
this.sinkCookie = this.fileOperation.Advise(this.callbackSink);
}
if (owner != null)
{
this.fileOperation.SetOwnerWindow((uint)owner.Handle);
}
}
/// <summary>
/// The copy item.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <param name="destination">
/// The destination.
/// </param>
/// <param name="newName">
/// The new name.
/// </param>
public void CopyItem(string source, string destination, string newName)
{
this.ThrowIfDisposed();
using (var sourceItem = CreateShellItem(source))
using (var destinationItem = CreateShellItem(destination))
{
this.fileOperation.CopyItem(sourceItem.Item, destinationItem.Item, newName, null);
}
}
/// <summary>
/// The move item.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <param name="destination">
/// The destination.
/// </param>
/// <param name="newName">
/// The new name.
/// </param>
public void MoveItem(string source, string destination, string newName)
{
this.ThrowIfDisposed();
using (var sourceItem = CreateShellItem(source))
using (var destinationItem = CreateShellItem(destination))
{
this.fileOperation.MoveItem(sourceItem.Item, destinationItem.Item, newName, null);
}
}
/// <summary>
/// The rename item.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <param name="newName">
/// The new name.
/// </param>
public void RenameItem(string source, string newName)
{
this.ThrowIfDisposed();
using (var sourceItem = CreateShellItem(source))
{
this.fileOperation.RenameItem(sourceItem.Item, newName, null);
}
}
/// <summary>
/// The delete item.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
public void DeleteItem(string source)
{
this.ThrowIfDisposed();
using (var sourceItem = CreateShellItem(source))
{
this.fileOperation.DeleteItem(sourceItem.Item, null);
}
}
/// <summary>
/// News the item.
/// </summary>
/// <param name="folderName">Name of the folder.</param>
/// <param name="name">The file name.</param>
/// <param name="attrs">The file attributes.</param>
/// <remarks></remarks>
public void NewItem(string folderName, string name, FileAttributes attrs)
{
this.ThrowIfDisposed();
using (var folderItem = CreateShellItem(folderName))
{
this.fileOperation.NewItem(folderItem.Item, attrs, name, string.Empty, this.callbackSink);
}
}
/// <summary>
/// The perform operations.
/// </summary>
public void PerformOperations()
{
this.ThrowIfDisposed();
this.fileOperation.PerformOperations();
}
/// <summary>
/// The dispose method
/// </summary>
public void Dispose()
{
if (this.disposed)
{
return;
}
this.disposed = true;
if (this.callbackSink != null)
{
this.fileOperation.Unadvise(this.sinkCookie);
}
Marshal.FinalReleaseComObject(this.fileOperation);
}
/// <summary>
/// The create shell item.
/// </summary>
/// <param name="path">
/// The output path.
/// </param>
/// <returns>
/// The Shell Item if it exists
/// </returns>
private static ComReleaser<IShellItem> CreateShellItem(string path)
{
return new ComReleaser<IShellItem>(
(IShellItem)SHCreateItemFromParsingName(path, null, ref shellItemGuid));
}
/// <summary>
/// Create shell item from name
/// </summary>
/// <param name="pszPath">
/// The output path.
/// </param>
/// <param name="pbc">
/// The binding context.
/// </param>
/// <param name="riid">
/// The id guid .
/// </param>
/// <returns>
/// The shell item.
/// </returns>
[DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Unicode, PreserveSig = false)]
[return: MarshalAs(UnmanagedType.Interface)]
private static extern object SHCreateItemFromParsingName(
[MarshalAs(UnmanagedType.LPWStr)] string pszPath, IBindCtx pbc, ref Guid riid);
/// <summary>
/// The throw if disposed.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// </exception>
private void ThrowIfDisposed()
{
if (this.disposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using NAudio.Wave;
namespace NAudio.Midi
{
internal class MidiInterop
{
public enum MidiInMessage
{
/// <summary>
/// MIM_OPEN
/// </summary>
Open = 0x3C1,
/// <summary>
/// MIM_CLOSE
/// </summary>
Close = 0x3C2,
/// <summary>
/// MIM_DATA
/// </summary>
Data = 0x3C3,
/// <summary>
/// MIM_LONGDATA
/// </summary>
LongData = 0x3C4,
/// <summary>
/// MIM_ERROR
/// </summary>
Error = 0x3C5,
/// <summary>
/// MIM_LONGERROR
/// </summary>
LongError = 0x3C6,
/// <summary>
/// MIM_MOREDATA
/// </summary>
MoreData = 0x3CC,
}
public enum MidiOutMessage
{
/// <summary>
/// MOM_OPEN
/// </summary>
Open = 0x3C7,
/// <summary>
/// MOM_CLOSE
/// </summary>
Close = 0x3C8,
/// <summary>
/// MOM_DONE
/// </summary>
Done = 0x3C9
}
// http://msdn.microsoft.com/en-us/library/dd798460%28VS.85%29.aspx
public delegate void MidiInCallback(IntPtr midiInHandle, MidiInMessage message, IntPtr userData, IntPtr messageParameter1, IntPtr messageParameter2);
// http://msdn.microsoft.com/en-us/library/dd798478%28VS.85%29.aspx
public delegate void MidiOutCallback(IntPtr midiInHandle, MidiOutMessage message, IntPtr userData, IntPtr messageParameter1, IntPtr messageParameter2);
// http://msdn.microsoft.com/en-us/library/dd798446%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiConnect(IntPtr hMidiIn, IntPtr hMidiOut, IntPtr pReserved);
// http://msdn.microsoft.com/en-us/library/dd798447%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiDisconnect(IntPtr hMidiIn, IntPtr hMidiOut, IntPtr pReserved);
// http://msdn.microsoft.com/en-us/library/dd798450%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiInAddBuffer(IntPtr hMidiIn, [MarshalAs(UnmanagedType.Struct)] ref MIDIHDR lpMidiInHdr, int uSize);
// http://msdn.microsoft.com/en-us/library/dd798452%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiInClose(IntPtr hMidiIn);
// http://msdn.microsoft.com/en-us/library/dd798453%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Auto)]
public static extern MmResult midiInGetDevCaps(IntPtr deviceId, out MidiInCapabilities capabilities, int size);
// http://msdn.microsoft.com/en-us/library/dd798454%28VS.85%29.aspx
// TODO: review this, probably doesn't work
[DllImport("winmm.dll")]
public static extern MmResult midiInGetErrorText(int err, string lpText, int uSize);
// http://msdn.microsoft.com/en-us/library/dd798455%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiInGetID(IntPtr hMidiIn, out int lpuDeviceId);
// http://msdn.microsoft.com/en-us/library/dd798456%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern int midiInGetNumDevs();
// http://msdn.microsoft.com/en-us/library/dd798457%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiInMessage(IntPtr hMidiIn, int msg, IntPtr dw1, IntPtr dw2);
// http://msdn.microsoft.com/en-us/library/dd798458%28VS.85%29.aspx
[DllImport("winmm.dll", EntryPoint = "midiInOpen")]
public static extern MmResult midiInOpen(out IntPtr hMidiIn, IntPtr uDeviceID, MidiInCallback callback, IntPtr dwInstance, int dwFlags);
// http://msdn.microsoft.com/en-us/library/dd798458%28VS.85%29.aspx
[DllImport("winmm.dll", EntryPoint = "midiInOpen")]
public static extern MmResult midiInOpenWindow(out IntPtr hMidiIn, IntPtr uDeviceID, IntPtr callbackWindowHandle, IntPtr dwInstance, int dwFlags);
// http://msdn.microsoft.com/en-us/library/dd798459%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiInPrepareHeader(IntPtr hMidiIn, [MarshalAs(UnmanagedType.Struct)] ref MIDIHDR lpMidiInHdr, int uSize);
// http://msdn.microsoft.com/en-us/library/dd798461%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiInReset(IntPtr hMidiIn);
// http://msdn.microsoft.com/en-us/library/dd798462%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiInStart(IntPtr hMidiIn);
// http://msdn.microsoft.com/en-us/library/dd798463%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiInStop(IntPtr hMidiIn);
// http://msdn.microsoft.com/en-us/library/dd798464%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiInUnprepareHeader(IntPtr hMidiIn, [MarshalAs(UnmanagedType.Struct)] ref MIDIHDR lpMidiInHdr, int uSize);
// http://msdn.microsoft.com/en-us/library/dd798465%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutCacheDrumPatches(IntPtr hMidiOut, int uPatch, IntPtr lpKeyArray, int uFlags);
// http://msdn.microsoft.com/en-us/library/dd798466%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutCachePatches(IntPtr hMidiOut, int uBank, IntPtr lpPatchArray, int uFlags);
// http://msdn.microsoft.com/en-us/library/dd798468%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutClose(IntPtr hMidiOut);
// http://msdn.microsoft.com/en-us/library/dd798469%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Auto)]
public static extern MmResult midiOutGetDevCaps(IntPtr deviceNumber, out MidiOutCapabilities caps, int uSize);
// http://msdn.microsoft.com/en-us/library/dd798470%28VS.85%29.aspx
// TODO: review, probably doesn't work
[DllImport("winmm.dll")]
public static extern MmResult midiOutGetErrorText(IntPtr err, string lpText, int uSize);
// http://msdn.microsoft.com/en-us/library/dd798471%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutGetID(IntPtr hMidiOut, out int lpuDeviceID);
// http://msdn.microsoft.com/en-us/library/dd798472%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern int midiOutGetNumDevs();
// http://msdn.microsoft.com/en-us/library/dd798473%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutGetVolume(IntPtr uDeviceID, ref int lpdwVolume);
// http://msdn.microsoft.com/en-us/library/dd798474%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutLongMsg(IntPtr hMidiOut, [MarshalAs(UnmanagedType.Struct)] ref MIDIHDR lpMidiOutHdr, int uSize);
// http://msdn.microsoft.com/en-us/library/dd798475%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutMessage(IntPtr hMidiOut, int msg, IntPtr dw1, IntPtr dw2);
// http://msdn.microsoft.com/en-us/library/dd798476%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutOpen(out IntPtr lphMidiOut, IntPtr uDeviceID, MidiOutCallback dwCallback, IntPtr dwInstance, int dwFlags);
// http://msdn.microsoft.com/en-us/library/dd798477%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutPrepareHeader(IntPtr hMidiOut, [MarshalAs(UnmanagedType.Struct)] ref MIDIHDR lpMidiOutHdr, int uSize);
// http://msdn.microsoft.com/en-us/library/dd798479%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutReset(IntPtr hMidiOut);
// http://msdn.microsoft.com/en-us/library/dd798480%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutSetVolume(IntPtr hMidiOut, int dwVolume);
// http://msdn.microsoft.com/en-us/library/dd798481%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutShortMsg(IntPtr hMidiOut, int dwMsg);
// http://msdn.microsoft.com/en-us/library/dd798482%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiOutUnprepareHeader(IntPtr hMidiOut, [MarshalAs(UnmanagedType.Struct)] ref MIDIHDR lpMidiOutHdr, int uSize);
// http://msdn.microsoft.com/en-us/library/dd798485%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiStreamClose(IntPtr hMidiStream);
// http://msdn.microsoft.com/en-us/library/dd798486%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiStreamOpen(out IntPtr hMidiStream, IntPtr puDeviceID, int cMidi, IntPtr dwCallback, IntPtr dwInstance, int fdwOpen);
// http://msdn.microsoft.com/en-us/library/dd798487%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiStreamOut(IntPtr hMidiStream, [MarshalAs(UnmanagedType.Struct)] ref MIDIHDR pmh, int cbmh);
// http://msdn.microsoft.com/en-us/library/dd798488%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiStreamPause(IntPtr hMidiStream);
// http://msdn.microsoft.com/en-us/library/dd798489%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiStreamPosition(IntPtr hMidiStream, [MarshalAs(UnmanagedType.Struct)] ref MMTIME lpmmt, int cbmmt);
// http://msdn.microsoft.com/en-us/library/dd798490%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiStreamProperty(IntPtr hMidiStream, IntPtr lppropdata, int dwProperty);
// http://msdn.microsoft.com/en-us/library/dd798491%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiStreamRestart(IntPtr hMidiStream);
// http://msdn.microsoft.com/en-us/library/dd798492%28VS.85%29.aspx
[DllImport("winmm.dll")]
public static extern MmResult midiStreamStop(IntPtr hMidiStream);
// TODO: this is general MM interop
public const int CALLBACK_FUNCTION = 0x30000;
public const int CALLBACK_NULL = 0;
// http://msdn.microsoft.com/en-us/library/dd757347%28VS.85%29.aspx
// TODO: not sure this is right
[StructLayout(LayoutKind.Sequential)]
public struct MMTIME
{
public int wType;
public int u;
}
// TODO: check for ANSI strings in these structs
// TODO: check for WORD params
[StructLayout(LayoutKind.Sequential)]
public struct MIDIEVENT
{
public int dwDeltaTime;
public int dwStreamID;
public int dwEvent;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public int dwParms;
}
// http://msdn.microsoft.com/en-us/library/dd798449%28VS.85%29.aspx
[StructLayout(LayoutKind.Sequential)]
public struct MIDIHDR
{
public string lpData;
public int dwBufferLength;
public int dwBytesRecorded;
public IntPtr dwUser;
public int dwFlags;
public IntPtr lpNext;
public IntPtr reserved;
public int dwOffset;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public int[] dwReserved;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIDIPROPTEMPO
{
public int cbStruct;
public int dwTempo;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: A Stream whose backing store is memory. Great
** for temporary storage without creating a temp file. Also
** lets users expose a byte[] as a stream.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Permissions;
namespace System.IO {
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
//
// There are two ways to create a MemoryStream. You can initialize one
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
[Serializable]
[ComVisible(true)]
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
private int _origin; // For user-provided arrays, start at this origin
private int _position; // read/write head.
[ContractPublicPropertyName("Length")]
private int _length; // Number of bytes within the memory stream
private int _capacity; // length of usable portion of buffer for stream
// Note that _capacity == _buffer.Length for non-user-provided byte[]'s
private bool _expandable; // User-provided buffers aren't expandable.
private bool _writable; // Can user write to this stream?
private bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
[NonSerialized]
private Task<int> _lastReadTask; // The last successful task returned from ReadAsync
private const int MemStreamMaxLength = Int32.MaxValue;
public MemoryStream()
: this(0) {
}
public MemoryStream(int capacity) {
if (capacity < 0) {
throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
Contract.EndContractBlock();
_buffer = capacity != 0 ? new byte[capacity] : EmptyArray<byte>.Value;
_capacity = capacity;
_expandable = true;
_writable = true;
_exposable = true;
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
public MemoryStream(byte[] buffer)
: this(buffer, true) {
}
public MemoryStream(byte[] buffer, bool writable) {
if (buffer == null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
Contract.EndContractBlock();
_buffer = buffer;
_length = _capacity = buffer.Length;
_writable = writable;
_exposable = false;
_origin = 0;
_isOpen = true;
}
public MemoryStream(byte[] buffer, int index, int count)
: this(buffer, index, count, true, false) {
}
public MemoryStream(byte[] buffer, int index, int count, bool writable)
: this(buffer, index, count, writable, false) {
}
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
_writable = writable;
_exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array?
_expandable = false;
_isOpen = true;
}
public override bool CanRead {
[Pure]
get { return _isOpen; }
}
public override bool CanSeek {
[Pure]
get { return _isOpen; }
}
public override bool CanWrite {
[Pure]
get { return _writable; }
}
private void EnsureWriteable() {
if (!CanWrite) __Error.WriteNotSupported();
}
protected override void Dispose(bool disposing)
{
try {
if (disposing) {
_isOpen = false;
_writable = false;
_expandable = false;
// Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work.
_lastReadTask = null;
}
}
finally {
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value) {
// Check for overflow
if (value < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (value > _capacity) {
int newCapacity = value;
if (newCapacity < 256)
newCapacity = 256;
// We are ok with this overflowing since the next statement will deal
// with the cases where _capacity*2 overflows.
if (newCapacity < _capacity * 2)
newCapacity = _capacity * 2;
// We want to expand the array up to Array.MaxArrayLengthOneDimensional
// And we want to give the user the value that they asked for
if ((uint)(_capacity * 2) > Array.MaxByteArrayLength)
newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength;
Capacity = newCapacity;
return true;
}
return false;
}
public override void Flush() {
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try {
Flush();
return Task.CompletedTask;
} catch(Exception ex) {
return Task.FromException(ex);
}
}
public virtual byte[] GetBuffer() {
if (!_exposable)
throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
return _buffer;
}
public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) {
if (!_exposable) {
buffer = default(ArraySegment<byte>);
return false;
}
buffer = new ArraySegment<byte>(_buffer, offset:_origin, count:(_length - _origin));
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
internal byte[] InternalGetBuffer() {
return _buffer;
}
// PERF: Get origin and length - used in ResourceWriter.
[FriendAccessAllowed]
internal void InternalGetOriginAndLength(out int origin, out int length)
{
if (!_isOpen) __Error.StreamIsClosed();
origin = _origin;
length = _length;
}
// PERF: True cursor position, we don't need _origin for direct access
internal int InternalGetPosition() {
if (!_isOpen) __Error.StreamIsClosed();
return _position;
}
// PERF: Takes out Int32 as fast as possible
internal int InternalReadInt32() {
if (!_isOpen)
__Error.StreamIsClosed();
int pos = (_position += 4); // use temp to avoid a race condition
if (pos > _length)
{
_position = _length;
__Error.EndOfFile();
}
return (int)(_buffer[pos-4] | _buffer[pos-3] << 8 | _buffer[pos-2] << 16 | _buffer[pos-1] << 24);
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
internal int InternalEmulateRead(int count) {
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
if (n > count) n = count;
if (n < 0) n = 0;
Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
public virtual int Capacity {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _capacity - _origin;
}
set {
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
if (value < Length) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
Contract.Ensures(_capacity - _origin == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable();
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
if (_expandable && value != _capacity) {
if (value > 0) {
byte[] newBuffer = new byte[value];
if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length);
_buffer = newBuffer;
}
else {
_buffer = null;
}
_capacity = value;
}
}
}
public override long Length {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _length - _origin;
}
}
public override long Position {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _position - _origin;
}
set {
if (value < 0)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Position == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (value > MemStreamMaxLength)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
_position = _origin + (int)value;
}
}
public override int Read([In, Out] byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
if (n > count) n = count;
if (n <= 0)
return 0;
Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
int byteCount = n;
while (--byteCount >= 0)
buffer[offset + byteCount] = _buffer[_position + byteCount];
}
else
Buffer.InternalBlockCopy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Read(...)
// If cancellation was requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
try
{
int n = Read(buffer, offset, count);
var t = _lastReadTask;
Contract.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<int>(oce);
}
catch (Exception exception)
{
return Task.FromException<int>(exception);
}
}
public override int ReadByte() {
if (!_isOpen) __Error.StreamIsClosed();
if (_position >= _length) return -1;
return _buffer[_position++];
}
public override void CopyTo(Stream destination, int bufferSize)
{
// Since we did not originally override this method, validate the arguments
// the same way Stream does for back-compat.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
base.CopyTo(destination, bufferSize);
return;
}
int originalPosition = _position;
// Seek to the end of the MemoryStream.
int remaining = InternalEmulateRead(_length - originalPosition);
// If we were already at or past the end, there's no copying to do so just quit.
if (remaining > 0)
{
// Call Write() on the other Stream, using our internal buffer and avoiding any
// intermediary allocations.
destination.Write(_buffer, originalPosition, remaining);
}
}
public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) {
// This implementation offers beter performance compared to the base class version.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into ReadAsync) when we are not sure.
if (this.GetType() != typeof(MemoryStream))
return base.CopyToAsync(destination, bufferSize, cancellationToken);
// If cancelled - return fast:
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
Int32 pos = _position;
Int32 n = InternalEmulateRead(_length - _position);
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
if (memStrDest == null)
return destination.WriteAsync(_buffer, pos, n, cancellationToken);
try {
// If destination is a MemoryStream, CopyTo synchronously:
memStrDest.Write(_buffer, pos, n);
return Task.CompletedTask;
} catch(Exception ex) {
return Task.FromException(ex);
}
}
public override long Seek(long offset, SeekOrigin loc) {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > MemStreamMaxLength)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
switch(loc) {
case SeekOrigin.Begin: {
int tempPosition = unchecked(_origin + (int)offset);
if (offset < 0 || tempPosition < _origin)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
case SeekOrigin.Current: {
int tempPosition = unchecked(_position + (int)offset);
if (unchecked(_position + offset) < _origin || tempPosition < _origin)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
case SeekOrigin.End: {
int tempPosition = unchecked(_length + (int)offset);
if ( unchecked(_length + offset) < _origin || tempPosition < _origin )
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
}
Contract.Assert(_position >= 0, "_position >= 0");
return _position;
}
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, Int32.MaxValue - origin
// Origin is 0 in all cases other than a MemoryStream created on
// top of an existing array and a specific starting offset was passed
// into the MemoryStream constructor. The upper bounds prevents any
// situations where a stream may be created on top of an array then
// the stream is made longer than the maximum possible length of the
// array (Int32.MaxValue).
//
public override void SetLength(long value) {
if (value < 0 || value > Int32.MaxValue) {
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
Contract.Ensures(_length - _origin == value);
Contract.EndContractBlock();
EnsureWriteable();
// Origin wasn't publicly exposed above.
Contract.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (Int32.MaxValue - _origin)) {
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
Array.Clear(_buffer, _length, newLength - _length);
_length = newLength;
if (_position > newLength) _position = newLength;
}
public virtual byte[] ToArray() {
BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy.");
byte[] copy = new byte[_length - _origin];
Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
int i = _position + count;
// Check for overflow
if (i < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (i > _length) {
bool mustZero = _position > _length;
if (i > _capacity) {
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
mustZero = false;
}
if (mustZero)
Array.Clear(_buffer, _length, i - _length);
_length = i;
}
if ((count <= 8) && (buffer != _buffer))
{
int byteCount = count;
while (--byteCount >= 0)
_buffer[_position + byteCount] = buffer[offset + byteCount];
}
else
Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count);
_position = i;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Write(...)
// If cancellation is already requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<VoidTaskResult>(oce);
}
catch (Exception exception)
{
return Task.FromException(exception);
}
}
public override void WriteByte(byte value) {
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
if (_position >= _length) {
int newLength = _position + 1;
bool mustZero = _position > _length;
if (newLength >= _capacity) {
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
mustZero = false;
}
if (mustZero)
Array.Clear(_buffer, _length, _position - _length);
_length = newLength;
}
_buffer[_position++] = value;
}
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream) {
if (stream==null)
throw new ArgumentNullException("stream", Environment.GetResourceString("ArgumentNull_Stream"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
stream.Write(_buffer, _origin, _length - _origin);
}
}
}
| |
/*
* Copyright (c) 2009 Jim Radford http://www.jimradford.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.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Microsoft.Win32;
using WeifenLuo.WinFormsUI.Docking;
using log4net;
using System.Xml.Serialization;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Drawing.Design;
using System.Drawing;
using System.Windows.Forms.Design;
using SuperPutty.Gui;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.ComponentModel.Design;
namespace SuperPutty.Data
{
public enum ConnectionProtocol
{
SSH,
SSH2,
Telnet,
Rlogin,
Raw,
Serial,
Cygterm,
Mintty
}
/// <summary>The main class containing configuration settings for a session</summary>
public class SessionData : IComparable, ICloneable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(SessionData));
public delegate void OnPropertyChangedHandler(SessionData Session, String AttributeName);
public delegate void OnPropertyChangingHandler(SessionData Session, String AttributeName, Object NewValue, ref bool CancelChange);
[XmlIgnore]
public OnPropertyChangedHandler OnPropertyChanged;
[XmlIgnore]
public OnPropertyChangingHandler OnPropertyChanging;
/// <summary>Full session id (includes path for session tree)e.g. FolderName/SessionName</summary>
private string _SessionId;
[XmlAttribute]
[Browsable(false)]
public string SessionId
{
get { return this._SessionId; }
set
{
if (_SessionId != value)
{
this.OldSessionId = SessionId;
UpdateField(ref _SessionId, value, "SessionId");
}
}
}
internal string OldSessionId { get; set; }
private string _OldName;
[XmlIgnore]
[Browsable(false)]
public string OldName
{
get { return _OldName; }
set
{
UpdateField(ref _OldName, value, "OldName");
}
}
private string _SessionName;
[XmlAttribute]
[DisplayName("Session Name")]
[Description("This is the name of the session.")]
public string SessionName
{
get { return _SessionName; }
set
{
if (_SessionName != value)
{
OldName = _SessionName;
UpdateField(ref _SessionName, value, "SessionName");
if (SessionId == null)
{
SessionId = value;
}
}
}
}
private string _ImageKey;
/// <summary>A string containing the key of the image associated with this session</summary>
[XmlAttribute]
[DisplayName("Image")]
[Description("This is the image associated to the session.")]
[Editor(typeof(ImageKeyEditor), typeof(UITypeEditor))]
[TypeConverter(typeof(ImageKeyConverter))]
public string ImageKey
{
get { return _ImageKey; }
set
{
UpdateField(ref _ImageKey, value, "ImageKey");
}
}
private string _Host;
[XmlAttribute]
[DisplayName("Host Name/Ip")]
[Description("This is the host name or the IP address of the destination.")]
public string Host
{
get { return _Host; }
set
{
UpdateField(ref _Host, value, "Host");
}
}
private int _Port;
[XmlAttribute]
[DisplayName("Port")]
[Description("This is the port that will be used to connect to the destination.")]
public int Port
{
get { return _Port; }
set
{
UpdateField(ref _Port, value, "Port");
}
}
private ConnectionProtocol _Proto;
[XmlAttribute]
[DisplayName("Connection Type")]
[Description("This is the login protocol.")]
public ConnectionProtocol Proto
{
get { return _Proto; }
set
{
UpdateField(ref _Proto, value, "Proto");
}
}
private string _PuttySession;
[XmlAttribute]
[TypeConverter(typeof(PuttySessionConverter))]
[DisplayName("Putty Profile")]
[Description("This is the PuTTY session profile associated to this session.")]
public string PuttySession
{
get { return _PuttySession; }
set
{
UpdateField(ref _PuttySession, value, "PuttySession");
}
}
private string _Username;
[XmlAttribute]
[DisplayName("Username")]
[Description("This is the username that will be used to login.")]
public string Username
{
get { return _Username; }
set
{
UpdateField(ref _Username, value, "Username");
}
}
private string _Password;
[XmlIgnore]
[Browsable(false)]
public string Password
{
get { return _Password; }
set
{
UpdateField(ref _Password, value, "Password");
}
}
private string _ExtraArgs;
[XmlAttribute]
[DisplayName("Extra Arguments")]
[Description("Extra PuTTY arguments.")]
public string ExtraArgs
{
get { return _ExtraArgs; }
set
{
UpdateField(ref _ExtraArgs, value, "ExtraArgs");
}
}
private DockState m_LastDockstate = DockState.Document;
[XmlIgnore]
[Browsable(false)]
public DockState LastDockstate
{
get { return m_LastDockstate; }
set
{
UpdateField(ref m_LastDockstate, value, "LastDockstate");
}
}
private bool m_AutoStartSession = false;
[XmlIgnore]
[Browsable(false)]
public bool AutoStartSession
{
get { return m_AutoStartSession; }
set
{
UpdateField(ref m_AutoStartSession, value, "AutoStartSession");
}
}
/// <summary>Construct a new session data object</summary>
/// <param name="sessionName">A string representing the name of the session</param>
/// <param name="hostName">The hostname or ip address of the remote host</param>
/// <param name="port">The port on the remote host</param>
/// <param name="protocol">The protocol to use when connecting to the remote host</param>
/// <param name="sessionConfig">the name of the saved configuration settings from putty to use</param>
public SessionData(string sessionName, string hostName, int port, ConnectionProtocol protocol, string sessionConfig)
{
SessionName = sessionName;
Host = hostName;
Port = port;
Proto = protocol;
PuttySession = sessionConfig;
}
/// <summary>Default constructor, instantiate a new <seealso cref="SessionData"/> object</summary>
public SessionData()
{
}
private void UpdateField<T>(ref T Field, T NewValue, string PropertyName)
{
if (!EqualityComparer<T>.Default.Equals(Field, NewValue))
{
Object NewValueObj = NewValue;
bool CancelChange = false;
if (OnPropertyChanging != null)
OnPropertyChanging(this, PropertyName, NewValueObj, ref CancelChange);
if (!CancelChange)
{
Field = NewValue;
if (OnPropertyChanged != null)
OnPropertyChanged(this, PropertyName);
}
}
}
/// <summary>Read any existing saved sessions from the registry, decode and populate a list containing the data</summary>
/// <returns>A list containing the configuration entries retrieved from the registry</returns>
public static List<SessionData> LoadSessionsFromRegistry()
{
Log.Info("LoadSessionsFromRegistry...");
List<SessionData> sessionList = new List<SessionData>();
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions");
if (key != null)
{
string[] sessionKeys = key.GetSubKeyNames();
foreach (string session in sessionKeys)
{
SessionData sessionData = new SessionData();
RegistryKey itemKey = key.OpenSubKey(session);
if (itemKey != null)
{
sessionData.Host = (string)itemKey.GetValue("Host", "");
sessionData.Port = (int)itemKey.GetValue("Port", 22);
sessionData.Proto = (ConnectionProtocol)Enum.Parse(typeof(ConnectionProtocol), (string)itemKey.GetValue("Proto", "SSH"));
sessionData.PuttySession = (string)itemKey.GetValue("PuttySession", "Default Session");
sessionData.SessionName = session;
sessionData.SessionId = (string)itemKey.GetValue("SessionId", session);
sessionData.Username = (string)itemKey.GetValue("Login", "");
sessionData.LastDockstate = (DockState)itemKey.GetValue("Last Dock", DockState.Document);
sessionData.AutoStartSession = bool.Parse((string)itemKey.GetValue("Auto Start", "False"));
sessionList.Add(sessionData);
}
}
}
return sessionList;
}
/// <summary>Load session configuration data from the specified XML file</summary>
/// <param name="fileName">The filename containing the settings</param>
/// <returns>A <seealso cref="List"/> containing the session configuration data</returns>
public static List<SessionData> LoadSessionsFromFile(string fileName)
{
List<SessionData> sessions = new List<SessionData>();
if (File.Exists(fileName))
{
WorkaroundCygwinBug();
XmlSerializer s = new XmlSerializer(sessions.GetType());
using (TextReader r = new StreamReader(fileName))
{
sessions = (List<SessionData>)s.Deserialize(r);
}
Log.InfoFormat("Loaded {0} sessions from {1}", sessions.Count, fileName);
}
else
{
Log.WarnFormat("Could not load sessions, file doesn't exist. file={0}", fileName);
}
return sessions;
}
static void WorkaroundCygwinBug()
{
try
{
// work around known bug with cygwin
Dictionary<string, string> envVars = new Dictionary<string, string>();
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
{
string envVar = (string) de.Key;
if (envVars.ContainsKey(envVar.ToUpper()))
{
// duplicate found... (e.g. TMP and tmp)
Log.DebugFormat("Clearing duplicate envVariable, {0}", envVar);
Environment.SetEnvironmentVariable(envVar, null);
continue;
}
envVars.Add(envVar.ToUpper(), envVar);
}
}
catch (Exception ex)
{
Log.WarnFormat("Error working around cygwin issue: {0}", ex.Message);
}
}
/// <summary>Save session configuration to the specified XML file</summary>
/// <param name="sessions">A <seealso cref="List"/> containing the session configuration data</param>
/// <param name="fileName">A path to a filename to save the data in</param>
public static void SaveSessionsToFile(List<SessionData> sessions, string fileName)
{
Log.InfoFormat("Saving {0} sessions to {1}", sessions.Count, fileName);
BackUpFiles(fileName, 20);
// sort and save file
sessions.Sort();
XmlSerializer s = new XmlSerializer(sessions.GetType());
using (TextWriter w = new StreamWriter(fileName))
{
s.Serialize(w, sessions);
}
}
private static void BackUpFiles(string fileName, int count)
{
if (File.Exists(fileName) && count > 0)
{
try
{
// backup
string fileBaseName = Path.GetFileNameWithoutExtension(fileName);
string dirName = Path.GetDirectoryName(fileName);
string backupName = Path.Combine(dirName, string.Format("{0}.{1:yyyyMMdd_hhmmss}.XML", fileBaseName, DateTime.Now));
File.Copy(fileName, backupName, true);
// limit last count saves
List<string> oldFiles = new List<string>(Directory.GetFiles(dirName, fileBaseName + ".*.XML"));
oldFiles.Sort();
oldFiles.Reverse();
if (oldFiles.Count > count)
{
for (int i = 20; i < oldFiles.Count; i++)
{
Log.InfoFormat("Cleaning up old file, {0}", oldFiles[i]);
File.Delete(oldFiles[i]);
}
}
}
catch (Exception ex)
{
Log.Error("Error backing up files", ex);
}
}
}
public int CompareTo(object obj)
{
SessionData s = obj as SessionData;
return s == null ? 1 : this.SessionId.CompareTo(s.SessionId);
}
public static string CombineSessionIds(string parent, string child)
{
if (parent == null && child == null)
{
return null;
}
else if (child == null)
{
return parent;
}
else if (parent == null)
{
return child;
}
else
{
return parent + "/" + child;
}
}
public static string GetSessionNameFromId(string sessionId)
{
string[] parts = GetSessionNameParts(sessionId);
return parts.Length > 0 ? parts[parts.Length - 1] : sessionId;
}
/// <summary>Split the SessionID into its parent/child parts</summary>
/// <param name="sessionId">The SessionID</param>
/// <returns>A string array containing the individual path components</returns>
public static string[] GetSessionNameParts(string sessionId)
{
return sessionId.Split('/');
}
/// <summary>Get the parent ID of the specified session</summary>
/// <param name="sessionId">the ID of the session</param>
/// <returns>A string containing the parent sessions ID</returns>
public static string GetSessionParentId(string sessionId)
{
string parentPath = null;
if (sessionId != null)
{
int idx = sessionId.LastIndexOf('/');
if (idx != -1)
{
parentPath = sessionId.Substring(0, idx);
}
}
return parentPath;
}
/// <summary>Create a deep copy of the SessionData object</summary>
/// <returns>A clone of the <seealso cref="SessionData"/> object</returns>
public object Clone()
{
SessionData session = new SessionData();
session.CopyFrom(this);
return session;
}
public void CopyFrom(SessionData SessionToCopy)
{
if (SessionToCopy == null)
return;
foreach (PropertyInfo pi in SessionToCopy.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (pi.CanWrite)
{
pi.SetValue(this, pi.GetValue(SessionToCopy, null), null);
}
}
}
/// <summary>Return a string containing a uri to the protocol://host:port of this sesssions defined host</summary>
/// <returns>A string in uri format containing connection information to this sessions host</returns>
public override string ToString()
{
if (this.Proto == ConnectionProtocol.Cygterm || this.Proto == ConnectionProtocol.Mintty)
{
return string.Format("{0}://{1}", this.Proto.ToString().ToLower(), this.Host);
}
else
{
return string.Format("{0}://{1}:{2}", this.Proto.ToString().ToLower(), this.Host, this.Port);
}
}
class PuttySessionConverter : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(PuttyDataHelper.GetSessionNames());
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
}
class ImageKeyConverter : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(SuperPuTTY.Images.Images.Keys);
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
}
class ImageKeyEditor : UITypeEditor
{
public override bool GetPaintValueSupported(ITypeDescriptorContext context)
{
return true;
}
public override void PaintValue(PaintValueEventArgs e)
{
string ImageKey = e.Value.ToString();
Image img = SuperPuTTY.Images.Images[ImageKey];
if (img == null)
return;
Rectangle destRect = new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Height, e.Bounds.Height);
e.Graphics.DrawImage(img, destRect);
e.Graphics.ExcludeClip(e.Bounds);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace DbgEng.NoExceptions
{
/// <summary>
/// Extension of IDebugClient interface.
/// </summary>
/// <seealso cref="DbgEng.IDebugClient2" />
[ComImport, Guid("DD492D7F-71B8-4AD6-A8DC-1C887479FF91"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDebugClient3 : IDebugClient2
{
#pragma warning disable CS0108 // XXX hides inherited member. This is COM default.
#region IDebugClient
/// <summary>
/// The AttachKernel methods connect the debugger engine to a kernel target.
/// </summary>
/// <param name="Flags">Specifies the flags that control how the debugger attaches to the kernel target.</param>
/// <param name="ConnectOptions">Specifies the connection settings for communicating with the computer running the kernel target.</param>
[PreserveSig]
int AttachKernel(
[In] DebugAttachKernel Flags,
[In, MarshalAs(UnmanagedType.LPStr)] string ConnectOptions = null);
/// <summary>
/// The GetKernelConnectionOptions method returns the connection options for the current kernel target.
/// </summary>
/// <param name="Buffer">Specifies the buffer to receive the connection options.</param>
/// <param name="BufferSize">Specifies the size in characters of the buffer Buffer.</param>
/// <param name="OptionsSize">Receives the size in characters of the connection options.</param>
[PreserveSig]
int GetKernelConnectionOptions(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint OptionsSize);
/// <summary>
/// The SetKernelConnectionOptions method updates some of the connection options for a live kernel target.
/// </summary>
/// <param name="Options">
/// Specifies the connection options to update. The possible values are:
/// <para><c>"resync"</c> Re-synchronize the connection between the debugger engine and the kernel.For more information, see Synchronizing with the Target Computer.</para>
/// <para><c>"cycle_speed"</c> For kernel connections through a COM port, cycle through the supported baud rates; for other connections, do nothing.</para>
/// </param>
[PreserveSig]
int SetKernelConnectionOptions(
[In, MarshalAs(UnmanagedType.LPStr)] string Options);
/// <summary>
/// The StartProcessServer method starts a process server.
/// </summary>
/// <param name="Flags">Specifies the class of the targets that will be available through the process server. This must be set to <see cref="DebugClass.UserWindows"/>.</param>
/// <param name="Options">Specifies the connections options for this process server. These are the same options given to the -t option of the DbgSrv command line.</param>
/// <param name="Reserved">Set to <see cref="IntPtr.Zero"/>.</param>
[PreserveSig]
int StartProcessServer(
[In] DebugClass Flags,
[In, MarshalAs(UnmanagedType.LPStr)] string Options,
[In] IntPtr Reserved = default(IntPtr));
/// <summary>
/// The ConnectProcessServer methods connect to a process server.
/// </summary>
/// <param name="RemoteOptions">Specifies how the debugger engine will connect with the process server. These are the same options passed to the -premote option on the WinDbg and CDB command lines.</param>
/// <param name="Server">A handle for the process server. This handle is used when creating or attaching to processes by using the process server.</param>
[PreserveSig]
int ConnectProcessServer(
[In, MarshalAs(UnmanagedType.LPStr)] string RemoteOptions,
[Out] out ulong Server);
/// <summary>
/// The DisconnectProcessServer method disconnects the debugger engine from a process server.
/// </summary>
/// <param name="Server">Specifies the server from which to disconnect. This handle must have been previously returned by <see cref="ConnectProcessServer"/>.</param>
[PreserveSig]
int DisconnectProcessServer(
[In] ulong Server);
/// <summary>
/// The GetRunningProcessSystemIds method returns the process IDs for each running process.
/// </summary>
/// <param name="Server">Specifies the process server to query for process IDs. If Server is zero, the engine will return the process IDs of the processes running on the local computer.</param>
/// <param name="Ids">Receives the process IDs. The size of this array is <paramref name="Count"/>. If <paramref name="Ids"/> is <c>null</c>, this information is not returned.</param>
/// <param name="Count">Specifies the number of process IDs the array <paramref name="Ids"/> can hold.</param>
/// <param name="ActualCount">Receives the actual number of process IDs returned in <paramref name="Ids"/>.</param>
[PreserveSig]
int GetRunningProcessSystemIds(
[In] ulong Server,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] Ids,
[In] uint Count,
[Out] out uint ActualCount);
/// <summary>
/// The GetRunningProcessSystemIdByExecutableName method searches for a process with a given executable file name and return its process ID.
/// </summary>
/// <param name="Server">Specifies the process server to search for the executable name. If Server is zero, the engine will search for the executable name among the processes running on the local computer.</param>
/// <param name="ExeName">Specifies the executable file name for which to search.</param>
/// <param name="Flags">Specifies a bit-set that controls how the executable name is matched.</param>
/// <param name="Id">The process ID of the first process to match <paramref name="ExeName"/>.</param>
[PreserveSig]
int GetRunningProcessSystemIdByExecutableName(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPStr)] string ExeName,
[In] DebugGetProc Flags,
[Out] out uint Id);
/// <summary>
/// The GetRunningProcessDescription method returns a description of the process that includes the executable image name, the service names, the MTS package names, and the command line.
/// </summary>
/// <param name="Server">Specifies the process server to query for the process description. If Server is zero, the engine will query information about the local process directly.</param>
/// <param name="SystemId">Specifies the process ID of the process whose description is desired.</param>
/// <param name="Flags">Specifies a bit-set containing options that affect the behavior of this method.</param>
/// <param name="ExeName">Receives the name of the executable file used to start the process. If ExeName is <c>null</c>, this information is not returned.</param>
/// <param name="ExeNameSize">Specifies the size in characters of the buffer <paramref name="ExeName"/>.</param>
/// <param name="ActualExeNameSize">Receives the size in characters of the executable file name.</param>
/// <param name="Description">Receives extra information about the process, including service names, MTS package names, and the command line. If Description is <c>null</c>, this information is not returned.</param>
/// <param name="DescriptionSize">Specifies the size in characters of the buffer <paramref name="Description"/>.</param>
/// <param name="ActualDescriptionSize">Receives the size in characters of the extra information.</param>
[PreserveSig]
int GetRunningProcessDescription(
[In] ulong Server,
[In] uint SystemId,
[In] DebugProcDesc Flags,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ExeName,
[In] uint ExeNameSize,
[Out] out uint ActualExeNameSize,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Description,
[In] uint DescriptionSize,
[Out] out uint ActualDescriptionSize);
/// <summary>
/// The AttachProcess method connects the debugger engine to a user-modeprocess.
/// </summary>
/// <param name="Server">Specifies the process server to use to attach to the process. If Server is zero, the engine will connect to a local process without using a process server.</param>
/// <param name="ProcessId">Specifies the process ID of the target process the debugger will attach to.</param>
/// <param name="AttachFlags">Specifies the flags that control how the debugger attaches to the target process.</param>
[PreserveSig]
int AttachProcess(
[In] ulong Server,
[In] uint ProcessId,
[In] DebugAttach AttachFlags);
/// <summary>
/// The CreateProcess method creates a process from the specified command line.
/// </summary>
/// <param name="Server">Specifies the process server to use to attach to the process. If Server is zero, the engine will create a local process without using a process server.</param>
/// <param name="CommandLine">Specifies the command line to execute to create the new process.</param>
/// <param name="CreateFlags">Specifies the flags to use when creating the process. When creating and attaching to a process through the debugger engine, set one of the Platform SDK's process creation flags: <see cref="DebugCreateProcess.DebugProcess"/> or <see cref="DebugCreateProcess.DebugOnlyThisProcess"/>.</param>
[PreserveSig]
int CreateProcess(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPStr)] string CommandLine,
[In] DebugCreateProcess CreateFlags);
/// <summary>
/// The CreateProcessAndAttach method creates a process from a specified command line, then attach to another user-mode process. The created process is suspended and only allowed to execute when the attach has completed. This allows rough synchronization when debugging both, client and server processes.
/// </summary>
/// <param name="Server">Specifies the process server to use to attach to the process. If Server is zero, the engine will connect to the local process without using a process server.</param>
/// <param name="CommandLine">Specifies the command line to execute to create the new process. If CommandLine is <c>null</c>, then no process is created and these methods attach to an existing process, as <see cref="AttachProcess"/> does.</param>
/// <param name="CreateFlags">Specifies the flags to use when creating the process. When creating and attaching to a process through the debugger engine, set one of the Platform SDK's process creation flags: <see cref="DebugCreateProcess.DebugProcess"/> or <see cref="DebugCreateProcess.DebugOnlyThisProcess"/>.</param>
/// <param name="ProcessId">Specifies the process ID of the target process the debugger will attach to. If ProcessId is zero, the debugger will attach to the process it created from CommandLine.</param>
/// <param name="AttachFlags">Specifies the flags that control how the debugger attaches to the target process.</param>
[PreserveSig]
int CreateProcessAndAttach(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPStr)] string CommandLine,
[In] DebugCreateProcess CreateFlags,
[In] uint ProcessId,
[In] DebugAttach AttachFlags);
/// <summary>
/// The GetProcessOptions method retrieves the process options affecting the current process.
/// </summary>
/// <param name="Options">Receives a set of flags representing the process options for the current process.</param>
[PreserveSig]
int GetProcessOptions(
[Out] out DebugProcess Options);
/// <summary>
/// The AddProcessOptions method adds the process options to those options that affect the current process.
/// </summary>
/// <param name="Options">Specifies the process options to add to those affecting the current process.</param>
[PreserveSig]
int AddProcessOptions(
[In] DebugProcess Options);
/// <summary>
/// The RemoveProcessOptions method removes process options from those options that affect the current process.
/// </summary>
/// <param name="Options">Specifies the process options to remove from those affecting the current process.</param>
[PreserveSig]
int RemoveProcessOptions(
[In] DebugProcess Options);
/// <summary>
/// The SetProcessOptions method sets the process options affecting the current process.
/// </summary>
/// <param name="Options">Specifies a set of flags that will become the new process options for the current process.</param>
[PreserveSig]
int SetProcessOptions(
[In] DebugProcess Options);
/// <summary>
/// The OpenDumpFile method opens a dump file as a debugger target.
/// <note> The engine doesn't completely attach to the dump file until the <see cref="IDebugControl.WaitForEvent"/> method has been called. When a dump file is created from a process or kernel, information about the last event is stored in the dump file. After the dump file is opened, the next time execution is attempted, the engine will generate this event for the event callbacks. Only then does the dump file become available in the debugging session.</note>
/// </summary>
/// <param name="DumpFile">Specifies the name of the dump file to open. DumpFile must include the file name extension. DumpFile can include a relative or absolute path; relative paths are relative to the directory in which the debugger was started. DumpFile can have the form of a file URL, starting with "file://". If DumpFile specifies a cabinet (.cab) file, the cabinet file is searched for the first file with extension .kdmp, then .hdmp, then .mdmp, and finally .dmp.</param>
[PreserveSig]
int OpenDumpFile(
[In, MarshalAs(UnmanagedType.LPStr)] string DumpFile);
/// <summary>
/// The WriteDumpFile method creates a user-mode or kernel-modecrash dump file.
/// </summary>
/// <param name="DumpFile">Specifies the name of the dump file to create. DumpFile must include the file name extension. DumpFile can include a relative or absolute path; relative paths are relative to the directory in which the debugger was started.</param>
/// <param name="Qualifier">Specifies the type of dump file to create.</param>
[PreserveSig]
int WriteDumpFile(
[In, MarshalAs(UnmanagedType.LPStr)] string DumpFile,
[In] DebugDump Qualifier);
/// <summary>
/// The ConnectSession method joins the client to an existing debugger session.
/// </summary>
/// <param name="Flags">Specifies a bit-set of option flags for connecting to the session.</param>
/// <param name="HistoryLimit">Specifies the maximum number of characters from the session's history to send to this client's output upon connection.</param>
[PreserveSig]
int ConnectSession(
[In] DebugConnectSession Flags,
[In] uint HistoryLimit);
/// <summary>
/// The StartServer method starts a debugging server.
/// </summary>
/// <param name="Options">Specifies the connections options for this server. These are the same options given to the .server debugger command or the WinDbg and CDB -server command-line option. For details on the syntax of this string, see Activating a Debugging Server.</param>
/// <remarks>The server that is started will be accessible by other debuggers through the transport specified in the Options parameter.</remarks>
[PreserveSig]
int StartServer(
[In, MarshalAs(UnmanagedType.LPStr)] string Options);
/// <summary>
/// The OutputServers method lists the servers running on a given computer.
/// </summary>
/// <param name="OutputControl">Specifies the output control to use while outputting the servers.</param>
/// <param name="Machine">Specifies the name of the computer whose servers will be listed. Machine has the following form: \\computername </param>
/// <param name="Flags">Specifies a bit-set that determines which servers to output.</param>
[PreserveSig]
int OutputServers(
[In] DebugOutctl OutputControl,
[In, MarshalAs(UnmanagedType.LPStr)] string Machine,
[In] DebugServers Flags);
/// <summary>
/// Attempts to terminate all processes in all targets.
/// </summary>
[PreserveSig]
int TerminateProcesses();
/// <summary>
/// Detaches the debugger engine from all processes in all targets, resuming all their threads.
/// </summary>
[PreserveSig]
int DetachProcesses();
/// <summary>
/// The EndSession method ends the current debugger session.
/// </summary>
/// <param name="Flags">Specifies how to end the session.</param>
[PreserveSig]
int EndSession(
[In] DebugEnd Flags);
/// <summary>
/// The GetExitCode method returns the exit code of the current process if that process has already run through to completion.
/// </summary>
/// <param name="Code">The exit code of the process. If the process is still running, Code will be set to STILL_ACTIVE.</param>
[PreserveSig]
int GetExitCode(
[Out] out uint Code);
/// <summary>
/// The DispatchCallbacks method lets the debugger engine use the current thread for callbacks.
/// </summary>
/// <param name="Timeout">Specifies how many milliseconds to wait before this method will return. If Timeout is uint.MaxValue, this method will not return until <see cref="IDebugClient.ExitDispatch"/> is called or an error occurs.</param>
[PreserveSig]
int DispatchCallbacks(
[In] uint Timeout);
/// <summary>
/// The ExitDispatch method causes the <see cref="DispatchCallbacks"/> method to return.
/// </summary>
/// <param name="Client">Specifies the client whose <see cref="DispatchCallbacks"/> method should return.</param>
[PreserveSig]
int ExitDispatch(
[In, MarshalAs(UnmanagedType.Interface)] IDebugClient Client);
/// <summary>
/// The CreateClient method creates a new client object for the current thread.
/// </summary>
/// <param name="Client">Receives an interface pointer for the new client.</param>
[PreserveSig]
int CreateClient(
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugClient Client);
/// <summary>
/// The GetInputCallbacks method returns the input callbacks object registered with this client.
/// </summary>
/// <param name="Callbacks">Receives an interface pointer for the <see cref="IDebugInputCallbacks"/> object registered with the client.</param>
[PreserveSig]
int GetInputCallbacks(
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugInputCallbacks Callbacks);
/// <summary>
/// The SetInputCallbacks method registers an input callbacks object with the client.
/// </summary>
/// <param name="Callbacks">Specifies the interface pointer to the input callbacks object to register with this client.</param>
[PreserveSig]
int SetInputCallbacks(
[In, MarshalAs(UnmanagedType.Interface)] IDebugInputCallbacks Callbacks = null);
/// <summary>
/// The GetOutputCallbacks method returns the output callbacks object registered with the client.
/// </summary>
/// <param name="Callbacks">Receives an interface pointer to the <see cref="IDebugOutputCallbacks"/> object registered with the client.</param>
[PreserveSig]
int GetOutputCallbacks(
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugOutputCallbacks Callbacks);
/// <summary>
/// The SetOutputCallbacks method registers an output callbacks object with this client.
/// </summary>
/// <param name="Callbacks">Specifies the interface pointer to the output callbacks object to register with this client.</param>
[PreserveSig]
int SetOutputCallbacks(
[In, MarshalAs(UnmanagedType.Interface)] IDebugOutputCallbacks Callbacks = null);
/// <summary>
/// The GetOutputMask method returns the output mask currently set for the client.
/// </summary>
/// <param name="Mask">Receives the output mask for the client.</param>
[PreserveSig]
int GetOutputMask(
[Out] out DebugOutput Mask);
/// <summary>
/// The SetOutputMask method sets the output mask for the client.
/// </summary>
/// <param name="Mask">Specifies the new output mask for the client.</param>
[PreserveSig]
int SetOutputMask(
[In] DebugOutput Mask);
/// <summary>
/// The GetOtherOutputMask method returns the output mask for another client.
/// </summary>
/// <param name="Client">Specifies the client whose output mask is desired.</param>
/// <param name="Mask">Receives the output mask for the client.</param>
[PreserveSig]
int GetOtherOutputMask(
[In, MarshalAs(UnmanagedType.Interface)] IDebugClient Client,
[Out] out DebugOutput Mask);
/// <summary>
/// The SetOtherOutputMask method sets the output mask for another client.
/// </summary>
/// <param name="Client">Specifies the client whose output mask will be set.</param>
/// <param name="Mask">Specifies the new output mask for the client.</param>
[PreserveSig]
int SetOtherOutputMask(
[In, MarshalAs(UnmanagedType.Interface)] IDebugClient Client,
[In] DebugOutput Mask);
/// <summary>
/// Undocumented on MSDN.
/// </summary>
/// <param name="Columns"></param>
[PreserveSig]
int GetOutputWidth(
[Out] out uint Columns);
/// <summary>
/// Undocumented on MSDN.
/// </summary>
/// <param name="Columns"></param>
[PreserveSig]
int SetOutputWidth(
[In] uint Columns);
/// <summary>
/// Undocumented on MSDN.
/// </summary>
/// <param name="Buffer"></param>
/// <param name="BufferSize"></param>
/// <param name="PrefixSize"></param>
[PreserveSig]
int GetOutputLinePrefix(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint PrefixSize);
/// <summary>
/// Undocumented on MSDN.
/// </summary>
/// <param name="Prefix"></param>
[PreserveSig]
int SetOutputLinePrefix(
[In, MarshalAs(UnmanagedType.LPStr)] string Prefix = null);
/// <summary>
/// The GetIdentity method returns a string describing the computer and user this client represents.
/// </summary>
/// <param name="Buffer">Specifies the buffer to receive the string. If <paramref name="Buffer"/> is <c>null</c>, this information is not returned.</param>
/// <param name="BufferSize">Specifies the size of the buffer <paramref name="Buffer"/>.</param>
/// <param name="IdentitySize">Receives the size of the string.</param>
[PreserveSig]
int GetIdentity(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint IdentitySize);
/// <summary>
/// The OutputIdentity method formats and outputs a string describing the computer and user this client represents.
/// </summary>
/// <param name="OutputControl">Specifies where to send the output.</param>
/// <param name="Flags">Set to zero.</param>
/// <param name="Format">Specifies a format string similar to the printf format string. However, this format string must only contain one formatting directive, %s, which will be replaced by a description of the computer and user this client represents.</param>
[PreserveSig]
int OutputIdentity(
[In] DebugOutctl OutputControl,
[In] uint Flags,
[In, MarshalAs(UnmanagedType.LPStr)] string Format);
/// <summary>
/// The GetEventCallbacks method returns the event callbacks object registered with this client.
/// </summary>
/// <param name="Callbacks">Receives an interface pointer to the event callbacks object registered with this client.</param>
[PreserveSig]
int GetEventCallbacks(
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugEventCallbacks Callbacks);
/// <summary>
/// The SetEventCallbacks method registers an event callbacks object with this client.
/// </summary>
/// <param name="Callbacks">Specifies the interface pointer to the event callbacks object to register with this client.</param>
[PreserveSig]
int SetEventCallbacks(
[In, MarshalAs(UnmanagedType.Interface)] IDebugEventCallbacks Callbacks = null);
/// <summary>
/// Forces any remaining buffered output to be delivered to the <see cref="IDebugOutputCallbacks"/> object registered with this client.
/// </summary>
[PreserveSig]
int FlushCallbacks();
#endregion
#region IDebugClient2
/// <summary>
/// The WriteDumpFile2 method creates a user-mode or kernel-modecrash dump file.
/// </summary>
/// <param name="DumpFile">Specifies the name of the dump file to create. DumpFile must include the file name extension. DumpFile can include a relative or absolute path; relative paths are relative to the directory in which the debugger was started.</param>
/// <param name="Qualifier">Specifies the type of dump file to create.</param>
/// <param name="FormatFlags">Specifies flags that determine the format of the dump file and--for user-mode minidumps--what information to include in the file.</param>
/// <param name="Comment">Specifies a comment string to be included in the crash dump file. This string is displayed in the debugger console when the dump file is loaded. Some dump file formats do not support the storing of comment strings.</param>
[PreserveSig]
int WriteDumpFile2(
[In, MarshalAs(UnmanagedType.LPStr)] string DumpFile,
[In] DebugDump Qualifier,
[In] DebugFormat FormatFlags,
[In, MarshalAs(UnmanagedType.LPStr)] string Comment = null);
/// <summary>
/// The AddDumpInformationFile method registers additional files containing supporting information that will be used when opening a dump file.
/// <note>ANSI version.</note>
/// </summary>
/// <param name="InfoFile">Specifies the name of the file containing the supporting information.</param>
/// <param name="Type">Specifies the type of the file InfoFile. Currently, only files containing paging file information are supported, and Type must be set to <see cref="DebugDumpFile.PageFileDump"/>.</param>
[PreserveSig]
int AddDumpInformationFile(
[In, MarshalAs(UnmanagedType.LPStr)] string InfoFile,
[In] DebugDumpFile Type);
/// <summary>
/// The EndProcessServer method requests that a process server be shut down.
/// </summary>
/// <param name="Server">Specifies the process server to shut down. This handle must have been previously returned by <see cref="IDebugClient.ConnectProcessServer"/>.</param>
[PreserveSig]
int EndProcessServer(
[In] ulong Server);
/// <summary>
/// The WaitForProcessServerEnd method waits for a local process server to exit.
/// </summary>
/// <param name="Timeout">Specifies how long in milliseconds to wait for a process server to exit. If Timeout is uint.MaxValue, this method will not return until a process server has ended.</param>
[PreserveSig]
int WaitForProcessServerEnd(
[In] uint Timeout);
/// <summary>
/// The IsKernelDebuggerEnabled method checks whether kernel debugging is enabled for the local kernel.
/// </summary>
/// <returns>S_OK if kernel debugging is enabled for the local kernel; S_FALSE otherwise.</returns>
[PreserveSig]
int IsKernelDebuggerEnabled();
/// <summary>
/// The TerminateCurrentProcess method attempts to terminate the current process.
/// </summary>
[PreserveSig]
int TerminateCurrentProcess();
/// <summary>
/// The DetachCurrentProcess method detaches the debugger engine from the current process, resuming all its threads.
/// </summary>
[PreserveSig]
int DetachCurrentProcess();
/// <summary>
/// The AbandonCurrentProcess method removes the current process from the debugger engine's process list without detaching or terminating the process.
/// </summary>
[PreserveSig]
int AbandonCurrentProcess();
#endregion
#pragma warning restore CS0108 // XXX hides inherited member. This is COM default.
/// <summary>
/// The GetRunningProcessSystemIdByExecutableNameWide method searches for a process with a given executable file name and return its process ID.
/// <note>Unicode version</note>
/// </summary>
/// <param name="Server">Specifies the process server to search for the executable name. If Server is zero, the engine will search for the executable name among the processes running on the local computer.</param>
/// <param name="ExeName">Specifies the executable file name for which to search.</param>
/// <param name="Flags">Specifies a bit-set that controls how the executable name is matched.</param>
/// <param name="Id">Receives the process ID of the first process to match <paramref name="ExeName"/>.</param>
[PreserveSig]
int GetRunningProcessSystemIdByExecutableNameWide(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPWStr)] string ExeName,
[In] DebugGetProc Flags,
[Out] out uint Id);
/// <summary>
/// The GetRunningProcessDescriptionWide method returns a description of the process that includes the executable image name, the service names, the MTS package names, and the command line.
/// <note>Unicode version</note>
/// </summary>
/// <param name="Server">Specifies the process server to query for the process description. If Server is zero, the engine will query information about the local process directly.</param>
/// <param name="SystemId">Specifies the process ID of the process whose description is desired.</param>
/// <param name="Flags">Specifies a bit-set containing options that affect the behavior of this method.</param>
/// <param name="ExeName">Receives the name of the executable file used to start the process. If ExeName is <c>null</c>, this information is not returned.</param>
/// <param name="ExeNameSize">Specifies the size in characters of the buffer <paramref name="ExeName"/>.</param>
/// <param name="ActualExeNameSize">Receives the size in characters of the executable file name.</param>
/// <param name="Description">Receives extra information about the process, including service names, MTS package names, and the command line. If Description is <c>null</c>, this information is not returned.</param>
/// <param name="DescriptionSize">Specifies the size in characters of the buffer <paramref name="Description"/>.</param>
/// <param name="ActualDescriptionSize">Receives the size in characters of the extra information.</param>
[PreserveSig]
int GetRunningProcessDescriptionWide(
[In] ulong Server,
[In] uint SystemId,
[In] DebugProcDesc Flags,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder ExeName,
[In] uint ExeNameSize,
[Out] out uint ActualExeNameSize,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Description,
[In] uint DescriptionSize,
[Out] out uint ActualDescriptionSize);
/// <summary>
/// The CreateProcessWide method creates a process from the specified command line.
/// <note>Unicode version</note>
/// </summary>
/// <param name="Server">Specifies the process server to use when attaching to the process. If Server is zero, the engine will create a local process without using a process server.</param>
/// <param name="CommandLine">Specifies the command line to execute to create the new process. The CreateProcessWide method might modify the contents of the string that you supply in this parameter. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). Passing a constant string in this parameter can lead to an access violation.</param>
/// <param name="CreateFlags">Specifies the flags to use when creating the process.</param>
[PreserveSig]
int CreateProcessWide(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPWStr)] string CommandLine,
[In] DebugCreateProcess CreateFlags);
/// <summary>
/// The CreateProcessAndAttachWide method creates a process from a specified command line, then attach to another user-mode process. The created process is suspended and only allowed to execute when the attach has completed. This allows rough synchronization when debugging both, client and server processes.
/// </summary>
/// <param name="Server">Specifies the process server to use to attach to the process. If Server is zero, the engine will connect to the local process without using a process server.</param>
/// <param name="CommandLine">Specifies the command line to execute to create the new process. If <paramref name="CommandLine"/> is <c>null</c>, then no process is created and these methods attach to an existing process, as <see cref="IDebugClient.AttachProcess"/> does.</param>
/// <param name="CreateFlags">Specifies the flags to use when creating the process.</param>
/// <param name="ProcessId">Specifies the process ID of the target process the debugger will attach to. If <paramref name="ProcessId"/> is zero, the debugger will attach to the process it created from <paramref name="CommandLine"/>.</param>
/// <param name="AttachFlags">Specifies the flags that control how the debugger attaches to the target process.</param>
[PreserveSig]
int CreateProcessAndAttachWide(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPWStr)] string CommandLine,
[In] DebugCreateProcess CreateFlags,
[In] uint ProcessId,
[In] DebugAttach AttachFlags);
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.Management.Automation.Remoting.Server;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// This class is an implementation of the abstract class ServerRemoteSessionDataStructureHandler.
/// </summary>
internal class ServerRemoteSessionDSHandlerlImpl : ServerRemoteSessionDataStructureHandler
{
private AbstractServerSessionTransportManager _transportManager;
private ServerRemoteSessionDSHandlerStateMachine _stateMachine;
private ServerRemoteSession _session;
internal override AbstractServerSessionTransportManager TransportManager
{
get
{
return _transportManager;
}
}
#region Constructors
/// <summary>
/// Constructs a ServerRemoteSession handler using the supplied transport manager. The
/// supplied transport manager will be used to send and receive data from the remote
/// client.
/// </summary>
/// <param name="session"></param>
/// <param name="transportManager"></param>
internal ServerRemoteSessionDSHandlerlImpl(ServerRemoteSession session,
AbstractServerSessionTransportManager transportManager)
{
Dbg.Assert(null != session, "session cannot be null.");
Dbg.Assert(null != transportManager, "transportManager cannot be null.");
_session = session;
_stateMachine = new ServerRemoteSessionDSHandlerStateMachine(session);
_transportManager = transportManager;
_transportManager.DataReceived += session.DispatchInputQueueData;
}
#endregion Constructors
#region Overrides
/// <summary>
/// Calls the transport layer connect to make a connection to the listener.
/// </summary>
internal override void ConnectAsync()
{
// for the WSMan implementation, this is a no-op..and statemachine is coded accordingly
// to move to negotiation pending.
}
/// <summary>
/// This method sends the server side capability negotitation packet to the client.
/// </summary>
internal override void SendNegotiationAsync()
{
RemoteSessionCapability serverCapability = _session.Context.ServerCapability;
RemoteDataObject data = RemotingEncoder.GenerateServerSessionCapability(serverCapability,
Guid.Empty);
RemoteSessionStateMachineEventArgs negotiationSendCompletedArg =
new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSendCompleted);
_stateMachine.RaiseEvent(negotiationSendCompletedArg);
RemoteDataObject<PSObject> dataToBeSent = RemoteDataObject<PSObject>.CreateFrom(
data.Destination, data.DataType, data.RunspacePoolId, data.PowerShellId, (PSObject)data.Data);
// send data to client..flush is not true as we expect to send state changed
// information (from runspace creation)
_transportManager.SendDataToClient<PSObject>(dataToBeSent, false);
}
/// <summary>
/// This event indicates that the client capability negotiation packet has been received.
/// </summary>
internal override event EventHandler<RemoteSessionNegotiationEventArgs> NegotiationReceived;
/// <summary>
/// Event that raised when session datastructure handler is closing.
/// </summary>
internal override event EventHandler<EventArgs> SessionClosing;
internal override event EventHandler<RemoteDataEventArgs<string>> PublicKeyReceived;
/// <summary>
/// Send the encrypted session key to the client side
/// </summary>
/// <param name="encryptedSessionKey">encrypted session key
/// as a string</param>
internal override void SendEncryptedSessionKey(string encryptedSessionKey)
{
_transportManager.SendDataToClient<object>(RemotingEncoder.GenerateEncryptedSessionKeyResponse(
Guid.Empty, encryptedSessionKey), true);
}
/// <summary>
/// Send request to the client for sending a public key
/// </summary>
internal override void SendRequestForPublicKey()
{
_transportManager.SendDataToClient<object>(
RemotingEncoder.GeneratePublicKeyRequest(Guid.Empty), true);
}
/// <summary>
/// Raise the public key received event
/// </summary>
/// <param name="receivedData">received data</param>
/// <remarks>This method is a hook to be called
/// from the transport manager</remarks>
internal override void RaiseKeyExchangeMessageReceived(RemoteDataObject<PSObject> receivedData)
{
RaiseDataReceivedEvent(new RemoteDataEventArgs(receivedData));
}
/// <summary>
/// This method calls the transport level call to close the connection to the listener.
/// </summary>
/// <param name="reasonForClose">
/// Message describing why the session is closing
/// </param>
/// <exception cref="PSRemotingTransportException">
/// If the transport call fails.
/// </exception>
internal override void CloseConnectionAsync(Exception reasonForClose)
{
// Raise the closing event
SessionClosing.SafeInvoke(this, EventArgs.Empty);
_transportManager.Close(reasonForClose);
RemoteSessionStateMachineEventArgs closeCompletedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.CloseCompleted);
_stateMachine.RaiseEvent(closeCompletedArg);
}
/// <summary>
/// This event indicates that the client has requested to create a new runspace pool
/// on the server side
/// </summary>
internal override event EventHandler<RemoteDataEventArgs> CreateRunspacePoolReceived;
/// <summary>
/// A reference to the FSM object.
/// </summary>
internal override ServerRemoteSessionDSHandlerStateMachine StateMachine
{
get
{
return _stateMachine;
}
}
/// <summary>
/// This method is used by the input queue dispatching mechanism.
/// It examines the data and takes appropriate actions.
/// </summary>
/// <param name="dataArg">
/// The received client data.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter is null.
/// </exception>
internal override void RaiseDataReceivedEvent(RemoteDataEventArgs dataArg)
{
if (dataArg == null)
{
throw PSTraceSource.NewArgumentNullException("dataArg");
}
RemoteDataObject<PSObject> rcvdData = dataArg.ReceivedData;
RemotingTargetInterface targetInterface = rcvdData.TargetInterface;
RemotingDataType dataType = rcvdData.DataType;
Dbg.Assert(targetInterface == RemotingTargetInterface.Session, "targetInterface must be Session");
switch (dataType)
{
case RemotingDataType.CreateRunspacePool:
{
// At this point, the negotiation is complete, so
// need to import the clients public key
CreateRunspacePoolReceived.SafeInvoke(this, dataArg);
}
break;
case RemotingDataType.CloseSession:
PSRemotingDataStructureException reasonOfClose = new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientRequestedToCloseSession);
RemoteSessionStateMachineEventArgs closeSessionArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, reasonOfClose);
_stateMachine.RaiseEvent(closeSessionArg);
break;
case RemotingDataType.SessionCapability:
RemoteSessionCapability capability = null;
try
{
capability = RemotingDecoder.GetSessionCapability(rcvdData.Data);
}
catch (PSRemotingDataStructureException dse)
{
// this will happen if expected properties are not
// received for session capability
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerNotFoundCapabilityProperties,
dse.Message, PSVersionInfo.BuildVersion, RemotingConstants.ProtocolVersion);
}
RemoteSessionStateMachineEventArgs capabilityArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationReceived);
capabilityArg.RemoteSessionCapability = capability;
_stateMachine.RaiseEvent(capabilityArg);
if (NegotiationReceived != null)
{
RemoteSessionNegotiationEventArgs negotiationArg = new RemoteSessionNegotiationEventArgs(capability);
negotiationArg.RemoteData = rcvdData;
NegotiationReceived.SafeInvoke(this, negotiationArg);
}
break;
case RemotingDataType.PublicKey:
{
string remotePublicKey = RemotingDecoder.GetPublicKey(rcvdData.Data);
PublicKeyReceived.SafeInvoke(this, new RemoteDataEventArgs<string>(remotePublicKey));
}
break;
default:
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedAction, dataType);
}
}
#endregion Overrides
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
namespace Aural_Probe
{
/// <summary>
/// Configuration file container.
/// </summary>
public class ConfigFile
{
private const string ConfigFilePath = "Aural Probe.cfg.json";
private const string DefaultConfigFilePath = "Default.cfg.json";
private const string OldFormatConfigFilePath = "Aural Probe.cfg";
[JsonIgnore] public const int MaxCategories = 256;
// Version History
// 0 = Unversioned config file
// 1 = Initial first versioned config file, no change in data
// 2 = Added default favorites directory
// 3 = Added file types + autoplay
// 4 = Added default sound device
// 5 = Added always on top
// 6 = Added use regular expression option (per category)
// 7 = Switched to JSON
// ...
// Resharper complains about it not being used, but we're writing it to file.
// ReSharper disable once UnusedMember.Global
public const int CurrentConfigFileVersion = 7;
public readonly List<Category> Categories;
public List<string> SearchDirectories;
public List<string> SearchDirectoriesScrubbed;
public bool RescanPrompt;
public bool IncludeFilePaths;
public bool AlwaysOnTop;
public string DefaultFavoritesDirectory;
public bool Autoplay;
public int AutoplayRepeats;
public bool LoadWav;
public bool LoadAiff;
public bool LoadFlac;
public bool LoadMp3;
public bool LoadWma;
public bool LoadOgg;
public string DefaultSoundDevice;
public int SampleDisplaySizeW;
public int SampleDisplaySizeH;
private ConfigFile()
{
this.Categories = new List<Category>();
this.SearchDirectories = new List<string>();
this.SearchDirectoriesScrubbed = new List<string>();
this.RescanPrompt = true;
this.IncludeFilePaths = true;
this.AlwaysOnTop = false;
this.Autoplay = false;
this.AutoplayRepeats = 4;
this.LoadWav = true;
this.LoadAiff = true;
this.LoadFlac = true;
this.LoadMp3 = true;
this.LoadWma = true;
this.LoadOgg = true;
this.SampleDisplaySizeH = 32;
this.SampleDisplaySizeH = 192;
}
private static ConfigFile ConvertLegacyConfig(LegacyConfigFile legacyConfig)
{
var config = new ConfigFile();
for (var i = 0; i < legacyConfig.lnNumCategories; ++i)
{
var searchStrings = new List<string>();
for (var j = 0; j < LegacyConfigFile.MaxSearchStringsPerCategory; ++j)
{
if (legacyConfig.categorySearchStrings[i, j] == null)
{
break;
}
searchStrings.Add(legacyConfig.categorySearchStrings[i, j]);
}
var useRegex = legacyConfig.categoryUseRegularExpressions[i];
config.Categories.Add(MainForm.app.Library.CreateCategory(
legacyConfig.categoryName[i],
useRegex
? null
: searchStrings,
useRegex,
useRegex
? searchStrings.First()
: null
));
}
config.SearchDirectories = legacyConfig.searchDirectories.Where(sd => sd != null).ToList();
config.DefaultFavoritesDirectory = legacyConfig.defaultFavoritesDirectory;
config.RescanPrompt = legacyConfig.lbRescanPrompt;
config.IncludeFilePaths = legacyConfig.lbIncludeFilePaths;
config.AlwaysOnTop = legacyConfig.lbAlwaysOnTop;
config.Autoplay = legacyConfig.lbAutoplay;
config.AutoplayRepeats = legacyConfig.lnAutoplayRepeats;
config.LoadWav = legacyConfig.lbWAV;
config.LoadAiff = legacyConfig.lbAIFF;
config.LoadFlac = legacyConfig.lbFLAC;
config.LoadMp3 = legacyConfig.lbMP3;
config.LoadWma = legacyConfig.lbWMA;
config.LoadOgg = legacyConfig.lbOGG;
config.SampleDisplaySizeH = legacyConfig.lnSampleDisplaySizeH;
config.SampleDisplaySizeW = legacyConfig.lnSampleDisplaySizeW;
config.DefaultSoundDevice = legacyConfig.defaultSoundDevice;
return config;
}
// scrub = search..?
// i.e. basically look in, find samples, or whatever
private void UpdateScrubbedSearchDirectories()
{
var scrubbedList = new List<string>();
// honestly I don't see exactly what this thing is for?
// I'm guessing if you have several search directories, and they overlap in some manner?
// or something like that?
foreach (var dir in this.SearchDirectories)
{
var searchDirectory = dir?.ToLower();
// ReSharper disable once AssignNullToNotNullAttribute
// We don't allow SearchDirectories to contain nulls.
if (!Directory.Exists(searchDirectory) || scrubbedList.Contains(searchDirectory))
{
continue;
}
// If searchDirectory is a subfolder of any other search directory,
// skip it, by adding it to the list of already scrubbed.
// Because it will be, later on, when we scrub the parent, since it goes
// into folders recursively.
// (afaik)
// (tbh this shit is pretty confusing, what exactly are we trying to avoid here?)
if (!this.SearchDirectories
.Select(directory => directory.ToLower())
.Where(directory => directory != searchDirectory)
.Any(directory => searchDirectory.Contains(directory)))
{
scrubbedList.Add(dir);
}
}
this.SearchDirectoriesScrubbed = scrubbedList;
}
private static string GetOldFormatConfigFilePath()
{
return MainForm.GetApplicationDataPath() + "\\" + OldFormatConfigFilePath;
}
private static string GetConfigFilePath()
{
return MainForm.GetApplicationDataPath() + "\\" + ConfigFilePath;
}
private static ConfigFile LoadJsonConfig(string path)
{
var json = File.ReadAllText(path);
var configFile = JsonConvert.DeserializeObject<ConfigFile>(json);
return configFile;
}
public static ConfigFile Load()
{
ConfigFile config;
Directory.SetCurrentDirectory(MainForm.workingDirectory);
var configExists = File.Exists(GetConfigFilePath());
var defaultExists = File.Exists(DefaultConfigFilePath);
var oldFormatConfigExists = File.Exists(GetOldFormatConfigFilePath());
var oldOldFormatConfigExists = File.Exists(OldFormatConfigFilePath);
if (configExists)
{
config = LoadJsonConfig(GetConfigFilePath());
}
else if (oldFormatConfigExists || oldOldFormatConfigExists)
{
config = ConvertLegacyConfig(LegacyConfigFile.CreateAndLoad());
}
else if (defaultExists)
{
config = LoadJsonConfig(DefaultConfigFilePath);
}
else
{
config = new ConfigFile
{
// Set up defaults
SampleDisplaySizeW = 192,
SampleDisplaySizeH = 32
};
config.Categories.Add(MainForm.app.Library.CreateCategory(
"All Samples",
null,
false,
null));
}
config.UpdateScrubbedSearchDirectories();
return config;
}
public void Save()
{
File.WriteAllText(
GetConfigFilePath(),
JsonConvert.SerializeObject(this, Formatting.Indented));
this.UpdateScrubbedSearchDirectories();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using NExpect.Implementations;
using NExpect.Interfaces;
using NExpect.MatcherLogic;
using static NExpect.Implementations.MessageHelpers;
using Imported.PeanutButter.Utils;
namespace NExpect
{
/// <summary>
/// Provides matchers for HttpResponseMessages
/// </summary>
public static class HttpResponseMessageMatchers
{
/// <summary>
/// Tests if an HttpResponseMessage contains the Set-Cookie
/// header that would set the cookie with the provided name
/// </summary>
/// <param name="have"></param>
/// <param name="name"></param>
/// <returns>Continuation to further test the cookie, if found</returns>
public static IMore<Cookie> Cookie(
this IHave<HttpResponseMessage> have,
string name
)
{
return have.Cookie(name, NULL_STRING);
}
/// <summary>
/// Tests if an HttpResponseMessage contains the Set-Cookie
/// header that would set the cookie with the provided name
/// </summary>
/// <param name="have"></param>
/// <param name="name"></param>
/// <param name="customMessage"></param>
/// <returns>Continuation to further test the cookie, if found</returns>
public static IMore<Cookie> Cookie(
this IHave<HttpResponseMessage> have,
string name,
string customMessage
)
{
return have.Cookie(name, () => customMessage);
}
/// <summary>
/// Tests if an HttpResponseMessage contains the Set-Cookie
/// header that would set the cookie with the provided name
/// </summary>
/// <param name="have"></param>
/// <param name="name"></param>
/// <param name="customMessageGenerator"></param>
/// <returns>Continuation to further test the cookie, if found</returns>
public static IMore<Cookie> Cookie(
this IHave<HttpResponseMessage> have,
string name,
Func<string> customMessageGenerator
)
{
Cookie resolvedCookie = null;
have.AddMatcher(actual =>
{
var cookies = actual.Headers.Where(
h => h.Key == "Set-Cookie"
).Select(h => h.Value.Select(ParseCookieHeader))
.SelectMany(o => o)
.ToArray();
resolvedCookie = cookies.FirstOrDefault(c => c.Name.Equals(name));
var passed = resolvedCookie != null;
return new MatcherResult(
passed,
FinalMessageFor(
() => $"Expected {passed.AsNot()}to find set-cookie for '{name}'",
customMessageGenerator
)
);
});
return new Next<Cookie>(
() => resolvedCookie,
have as IExpectationContext
);
}
/// <summary>
/// Tests that a cookie has the expected value
/// </summary>
/// <param name="with"></param>
/// <param name="value"></param>
/// <returns></returns>
public static IMore<Cookie> Value(
this IWith<Cookie> with,
string value
)
{
return with.Value(value, NULL_STRING);
}
/// <summary>
/// Tests that a cookie has the expected value
/// </summary>
/// <param name="with"></param>
/// <param name="value"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<Cookie> Value(
this IWith<Cookie> with,
string value,
string customMessage
)
{
return with.Value(value, () => customMessage);
}
/// <summary>
/// Tests that a cookie has the expected value
/// </summary>
/// <param name="with"></param>
/// <param name="value"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<Cookie> Value(
this IWith<Cookie> with,
string value,
Func<string> customMessageGenerator
)
{
return with.AddMatcher(actual =>
{
var passed = actual is not null && actual.Value.Equals(value);
return new MatcherResult(
passed,
() => actual is null
? $"Expected {passed.AsNot()}to find cookie with value '{value}'"
: $"Expected {passed.AsNot()}to find value '{value}' for cookie '{actual.Name}' (found value: '{actual.Value}')",
customMessageGenerator
);
});
}
/// <summary>
/// Tests if the cookie has the Secure flag
/// </summary>
/// <param name="more"></param>
/// <returns></returns>
public static IMore<Cookie> Secure(
this ICanAddMatcher<Cookie> more
)
{
return more.Secure(NULL_STRING);
}
/// <summary>
/// Tests if the cookie has the Secure flag
/// </summary>
/// <param name="more"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<Cookie> Secure(
this ICanAddMatcher<Cookie> more,
string customMessage
)
{
return more.Secure(() => customMessage);
}
/// <summary>
/// Tests if the cookie has the Secure flag
/// </summary>
/// <param name="more"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<Cookie> Secure(
this ICanAddMatcher<Cookie> more,
Func<string> customMessageGenerator
)
{
return more.AddMatcher(actual =>
{
var passed = actual?.Secure ?? false;
return new MatcherResult(
passed,
() => $"Expected {actual.Name()} {passed.AsNot()}to be secure",
customMessageGenerator
);
});
}
/// <summary>
/// Tests if the cookie has the HttpOnly flag
/// </summary>
/// <param name="more"></param>
/// <returns></returns>
public static IMore<Cookie> HttpOnly(
this ICanAddMatcher<Cookie> more
)
{
return more.HttpOnly(NULL_STRING);
}
/// <summary>
/// Tests if the cookie has the HttpOnly flag
/// </summary>
/// <param name="more"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<Cookie> HttpOnly(
this ICanAddMatcher<Cookie> more,
string customMessage
)
{
return more.HttpOnly(() => customMessage);
}
/// <summary>
/// Tests if the cookie has the HttpOnly flag
/// </summary>
/// <param name="more"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<Cookie> HttpOnly(
this ICanAddMatcher<Cookie> more,
Func<string> customMessageGenerator
)
{
return more.AddMatcher(actual =>
{
var passed = actual?.HttpOnly ?? false;
return new MatcherResult(
passed,
() => $"Expected {actual.Name()} {passed.AsNot()}to be http-only",
customMessageGenerator
);
});
}
/// <summary>
/// Tests if the cookie has the Domain flag
/// </summary>
/// <param name="more"></param>
/// <param name="expectedDomain"></param>
/// <returns></returns>
public static IMore<Cookie> Domain(
this ICanAddMatcher<Cookie> more,
string expectedDomain
)
{
return more.Domain(expectedDomain, NULL_STRING);
}
/// <summary>
/// Tests if the cookie has the Domain flag
/// </summary>
/// <param name="more"></param>
/// <param name="expectedDomain"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<Cookie> Domain(
this ICanAddMatcher<Cookie> more,
string expectedDomain,
string customMessage
)
{
return more.Domain(expectedDomain, () => customMessage);
}
/// <summary>
/// Tests if the cookie has the Domain flag
/// </summary>
/// <param name="more"></param>
/// <param name="expectedDomain"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<Cookie> Domain(
this ICanAddMatcher<Cookie> more,
string expectedDomain,
Func<string> customMessageGenerator
)
{
return more.AddMatcher(actual =>
{
var passed = actual?.Domain == expectedDomain;
return new MatcherResult(
passed,
() => $"Expected {actual.Name()} to be for domain '{expectedDomain}'",
customMessageGenerator
);
});
}
/// <summary>
/// Tests if the cookie has the Age flag
/// </summary>
/// <param name="more"></param>
/// <param name="expectedAge"></param>
/// <returns></returns>
public static IMore<Cookie> Age(
this IMax<Cookie> more,
int expectedAge
)
{
return more.Age(expectedAge, NULL_STRING);
}
/// <summary>
/// Tests if the cookie has the Age flag
/// </summary>
/// <param name="more"></param>
/// <param name="expectedAge"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<Cookie> Age(
this IMax<Cookie> more,
int expectedAge,
string customMessage
)
{
return more.Age(expectedAge, () => customMessage);
}
/// <summary>
/// Tests if the cookie has the Age flag
/// </summary>
/// <param name="more"></param>
/// <param name="expectedAge"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<Cookie> Age(
this IMax<Cookie> more,
int expectedAge,
Func<string> customMessageGenerator
)
{
return more.AddMatcher(actual =>
{
var passed = false;
var hasMaxAge = actual.TryGetMetadata<int>("MaxAge", out var maxAge);
if (hasMaxAge)
{
passed = maxAge == expectedAge;
}
return new MatcherResult(
passed,
() =>
hasMaxAge
? $"Expected {actual.Name()} {passed.AsNot()}to have Max-Age '{expectedAge}' (found {maxAge})"
: $"Expected {actual.Name()} {passed.AsNot()}to have Max-Age set",
customMessageGenerator
);
});
}
private static Cookie ParseCookieHeader(
string header
)
{
var parts = header.Split(';');
return parts.Aggregate(
new Cookie(),
(acc, cur) =>
{
var subs = cur.Split('=');
var key = subs[0].Trim();
var value = string.Join("=", subs.Skip(1));
if (string.IsNullOrWhiteSpace(acc.Name))
{
acc.Name = key;
acc.Value = value;
}
else
{
if (CookieMutations.TryGetValue(key, out var modifier))
{
modifier(acc, value);
}
}
return acc;
}
);
}
private static readonly Dictionary<string, Action<Cookie, string>>
CookieMutations = new Dictionary<string, Action<Cookie, string>>(
StringComparer.InvariantCultureIgnoreCase
)
{
["Expires"] = SetCookieExpiration,
["Max-Age"] = SetCookieMaxAge,
["Domain"] = SetCookieDomain,
["Secure"] = SetCookieSecure,
["HttpOnly"] = SetCookieHttpOnly,
["SameSite"] = SetCookieSameSite
};
private static void SetCookieSameSite(
Cookie cookie,
string value
)
{
// Cookie object doesn't natively support the SameSite property, yet
cookie.SetMetadata("SameSite", value);
}
private static void SetCookieHttpOnly(
Cookie cookie,
string value
)
{
cookie.HttpOnly = true;
}
private static void SetCookieSecure(
Cookie cookie,
string value
)
{
cookie.Secure = true;
}
private static void SetCookieDomain(
Cookie cookie,
string value
)
{
cookie.Domain = value;
}
private static void SetCookieMaxAge(
Cookie cookie,
string value
)
{
if (!int.TryParse(value, out var seconds))
{
throw new ArgumentException(
$"Unable to parse '{value}' as an integer value"
);
}
cookie.Expires = DateTime.Now.AddSeconds(seconds);
cookie.Expired = seconds < 1;
cookie.SetMetadata("MaxAge", seconds);
}
private static void SetCookieExpiration(
Cookie cookie,
string value
)
{
if (cookie.TryGetMetadata<int>("MaxAge", out _))
{
// Max-Age takes precedence over Expires
return;
}
if (!DateTime.TryParse(value, out var expires))
{
throw new ArgumentException(
$"Unable to parse '{value}' as a date-time value"
);
}
cookie.Expires = expires;
cookie.Expired = expires <= DateTime.Now;
}
private static string Name(this Cookie cookie)
{
return cookie?.Name ?? "unknown cookie";
}
}
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Net;
using System.Text;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.Messages;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Interfaces;
using GridProxy;
namespace WinGridProxy
{
#region Base Class
internal abstract class Session
{
internal const string EmptyXml = "<?xml version=\"1.0\"?><Empty>XML representation of this item is not available.</Empty>";
internal const string EmptyString = "String representation of this item is not available.";
internal const string EmptyNotation = "Notation representation of this item is not available.";
public Direction Direction { get; set; }
public String Host { get; set; }
public String Protocol { get; set; }
public String Name { get; set; }
public String ContentType { get; set; }
public int Length { get; set; }
public DateTime TimeStamp { get; set; }
// listview specific stuff, not serialized or deserialized
public bool Selected { get; set; }
public System.Drawing.Color BackColor { get; set; }
public Session()
{
this.TimeStamp = DateTime.UtcNow;
this.Host = this.Protocol = this.Name = String.Empty;
this.Length = 0;
this.ContentType = String.Empty;
}
public virtual string ToRawString(Direction direction)
{
return EmptyString;
}
public virtual byte[] ToBytes(Direction direction)
{
return OpenMetaverse.Utils.EmptyBytes;
}
public virtual string ToXml(Direction direction)
{
return EmptyXml;
}
public virtual string ToStringNotation(Direction direction)
{
return EmptyNotation;
}
public abstract string ToPrettyString(Direction direction);
public abstract byte[] Serialize();
public abstract Session Deserialize(byte[] bytes);
}
#endregion
#region Packets
internal sealed class SessionPacket : Session
{
public Packet Packet { get; set; }
public SessionPacket() : base() { this.Protocol = "UDP"; }
public SessionPacket(Packet packet, Direction direction, IPEndPoint endpoint, String contentType)
: base()
{
this.Packet = packet;
this.Name = packet.Type.ToString();
this.Direction = direction;
this.Host = String.Format("{0}:{1}", endpoint.Address, endpoint.Port);
this.ContentType = contentType;
this.Length = packet.Length;
this.Protocol = "UDP";
}
public override string ToPrettyString(Direction direction)
{
if (direction == this.Direction)
return PacketDecoder.PacketToString(this.Packet);
else
return String.Empty;
}
public override string ToRawString(Direction direction)
{
if (direction == this.Direction)
return PacketDecoder.PacketToString(this.Packet);
else
return String.Empty;
}
public override byte[] ToBytes(Direction direction)
{
if (direction == this.Direction)
return Packet.ToBytes();
else
return base.ToBytes(direction);
}
//public override string ToXml(Direction direction)
//{
// if (direction == this.Direction)
// return Packet.ToXmlString(this.Packet);
// else
// return base.ToXml(direction);
//}
//public override string ToStringNotation(Direction direction)
//{
// if (direction == this.Direction)
// return Packet.GetLLSD(this.Packet).ToString();
// else
// return base.ToStringNotation(direction);
//}
public override byte[] Serialize()
{
OSDMap map = new OSDMap(5);
map["Name"] = OSD.FromString(this.Name);
map["Host"] = OSD.FromString(this.Host);
map["PacketBytes"] = OSD.FromBinary(this.Packet.ToBytes());
map["Direction"] = OSD.FromInteger((int)this.Direction);
map["ContentType"] = OSD.FromString(this.ContentType);
return OpenMetaverse.Utils.StringToBytes(map.ToString());
}
public override Session Deserialize(byte[] bytes)
{
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDNotation(OpenMetaverse.Utils.BytesToString(bytes));
this.Host = map["Host"].AsString();
this.Direction = (Direction)map["Direction"].AsInteger();
this.ContentType = map["ContentType"].AsString();
byte[] packetData = map["PacketBytes"].AsBinary();
this.Length = packetData.Length;
int packetEnd = packetData.Length - 1;
this.Packet = Packet.BuildPacket(packetData, ref packetEnd, null);
this.Name = this.Packet.Type.ToString();
return this;
}
}
#endregion Packets
#region Capabilities
internal sealed class SessionCaps : Session
{
byte[] RequestBytes { get; set; }
byte[] ResponseBytes { get; set; }
WebHeaderCollection RequestHeaders { get; set; }
WebHeaderCollection ResponseHeaders { get; set; }
string FullUri { get; set; }
public SessionCaps() : base() { /*this.Protocol = "Caps";*/ }
public SessionCaps(byte[] requestBytes, byte[] responseBytes,
WebHeaderCollection requestHeaders, WebHeaderCollection responseHeaders,
Direction direction, string uri, string capsKey, String proto, string fullUri)
: base()
{
if (requestBytes != null)
this.RequestBytes = requestBytes;
else
this.RequestBytes = OpenMetaverse.Utils.EmptyBytes;
if (responseBytes != null)
this.ResponseBytes = responseBytes;
else
this.ResponseBytes = OpenMetaverse.Utils.EmptyBytes;
this.RequestHeaders = requestHeaders;
this.ResponseHeaders = responseHeaders;
this.Protocol = proto;
this.FullUri = fullUri;
this.Name = capsKey;
this.Direction = direction;
this.Host = uri;
this.ContentType = (direction == Direction.Incoming) ? this.ResponseHeaders.Get("Content-Type") : this.RequestHeaders.Get("Content-Type");
this.Length = (requestBytes != null) ? requestBytes.Length : 0;
this.Length += (responseBytes != null) ? responseBytes.Length : 0;
}
public override string ToPrettyString(Direction direction)
{
try
{
if (direction == Direction.Incoming)
{
if (this.ResponseBytes != null && this.ResponseBytes.Length > 0)
{
IMessage message = null;
OSD osd = OSDParser.Deserialize(this.ResponseBytes);
if (osd is OSDMap)
{
OSDMap data = (OSDMap)osd;
if (data.ContainsKey("body"))
message = OpenMetaverse.Messages.MessageUtils.DecodeEvent(this.Name, (OSDMap)data["body"]);
else
message = OpenMetaverse.Messages.MessageUtils.DecodeEvent(this.Name, data);
if (message != null)
return PacketDecoder.MessageToString(message, 0);
else
return "No Decoder for " + this.Name + Environment.NewLine +
OSDParser.SerializeLLSDNotationFormatted(data) + Environment.NewLine +
"Please report this at http://jira.openmetaverse.co Be sure to include the entire message.";
}
}
}
else
{
if (this.RequestBytes != null && this.RequestBytes.Length > 0)
{
if (this.RequestBytes[0] == 60)
{
OSD osd = OSDParser.Deserialize(this.RequestBytes);
if (osd is OSDMap)
{
IMessage message = null;
OSDMap data = (OSDMap)osd;
if (data.ContainsKey("body"))
message = MessageUtils.DecodeEvent(this.Name, (OSDMap)data["body"]);
else
message = MessageUtils.DecodeEvent(this.Name, data);
if (message != null)
return PacketDecoder.MessageToString(message, 0);
else
return "No Decoder for " + this.Name + Environment.NewLine +
OSDParser.SerializeLLSDNotationFormatted(data) + Environment.NewLine +
"Please report this at http://jira.openmetaverse.co Be sure to include the entire message.";
}
else
{
return osd.ToString();
}
}
else
{
// this means its probably a script or asset using the uploader capability
// so we'll just return the raw bytes as a string
//if (this.RequestBytes[0] == 100)
//{
return Utils.BytesToString(this.RequestBytes);
//}
}
}
else
{
return String.Empty;
}
}
}
catch { }
return String.Empty;
}
public override string ToRawString(Direction direction)
{
try
{
if (direction == Direction.Incoming)
{
if (this.ResponseBytes != null)
{
StringBuilder result = new StringBuilder();
foreach (String key in ResponseHeaders.Keys)
{
result.AppendFormat("{0} {1}" + Environment.NewLine, key, ResponseHeaders[key]);
}
result.AppendLine();
result.AppendLine(OpenMetaverse.Utils.BytesToString(this.ResponseBytes));
return result.ToString();
}
else
return String.Empty;
}
else
{
if (this.RequestBytes != null)
{
StringBuilder result = new StringBuilder();
result.AppendFormat("Request URI: {0}{1}", FullUri, Environment.NewLine);
foreach (String key in RequestHeaders.Keys)
{
result.AppendFormat("{0}: {1}" + Environment.NewLine, key, RequestHeaders[key]);
}
result.AppendLine();
result.AppendLine(OpenMetaverse.Utils.BytesToString(this.RequestBytes));
return result.ToString();
}
else
return String.Empty;
}
}
catch { }
return string.Empty;
}
public override byte[] ToBytes(Direction direction)
{
if (direction == Direction.Incoming)
{
if (this.ResponseBytes != null)
return this.ResponseBytes;
else
return base.ToBytes(direction);
}
else
{
if (this.RequestBytes != null)
return this.RequestBytes;
else
return base.ToBytes(direction);
}
}
public override string ToStringNotation(Direction direction)
{
try
{
if (direction == Direction.Incoming)
{
if (this.ResponseBytes != null)
return BytesToOsd(this.ResponseBytes);
//return this.ResponseBytes;
else
return base.ToStringNotation(direction);
}
else
{
if (this.RequestBytes != null)
{
return BytesToOsd(this.RequestBytes);
}
else
return base.ToStringNotation(direction);
}
}
catch { }
return string.Empty;
}
public override string ToXml(Direction direction)
{
try
{
if (direction == Direction.Incoming)
{
if (this.ResponseBytes != null)
return BytesToXml(this.ResponseBytes);
else
return base.ToXml(direction);
}
else
{
if (this.RequestBytes != null)
return BytesToXml(this.RequestBytes);
else
return base.ToXml(direction);
}
}
catch { }
return string.Empty;
}
// Sanity check the bytes are infact OSD
private string BytesToOsd(byte[] bytes)
{
try
{
OSD osd = OSDParser.Deserialize(bytes);
return OSDParser.SerializeLLSDNotationFormatted(osd);
}
catch (LitJson.JsonException)
{
// unable to decode as notation format
return base.ToStringNotation(this.Direction);
}
}
// Sanity check the bytes are infact an XML
private string BytesToXml(byte[] bytes)
{
String result = Utils.BytesToString(bytes);
if (result.StartsWith("<?xml"))
return result;
else
return base.ToXml(this.Direction);
}
public override byte[] Serialize()
{
OSDMap map = new OSDMap(5);
map["Name"] = OSD.FromString(this.Name);
map["Host"] = OSD.FromString(this.Host);
map["RequestBytes"] = OSD.FromBinary(this.RequestBytes);
map["ResponseBytes"] = OSD.FromBinary(this.ResponseBytes);
map["Direction"] = OSD.FromInteger((int)this.Direction);
map["ContentType"] = OSD.FromString(this.ContentType);
map["Protocol"] = OSD.FromString(this.Protocol);
OSDArray requestHeadersArray = new OSDArray();
foreach (String key in this.RequestHeaders.Keys)
{
OSDMap rMap = new OSDMap(1);
rMap[key] = OSD.FromString(this.RequestHeaders[key]);
requestHeadersArray.Add(rMap);
}
if(requestHeadersArray.Count > 0)
map["RequestHeaders"] = requestHeadersArray;
OSDArray responseHeadersArray = new OSDArray();
foreach (String key in this.ResponseHeaders.Keys)
{
OSDMap rMap = new OSDMap(1);
rMap[key] = OSD.FromString(this.ResponseHeaders[key]);
responseHeadersArray.Add(rMap);
}
if(responseHeadersArray.Count > 0)
map["ResponseHeaders"] = responseHeadersArray;
return OpenMetaverse.Utils.StringToBytes(map.ToString());
}
public override Session Deserialize(byte[] bytes)
{
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDNotation(OpenMetaverse.Utils.BytesToString(bytes));
this.Name = map["Name"].AsString();
this.Host = map["Host"].AsString();
this.RequestBytes = map["RequestBytes"].AsBinary();
this.ResponseBytes = map["ResponseBytes"].AsBinary();
this.Direction = (Direction)map["Direction"].AsInteger();
this.Length = ResponseBytes.Length + RequestBytes.Length;
this.ContentType = map["ContentType"].AsString();
this.Protocol = map["Protocol"].AsString();
this.RequestHeaders = new WebHeaderCollection();
if (map.ContainsKey("RequestHeaders"))
{
OSDArray requestHeadersArray = (OSDArray)map["RequestHeaders"];
for (int i = 0; i < requestHeadersArray.Count; i++)
{
OSDMap rMap = (OSDMap)requestHeadersArray[i];
foreach (string key in rMap.Keys)
{
this.RequestHeaders.Add(key, rMap[key].AsString());
}
}
}
this.ResponseHeaders = new WebHeaderCollection();
if (map.ContainsKey("ResponseHeaders"))
{
OSDArray responseHeadersArray = (OSDArray)map["ResponseHeaders"];
for (int i = 0; i < responseHeadersArray.Count; i++)
{
OSDMap rMap = (OSDMap)responseHeadersArray[i];
foreach (string key in rMap.Keys)
{
this.ResponseHeaders.Add(key, rMap[key].AsString());
}
}
}
return this;
}
}
#endregion Capabilities
#region Login
internal sealed class SessionLogin : Session
{
private object Data { get; set; }
//request, direction, comboBoxLoginURL.Text
public SessionLogin() : base() { this.Protocol = "https"; }
public SessionLogin(object request, Direction direction, String url, String contentType)
: base()
{
this.Data = request;
this.Direction = direction;
this.Host = url;
this.ContentType = contentType;
this.Name = (direction == Direction.Incoming) ? "Login Response" : "Login Request";
this.Protocol = "https";
this.Length = this.Data.ToString().Length;
}
public override string ToPrettyString(Direction direction)
{
if (direction == this.Direction)
{
return this.Data.ToString();
}
else
{
return String.Empty;
}
}
public override string ToRawString(Direction direction)
{
if (direction == this.Direction)
{
return this.Data.ToString();
}
else
{
return String.Empty;
}
}
public override string ToXml(Direction direction)
{
return base.ToXml(direction);
//if (direction == this.Direction)
//{
// return this.Data.ToString();
//}
//else
//{
// return base.ToXml(direction);
//}
}
public override byte[] ToBytes(Direction direction)
{
if (direction == this.Direction)
{
return OpenMetaverse.Utils.StringToBytes(this.Data.ToString());
}
else
{
return base.ToBytes(direction);
}
}
public override byte[] Serialize()
{
OSDMap map = new OSDMap(6);
map["Name"] = OSD.FromString(this.Name);
map["Host"] = OSD.FromString(this.Host);
map["Data"] = OSD.FromString(this.Data.ToString());
map["Direction"] = OSD.FromInteger((int)this.Direction);
map["ContentType"] = OSD.FromString(this.ContentType);
map["Protocol"] = OSD.FromString(this.Protocol);
return OpenMetaverse.Utils.StringToBytes(map.ToString());
}
public override Session Deserialize(byte[] bytes)
{
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDNotation(OpenMetaverse.Utils.BytesToString(bytes));
this.Name = map["Name"].AsString();
this.Host = map["Host"].AsString();
this.Data = map["Data"].AsString();
this.Length = this.Data.ToString().Length;
this.Direction = (Direction)map["Direction"].AsInteger();
this.ContentType = map["ContentType"].AsString();
this.Protocol = map["Protocol"].AsString();
return this;
}
}
#endregion Login
#region EventQueue Messages
internal class SessionEvent : Session
{
private byte[] ResponseBytes;
private WebHeaderCollection ResponseHeaders;
public SessionEvent() : base() { this.Protocol = "EventQ"; }
public SessionEvent(byte[] responseBytes, WebHeaderCollection responseHeaders,
String uri, String capsKey, String proto)
: base()
{
this.Protocol = proto;
this.Direction = Direction.Incoming; // EventQueue Messages are always inbound from the simulator
this.ResponseBytes = responseBytes;
this.ResponseHeaders = responseHeaders;
this.Host = uri;
this.Name = capsKey;
this.ContentType = responseHeaders.Get("Content-Type");
var ContentLength = responseHeaders.Get("Content-Length");
if (ContentLength != null)
this.Length = Int32.Parse (ContentLength);
else
this.Length = 0;
}
public override string ToPrettyString(Direction direction)
{
if (direction == this.Direction)
{
IMessage message = null;
OSD osd = OSDParser.Deserialize(this.ResponseBytes);
OSDMap data = (OSDMap)osd;
if (data.ContainsKey("body"))
message = MessageUtils.DecodeEvent(this.Name, (OSDMap)data["body"]);
else
message = MessageUtils.DecodeEvent(this.Name, data);
if (message != null)
return PacketDecoder.MessageToString(message, 0);
else
return "No Decoder for " + this.Name + Environment.NewLine + osd.ToString();
}
else
{
return String.Empty;
}
}
public override byte[] ToBytes(Direction direction)
{
if (direction == this.Direction)
{
return this.ResponseBytes;
}
else
{
return base.ToBytes(direction);
}
}
public override string ToRawString(Direction direction)
{
if (direction == this.Direction)
{
StringBuilder result = new StringBuilder();
foreach (String key in ResponseHeaders.Keys)
{
result.AppendFormat("{0} {1}" + Environment.NewLine, key, ResponseHeaders[key]);
}
result.AppendLine();
result.AppendLine(this.ToXml(direction));
return result.ToString();
}
else
{
return String.Empty;
}
}
public override string ToXml(Direction direction)
{
if (direction == this.Direction)
{
return OpenMetaverse.Utils.BytesToString(this.ResponseBytes);
}
else
{
return base.ToXml(direction);
}
}
public override string ToStringNotation(Direction direction)
{
if (direction == this.Direction)
{
OSD osd = OSDParser.DeserializeLLSDXml(this.ResponseBytes);
return osd.ToString();
}
else
{
return base.ToStringNotation(direction);
}
}
public override byte[] Serialize()
{
OSDMap map = new OSDMap(7);
map["Name"] = OSD.FromString(this.Name);
map["Host"] = OSD.FromString(this.Host);
map["ResponseBytes"] = OSD.FromBinary(this.ResponseBytes);
map["Direction"] = OSD.FromInteger((int)this.Direction);
map["ContentType"] = OSD.FromString(this.ContentType);
map["Protocol"] = OSD.FromString(this.Protocol);
OSDArray responseHeadersArray = new OSDArray();
foreach (String key in this.ResponseHeaders.Keys)
{
OSDMap rMap = new OSDMap(1);
rMap[key] = OSD.FromString(this.ResponseHeaders[key]);
responseHeadersArray.Add(rMap);
}
map["ResponseHeaders"] = responseHeadersArray;
return Utils.StringToBytes(map.ToString());
}
public override Session Deserialize(byte[] bytes)
{
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDNotation(OpenMetaverse.Utils.BytesToString(bytes));
this.Name = map["Name"].AsString();
this.Host = map["Host"].AsString();
this.ResponseBytes = map["ResponseBytes"].AsBinary();
this.Direction = (Direction)map["Direction"].AsInteger();
this.ContentType = map["ContentType"].AsString();
this.Protocol = map["Protocol"].AsString();
this.Length = ResponseBytes.Length;
if (map.ContainsKey("ResponseHeaders"))
{
this.ResponseHeaders = new WebHeaderCollection();
OSDArray responseHeadersArray = (OSDArray)map["ResponseHeaders"];
for (int i = 0; i < responseHeadersArray.Count; i++)
{
OSDMap rMap = (OSDMap)responseHeadersArray[i];
foreach (string key in rMap.Keys)
{
this.ResponseHeaders.Add(key, rMap[key].AsString());
}
}
}
return this;
}
}
#endregion
}
| |
namespace Orleans.CodeGenerator
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.CodeGeneration;
using Orleans.CodeGenerator.Utilities;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Serialization;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
/// <summary>
/// Code generator which generates serializers.
/// </summary>
public static class SerializerGenerator
{
private static readonly TypeFormattingOptions GeneratedTypeNameOptions = new TypeFormattingOptions(
ClassSuffix,
includeGenericParameters: false,
includeTypeParameters: false,
nestedClassSeparator: '_',
includeGlobal: false);
/// <summary>
/// The suffix appended to the name of generated classes.
/// </summary>
private const string ClassSuffix = "Serializer";
/// <summary>
/// The suffix appended to the name of the generic serializer registration class.
/// </summary>
private const string RegistererClassSuffix = "Registerer";
/// <summary>
/// Generates the class for the provided grain types.
/// </summary>
/// <param name="type">The grain interface type.</param>
/// <param name="onEncounteredType">
/// The callback invoked when a type is encountered.
/// </param>
/// <returns>
/// The generated class.
/// </returns>
internal static IEnumerable<TypeDeclarationSyntax> GenerateClass(Type type, Action<Type> onEncounteredType)
{
var typeInfo = type.GetTypeInfo();
var genericTypes = typeInfo.IsGenericTypeDefinition
? typeInfo.GetGenericArguments().Select(_ => SF.TypeParameter(_.ToString())).ToArray()
: new TypeParameterSyntax[0];
var attributes = new List<AttributeSyntax>
{
CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),
SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()),
SF.Attribute(typeof(SerializerAttribute).GetNameSyntax())
.AddArgumentListArguments(
SF.AttributeArgument(SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false))))
};
var className = CodeGeneratorCommon.ClassPrefix + type.GetParseableName(GeneratedTypeNameOptions);
var fields = GetFields(type);
// Mark each field type for generation
foreach (var field in fields)
{
var fieldType = field.FieldInfo.FieldType;
onEncounteredType(fieldType);
}
var members = new List<MemberDeclarationSyntax>(GenerateStaticFields(fields))
{
GenerateDeepCopierMethod(type, fields),
GenerateSerializerMethod(type, fields),
GenerateDeserializerMethod(type, fields),
};
if (typeInfo.IsConstructedGenericType || !typeInfo.IsGenericTypeDefinition)
{
members.Add(GenerateRegisterMethod(type));
members.Add(GenerateConstructor(className));
attributes.Add(SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax()));
}
var classDeclaration =
SF.ClassDeclaration(className)
.AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
.AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray()))
.AddMembers(members.ToArray())
.AddConstraintClauses(type.GetTypeConstraintSyntax());
if (genericTypes.Length > 0)
{
classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
}
var classes = new List<TypeDeclarationSyntax> { classDeclaration };
if (typeInfo.IsGenericTypeDefinition)
{
// Create a generic representation of the serializer type.
var serializerType =
SF.GenericName(classDeclaration.Identifier)
.WithTypeArgumentList(
SF.TypeArgumentList()
.AddArguments(
type.GetGenericArguments()
.Select(_ => SF.OmittedTypeArgument())
.Cast<TypeSyntax>()
.ToArray()));
var registererClassName = className + "_" +
string.Join("_",
type.GetTypeInfo().GenericTypeParameters.Select(_ => _.Name)) + "_" +
RegistererClassSuffix;
classes.Add(
SF.ClassDeclaration(registererClassName)
.AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
.AddAttributeLists(
SF.AttributeList()
.AddAttributes(
CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),
SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()),
SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax())))
.AddMembers(
GenerateMasterRegisterMethod(type, serializerType),
GenerateConstructor(registererClassName)));
}
return classes;
}
/// <summary>
/// Returns syntax for the deserializer method.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="fields">The fields.</param>
/// <returns>Syntax for the deserializer method.</returns>
private static MemberDeclarationSyntax GenerateDeserializerMethod(Type type, List<FieldInfoMember> fields)
{
Expression<Action> deserializeInner =
() => SerializationManager.DeserializeInner(default(Type), default(BinaryTokenStreamReader));
var streamParameter = SF.IdentifierName("stream");
var resultDeclaration =
SF.LocalDeclarationStatement(
SF.VariableDeclaration(type.GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("result")
.WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type)))));
var resultVariable = SF.IdentifierName("result");
var body = new List<StatementSyntax> { resultDeclaration };
// Value types cannot be referenced, only copied, so there is no need to box & record instances of value types.
if (!type.IsValueType)
{
// Record the result for cyclic deserialization.
Expression<Action> recordObject = () => DeserializationContext.Current.RecordObject(default(object));
var currentSerializationContext =
SyntaxFactory.AliasQualifiedName(
SF.IdentifierName(SF.Token(SyntaxKind.GlobalKeyword)),
SF.IdentifierName("Orleans"))
.Qualify("Serialization")
.Qualify("DeserializationContext")
.Qualify("Current");
body.Add(
SF.ExpressionStatement(
recordObject.Invoke(currentSerializationContext)
.AddArgumentListArguments(SF.Argument(resultVariable))));
}
// Deserialize all fields.
foreach (var field in fields)
{
var deserialized =
deserializeInner.Invoke()
.AddArgumentListArguments(
SF.Argument(SF.TypeOfExpression(field.Type)),
SF.Argument(streamParameter));
body.Add(
SF.ExpressionStatement(
field.GetSetter(
resultVariable,
SF.CastExpression(field.Type, deserialized))));
}
body.Add(SF.ReturnStatement(SF.CastExpression(type.GetTypeSyntax(), resultVariable)));
return
SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "Deserializer")
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()),
SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamReader).GetTypeSyntax()))
.AddBodyStatements(body.ToArray())
.AddAttributeLists(
SF.AttributeList()
.AddAttributes(SF.Attribute(typeof(DeserializerMethodAttribute).GetNameSyntax())));
}
private static MemberDeclarationSyntax GenerateSerializerMethod(Type type, List<FieldInfoMember> fields)
{
Expression<Action> serializeInner =
() =>
SerializationManager.SerializeInner(default(object), default(BinaryTokenStreamWriter), default(Type));
var body = new List<StatementSyntax>
{
SF.LocalDeclarationStatement(
SF.VariableDeclaration(type.GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("input")
.WithInitializer(
SF.EqualsValueClause(
SF.CastExpression(type.GetTypeSyntax(), SF.IdentifierName("untypedInput"))))))
};
var inputExpression = SF.IdentifierName("input");
// Serialize all members.
foreach (var field in fields)
{
body.Add(
SF.ExpressionStatement(
serializeInner.Invoke()
.AddArgumentListArguments(
SF.Argument(field.GetGetter(inputExpression, forceAvoidCopy: true)),
SF.Argument(SF.IdentifierName("stream")),
SF.Argument(SF.TypeOfExpression(field.FieldInfo.FieldType.GetTypeSyntax())))));
}
return
SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Serializer")
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("untypedInput")).WithType(typeof(object).GetTypeSyntax()),
SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamWriter).GetTypeSyntax()),
SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()))
.AddBodyStatements(body.ToArray())
.AddAttributeLists(
SF.AttributeList()
.AddAttributes(SF.Attribute(typeof(SerializerMethodAttribute).GetNameSyntax())));
}
/// <summary>
/// Returns syntax for the deep copier method.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="fields">The fields.</param>
/// <returns>Syntax for the deep copier method.</returns>
private static MemberDeclarationSyntax GenerateDeepCopierMethod(Type type, List<FieldInfoMember> fields)
{
var originalVariable = SF.IdentifierName("original");
var inputVariable = SF.IdentifierName("input");
var resultVariable = SF.IdentifierName("result");
var body = new List<StatementSyntax>();
if (type.GetCustomAttribute<ImmutableAttribute>() != null)
{
// Immutable types do not require copying.
body.Add(SF.ReturnStatement(originalVariable));
}
else
{
body.Add(
SF.LocalDeclarationStatement(
SF.VariableDeclaration(type.GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("input")
.WithInitializer(
SF.EqualsValueClause(
SF.ParenthesizedExpression(
SF.CastExpression(type.GetTypeSyntax(), originalVariable)))))));
body.Add(
SF.LocalDeclarationStatement(
SF.VariableDeclaration(type.GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("result")
.WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type))))));
// Record this serialization.
Expression<Action> recordObject =
() => SerializationContext.Current.RecordObject(default(object), default(object));
var currentSerializationContext =
SyntaxFactory.AliasQualifiedName(
SF.IdentifierName(SF.Token(SyntaxKind.GlobalKeyword)),
SF.IdentifierName("Orleans"))
.Qualify("Serialization")
.Qualify("SerializationContext")
.Qualify("Current");
body.Add(
SF.ExpressionStatement(
recordObject.Invoke(currentSerializationContext)
.AddArgumentListArguments(SF.Argument(originalVariable), SF.Argument(resultVariable))));
// Copy all members from the input to the result.
foreach (var field in fields)
{
body.Add(SF.ExpressionStatement(field.GetSetter(resultVariable, field.GetGetter(inputVariable))));
}
body.Add(SF.ReturnStatement(resultVariable));
}
return
SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "DeepCopier")
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("original")).WithType(typeof(object).GetTypeSyntax()))
.AddBodyStatements(body.ToArray())
.AddAttributeLists(
SF.AttributeList().AddAttributes(SF.Attribute(typeof(CopierMethodAttribute).GetNameSyntax())));
}
/// <summary>
/// Returns syntax for the static fields of the serializer class.
/// </summary>
/// <param name="fields">The fields.</param>
/// <returns>Syntax for the static fields of the serializer class.</returns>
private static MemberDeclarationSyntax[] GenerateStaticFields(List<FieldInfoMember> fields)
{
var result = new List<MemberDeclarationSyntax>();
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Expression<Action<TypeInfo>> getField = _ => _.GetField(string.Empty, BindingFlags.Default);
Expression<Action<Type>> getTypeInfo = _ => _.GetTypeInfo();
Expression<Action> getGetter = () => SerializationManager.GetGetter(default(FieldInfo));
Expression<Action> getReferenceSetter = () => SerializationManager.GetReferenceSetter(default(FieldInfo));
Expression<Action> getValueSetter = () => SerializationManager.GetValueSetter(default(FieldInfo));
// Expressions for specifying binding flags.
var bindingFlags = SyntaxFactoryExtensions.GetBindingFlagsParenthesizedExpressionSyntax(
SyntaxKind.BitwiseOrExpression,
BindingFlags.Instance,
BindingFlags.NonPublic,
BindingFlags.Public);
// Add each field and initialize it.
foreach (var field in fields)
{
var fieldInfo =
getField.Invoke(getTypeInfo.Invoke(SF.TypeOfExpression(field.FieldInfo.DeclaringType.GetTypeSyntax())))
.AddArgumentListArguments(
SF.Argument(field.FieldInfo.Name.GetLiteralExpression()),
SF.Argument(bindingFlags));
var fieldInfoVariable =
SF.VariableDeclarator(field.InfoFieldName).WithInitializer(SF.EqualsValueClause(fieldInfo));
var fieldInfoField = SF.IdentifierName(field.InfoFieldName);
if (!field.IsGettableProperty || !field.IsSettableProperty)
{
result.Add(
SF.FieldDeclaration(
SF.VariableDeclaration(typeof(FieldInfo).GetTypeSyntax()).AddVariables(fieldInfoVariable))
.AddModifiers(
SF.Token(SyntaxKind.PrivateKeyword),
SF.Token(SyntaxKind.StaticKeyword),
SF.Token(SyntaxKind.ReadOnlyKeyword)));
}
// Declare the getter for this field.
if (!field.IsGettableProperty)
{
var getterType =
typeof(Func<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType)
.GetTypeSyntax();
var fieldGetterVariable =
SF.VariableDeclarator(field.GetterFieldName)
.WithInitializer(
SF.EqualsValueClause(
SF.CastExpression(
getterType,
getGetter.Invoke().AddArgumentListArguments(SF.Argument(fieldInfoField)))));
result.Add(
SF.FieldDeclaration(SF.VariableDeclaration(getterType).AddVariables(fieldGetterVariable))
.AddModifiers(
SF.Token(SyntaxKind.PrivateKeyword),
SF.Token(SyntaxKind.StaticKeyword),
SF.Token(SyntaxKind.ReadOnlyKeyword)));
}
if (!field.IsSettableProperty)
{
if (field.FieldInfo.DeclaringType != null && field.FieldInfo.DeclaringType.IsValueType)
{
var setterType =
typeof(SerializationManager.ValueTypeSetter<,>).MakeGenericType(
field.FieldInfo.DeclaringType,
field.FieldInfo.FieldType).GetTypeSyntax();
var fieldSetterVariable =
SF.VariableDeclarator(field.SetterFieldName)
.WithInitializer(
SF.EqualsValueClause(
SF.CastExpression(
setterType,
getValueSetter.Invoke()
.AddArgumentListArguments(SF.Argument(fieldInfoField)))));
result.Add(
SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable))
.AddModifiers(
SF.Token(SyntaxKind.PrivateKeyword),
SF.Token(SyntaxKind.StaticKeyword),
SF.Token(SyntaxKind.ReadOnlyKeyword)));
}
else
{
var setterType =
typeof(Action<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType)
.GetTypeSyntax();
var fieldSetterVariable =
SF.VariableDeclarator(field.SetterFieldName)
.WithInitializer(
SF.EqualsValueClause(
SF.CastExpression(
setterType,
getReferenceSetter.Invoke()
.AddArgumentListArguments(SF.Argument(fieldInfoField)))));
result.Add(
SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable))
.AddModifiers(
SF.Token(SyntaxKind.PrivateKeyword),
SF.Token(SyntaxKind.StaticKeyword),
SF.Token(SyntaxKind.ReadOnlyKeyword)));
}
}
}
return result.ToArray();
}
/// <summary>
/// Returns syntax for initializing a new instance of the provided type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>Syntax for initializing a new instance of the provided type.</returns>
private static ExpressionSyntax GetObjectCreationExpressionSyntax(Type type)
{
ExpressionSyntax result;
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsValueType)
{
// Use the default value.
result = SF.DefaultExpression(typeInfo.GetTypeSyntax());
}
else if (type.GetConstructor(Type.EmptyTypes) != null)
{
// Use the default constructor.
result = SF.ObjectCreationExpression(typeInfo.GetTypeSyntax()).AddArgumentListArguments();
}
else
{
// Create an unformatted object.
Expression<Func<object>> getUninitializedObject =
#if NETSTANDARD
() => SerializationManager.GetUninitializedObjectWithFormatterServices(default(Type));
#else
() => FormatterServices.GetUninitializedObject(default(Type));
#endif
result = SF.CastExpression(
type.GetTypeSyntax(),
getUninitializedObject.Invoke()
.AddArgumentListArguments(
SF.Argument(SF.TypeOfExpression(typeInfo.GetTypeSyntax()))));
}
return result;
}
/// <summary>
/// Returns syntax for the serializer registration method.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>Syntax for the serializer registration method.</returns>
private static MemberDeclarationSyntax GenerateRegisterMethod(Type type)
{
Expression<Action> register =
() =>
SerializationManager.Register(
default(Type),
default(SerializationManager.DeepCopier),
default(SerializationManager.Serializer),
default(SerializationManager.Deserializer));
return
SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Register")
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters()
.AddBodyStatements(
SF.ExpressionStatement(
register.Invoke()
.AddArgumentListArguments(
SF.Argument(SF.TypeOfExpression(type.GetTypeSyntax())),
SF.Argument(SF.IdentifierName("DeepCopier")),
SF.Argument(SF.IdentifierName("Serializer")),
SF.Argument(SF.IdentifierName("Deserializer")))));
}
/// <summary>
/// Returns syntax for the constructor.
/// </summary>
/// <param name="className">The name of the class.</param>
/// <returns>Syntax for the constructor.</returns>
private static ConstructorDeclarationSyntax GenerateConstructor(string className)
{
return
SF.ConstructorDeclaration(className)
.AddModifiers(SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters()
.AddBodyStatements(
SF.ExpressionStatement(
SF.InvocationExpression(SF.IdentifierName("Register")).AddArgumentListArguments()));
}
/// <summary>
/// Returns syntax for the generic serializer registration method for the provided type..
/// </summary>
/// <param name="type">The type which is supported by this serializer.</param>
/// <param name="serializerType">The type of the serializer.</param>
/// <returns>Syntax for the generic serializer registration method for the provided type..</returns>
private static MemberDeclarationSyntax GenerateMasterRegisterMethod(Type type, TypeSyntax serializerType)
{
Expression<Action> register = () => SerializationManager.Register(default(Type), default(Type));
return
SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Register")
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters()
.AddBodyStatements(
SF.ExpressionStatement(
register.Invoke()
.AddArgumentListArguments(
SF.Argument(
SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false))),
SF.Argument(SF.TypeOfExpression(serializerType)))));
}
/// <summary>
/// Returns a sorted list of the fields of the provided type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>A sorted list of the fields of the provided type.</returns>
private static List<FieldInfoMember> GetFields(Type type)
{
var result =
type.GetAllFields()
.Where(field => !field.IsNotSerialized)
.Select((info, i) => new FieldInfoMember { FieldInfo = info, FieldNumber = i })
.ToList();
result.Sort(FieldInfoMember.Comparer.Instance);
return result;
}
/// <summary>
/// Represents a field.
/// </summary>
private class FieldInfoMember
{
private PropertyInfo property;
/// <summary>
/// Gets or sets the underlying <see cref="FieldInfo"/> instance.
/// </summary>
public FieldInfo FieldInfo { get; set; }
/// <summary>
/// Sets the ordinal assigned to this field.
/// </summary>
public int FieldNumber { private get; set; }
/// <summary>
/// Gets the name of the field info field.
/// </summary>
public string InfoFieldName
{
get
{
return "field" + this.FieldNumber;
}
}
/// <summary>
/// Gets the name of the getter field.
/// </summary>
public string GetterFieldName
{
get
{
return "getField" + this.FieldNumber;
}
}
/// <summary>
/// Gets the name of the setter field.
/// </summary>
public string SetterFieldName
{
get
{
return "setField" + this.FieldNumber;
}
}
/// <summary>
/// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete getter.
/// </summary>
public bool IsGettableProperty
{
get
{
return this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete;
}
}
/// <summary>
/// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete setter.
/// </summary>
public bool IsSettableProperty
{
get
{
return this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete;
}
}
/// <summary>
/// Gets syntax representing the type of this field.
/// </summary>
public TypeSyntax Type
{
get
{
return this.FieldInfo.FieldType.GetTypeSyntax();
}
}
/// <summary>
/// Gets the <see cref="PropertyInfo"/> which this field is the backing property for, or
/// <see langword="null" /> if this is not the backing field of an auto-property.
/// </summary>
private PropertyInfo PropertyInfo
{
get
{
if (this.property != null)
{
return this.property;
}
var propertyName = Regex.Match(this.FieldInfo.Name, "^<([^>]+)>.*$");
if (propertyName.Success && this.FieldInfo.DeclaringType != null)
{
var name = propertyName.Groups[1].Value;
this.property = this.FieldInfo.DeclaringType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public);
}
return this.property;
}
}
/// <summary>
/// Gets a value indicating whether or not this field is obsolete.
/// </summary>
private bool IsObsolete
{
get
{
var obsoleteAttr = this.FieldInfo.GetCustomAttribute<ObsoleteAttribute>();
// Get the attribute from the property, if present.
if (this.property != null && obsoleteAttr == null)
{
obsoleteAttr = this.property.GetCustomAttribute<ObsoleteAttribute>();
}
return obsoleteAttr != null;
}
}
/// <summary>
/// Returns syntax for retrieving the value of this field, deep copying it if neccessary.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param>
/// <returns>Syntax for retrieving the value of this field.</returns>
public ExpressionSyntax GetGetter(ExpressionSyntax instance, bool forceAvoidCopy = false)
{
// Retrieve the value of the field.
var getValueExpression = this.GetValueExpression(instance);
// Avoid deep-copying the field if possible.
if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable())
{
// Return the value without deep-copying it.
return getValueExpression;
}
// Deep-copy the value.
Expression<Action> deepCopyInner = () => SerializationManager.DeepCopyInner(default(object));
var typeSyntax = this.FieldInfo.FieldType.GetTypeSyntax();
return SF.CastExpression(
typeSyntax,
deepCopyInner.Invoke().AddArgumentListArguments(SF.Argument(getValueExpression)));
}
/// <summary>
/// Returns syntax for setting the value of this field.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <param name="value">Syntax for the new value.</param>
/// <returns>Syntax for setting the value of this field.</returns>
public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value)
{
// If the field is the backing field for an accessible auto-property use the property directly.
if (this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete)
{
return SF.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
instance.Member(this.PropertyInfo.Name),
value);
}
var instanceArg = SF.Argument(instance);
if (this.FieldInfo.DeclaringType != null && this.FieldInfo.DeclaringType.IsValueType)
{
instanceArg = instanceArg.WithRefOrOutKeyword(SF.Token(SyntaxKind.RefKeyword));
}
return
SF.InvocationExpression(SF.IdentifierName(this.SetterFieldName))
.AddArgumentListArguments(instanceArg, SF.Argument(value));
}
/// <summary>
/// Returns syntax for retrieving the value of this field.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <returns>Syntax for retrieving the value of this field.</returns>
private ExpressionSyntax GetValueExpression(ExpressionSyntax instance)
{
// If the field is the backing field for an accessible auto-property use the property directly.
ExpressionSyntax result;
if (this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete)
{
result = instance.Member(this.PropertyInfo.Name);
}
else
{
// Retrieve the field using the generated getter.
result =
SF.InvocationExpression(SF.IdentifierName(this.GetterFieldName))
.AddArgumentListArguments(SF.Argument(instance));
}
return result;
}
/// <summary>
/// A comparer for <see cref="FieldInfoMember"/> which compares by name.
/// </summary>
public class Comparer : IComparer<FieldInfoMember>
{
/// <summary>
/// The singleton instance.
/// </summary>
private static readonly Comparer Singleton = new Comparer();
/// <summary>
/// Gets the singleton instance of this class.
/// </summary>
public static Comparer Instance
{
get
{
return Singleton;
}
}
public int Compare(FieldInfoMember x, FieldInfoMember y)
{
return string.Compare(x.FieldInfo.Name, y.FieldInfo.Name, StringComparison.Ordinal);
}
}
}
}
}
| |
//------------------------------------------------------------------------------
//
// Copyright (c) 2014 Glympse Inc. All rights reserved.
//
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Glympse
{
namespace EnRoute
{
/*O*/public/**/ class EnRouteConstants
{
/**
* @name Authentication modes
*/
public const int AUTH_MODE_NONE = 0;
public const int AUTH_MODE_CREDENTIALS = 1;
public const int AUTH_MODE_TOKEN = 2;
/**
* @name Task states
*/
public const int TASK_STATE_CREATED = 1;
public const int TASK_STATE_STARTING = 2;
public const int TASK_STATE_STARTED = 3;
public const int TASK_STATE_FAILED_TO_START = 4;
public const int TASK_STATE_COMPLETED = 5;
/**
* @name Operation states
*/
public const int OPERATION_STATE_ACTIVE = 1;
public const int OPERATION_STATE_COMPLETING = 2;
public const int OPERATION_STATE_COMPLETE = 3;
public const int OPERATION_STATE_FAILED_TO_COMPLETE = 4;
/**
* @name Logout reasons
*/
public const int LOGOUT_REASON_UNKNOWN = 0;
public const int LOGOUT_REASON_USER_ACTION = 1;
public const int LOGOUT_REASON_OLD_VERSION = 2;
public const int LOGOUT_REASON_INVALID_CREDENTIALS = 3;
public const int LOGOUT_REASON_INVALID_TOKEN = 4;
public const int LOGOUT_REASON_LOCATION_SERVICES_UNAVAILABLE = 5;
public const int LOGOUT_REASON_SERVER_ERROR = 6;
/**
* @name Task completion reasons
*/
public const int TASK_COMPLETE_REASON_UNKNOWN = 0;
public const int TASK_COMPLETE_REASON_MANUAL_ARRIVAL = 1;
public const int TASK_COMPLETE_REASON_ARRIVAL_DETECTED = 2;
public const int TASK_COMPLETE_REASON_CANCELLED = 3;
public const int TASK_COMPLETE_REASON_TICKET_EXPIRED = 4;
public const int TASK_COMPLETE_REASON_TASK_REMOVED = 5;
/**
* @name Session completion reasons
*/
/**
* Completion reason for when a session is completed for an unknown reason.
*/
public const int SESSION_COMPLETION_REASON_UNKNOWN = 0x00000000;
/**
* Completion reason for when a session is completed due to a geofence trigger.
*/
public const int SESSION_COMPLETION_REASON_GEOFENCE = 0x00000001;
/**
* Completion reason for when a session is completed due to manual user action.
*/
public const int SESSION_COMPLETION_REASON_USER_ACTION = 0x00000002;
/**
* @name Ticket extension constants
*/
public const int TICKET_EXTEND_CHECK = 300000;
public const int TICKET_EXTEND_CUTOFF = 3600000;
public const int TICKET_EXTEND_LENGTH = 14400000;
/**
* @name ETA constants
*/
public const long MINIMUM_MANUAL_ETA = 300000;
/**
* @name Diagnostics constants
*/
public const int DIAGNOSTICS_COLLECTOR_MAX_CAPACITY = 200;
public const int DIAGNOSTICS_COLLECTOR_UPLOAD_DELAY_MS = 5000;
/**
* @name Index constants
*
* Used to keep track of indices of stages when the active stage index is outside the normal range.
*/
public const int INDEX_BEFORE = -2;
public const int INDEX_AFTER = -1;
/**
* @name Session states
*/
public const int SESSION_STATE_UNKNOWN = 0;
public const int SESSION_STATE_CREATED = 1;
public const int SESSION_STATE_STARTING = 2;
public const int SESSION_STATE_STARTED = 3;
public const int SESSION_STATE_COMPLETING = 4;
public const int SESSION_STATE_COMPLETED = 5;
/**
* @name Batch constants
*/
public const int BATCH_MAXIMUM_ENDPOINTS = 16;
/**
* @name Minimum auto refresh period
*/
public const int MINIMUM_AUTO_REFRESH_PERIOD = 10000;
/**
* @name Completed Pickup Keep Threshold
* Pickups older than this value should be discarded
* Value is 48 hours in ms
*/
public const long PICKUP_COMPLETED_KEEP_THRESHOLD_MS = 172800000;
/**
* @name Completed Task Keep Threshold
* Tasks older than this value should be discarded
* Value is 48 hours in ms
*/
public const long TASK_COMPLETED_KEEP_THRESHOLD_MS = 172800000;
/**
* @name Phase properties
*/
public static String PHASE_PROPERTY_KEY()
{
return CoreFactory.createString("phase");
}
public static String PHASE_PROPERTY_UNKNOWN()
{
return CoreFactory.createString("unknown");
}
public static String PHASE_PROPERTY_PRE()
{
return CoreFactory.createString("pre");
}
public static String PHASE_PROPERTY_ETA()
{
return CoreFactory.createString("eta");
}
public static String PHASE_PROPERTY_NEW()
{
return CoreFactory.createString("new");
}
public static String PHASE_PROPERTY_LIVE()
{
return CoreFactory.createString("live");
}
public static String PHASE_PROPERTY_ARRIVED()
{
return CoreFactory.createString("arrived");
}
public static String PHASE_PROPERTY_FEEDBACK()
{
return CoreFactory.createString("feedback");
}
public static String PHASE_PROPERTY_COMPLETING()
{
return CoreFactory.createString("completing");
}
public static String PHASE_PROPERTY_COMPLETED()
{
return CoreFactory.createString("completed");
}
public static String PHASE_PROPERTY_NOT_COMPLETED()
{
return CoreFactory.createString("not_completed");
}
public static String PHASE_PROPERTY_CANCELLED()
{
return CoreFactory.createString("cancelled");
}
public static String PHASE_PROPERTY_READY()
{
return CoreFactory.createString("ready");
}
/**
* @name Pickup remote trigger names
*/
public static String PICKUP_TRIGGER_GEOFENCE()
{
return CoreFactory.createString("pickup_geocircle");
}
public static String PICKUP_TRIGGER_ETA()
{
return CoreFactory.createString("pickup_eta");
}
/**
* @name Session control modes
*/
public static String SESSION_CONTROL_MODE_MANUAL()
{
return CoreFactory.createString("manual");
}
public static String SESSION_CONTROL_MODE_SHUTTLE_SERVICE()
{
return CoreFactory.createString("sdk_shuttle_service");
}
public static String SESSION_CONTROL_MODE_FOOD_DELIVERY()
{
return CoreFactory.createString("sdk_food_delivery");
}
/**
* @name Travel modes
*/
public static String TRAVEL_MODE_DRIVING()
{
return CoreFactory.createString("drive");
}
public static String TRAVEL_MODE_WALKING()
{
return CoreFactory.createString("walk");
}
public static String TRAVEL_MODE_TRANSIT()
{
return CoreFactory.createString("transit");
}
public static String TRAVEL_MODE_BICYCLE()
{
return CoreFactory.createString("cycle");
}
};
}
}
| |
using Lucene.Net.Codecs.Asserting;
using Lucene.Net.Codecs.Compressing;
using Lucene.Net.Codecs.Lucene3x;
using Lucene.Net.Codecs.Lucene40;
using Lucene.Net.Codecs.Lucene41;
using Lucene.Net.Codecs.Lucene42;
using Lucene.Net.Codecs.Lucene45;
using Lucene.Net.JavaCompatibility;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Console = Lucene.Net.Support.SystemConsole;
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.
*/
/*
import static Lucene.Net.Util.LuceneTestCase.INFOSTREAM;
import static Lucene.Net.Util.LuceneTestCase.TEST_CODEC;
import static Lucene.Net.Util.LuceneTestCase.TEST_DOCVALUESFORMAT;
import static Lucene.Net.Util.LuceneTestCase.TEST_POSTINGSFORMAT;
import static Lucene.Net.Util.LuceneTestCase.VERBOSE;
import static Lucene.Net.Util.LuceneTestCase.assumeFalse;
import static Lucene.Net.Util.LuceneTestCase.localeForName;
import static Lucene.Net.Util.LuceneTestCase.random;
import static Lucene.Net.Util.LuceneTestCase.randomLocale;
import static Lucene.Net.Util.LuceneTestCase.randomTimeZone;*/
using CheapBastardCodec = Lucene.Net.Codecs.CheapBastard.CheapBastardCodec;
using Codec = Lucene.Net.Codecs.Codec;
using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using DocValuesFormat = Lucene.Net.Codecs.DocValuesFormat;
using Lucene46Codec = Lucene.Net.Codecs.Lucene46.Lucene46Codec;
using MockRandomPostingsFormat = Lucene.Net.Codecs.MockRandom.MockRandomPostingsFormat;
using PostingsFormat = Lucene.Net.Codecs.PostingsFormat;
using RandomCodec = Lucene.Net.Index.RandomCodec;
using RandomSimilarityProvider = Lucene.Net.Search.RandomSimilarityProvider;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using SimpleTextCodec = Lucene.Net.Codecs.SimpleText.SimpleTextCodec;
//using RandomizedContext = com.carrotsearch.randomizedtesting.RandomizedContext;
/// <summary>
/// Setup and restore suite-level environment (fine grained junk that
/// doesn't fit anywhere else).
/// </summary>
internal sealed class TestRuleSetupAndRestoreClassEnv : AbstractBeforeAfterRule
{
/// <summary>
/// Restore these system property values.
/// </summary>
private Dictionary<string, string> restoreProperties = new Dictionary<string, string>();
private Codec savedCodec;
private CultureInfo savedLocale;
private InfoStream savedInfoStream;
private TimeZoneInfo savedTimeZone;
internal CultureInfo locale;
internal TimeZoneInfo timeZone;
internal Similarity similarity;
internal Codec codec;
/// <seealso cref= SuppressCodecs </seealso>
internal HashSet<string> avoidCodecs;
public override void Before(LuceneTestCase testInstance)
{
// if verbose: print some debugging stuff about which codecs are loaded.
if (LuceneTestCase.VERBOSE)
{
ICollection<string> codecs = Codec.AvailableCodecs();
foreach (string codec in codecs)
{
Console.WriteLine("Loaded codec: '" + codec + "': " + Codec.ForName(codec).GetType().Name);
}
ICollection<string> postingsFormats = PostingsFormat.AvailablePostingsFormats();
foreach (string postingsFormat in postingsFormats)
{
Console.WriteLine("Loaded postingsFormat: '" + postingsFormat + "': " + PostingsFormat.ForName(postingsFormat).GetType().Name);
}
}
savedInfoStream = InfoStream.Default;
Random random = LuceneTestCase.Random();
bool v = random.NextBoolean();
if (LuceneTestCase.INFOSTREAM)
{
InfoStream.Default = new ThreadNameFixingPrintStreamInfoStream(Console.Out);
}
else if (v)
{
InfoStream.Default = new NullInfoStream();
}
Type targetClass = testInstance.GetType();
avoidCodecs = new HashSet<string>();
var suppressCodecsAttribute = targetClass.GetTypeInfo().GetCustomAttribute<LuceneTestCase.SuppressCodecsAttribute>();
if (suppressCodecsAttribute != null)
{
avoidCodecs.AddAll(suppressCodecsAttribute.Value);
}
// set back to default
LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = false;
savedCodec = Codec.Default;
int randomVal = random.Next(10);
if ("Lucene3x".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal) &&
randomVal == 3 &&
!ShouldAvoidCodec("Lucene3x"))) // preflex-only setup
{
codec = Codec.ForName("Lucene3x");
Debug.Assert((codec is PreFlexRWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
}
else if ("Lucene40".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) &&
randomVal == 0 &&
!ShouldAvoidCodec("Lucene40"))) // 4.0 setup
{
codec = Codec.ForName("Lucene40");
LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
Debug.Assert((codec is Lucene40RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
Debug.Assert((PostingsFormat.ForName("Lucene40") is Lucene40RWPostingsFormat), "fix your IPostingsFormatFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
}
else if ("Lucene41".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal) &&
randomVal == 1 &&
!ShouldAvoidCodec("Lucene41")))
{
codec = Codec.ForName("Lucene41");
LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
Debug.Assert((codec is Lucene41RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
}
else if ("Lucene42".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal) &&
randomVal == 2 &&
!ShouldAvoidCodec("Lucene42")))
{
codec = Codec.ForName("Lucene42");
LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
Debug.Assert((codec is Lucene42RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
}
else if ("Lucene45".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) &&
"random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal) &&
randomVal == 5 &&
!ShouldAvoidCodec("Lucene45")))
{
codec = Codec.ForName("Lucene45");
LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
Debug.Assert((codec is Lucene45RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework");
}
else if (("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) == false)
|| ("random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal) == false))
{
// the user wired postings or DV: this is messy
// refactor into RandomCodec....
PostingsFormat format;
if ("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal))
{
format = PostingsFormat.ForName("Lucene41");
}
else if ("MockRandom".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal))
{
format = new MockRandomPostingsFormat(new Random(random.Next()));
}
else
{
format = PostingsFormat.ForName(LuceneTestCase.TEST_POSTINGSFORMAT);
}
DocValuesFormat dvFormat;
if ("random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal))
{
dvFormat = DocValuesFormat.ForName("Lucene45");
}
else
{
dvFormat = DocValuesFormat.ForName(LuceneTestCase.TEST_DOCVALUESFORMAT);
}
codec = new Lucene46CodecAnonymousInnerClassHelper(this, format, dvFormat);
}
else if ("SimpleText".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal)
|| ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && randomVal == 9 && LuceneTestCase.Rarely(random) && !ShouldAvoidCodec("SimpleText")))
{
codec = new SimpleTextCodec();
}
else if ("CheapBastard".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal)
|| ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && randomVal == 8 && !ShouldAvoidCodec("CheapBastard") && !ShouldAvoidCodec("Lucene41")))
{
// we also avoid this codec if Lucene41 is avoided, since thats the postings format it uses.
codec = new CheapBastardCodec();
}
else if ("Asserting".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal)
|| ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && randomVal == 6 && !ShouldAvoidCodec("Asserting")))
{
codec = new AssertingCodec();
}
else if ("Compressing".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal)
|| ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && randomVal == 5 && !ShouldAvoidCodec("Compressing")))
{
codec = CompressingCodec.RandomInstance(random);
}
else if (!"random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal))
{
codec = Codec.ForName(LuceneTestCase.TEST_CODEC);
}
else if ("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal))
{
codec = new RandomCodec(random, avoidCodecs);
}
else
{
Debug.Assert(false);
}
Codec.Default = codec;
// Initialize locale/ timezone.
string testLocale = SystemProperties.GetProperty("tests.locale", "random");
string testTimeZone = SystemProperties.GetProperty("tests.timezone", "random");
// Always pick a random one for consistency (whether tests.locale was specified or not).
savedLocale = CultureInfo.CurrentCulture;
CultureInfo randomLocale = LuceneTestCase.RandomLocale(random);
locale = testLocale.Equals("random", StringComparison.Ordinal) ? randomLocale : LuceneTestCase.LocaleForName(testLocale);
#if NETSTANDARD
CultureInfo.CurrentCulture = locale;
#else
Thread.CurrentThread.CurrentCulture = locale;
#endif
// TimeZone.getDefault will set user.timezone to the default timezone of the user's locale.
// So store the original property value and restore it at end.
restoreProperties["user.timezone"] = SystemProperties.GetProperty("user.timezone");
savedTimeZone = testInstance.TimeZone;
TimeZoneInfo randomTimeZone = LuceneTestCase.RandomTimeZone(random);
timeZone = testTimeZone.Equals("random", StringComparison.Ordinal) ? randomTimeZone : TimeZoneInfo.FindSystemTimeZoneById(testTimeZone);
//TimeZone.Default = TimeZone; // LUCENENET NOTE: There doesn't seem to be an equivalent to this, but I don't think we need it.
similarity = random.NextBoolean() ? (Similarity)new DefaultSimilarity() : new RandomSimilarityProvider(random);
// Check codec restrictions once at class level.
try
{
CheckCodecRestrictions(codec);
}
catch (Exception e)
{
Console.Error.WriteLine("NOTE: " + e.Message + " Suppressed codecs: " + Arrays.ToString(avoidCodecs.ToArray()));
throw e;
}
}
internal class ThreadNameFixingPrintStreamInfoStream : TextWriterInfoStream
{
public ThreadNameFixingPrintStreamInfoStream(TextWriter @out)
: base(@out)
{
}
public override void Message(string component, string message)
{
if ("TP".Equals(component, StringComparison.Ordinal))
{
return; // ignore test points!
}
string name;
if (Thread.CurrentThread.Name != null && Thread.CurrentThread.Name.StartsWith("TEST-", StringComparison.Ordinal))
{
// The name of the main thread is way too
// long when looking at IW verbose output...
name = "main";
}
else
{
name = Thread.CurrentThread.Name;
}
m_stream.WriteLine(component + " " + m_messageID + " [" + DateTime.Now + "; " + name + "]: " + message);
}
}
private class Lucene46CodecAnonymousInnerClassHelper : Lucene46Codec
{
private readonly TestRuleSetupAndRestoreClassEnv outerInstance;
private PostingsFormat format;
private DocValuesFormat dvFormat;
public Lucene46CodecAnonymousInnerClassHelper(TestRuleSetupAndRestoreClassEnv outerInstance, PostingsFormat format, DocValuesFormat dvFormat)
{
this.outerInstance = outerInstance;
this.format = format;
this.dvFormat = dvFormat;
}
public override PostingsFormat GetPostingsFormatForField(string field)
{
return format;
}
public override DocValuesFormat GetDocValuesFormatForField(string field)
{
return dvFormat;
}
public override string ToString()
{
return base.ToString() + ": " + format.ToString() + ", " + dvFormat.ToString();
}
}
/// <summary>
/// Check codec restrictions.
/// </summary>
/// <exception cref="AssumptionViolatedException"> if the class does not work with a given codec. </exception>
private void CheckCodecRestrictions(Codec codec)
{
LuceneTestCase.AssumeFalse("Class not allowed to use codec: " + codec.Name + ".", ShouldAvoidCodec(codec.Name));
if (codec is RandomCodec && avoidCodecs.Count > 0)
{
foreach (string name in ((RandomCodec)codec).formatNames)
{
LuceneTestCase.AssumeFalse("Class not allowed to use postings format: " + name + ".", ShouldAvoidCodec(name));
}
}
PostingsFormat pf = codec.PostingsFormat;
LuceneTestCase.AssumeFalse("Class not allowed to use postings format: " + pf.Name + ".", ShouldAvoidCodec(pf.Name));
LuceneTestCase.AssumeFalse("Class not allowed to use postings format: " + LuceneTestCase.TEST_POSTINGSFORMAT + ".", ShouldAvoidCodec(LuceneTestCase.TEST_POSTINGSFORMAT));
}
/// <summary>
/// After suite cleanup (always invoked).
/// </summary>
public override void After(LuceneTestCase testInstance)
{
foreach (KeyValuePair<string, string> e in restoreProperties)
{
SystemProperties.SetProperty(e.Key, e.Value);
}
restoreProperties.Clear();
Codec.Default = savedCodec;
InfoStream.Default = savedInfoStream;
if (savedLocale != null)
{
locale = savedLocale;
#if NETSTANDARD
CultureInfo.CurrentCulture = savedLocale;
#else
Thread.CurrentThread.CurrentCulture = savedLocale;
#endif
}
if (savedTimeZone != null)
{
timeZone = savedTimeZone;
}
}
/// <summary>
/// Should a given codec be avoided for the currently executing suite?
/// </summary>
private bool ShouldAvoidCodec(string codec)
{
return avoidCodecs.Count > 0 && avoidCodecs.Contains(codec);
}
}
}
| |
// 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.Diagnostics;
using System.Reflection;
namespace System.ComponentModel
{
/// <summary>
/// <para>
/// Declares an array of attributes for a member and defines
/// the properties and methods that give you access to the attributes in the array.
/// All attributes must derive from <see cref='System.Attribute'/>.
/// </para>
/// </summary>
public abstract class MemberDescriptor
{
private readonly string _name;
private readonly string _displayName;
private readonly int _nameHash;
private AttributeCollection _attributeCollection;
private Attribute[] _attributes;
private Attribute[] _originalAttributes;
private bool _attributesFiltered;
private bool _attributesFilled;
private int _metadataVersion;
private string _category;
private string _description;
private object _lockCookie = new object();
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <paramref name="name"/> and no attributes.
/// </para>
/// </summary>
protected MemberDescriptor(string name) : this(name, null)
{
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <paramref name="name"/> and <paramref name="attributes "/> array.
/// </para>
/// </summary>
protected MemberDescriptor(string name, Attribute[] attributes)
{
if (name == null || name.Length == 0)
{
throw new ArgumentException(SR.InvalidMemberName);
}
_name = name;
_displayName = name;
_nameHash = name.GetHashCode();
if (attributes != null)
{
_attributes = attributes;
_attributesFiltered = false;
}
_originalAttributes = _attributes;
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <see cref='System.ComponentModel.MemberDescriptor'/>.
/// </para>
/// </summary>
protected MemberDescriptor(MemberDescriptor descr)
{
_name = descr.Name;
_displayName = _name;
_nameHash = _name.GetHashCode();
_attributes = new Attribute[descr.Attributes.Count];
descr.Attributes.CopyTo(_attributes, 0);
_attributesFiltered = true;
_originalAttributes = _attributes;
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the name in the specified
/// <see cref='System.ComponentModel.MemberDescriptor'/> and the attributes
/// in both the old <see cref='System.ComponentModel.MemberDescriptor'/> and the <see cref='System.Attribute'/> array.
/// </para>
/// </summary>
protected MemberDescriptor(MemberDescriptor oldMemberDescriptor, Attribute[] newAttributes)
{
_name = oldMemberDescriptor.Name;
_displayName = oldMemberDescriptor.DisplayName;
_nameHash = _name.GetHashCode();
List<Attribute> newList = new List<Attribute>();
if (oldMemberDescriptor.Attributes.Count != 0)
{
foreach (Attribute o in oldMemberDescriptor.Attributes)
{
newList.Add(o);
}
}
if (newAttributes != null)
{
foreach (Attribute o in newAttributes)
{
newList.Add(o);
}
}
_attributes = new Attribute[newList.Count];
newList.CopyTo(_attributes, 0);
_attributesFiltered = false;
_originalAttributes = _attributes;
}
/// <summary>
/// <para>
/// Gets or sets an array of
/// attributes.
/// </para>
/// </summary>
protected virtual Attribute[] AttributeArray
{
get
{
CheckAttributesValid();
FilterAttributesIfNeeded();
return _attributes;
}
set
{
lock (_lockCookie)
{
_attributes = value;
_originalAttributes = value;
_attributesFiltered = false;
_attributeCollection = null;
}
}
}
/// <summary>
/// <para>
/// Gets the collection of attributes for this member.
/// </para>
/// </summary>
public virtual AttributeCollection Attributes
{
get
{
CheckAttributesValid();
AttributeCollection attrs = _attributeCollection;
if (attrs == null)
{
lock (_lockCookie)
{
attrs = CreateAttributeCollection();
_attributeCollection = attrs;
}
}
return attrs;
}
}
/// <summary>
/// <para>
/// Gets the name of the category that the member belongs to, as specified
/// in the <see cref='System.ComponentModel.CategoryAttribute'/>.
/// </para>
/// </summary>
public virtual string Category => _category ?? (_category = ((CategoryAttribute) Attributes[typeof(CategoryAttribute)]).Category);
/// <summary>
/// <para>
/// Gets the description of
/// the member as specified in the <see cref='System.ComponentModel.DescriptionAttribute'/>.
/// </para>
/// </summary>
public virtual string Description => _description ??
(_description = ((DescriptionAttribute) Attributes[typeof(DescriptionAttribute)]).Description);
/// <summary>
/// <para>
/// Gets a value indicating whether the member is browsable as specified in the
/// <see cref='System.ComponentModel.BrowsableAttribute'/>.
/// </para>
/// </summary>
public virtual bool IsBrowsable => ((BrowsableAttribute)Attributes[typeof(BrowsableAttribute)]).Browsable;
/// <summary>
/// <para>
/// Gets the
/// name of the member.
/// </para>
/// </summary>
public virtual string Name => _name ?? "";
/// <summary>
/// <para>
/// Gets the hash
/// code for the name of the member as specified in <see cref='System.String.GetHashCode'/>.
/// </para>
/// </summary>
protected virtual int NameHashCode => _nameHash;
/// <summary>
/// <para>
/// Determines whether this member should be set only at
/// design time as specified in the <see cref='System.ComponentModel.DesignOnlyAttribute'/>.
/// </para>
/// </summary>
public virtual bool DesignTimeOnly => (DesignOnlyAttribute.Yes.Equals(Attributes[typeof(DesignOnlyAttribute)]));
/// <summary>
/// <para>
/// Gets the name that can be displayed in a window like a
/// properties window.
/// </para>
/// </summary>
public virtual string DisplayName
{
get
{
DisplayNameAttribute displayNameAttr = Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute;
if (displayNameAttr == null || displayNameAttr.IsDefaultAttribute())
{
return _displayName;
}
return displayNameAttr.DisplayName;
}
}
/// <summary>
/// Called each time we access the attribtes on
/// this member descriptor to give deriving classes
/// a chance to change them on the fly.
/// </summary>
private void CheckAttributesValid()
{
if (_attributesFiltered)
{
if (_metadataVersion != TypeDescriptor.MetadataVersion)
{
_attributesFilled = false;
_attributesFiltered = false;
_attributeCollection = null;
}
}
}
/// <summary>
/// <para>
/// Creates a collection of attributes using the
/// array of attributes that you passed to the constructor.
/// </para>
/// </summary>
protected virtual AttributeCollection CreateAttributeCollection()
{
return new AttributeCollection(AttributeArray);
}
/// <summary>
/// <para>
/// Compares this instance to the specified <see cref='System.ComponentModel.MemberDescriptor'/> to see if they are equivalent.
/// NOTE: If you make a change here, you likely need to change GetHashCode() as well.
/// </para>
/// </summary>
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (obj.GetType() != GetType())
{
return false;
}
MemberDescriptor mdObj = (MemberDescriptor)obj;
FilterAttributesIfNeeded();
mdObj.FilterAttributesIfNeeded();
if (mdObj._nameHash != _nameHash)
{
return false;
}
if ((mdObj._category == null) != (_category == null) ||
(_category != null && !mdObj._category.Equals(_category)))
{
return false;
}
if ((mdObj._description == null) != (_description == null) ||
(_description != null && !mdObj._description.Equals(_description)))
{
return false;
}
if ((mdObj._attributes == null) != (_attributes == null))
{
return false;
}
bool sameAttrs = true;
if (_attributes != null)
{
if (_attributes.Length != mdObj._attributes.Length)
{
return false;
}
for (int i = 0; i < _attributes.Length; i++)
{
if (!_attributes[i].Equals(mdObj._attributes[i]))
{
sameAttrs = false;
break;
}
}
}
return sameAttrs;
}
/// <summary>
/// <para>
/// In an inheriting class, adds the attributes of the inheriting class to the
/// specified list of attributes in the parent class. For duplicate attributes,
/// the last one added to the list will be kept.
/// </para>
/// </summary>
protected virtual void FillAttributes(IList attributeList)
{
if (_originalAttributes != null)
{
foreach (Attribute attr in _originalAttributes)
{
attributeList.Add(attr);
}
}
}
private void FilterAttributesIfNeeded()
{
if (!_attributesFiltered)
{
List<Attribute> list;
if (!_attributesFilled)
{
list = new List<Attribute>();
try
{
FillAttributes(list);
}
catch (Exception e)
{
Debug.Fail($"{_name}>>{e}");
}
}
else
{
list = new List<Attribute>(_attributes);
}
var set = new HashSet<object>();
for (int i = 0; i < list.Count;)
{
if (set.Add(list[i].TypeId))
{
++i;
}
else
{
list.RemoveAt(i);
}
}
Attribute[] newAttributes = list.ToArray();
lock (_lockCookie)
{
_attributes = newAttributes;
_attributesFiltered = true;
_attributesFilled = true;
_metadataVersion = TypeDescriptor.MetadataVersion;
}
}
}
/// <summary>
/// <para>
/// Finds the given method through reflection. This method only looks for public methods.
/// </para>
/// </summary>
protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType)
{
return FindMethod(componentClass, name, args, returnType, true);
}
/// <summary>
/// <para>
/// Finds the given method through reflection.
/// </para>
/// </summary>
protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType, bool publicOnly)
{
MethodInfo result = null;
if (publicOnly)
{
result = componentClass.GetMethod(name, args);
}
else
{
// The original impementation requires the method https://msdn.microsoft.com/en-us/library/5fed8f59(v=vs.110).aspx which is not
// available on .NET Core. The replacement will use the default BindingFlags, which may miss some methods that had been found
// on .NET Framework.
result = componentClass.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null);
}
if (result != null && !result.ReturnType.IsEquivalentTo(returnType))
{
result = null;
}
return result;
}
/// <summary>
/// Try to keep this reasonable in [....] with Equals(). Specifically,
/// if A.Equals(B) returns true, A & B should have the same hash code.
/// </summary>
public override int GetHashCode()
{
return _nameHash;
}
/// <summary>
/// This method returns the object that should be used during invocation of members.
/// Normally the return value will be the same as the instance passed in. If
/// someone associated another object with this instance, or if the instance is a
/// custom type descriptor, GetInvocationTarget may return a different value.
/// </summary>
protected virtual object GetInvocationTarget(Type type, object instance)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
return TypeDescriptor.GetAssociation(type, instance);
}
/// <summary>
/// <para>
/// Gets a component site
/// for the given component.
/// </para>
/// </summary>
protected static ISite GetSite(object component)
{
return (component as IComponent)?.Site;
}
[Obsolete("This method has been deprecated. Use GetInvocationTarget instead. http://go.microsoft.com/fwlink/?linkid=14202")]
protected static object GetInvokee(Type componentClass, object component) {
if (componentClass == null)
{
throw new ArgumentNullException(nameof(componentClass));
}
if (component == null)
{
throw new ArgumentNullException(nameof(component));
}
return TypeDescriptor.GetAssociation(componentClass, component);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Mono.Addins;
using NDesk.Options;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace OpenSim.Region.OptionalModules.Avatar.SitStand
{
/// <summary>
/// A module that just holds commands for changing avatar sitting and standing states.
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AnimationsCommandModule")]
public class SitStandCommandModule : INonSharedRegionModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
public string Name { get { return "SitStand Command Module"; } }
public Type ReplaceableInterface { get { return null; } }
public void Initialise(IConfigSource source)
{
// m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: INITIALIZED MODULE");
}
public void PostInitialise()
{
// m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: POST INITIALIZED MODULE");
}
public void Close()
{
// m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: CLOSED MODULE");
}
public void AddRegion(Scene scene)
{
// m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName);
}
public void RemoveRegion(Scene scene)
{
// m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName);
}
public void RegionLoaded(Scene scene)
{
// m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName);
m_scene = scene;
scene.AddCommand(
"Users", this, "sit user name",
"sit user name [--regex] <first-name> <last-name>",
"Sit the named user on an unoccupied object with a sit target.",
"If there are no such objects then nothing happens.\n"
+ "If --regex is specified then the names are treated as regular expressions.",
HandleSitUserNameCommand);
scene.AddCommand(
"Users", this, "stand user name",
"stand user name [--regex] <first-name> <last-name>",
"Stand the named user.",
"If --regex is specified then the names are treated as regular expressions.",
HandleStandUserNameCommand);
}
private void HandleSitUserNameCommand(string module, string[] cmd)
{
if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene != null)
return;
if (cmd.Length < 5)
{
MainConsole.Instance.Output("Usage: sit user name [--regex] <first-name> <last-name>");
return;
}
List<ScenePresence> scenePresences = GetScenePresences(cmd);
foreach (ScenePresence sp in scenePresences)
{
if (sp.SitGround || sp.IsSatOnObject)
continue;
SceneObjectPart sitPart = null;
List<SceneObjectGroup> sceneObjects = m_scene.GetSceneObjectGroups();
foreach (SceneObjectGroup sceneObject in sceneObjects)
{
if (sceneObject.IsAttachment)
continue;
foreach (SceneObjectPart part in sceneObject.Parts)
{
if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
{
sitPart = part;
break;
}
}
}
if (sitPart != null)
{
MainConsole.Instance.OutputFormat(
"Sitting {0} on {1} {2} in {3}",
sp.Name, sitPart.ParentGroup.Name, sitPart.ParentGroup.UUID, m_scene.Name);
sp.HandleAgentRequestSit(sp.ControllingClient, sp.UUID, sitPart.UUID, Vector3.Zero);
sp.HandleAgentSit(sp.ControllingClient, sp.UUID);
}
else
{
MainConsole.Instance.OutputFormat(
"Could not find any unoccupied set seat on which to sit {0} in {1}. Aborting",
sp.Name, m_scene.Name);
break;
}
}
}
private void HandleStandUserNameCommand(string module, string[] cmd)
{
if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene != null)
return;
if (cmd.Length < 5)
{
MainConsole.Instance.Output("Usage: stand user name [--regex] <first-name> <last-name>");
return;
}
List<ScenePresence> scenePresences = GetScenePresences(cmd);
foreach (ScenePresence sp in scenePresences)
{
if (sp.SitGround || sp.IsSatOnObject)
{
MainConsole.Instance.OutputFormat("Standing {0} in {1}", sp.Name, m_scene.Name);
sp.StandUp();
}
}
}
private List<ScenePresence> GetScenePresences(string[] cmdParams)
{
bool useRegex = false;
OptionSet options = new OptionSet().Add("regex", v=> useRegex = v != null );
List<string> mainParams = options.Parse(cmdParams);
string firstName = mainParams[3];
string lastName = mainParams[4];
List<ScenePresence> scenePresencesMatched = new List<ScenePresence>();
if (useRegex)
{
Regex nameRegex = new Regex(string.Format("{0} {1}", firstName, lastName));
List<ScenePresence> scenePresences = m_scene.GetScenePresences();
foreach (ScenePresence sp in scenePresences)
{
if (!sp.IsChildAgent && nameRegex.IsMatch(sp.Name))
scenePresencesMatched.Add(sp);
}
}
else
{
ScenePresence sp = m_scene.GetScenePresence(firstName, lastName);
if (sp != null && !sp.IsChildAgent)
scenePresencesMatched.Add(sp);
}
return scenePresencesMatched;
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.ElastiCache.Model
{
/// <summary>
/// <para>Contains all of the attributes of a specific cache cluster.</para>
/// </summary>
public class CacheCluster
{
private string cacheClusterId;
private Endpoint configurationEndpoint;
private string clientDownloadLandingPage;
private string cacheNodeType;
private string engine;
private string engineVersion;
private string cacheClusterStatus;
private int? numCacheNodes;
private string preferredAvailabilityZone;
private DateTime? cacheClusterCreateTime;
private string preferredMaintenanceWindow;
private PendingModifiedValues pendingModifiedValues;
private NotificationConfiguration notificationConfiguration;
private List<CacheSecurityGroupMembership> cacheSecurityGroups = new List<CacheSecurityGroupMembership>();
private CacheParameterGroupStatus cacheParameterGroup;
private string cacheSubnetGroupName;
private List<CacheNode> cacheNodes = new List<CacheNode>();
private bool? autoMinorVersionUpgrade;
private List<SecurityGroupMembership> securityGroups = new List<SecurityGroupMembership>();
private string replicationGroupId;
/// <summary>
/// The user-supplied identifier of the cache cluster. This is a unique key that identifies a cache cluster.
///
/// </summary>
public string CacheClusterId
{
get { return this.cacheClusterId; }
set { this.cacheClusterId = value; }
}
/// <summary>
/// Sets the CacheClusterId property
/// </summary>
/// <param name="cacheClusterId">The value to set for the CacheClusterId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithCacheClusterId(string cacheClusterId)
{
this.cacheClusterId = cacheClusterId;
return this;
}
// Check to see if CacheClusterId property is set
internal bool IsSetCacheClusterId()
{
return this.cacheClusterId != null;
}
/// <summary>
/// Represents the information required for client programs to connect to a cache node.
///
/// </summary>
public Endpoint ConfigurationEndpoint
{
get { return this.configurationEndpoint; }
set { this.configurationEndpoint = value; }
}
/// <summary>
/// Sets the ConfigurationEndpoint property
/// </summary>
/// <param name="configurationEndpoint">The value to set for the ConfigurationEndpoint property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithConfigurationEndpoint(Endpoint configurationEndpoint)
{
this.configurationEndpoint = configurationEndpoint;
return this;
}
// Check to see if ConfigurationEndpoint property is set
internal bool IsSetConfigurationEndpoint()
{
return this.configurationEndpoint != null;
}
/// <summary>
/// The URL of the web page where you can download the latest ElastiCache client library.
///
/// </summary>
public string ClientDownloadLandingPage
{
get { return this.clientDownloadLandingPage; }
set { this.clientDownloadLandingPage = value; }
}
/// <summary>
/// Sets the ClientDownloadLandingPage property
/// </summary>
/// <param name="clientDownloadLandingPage">The value to set for the ClientDownloadLandingPage property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithClientDownloadLandingPage(string clientDownloadLandingPage)
{
this.clientDownloadLandingPage = clientDownloadLandingPage;
return this;
}
// Check to see if ClientDownloadLandingPage property is set
internal bool IsSetClientDownloadLandingPage()
{
return this.clientDownloadLandingPage != null;
}
/// <summary>
/// The name of the compute and memory capacity node type for the cache cluster.
///
/// </summary>
public string CacheNodeType
{
get { return this.cacheNodeType; }
set { this.cacheNodeType = value; }
}
/// <summary>
/// Sets the CacheNodeType property
/// </summary>
/// <param name="cacheNodeType">The value to set for the CacheNodeType property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithCacheNodeType(string cacheNodeType)
{
this.cacheNodeType = cacheNodeType;
return this;
}
// Check to see if CacheNodeType property is set
internal bool IsSetCacheNodeType()
{
return this.cacheNodeType != null;
}
/// <summary>
/// The name of the cache engine (<i>memcached</i> or <i>redis</i>) to be used for this cache cluster.
///
/// </summary>
public string Engine
{
get { return this.engine; }
set { this.engine = value; }
}
/// <summary>
/// Sets the Engine property
/// </summary>
/// <param name="engine">The value to set for the Engine property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithEngine(string engine)
{
this.engine = engine;
return this;
}
// Check to see if Engine property is set
internal bool IsSetEngine()
{
return this.engine != null;
}
/// <summary>
/// The version of the cache engine version that is used in this cache cluster.
///
/// </summary>
public string EngineVersion
{
get { return this.engineVersion; }
set { this.engineVersion = value; }
}
/// <summary>
/// Sets the EngineVersion property
/// </summary>
/// <param name="engineVersion">The value to set for the EngineVersion property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithEngineVersion(string engineVersion)
{
this.engineVersion = engineVersion;
return this;
}
// Check to see if EngineVersion property is set
internal bool IsSetEngineVersion()
{
return this.engineVersion != null;
}
/// <summary>
/// The current state of this cache cluster - <i>creating</i>, <i>available</i>, etc.
///
/// </summary>
public string CacheClusterStatus
{
get { return this.cacheClusterStatus; }
set { this.cacheClusterStatus = value; }
}
/// <summary>
/// Sets the CacheClusterStatus property
/// </summary>
/// <param name="cacheClusterStatus">The value to set for the CacheClusterStatus property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithCacheClusterStatus(string cacheClusterStatus)
{
this.cacheClusterStatus = cacheClusterStatus;
return this;
}
// Check to see if CacheClusterStatus property is set
internal bool IsSetCacheClusterStatus()
{
return this.cacheClusterStatus != null;
}
/// <summary>
/// The number of cache nodes in the cache cluster.
///
/// </summary>
public int NumCacheNodes
{
get { return this.numCacheNodes ?? default(int); }
set { this.numCacheNodes = value; }
}
/// <summary>
/// Sets the NumCacheNodes property
/// </summary>
/// <param name="numCacheNodes">The value to set for the NumCacheNodes property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithNumCacheNodes(int numCacheNodes)
{
this.numCacheNodes = numCacheNodes;
return this;
}
// Check to see if NumCacheNodes property is set
internal bool IsSetNumCacheNodes()
{
return this.numCacheNodes.HasValue;
}
/// <summary>
/// The name of the Availability Zone in which the cache cluster is located.
///
/// </summary>
public string PreferredAvailabilityZone
{
get { return this.preferredAvailabilityZone; }
set { this.preferredAvailabilityZone = value; }
}
/// <summary>
/// Sets the PreferredAvailabilityZone property
/// </summary>
/// <param name="preferredAvailabilityZone">The value to set for the PreferredAvailabilityZone property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithPreferredAvailabilityZone(string preferredAvailabilityZone)
{
this.preferredAvailabilityZone = preferredAvailabilityZone;
return this;
}
// Check to see if PreferredAvailabilityZone property is set
internal bool IsSetPreferredAvailabilityZone()
{
return this.preferredAvailabilityZone != null;
}
/// <summary>
/// The date and time the cache cluster was created.
///
/// </summary>
public DateTime CacheClusterCreateTime
{
get { return this.cacheClusterCreateTime ?? default(DateTime); }
set { this.cacheClusterCreateTime = value; }
}
/// <summary>
/// Sets the CacheClusterCreateTime property
/// </summary>
/// <param name="cacheClusterCreateTime">The value to set for the CacheClusterCreateTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithCacheClusterCreateTime(DateTime cacheClusterCreateTime)
{
this.cacheClusterCreateTime = cacheClusterCreateTime;
return this;
}
// Check to see if CacheClusterCreateTime property is set
internal bool IsSetCacheClusterCreateTime()
{
return this.cacheClusterCreateTime.HasValue;
}
/// <summary>
/// The time range (in UTC) during which weekly system maintenance can occur.
///
/// </summary>
public string PreferredMaintenanceWindow
{
get { return this.preferredMaintenanceWindow; }
set { this.preferredMaintenanceWindow = value; }
}
/// <summary>
/// Sets the PreferredMaintenanceWindow property
/// </summary>
/// <param name="preferredMaintenanceWindow">The value to set for the PreferredMaintenanceWindow property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithPreferredMaintenanceWindow(string preferredMaintenanceWindow)
{
this.preferredMaintenanceWindow = preferredMaintenanceWindow;
return this;
}
// Check to see if PreferredMaintenanceWindow property is set
internal bool IsSetPreferredMaintenanceWindow()
{
return this.preferredMaintenanceWindow != null;
}
/// <summary>
/// A group of settings that will be applied to the cache cluster in the future, or that are currently being applied.
///
/// </summary>
public PendingModifiedValues PendingModifiedValues
{
get { return this.pendingModifiedValues; }
set { this.pendingModifiedValues = value; }
}
/// <summary>
/// Sets the PendingModifiedValues property
/// </summary>
/// <param name="pendingModifiedValues">The value to set for the PendingModifiedValues property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithPendingModifiedValues(PendingModifiedValues pendingModifiedValues)
{
this.pendingModifiedValues = pendingModifiedValues;
return this;
}
// Check to see if PendingModifiedValues property is set
internal bool IsSetPendingModifiedValues()
{
return this.pendingModifiedValues != null;
}
/// <summary>
/// Describes a notification topic and its status. Notification topics are used for publishing ElastiCache events to subscribers using Amazon
/// Simple Notification Service (SNS).
///
/// </summary>
public NotificationConfiguration NotificationConfiguration
{
get { return this.notificationConfiguration; }
set { this.notificationConfiguration = value; }
}
/// <summary>
/// Sets the NotificationConfiguration property
/// </summary>
/// <param name="notificationConfiguration">The value to set for the NotificationConfiguration property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithNotificationConfiguration(NotificationConfiguration notificationConfiguration)
{
this.notificationConfiguration = notificationConfiguration;
return this;
}
// Check to see if NotificationConfiguration property is set
internal bool IsSetNotificationConfiguration()
{
return this.notificationConfiguration != null;
}
/// <summary>
/// A list of cache security group elements, composed of name and status sub-elements.
///
/// </summary>
public List<CacheSecurityGroupMembership> CacheSecurityGroups
{
get { return this.cacheSecurityGroups; }
set { this.cacheSecurityGroups = value; }
}
/// <summary>
/// Adds elements to the CacheSecurityGroups collection
/// </summary>
/// <param name="cacheSecurityGroups">The values to add to the CacheSecurityGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithCacheSecurityGroups(params CacheSecurityGroupMembership[] cacheSecurityGroups)
{
foreach (CacheSecurityGroupMembership element in cacheSecurityGroups)
{
this.cacheSecurityGroups.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the CacheSecurityGroups collection
/// </summary>
/// <param name="cacheSecurityGroups">The values to add to the CacheSecurityGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithCacheSecurityGroups(IEnumerable<CacheSecurityGroupMembership> cacheSecurityGroups)
{
foreach (CacheSecurityGroupMembership element in cacheSecurityGroups)
{
this.cacheSecurityGroups.Add(element);
}
return this;
}
// Check to see if CacheSecurityGroups property is set
internal bool IsSetCacheSecurityGroups()
{
return this.cacheSecurityGroups.Count > 0;
}
/// <summary>
/// The status of the cache parameter group.
///
/// </summary>
public CacheParameterGroupStatus CacheParameterGroup
{
get { return this.cacheParameterGroup; }
set { this.cacheParameterGroup = value; }
}
/// <summary>
/// Sets the CacheParameterGroup property
/// </summary>
/// <param name="cacheParameterGroup">The value to set for the CacheParameterGroup property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithCacheParameterGroup(CacheParameterGroupStatus cacheParameterGroup)
{
this.cacheParameterGroup = cacheParameterGroup;
return this;
}
// Check to see if CacheParameterGroup property is set
internal bool IsSetCacheParameterGroup()
{
return this.cacheParameterGroup != null;
}
/// <summary>
/// The name of the cache subnet group associated with the cache cluster.
///
/// </summary>
public string CacheSubnetGroupName
{
get { return this.cacheSubnetGroupName; }
set { this.cacheSubnetGroupName = value; }
}
/// <summary>
/// Sets the CacheSubnetGroupName property
/// </summary>
/// <param name="cacheSubnetGroupName">The value to set for the CacheSubnetGroupName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithCacheSubnetGroupName(string cacheSubnetGroupName)
{
this.cacheSubnetGroupName = cacheSubnetGroupName;
return this;
}
// Check to see if CacheSubnetGroupName property is set
internal bool IsSetCacheSubnetGroupName()
{
return this.cacheSubnetGroupName != null;
}
/// <summary>
/// A list of cache nodes that are members of the cache cluster.
///
/// </summary>
public List<CacheNode> CacheNodes
{
get { return this.cacheNodes; }
set { this.cacheNodes = value; }
}
/// <summary>
/// Adds elements to the CacheNodes collection
/// </summary>
/// <param name="cacheNodes">The values to add to the CacheNodes collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithCacheNodes(params CacheNode[] cacheNodes)
{
foreach (CacheNode element in cacheNodes)
{
this.cacheNodes.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the CacheNodes collection
/// </summary>
/// <param name="cacheNodes">The values to add to the CacheNodes collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithCacheNodes(IEnumerable<CacheNode> cacheNodes)
{
foreach (CacheNode element in cacheNodes)
{
this.cacheNodes.Add(element);
}
return this;
}
// Check to see if CacheNodes property is set
internal bool IsSetCacheNodes()
{
return this.cacheNodes.Count > 0;
}
/// <summary>
/// If <c>true</c>, then minor version patches are applied automatically; if <c>false</c>, then automatic minor version patches are disabled.
///
/// </summary>
public bool AutoMinorVersionUpgrade
{
get { return this.autoMinorVersionUpgrade ?? default(bool); }
set { this.autoMinorVersionUpgrade = value; }
}
/// <summary>
/// Sets the AutoMinorVersionUpgrade property
/// </summary>
/// <param name="autoMinorVersionUpgrade">The value to set for the AutoMinorVersionUpgrade property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithAutoMinorVersionUpgrade(bool autoMinorVersionUpgrade)
{
this.autoMinorVersionUpgrade = autoMinorVersionUpgrade;
return this;
}
// Check to see if AutoMinorVersionUpgrade property is set
internal bool IsSetAutoMinorVersionUpgrade()
{
return this.autoMinorVersionUpgrade.HasValue;
}
/// <summary>
/// A list of VPC Security Groups associated with the cache cluster.
///
/// </summary>
public List<SecurityGroupMembership> SecurityGroups
{
get { return this.securityGroups; }
set { this.securityGroups = value; }
}
/// <summary>
/// Adds elements to the SecurityGroups collection
/// </summary>
/// <param name="securityGroups">The values to add to the SecurityGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithSecurityGroups(params SecurityGroupMembership[] securityGroups)
{
foreach (SecurityGroupMembership element in securityGroups)
{
this.securityGroups.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the SecurityGroups collection
/// </summary>
/// <param name="securityGroups">The values to add to the SecurityGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithSecurityGroups(IEnumerable<SecurityGroupMembership> securityGroups)
{
foreach (SecurityGroupMembership element in securityGroups)
{
this.securityGroups.Add(element);
}
return this;
}
// Check to see if SecurityGroups property is set
internal bool IsSetSecurityGroups()
{
return this.securityGroups.Count > 0;
}
/// <summary>
/// The replication group to which this cache cluster belongs. If this field is empty, the cache cluster is not associated with any replication
/// group.
///
/// </summary>
public string ReplicationGroupId
{
get { return this.replicationGroupId; }
set { this.replicationGroupId = value; }
}
/// <summary>
/// Sets the ReplicationGroupId property
/// </summary>
/// <param name="replicationGroupId">The value to set for the ReplicationGroupId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CacheCluster WithReplicationGroupId(string replicationGroupId)
{
this.replicationGroupId = replicationGroupId;
return this;
}
// Check to see if ReplicationGroupId property is set
internal bool IsSetReplicationGroupId()
{
return this.replicationGroupId != null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Service.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);
}
}
}
}
| |
/*
* 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.
*/
/*
* Created on May 30, 2005
*
*/
namespace TestCases.SS.Formula.Functions
{
using NPOI.SS.Formula.Eval;
using NUnit.Framework;
using NPOI.SS.Formula.Functions;
using System;
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*/
[TestFixture]
public class TestStatsLib : AbstractNumericTestCase
{
[Test]
public void TestDevsq()
{
double[] v = null;
double d, x = 0;
v = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
d = StatsLib.devsq(v);
x = 82.5;
Assert.AreEqual( x, d,"devsq ");
v = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
d = StatsLib.devsq(v);
x = 0;
Assert.AreEqual( x, d,"devsq ");
v = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
d = StatsLib.devsq(v);
x = 0;
Assert.AreEqual( x, d,"devsq ");
v = new double[] { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 };
d = StatsLib.devsq(v);
x = 2.5;
Assert.AreEqual( x, d,"devsq ");
v = new double[] { 123.12, 33.3333, 2d / 3d, 5.37828, 0.999 };
d = StatsLib.devsq(v);
x = 10953.7416965767;
Assert.AreEqual( x, d, 0.0000000001, "devsq ");
v = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
d = StatsLib.devsq(v);
x = 82.5;
Assert.AreEqual( x, d,"devsq ");
}
[Test]
public void TestKthLargest()
{
double[] v = null;
double d, x = 0;
v = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
d = StatsLib.kthLargest(v, 3);
x = 8;
Assert.AreEqual( x, d,"kthLargest ");
v = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
d = StatsLib.kthLargest(v, 3);
x = 1;
Assert.AreEqual( x, d,"kthLargest ");
v = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
d = StatsLib.kthLargest(v, 3);
x = 0;
Assert.AreEqual( x, d,"kthLargest ");
v = new double[] { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 };
d = StatsLib.kthLargest(v, 3);
x = 2;
Assert.AreEqual( x, d,"kthLargest ");
v = new double[] { 123.12, 33.3333, 2d / 3d, 5.37828, 0.999 };
d = StatsLib.kthLargest(v, 3);
x = 5.37828;
Assert.AreEqual( x, d,"kthLargest ");
v = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
d = StatsLib.kthLargest(v, 3);
x = -3;
Assert.AreEqual( x, d,"kthLargest ");
}
[Test]
public void TestKthSmallest()
{
}
[Test]
public void TestAvedev()
{
double[] v = null;
double d, x = 0;
v = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
d = StatsLib.avedev(v);
x = 2.5;
Assert.AreEqual( x, d,"avedev ");
v = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
d = StatsLib.avedev(v);
x = 0;
Assert.AreEqual( x, d,"avedev ");
v = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
d = StatsLib.avedev(v);
x = 0;
Assert.AreEqual( x, d,"avedev ");
v = new double[] { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 };
d = StatsLib.avedev(v);
x = 0.5;
Assert.AreEqual( x, d,"avedev ");
v = new double[] { 123.12, 33.3333, 2d / 3d, 5.37828, 0.999 };
d = StatsLib.avedev(v);
x = 36.42176053333;
Assert.AreEqual( x, d,0.00000000001,"avedev ");
v = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
d = StatsLib.avedev(v);
x = 2.5;
Assert.AreEqual( x, d,"avedev ");
}
[Test]
public void TestMedian()
{
double[] v = null;
double d, x = 0;
v = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
d = StatsLib.median(v);
x = 5.5;
Assert.AreEqual( x, d,"median ");
v = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
d = StatsLib.median(v);
x = 1;
Assert.AreEqual( x, d,"median ");
v = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
d = StatsLib.median(v);
x = 0;
Assert.AreEqual( x, d,"median ");
v = new double[] { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 };
d = StatsLib.median(v);
x = 1.5;
Assert.AreEqual( x, d,"median ");
v = new double[] { 123.12, 33.3333, 2d / 3d, 5.37828, 0.999 };
d = StatsLib.median(v);
x = 5.37828;
Assert.AreEqual( x, d,"median ");
v = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
d = StatsLib.median(v);
x = -5.5;
Assert.AreEqual( x, d,"median ");
v = new double[] { -2, -3, -4, -5, -6, -7, -8, -9, -10 };
d = StatsLib.median(v);
x = -6;
Assert.AreEqual( x, d,"median ");
v = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
d = StatsLib.median(v);
x = 5;
Assert.AreEqual( x, d,"median ");
}
[Test]
public void TestMode()
{
double[] v;
v = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmMode(v, null);
v = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
ConfirmMode(v, 1.0);
v = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
ConfirmMode(v, 0.0);
v = new double[] { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 };
ConfirmMode(v, 1.0);
v = new double[] { 123.12, 33.3333, 2d / 3d, 5.37828, 0.999 };
ConfirmMode(v, null);
v = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
ConfirmMode(v, null);
v = new double[] { 1, 2, 3, 4, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
ConfirmMode(v, 1.0);
v = new double[] { 0, 1, 2, 3, 4, 1, 1, 1, 0, 0, 0, 0, 1 };
ConfirmMode(v, 0.0);
}
private static void ConfirmMode(double[] v, double expectedResult)
{
ConfirmMode(v, (Double?)expectedResult);
}
private static void ConfirmMode(double[] v, Double? expectedResult)
{
double actual;
try
{
actual = Mode.Evaluate(v);
if (expectedResult == null)
{
throw new AssertionException("Expected N/A exception was not thrown");
}
}
catch (EvaluationException e)
{
if (expectedResult == null)
{
Assert.AreEqual(ErrorEval.NA, e.GetErrorEval());
return;
}
throw e;
}
Assert.AreEqual( expectedResult.Value, actual,"mode");
}
[Test]
public void TestStddev()
{
double[] v = null;
double d, x = 0;
v = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
d = StatsLib.stdev(v);
x = 3.02765035409749;
Assert.AreEqual( x, d,0.0000000001, "stdev ");
v = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
d = StatsLib.stdev(v);
x = 0;
Assert.AreEqual( x, d,"stdev ");
v = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
d = StatsLib.stdev(v);
x = 0;
Assert.AreEqual( x, d,"stdev ");
v = new double[] { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 };
d = StatsLib.stdev(v);
x = 0.52704627669;
Assert.AreEqual( x, d,0.000000001,"stdev ");
v = new double[] { 123.12, 33.3333, 2d / 3d, 5.37828, 0.999 };
d = StatsLib.stdev(v);
x = 52.33006233652;
Assert.AreEqual( x, d,0.0000000001,"stdev ");
v = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
d = StatsLib.stdev(v);
x = 3.02765035410;
Assert.AreEqual( x, d,0.0000000001,"stdev ");
}
[Test]
public void TestVar()
{
double[] v = null;
double d, x = 0;
v = new double[] { 3.50, 5.00, 7.23, 2.99 };
d = StatsLib.var(v);
x = 3.6178;
//the following AreEqual add a delta param against java version, otherwise tests fail.
Assert.AreEqual( x, d, 0.00001,"var ");
v = new double[] { 34.5, 2.0, 8.9, -4.0 };
d = StatsLib.var(v);
x = 286.99;
Assert.AreEqual( x, d,0.001,"var ");
v = new double[] { 7.0, 25.0, 21.69 };
d = StatsLib.var(v);
x = 91.79203333;
Assert.AreEqual( x, d,0.00000001,"var ");
v = new double[] { 1345, 1301, 1368, 1322, 1310, 1370, 1318, 1350, 1303, 1299 };
d = StatsLib.var(v);
x = 754.2666667;
Assert.AreEqual( x, d, 0.0000001,"var ");
}
[Test]
public void TestVarp()
{
double[] v = null;
double d, x = 0;
v = new double[] { 3.50, 5.00, 7.23, 2.99 };
d = StatsLib.varp(v);
x = 2.71335;
Assert.AreEqual( x, d, 0.000001, "varp ");
v = new double[] { 34.5, 2.0, 8.9, -4.0 };
d = StatsLib.varp(v);
x = 215.2425;
Assert.AreEqual( x, d,0.00001,"varp ");
v = new double[] { 7.0, 25.0, 21.69 };
d = StatsLib.varp(v);
x = 61.19468889;
Assert.AreEqual( x, d, 0.00000001, "varp ");
v = new double[] { 1345, 1301, 1368, 1322, 1310, 1370, 1318, 1350, 1303, 1299 };
d = StatsLib.varp(v);
x = 678.84;
Assert.AreEqual( x, d, 0.001,"varp ");
}
}
}
| |
using System.Data;
using NUnit.Framework;
namespace SequelocityDotNet.Tests.SqlServer.DatabaseCommandExtensionsTests
{
[TestFixture]
public class ExecuteToMapTests
{
public class SuperHero
{
public long SuperHeroId;
public string SuperHeroName;
}
[Test]
public void Should_Call_The_DataRecordCall_Action_For_Each_Record_In_The_Result_Set()
{
// Arrange
const string sql = @"
CREATE TABLE #SuperHero
(
SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
SuperHeroName NVARCHAR(120) NOT NULL
);
INSERT INTO #SuperHero ( SuperHeroName )
VALUES ( 'Superman' );
INSERT INTO #SuperHero ( SuperHeroName )
VALUES ( 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM #SuperHero;
";
// Act
var superHeroes = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString )
.SetCommandText( sql )
.ExecuteToMap( record =>
{
var obj = new SuperHero
{
SuperHeroId = record.GetValue( 0 ).ToLong(),
SuperHeroName = record.GetValue( 1 ).ToString()
};
return obj;
} );
// Assert
Assert.That( superHeroes.Count == 2 );
}
[Test]
public void Should_Null_The_DbCommand_By_Default()
{
// Arrange
const string sql = @"
CREATE TABLE #SuperHero
(
SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
SuperHeroName NVARCHAR(120) NOT NULL
);
INSERT INTO #SuperHero ( SuperHeroName )
VALUES ( 'Superman' );
INSERT INTO #SuperHero ( SuperHeroName )
VALUES ( 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM #SuperHero;
";
var databaseCommand = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString )
.SetCommandText( sql );
// Act
var superHeroes = databaseCommand.ExecuteToMap( record =>
{
var obj = new SuperHero
{
SuperHeroId = record.GetValue( 0 ).ToLong(),
SuperHeroName = record.GetValue( 1 ).ToString()
};
return obj;
} );
// Assert
Assert.IsNull( databaseCommand.DbCommand );
}
[Test]
public void Should_Keep_The_Database_Connection_Open_If_keepConnectionOpen_Parameter_Was_True()
{
// Arrange
const string sql = @"
CREATE TABLE #SuperHero
(
SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
SuperHeroName NVARCHAR(120) NOT NULL
);
INSERT INTO #SuperHero ( SuperHeroName )
VALUES ( 'Superman' );
INSERT INTO #SuperHero ( SuperHeroName )
VALUES ( 'Batman' );
SELECT SuperHeroId,
SuperHeroName
FROM #SuperHero;
";
var databaseCommand = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString )
.SetCommandText( sql );
// Act
var superHeroes = databaseCommand.ExecuteToMap( record =>
{
var obj = new SuperHero
{
SuperHeroId = record.GetValue( 0 ).ToLong(),
SuperHeroName = record.GetValue( 1 ).ToString()
};
return obj;
}, true );
// Assert
Assert.That( databaseCommand.DbCommand.Connection.State == ConnectionState.Open );
// Cleanup
databaseCommand.Dispose();
}
[Test]
public void Should_Call_The_DatabaseCommandPreExecuteEventHandler()
{
// Arrange
bool wasPreExecuteEventHandlerCalled = false;
Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPreExecuteEventHandlers.Add( command => wasPreExecuteEventHandlerCalled = true );
// Act
var superHeroes = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString )
.SetCommandText( "SELECT 1 as SuperHeroId, 'Superman' as SuperHeroName" )
.ExecuteToMap( record =>
{
var obj = new SuperHero
{
SuperHeroId = record.GetValue( 0 ).ToLong(),
SuperHeroName = record.GetValue( 1 ).ToString()
};
return obj;
} );
// Assert
Assert.IsTrue( wasPreExecuteEventHandlerCalled );
}
[Test]
public void Should_Call_The_DatabaseCommandPostExecuteEventHandler()
{
// Arrange
bool wasPostExecuteEventHandlerCalled = false;
Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPostExecuteEventHandlers.Add( command => wasPostExecuteEventHandlerCalled = true );
// Act
var superHeroes = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString )
.SetCommandText( "SELECT 1 as SuperHeroId, 'Superman' as SuperHeroName" )
.ExecuteToMap( record =>
{
var obj = new SuperHero
{
SuperHeroId = record.GetValue( 0 ).ToLong(),
SuperHeroName = record.GetValue( 1 ).ToString()
};
return obj;
} );
// Assert
Assert.IsTrue( wasPostExecuteEventHandlerCalled );
}
[Test]
public void Should_Call_The_DatabaseCommandUnhandledExceptionEventHandler()
{
// Arrange
bool wasUnhandledExceptionEventHandlerCalled = false;
Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandUnhandledExceptionEventHandlers.Add( ( exception, command ) =>
{
wasUnhandledExceptionEventHandlerCalled = true;
} );
// Act
TestDelegate action = () => Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString )
.SetCommandText( "asdf;lkj" )
.ExecuteToMap( record =>
{
var obj = new SuperHero
{
SuperHeroId = record.GetValue( 0 ).ToLong(),
SuperHeroName = record.GetValue( 1 ).ToString()
};
return obj;
} );
// Assert
Assert.Throws<System.Data.SqlClient.SqlException>( action );
Assert.IsTrue( wasUnhandledExceptionEventHandlerCalled );
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// GeocodeResponse
/// </summary>
[DataContract]
public partial class GeocodeResponse : IEquatable<GeocodeResponse>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="GeocodeResponse" /> class.
/// </summary>
/// <param name="error">error.</param>
/// <param name="latitude">latitude.</param>
/// <param name="longitude">longitude.</param>
/// <param name="metadata">metadata.</param>
/// <param name="success">Indicates if API call was successful.</param>
/// <param name="warning">warning.</param>
public GeocodeResponse(Error error = default(Error), decimal? latitude = default(decimal?), decimal? longitude = default(decimal?), ResponseMetadata metadata = default(ResponseMetadata), bool? success = default(bool?), Warning warning = default(Warning))
{
this.Error = error;
this.Latitude = latitude;
this.Longitude = longitude;
this.Metadata = metadata;
this.Success = success;
this.Warning = warning;
}
/// <summary>
/// Gets or Sets Error
/// </summary>
[DataMember(Name="error", EmitDefaultValue=false)]
public Error Error { get; set; }
/// <summary>
/// Gets or Sets Latitude
/// </summary>
[DataMember(Name="latitude", EmitDefaultValue=false)]
public decimal? Latitude { get; set; }
/// <summary>
/// Gets or Sets Longitude
/// </summary>
[DataMember(Name="longitude", EmitDefaultValue=false)]
public decimal? Longitude { get; set; }
/// <summary>
/// Gets or Sets Metadata
/// </summary>
[DataMember(Name="metadata", EmitDefaultValue=false)]
public ResponseMetadata Metadata { get; set; }
/// <summary>
/// Indicates if API call was successful
/// </summary>
/// <value>Indicates if API call was successful</value>
[DataMember(Name="success", EmitDefaultValue=false)]
public bool? Success { get; set; }
/// <summary>
/// Gets or Sets Warning
/// </summary>
[DataMember(Name="warning", EmitDefaultValue=false)]
public Warning Warning { 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 GeocodeResponse {\n");
sb.Append(" Error: ").Append(Error).Append("\n");
sb.Append(" Latitude: ").Append(Latitude).Append("\n");
sb.Append(" Longitude: ").Append(Longitude).Append("\n");
sb.Append(" Metadata: ").Append(Metadata).Append("\n");
sb.Append(" Success: ").Append(Success).Append("\n");
sb.Append(" Warning: ").Append(Warning).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as GeocodeResponse);
}
/// <summary>
/// Returns true if GeocodeResponse instances are equal
/// </summary>
/// <param name="input">Instance of GeocodeResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GeocodeResponse input)
{
if (input == null)
return false;
return
(
this.Error == input.Error ||
(this.Error != null &&
this.Error.Equals(input.Error))
) &&
(
this.Latitude == input.Latitude ||
(this.Latitude != null &&
this.Latitude.Equals(input.Latitude))
) &&
(
this.Longitude == input.Longitude ||
(this.Longitude != null &&
this.Longitude.Equals(input.Longitude))
) &&
(
this.Metadata == input.Metadata ||
(this.Metadata != null &&
this.Metadata.Equals(input.Metadata))
) &&
(
this.Success == input.Success ||
(this.Success != null &&
this.Success.Equals(input.Success))
) &&
(
this.Warning == input.Warning ||
(this.Warning != null &&
this.Warning.Equals(input.Warning))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Error != null)
hashCode = hashCode * 59 + this.Error.GetHashCode();
if (this.Latitude != null)
hashCode = hashCode * 59 + this.Latitude.GetHashCode();
if (this.Longitude != null)
hashCode = hashCode * 59 + this.Longitude.GetHashCode();
if (this.Metadata != null)
hashCode = hashCode * 59 + this.Metadata.GetHashCode();
if (this.Success != null)
hashCode = hashCode * 59 + this.Success.GetHashCode();
if (this.Warning != null)
hashCode = hashCode * 59 + this.Warning.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
//Copyright (C) 2005 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the GISTrainer.java source file found in the
//original java implementation of MaxEnt. That source file contains the following header:
// Copyright (C) 2001 Jason Baldridge and Gann Bierner
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections;
using System.Collections.Generic;
namespace SharpEntropy
{
/// <summary>
/// An implementation of Generalized Iterative Scaling. The reference paper
/// for this implementation was Adwait Ratnaparkhi's tech report at the
/// University of Pennsylvania's Institute for Research in Cognitive Science,
/// and is available at <a href ="ftp://ftp.cis.upenn.edu/pub/ircs/tr/97-08.ps.Z"><code>ftp://ftp.cis.upenn.edu/pub/ircs/tr/97-08.ps.Z</code></a>.
/// </summary>
/// <author>
/// Jason Baldridge
/// </author>
/// <author>
/// Richard J, Northedge
/// </author>
/// <version>
/// based on GISTrainer.java, $Revision: 1.15 $, $Date: 2004/06/14 20:52:41 $
/// </version>
public class GisTrainer : IO.IGisModelReader
{
private int mTokenCount; // # of event tokens
private int mPredicateCount; // # of predicates
private int mOutcomeCount; // # of mOutcomes
private int mTokenID; // global index variable for Tokens
private int mPredicateId; // global index variable for Predicates
private int mOutcomeId; // global index variable for Outcomes
// records the array of predicates seen in each event
private int[][] mContexts;
// records the array of outcomes seen in each event
private int[] mOutcomes;
// records the num of times an event has been seen, paired to
// int[][] mContexts
private int[] mNumTimesEventsSeen;
// stores the string names of the outcomes. The GIS only tracks outcomes
// as ints, and so this array is needed to save the model to disk and
// thereby allow users to know what the outcome was in human
// understandable terms.
private string[] mOutcomeLabels;
// stores the string names of the predicates. The GIS only tracks
// predicates as ints, and so this array is needed to save the model to
// disk and thereby allow users to know what the outcome was in human
// understandable terms.
private string[] mPredicateLabels;
// stores the observed expections of each of the events
private double[][] mObservedExpections;
// stores the estimated parameter value of each predicate during iteration
private double[][] mParameters;
// Stores the expected values of the features based on the current models
private double[][] mModelExpections;
//The maximum number of features fired in an event. Usually referred to as C.
private int mMaximumFeatureCount;
// stores inverse of constant, 1/C.
private double mMaximumFeatureCountInverse;
// the correction parameter of the model
private double mCorrectionParameter;
// observed expectation of correction feature
private double mCorrectionFeatureObservedExpectation;
// a global variable to help compute the amount to modify the correction
// parameter
private double mCorrectionFeatureModifier;
private const double mNearZero = 0.01;
private const double mLLThreshold = 0.0001;
// Stores the output of the current model on a single event durring
// training. This will be reset for every event for every iteration.
private double[] mModelDistribution;
// Stores the number of features that get fired per event
private int[] mFeatureCounts;
// initial probability for all outcomes.
private double mInitialProbability;
private Dictionary<string, PatternedPredicate> mPredicates;
private int[][] mOutcomePatterns;
// smoothing algorithm (unused) --------
// internal class UpdateParametersWithSmoothingProcedure : Trove.IIntDoubleProcedure
// {
// private double mdSigma = 2.0;
// public UpdateParametersWithSmoothingProcedure(GisTrainer enclosingInstance)
// {
// moEnclosingInstance = enclosingInstance;
// }
//
// private GisTrainer moEnclosingInstance;
//
// public virtual bool Execute(int outcomeID, double input)
// {
// double x = 0.0;
// double x0 = 0.0;
// double tmp;
// double f;
// double fp;
// for (int i = 0; i < 50; i++)
// {
// // check what domain these parameters are in
// tmp = moEnclosingInstance.maoModelExpections[moEnclosingInstance.miPredicateID][outcomeID] * System.Math.Exp(moEnclosingInstance.miConstant * x0);
// f = tmp + (input + x0) / moEnclosingInstance.mdSigma - moEnclosingInstance.maoObservedExpections[moEnclosingInstance.miPredicateID][outcomeID];
// fp = tmp * moEnclosingInstance.miConstant + 1 / moEnclosingInstance.mdSigma;
// if (fp == 0)
// {
// break;
// }
// x = x0 - f / fp;
// if (System.Math.Abs(x - x0) < 0.000001)
// {
// x0 = x;
// break;
// }
// x0 = x;
// }
// moEnclosingInstance.maoParameters[moEnclosingInstance.miPredicateID].Put(outcomeID, input + x0);
// return true;
// }
// }
// training progress event -----------
/// <summary>
/// Used to provide informational messages regarding the
/// progress of the training algorithm.
/// </summary>
public event TrainingProgressEventHandler TrainingProgress;
/// <summary>
/// Used to raise events providing messages with information
/// about training progress.
/// </summary>
/// <param name="e">
/// Contains the message with information about the progress of
/// the training algorithm.
/// </param>
protected virtual void OnTrainingProgress(TrainingProgressEventArgs e)
{
if (TrainingProgress != null)
{
TrainingProgress(this, e);
}
}
private void NotifyProgress(string message)
{
OnTrainingProgress(new TrainingProgressEventArgs(message));
}
// training options --------------
/// <summary>
/// Sets whether this trainer will use smoothing while training the model.
/// This can improve model accuracy, though training will potentially take
/// longer and use more memory. Model size will also be larger.
/// </summary>
/// <remarks>
/// Initial testing indicates improvements for models built on small data sets and
/// few outcomes, but performance degradation for those with large data
/// sets and lots of outcomes.
/// </remarks>
public bool Smoothing { get; set; }
/// <summary>
/// Sets whether this trainer will use slack parameters while training the model.
/// </summary>
public bool UseSlackParameter { get; set; }
/// <summary>
/// If smoothing is in use, this value indicates the "number" of
/// times we want the trainer to imagine that it saw a feature that it
/// actually didn't see. Defaulted to 0.1.
/// </summary>
public double SmoothingObservation { get; set; }
/// <summary>
/// Creates a new <code>GisTrainer</code> instance.
/// </summary>
public GisTrainer()
{
Smoothing = false;
UseSlackParameter = false;
SmoothingObservation = 0.1;
}
/// <summary>
/// Creates a new <code>GisTrainer</code> instance.
/// </summary>
/// <param name="useSlackParameter">
/// Sets whether this trainer will use slack parameters while training the model.
/// </param>
public GisTrainer(bool useSlackParameter)
{
Smoothing = false;
UseSlackParameter = useSlackParameter;
SmoothingObservation = 0.1;
}
/// <summary>
/// Creates a new <code>GisTrainer</code> instance.
/// </summary>
/// <param name="smoothingObservation">
/// If smoothing is in use, this value indicates the "number" of
/// times we want the trainer to imagine that it saw a feature that it
/// actually didn't see. Defaulted to 0.1.
/// </param>
public GisTrainer(double smoothingObservation)
{
Smoothing = true;
UseSlackParameter = false;
SmoothingObservation = smoothingObservation;
}
/// <summary>
/// Creates a new <code>GisTrainer</code> instance.
/// </summary>
/// <param name="useSlackParameter">
/// Sets whether this trainer will use slack parameters while training the model.
/// </param>
/// <param name="smoothingObservation">
/// If smoothing is in use, this value indicates the "number" of
/// times we want the trainer to imagine that it saw a feature that it
/// actually didn't see. Defaulted to 0.1.
/// </param>
public GisTrainer(bool useSlackParameter, double smoothingObservation)
{
Smoothing = true;
UseSlackParameter = useSlackParameter;
SmoothingObservation = smoothingObservation;
}
// alternative TrainModel signatures --------------
/// <summary>
/// Train a model using the GIS algorithm.
/// </summary>
/// <param name="eventReader">
/// The ITrainingEventReader holding the data on which this model
/// will be trained.
/// </param>
public virtual void TrainModel(ITrainingEventReader eventReader)
{
TrainModel(eventReader, 100, 0);
}
/// <summary>
/// Train a model using the GIS algorithm.
/// </summary>
/// <param name="eventReader">
/// The ITrainingEventReader holding the data on which this model will be trained
/// </param>
/// <param name="iterations">The number of GIS iterations to perform</param>
/// <param name="cutoff">
/// The number of times a predicate must be seen in order
/// to be relevant for training.
/// </param>
public virtual void TrainModel(ITrainingEventReader eventReader, int iterations, int cutoff)
{
TrainModel(iterations, new OnePassDataIndexer(eventReader, cutoff));
}
// training algorithm -----------------------------
/// <summary>
/// Train a model using the GIS algorithm.
/// </summary>
/// <param name="iterations">
/// The number of GIS iterations to perform.
/// </param>
/// <param name="dataIndexer">
/// The data indexer used to compress events in memory.
/// </param>
public virtual void TrainModel(int iterations, ITrainingDataIndexer dataIndexer)
{
int[] outcomeList;
//incorporate all of the needed info
NotifyProgress("Incorporating indexed data for training...");
mContexts = dataIndexer.GetContexts();
mOutcomes = dataIndexer.GetOutcomeList();
mNumTimesEventsSeen = dataIndexer.GetNumTimesEventsSeen();
mTokenCount = mContexts.Length;
// determine the correction constant and its inverse
mMaximumFeatureCount = mContexts[0].Length;
for (mTokenID = 1; mTokenID < mContexts.Length; mTokenID++)
{
if (mContexts[mTokenID].Length > mMaximumFeatureCount)
{
mMaximumFeatureCount = mContexts[mTokenID].Length;
}
}
mMaximumFeatureCountInverse = 1.0 / mMaximumFeatureCount;
NotifyProgress("done.");
mOutcomeLabels = dataIndexer.GetOutcomeLabels();
outcomeList = dataIndexer.GetOutcomeList();
mOutcomeCount = mOutcomeLabels.Length;
mInitialProbability = Math.Log(1.0 / mOutcomeCount);
mPredicateLabels = dataIndexer.GetPredicateLabels();
mPredicateCount = mPredicateLabels.Length;
NotifyProgress("\tNumber of Event Tokens: " + mTokenCount);
NotifyProgress("\t Number of Outcomes: " + mOutcomeCount);
NotifyProgress("\t Number of Predicates: " + mPredicateCount);
// set up feature arrays
var predicateCounts = new int[mPredicateCount][];
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
predicateCounts[mPredicateId] = new int[mOutcomeCount];
}
for (mTokenID = 0; mTokenID < mTokenCount; mTokenID++)
{
for (int currentContext = 0; currentContext < mContexts[mTokenID].Length; currentContext++)
{
predicateCounts[mContexts[mTokenID][currentContext]][outcomeList[mTokenID]] += mNumTimesEventsSeen[mTokenID];
}
}
// A fake "observation" to cover features which are not detected in
// the data. The default is to assume that we observed "1/10th" of a
// feature during training.
double smoothingObservation = SmoothingObservation;
// Get the observed expectations of the features. Strictly speaking,
// we should divide the counts by the number of Tokens, but because of
// the way the model's expectations are approximated in the
// implementation, this is cancelled out when we compute the next
// iteration of a parameter, making the extra divisions wasteful.
mOutcomePatterns = new int[mPredicateCount][];
mParameters = new double[mPredicateCount][];
mModelExpections = new double[mPredicateCount][];
mObservedExpections = new double[mPredicateCount][];
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
int activeOutcomeCount;
if (Smoothing)
{
activeOutcomeCount = mOutcomeCount;
}
else
{
activeOutcomeCount = 0;
for (mOutcomeId = 0; mOutcomeId < mOutcomeCount; mOutcomeId++)
{
if (predicateCounts[mPredicateId][mOutcomeId] > 0)
{
activeOutcomeCount++;
}
}
}
mOutcomePatterns[mPredicateId] = new int[activeOutcomeCount];
mParameters[mPredicateId] = new double[activeOutcomeCount];
mModelExpections[mPredicateId] = new double[activeOutcomeCount];
mObservedExpections[mPredicateId] = new double[activeOutcomeCount];
int currentOutcome = 0;
for (mOutcomeId = 0; mOutcomeId < mOutcomeCount; mOutcomeId++)
{
if (predicateCounts[mPredicateId][mOutcomeId] > 0)
{
mOutcomePatterns[mPredicateId][currentOutcome] = mOutcomeId;
mObservedExpections[mPredicateId][currentOutcome] = Math.Log(predicateCounts[mPredicateId][mOutcomeId]);
currentOutcome++;
}
else if (Smoothing)
{
mOutcomePatterns[mPredicateId][currentOutcome] = mOutcomeId;
mObservedExpections[mPredicateId][currentOutcome] = Math.Log(smoothingObservation);
currentOutcome++;
}
}
}
// compute the expected value of correction
if (UseSlackParameter)
{
int correctionFeatureValueSum = 0;
for (mTokenID = 0; mTokenID < mTokenCount; mTokenID++)
{
for (int currentContext = 0; currentContext < mContexts[mTokenID].Length; currentContext++)
{
mPredicateId = mContexts[mTokenID][currentContext];
if ((!Smoothing) && predicateCounts[mPredicateId][mOutcomes[mTokenID]] == 0)
{
correctionFeatureValueSum += mNumTimesEventsSeen[mTokenID];
}
}
correctionFeatureValueSum += (mMaximumFeatureCount - mContexts[mTokenID].Length) * mNumTimesEventsSeen[mTokenID];
}
if (correctionFeatureValueSum == 0)
{
mCorrectionFeatureObservedExpectation = Math.Log(mNearZero); //nearly zero so log is defined
}
else
{
mCorrectionFeatureObservedExpectation = Math.Log(correctionFeatureValueSum);
}
mCorrectionParameter = 0.0;
}
NotifyProgress("...done.");
mModelDistribution = new double[mOutcomeCount];
mFeatureCounts = new int[mOutcomeCount];
//Find the parameters
NotifyProgress("Computing model parameters...");
FindParameters(iterations);
NotifyProgress("Converting to new predicate format...");
ConvertPredicates();
}
/// <summary>
/// Estimate and return the model parameters.
/// </summary>
/// <param name="iterations">
/// Number of iterations to run through.
/// </param>
private void FindParameters(int iterations)
{
double previousLogLikelihood = 0.0;
NotifyProgress("Performing " + iterations + " iterations.");
for (int currentIteration = 1; currentIteration <= iterations; currentIteration++)
{
if (currentIteration < 10)
{
NotifyProgress(" " + currentIteration + ": ");
}
else if (currentIteration < 100)
{
NotifyProgress(" " + currentIteration + ": ");
}
else
{
NotifyProgress(currentIteration + ": ");
}
double currentLogLikelihood = NextIteration();
if (currentIteration > 1)
{
if (previousLogLikelihood > currentLogLikelihood)
{
throw new SystemException("Model Diverging: loglikelihood decreased");
}
if (currentLogLikelihood - previousLogLikelihood < mLLThreshold)
{
break;
}
}
previousLogLikelihood = currentLogLikelihood;
}
// kill a bunch of these big objects now that we don't need them
mObservedExpections = null;
mModelExpections = null;
mNumTimesEventsSeen = null;
mContexts = null;
}
/// <summary>
/// Use this model to evaluate a context and return an array of the
/// likelihood of each outcome given that context.
/// </summary>
/// <param name="context">
/// The integers of the predicates which have been
/// observed at the present decision point.
/// </param>
/// <param name="outcomeSums">
/// The normalized probabilities for the outcomes given the
/// context. The indexes of the double[] are the outcome
/// ids.
/// </param>
protected virtual void Evaluate(int[] context, double[] outcomeSums)
{
for (int outcomeIndex = 0; outcomeIndex < mOutcomeCount; outcomeIndex++)
{
outcomeSums[outcomeIndex] = mInitialProbability;
mFeatureCounts[outcomeIndex] = 0;
}
int[] activeOutcomes;
int outcomeId;
int predicateId;
int currentActiveOutcome;
for (int currentContext = 0; currentContext < context.Length; currentContext++)
{
predicateId = context[currentContext];
activeOutcomes = mOutcomePatterns[predicateId];
for (currentActiveOutcome = 0; currentActiveOutcome < activeOutcomes.Length; currentActiveOutcome++)
{
outcomeId = activeOutcomes[currentActiveOutcome];
mFeatureCounts[outcomeId]++;
outcomeSums[outcomeId] += mMaximumFeatureCountInverse * mParameters[predicateId][currentActiveOutcome];
}
}
double sum = 0.0;
for (int currentOutcomeId = 0; currentOutcomeId < mOutcomeCount; currentOutcomeId++)
{
outcomeSums[currentOutcomeId] = System.Math.Exp(outcomeSums[currentOutcomeId]);
if (UseSlackParameter)
{
outcomeSums[currentOutcomeId] += ((1.0 - ((double) mFeatureCounts[currentOutcomeId] / mMaximumFeatureCount)) * mCorrectionParameter);
}
sum += outcomeSums[currentOutcomeId];
}
for (int currentOutcomeId = 0; currentOutcomeId < mOutcomeCount; currentOutcomeId++)
{
outcomeSums[currentOutcomeId] /= sum;
}
}
/// <summary>
/// Compute one iteration of GIS and retutn log-likelihood.
/// </summary>
/// <returns>The log-likelihood.</returns>
private double NextIteration()
{
// compute contribution of p(a|b_i) for each feature and the new
// correction parameter
double logLikelihood = 0.0;
mCorrectionFeatureModifier = 0.0;
int eventCount = 0;
int numCorrect = 0;
int outcomeId;
for (mTokenID = 0; mTokenID < mTokenCount; mTokenID++)
{
Evaluate(mContexts[mTokenID], mModelDistribution);
for (int currentContext = 0; currentContext < mContexts[mTokenID].Length; currentContext++)
{
mPredicateId = mContexts[mTokenID][currentContext];
for (int currentActiveOutcome = 0; currentActiveOutcome < mOutcomePatterns[mPredicateId].Length; currentActiveOutcome++)
{
outcomeId = mOutcomePatterns[mPredicateId][currentActiveOutcome];
mModelExpections[mPredicateId][currentActiveOutcome] += (mModelDistribution[outcomeId] * mNumTimesEventsSeen[mTokenID]);
if (UseSlackParameter)
{
mCorrectionFeatureModifier += mModelDistribution[mOutcomeId] * mNumTimesEventsSeen[mTokenID];
}
}
}
if (UseSlackParameter)
{
mCorrectionFeatureModifier += (mMaximumFeatureCount - mContexts[mTokenID].Length) * mNumTimesEventsSeen[mTokenID];
}
logLikelihood += System.Math.Log(mModelDistribution[mOutcomes[mTokenID]]) * mNumTimesEventsSeen[mTokenID];
eventCount += mNumTimesEventsSeen[mTokenID];
//calculation solely for the information messages
int max = 0;
for (mOutcomeId = 1; mOutcomeId < mOutcomeCount; mOutcomeId++)
{
if (mModelDistribution[mOutcomeId] > mModelDistribution[max])
{
max = mOutcomeId;
}
}
if (max == mOutcomes[mTokenID])
{
numCorrect += mNumTimesEventsSeen[mTokenID];
}
}
NotifyProgress(".");
// compute the new parameter values
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
for (int currentActiveOutcome = 0; currentActiveOutcome < mOutcomePatterns[mPredicateId].Length; currentActiveOutcome++)
{
outcomeId = mOutcomePatterns[mPredicateId][currentActiveOutcome];
mParameters[mPredicateId][currentActiveOutcome] += (mObservedExpections[mPredicateId][currentActiveOutcome] - Math.Log(mModelExpections[mPredicateId][currentActiveOutcome]));
mModelExpections[mPredicateId][currentActiveOutcome] = 0.0;// re-initialize to 0.0's
}
}
if (mCorrectionFeatureModifier > 0.0 && UseSlackParameter)
{
mCorrectionParameter += (mCorrectionFeatureObservedExpectation - Math.Log(mCorrectionFeatureModifier));
}
NotifyProgress(". logLikelihood=" + logLikelihood + "\t" + ((double) numCorrect / eventCount));
return (logLikelihood);
}
/// <summary>
/// Convert the predicate data into the outcome pattern / patterned predicate format used by the GIS models.
/// </summary>
private void ConvertPredicates()
{
var predicates = new PatternedPredicate[mParameters.Length];
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
double[] parameters = mParameters[mPredicateId];
predicates[mPredicateId] = new PatternedPredicate(mPredicateLabels[mPredicateId], parameters);
}
var comparer = new OutcomePatternComparer();
Array.Sort(mOutcomePatterns, predicates, comparer);
List<int[]> outcomePatterns = new List<int[]>();
int currentPatternId = 0;
int predicatesInPattern = 0;
int[] currentPattern = mOutcomePatterns[0];
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
if (comparer.Compare(currentPattern, mOutcomePatterns[mPredicateId]) == 0)
{
predicates[mPredicateId].OutcomePattern = currentPatternId;
predicatesInPattern++;
}
else
{
int[] pattern = new int[currentPattern.Length + 1];
pattern[0] = predicatesInPattern;
currentPattern.CopyTo(pattern, 1);
outcomePatterns.Add(pattern);
currentPattern = mOutcomePatterns[mPredicateId];
currentPatternId++;
predicates[mPredicateId].OutcomePattern = currentPatternId;
predicatesInPattern = 1;
}
}
int[] finalPattern = new int[currentPattern.Length + 1];
finalPattern[0] = predicatesInPattern;
currentPattern.CopyTo(finalPattern, 1);
outcomePatterns.Add(finalPattern);
mOutcomePatterns = outcomePatterns.ToArray();
mPredicates = new Dictionary<string, PatternedPredicate>(predicates.Length);
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
mPredicates.Add(predicates[mPredicateId].Name, predicates[mPredicateId]);
}
}
// IGisModelReader implementation --------------------
/// <summary>
/// The correction constant for the model produced as a result of training.
/// </summary>
public int CorrectionConstant
{
get
{
return mMaximumFeatureCount;
}
}
/// <summary>
/// The correction parameter for the model produced as a result of training.
/// </summary>
public double CorrectionParameter
{
get
{
return mCorrectionParameter;
}
}
/// <summary>
/// Obtains the outcome labels for the model produced as a result of training.
/// </summary>
/// <returns>
/// Array of outcome labels.
/// </returns>
public string[] GetOutcomeLabels()
{
return mOutcomeLabels;
}
/// <summary>
/// Obtains the outcome patterns for the model produced as a result of training.
/// </summary>
/// <returns>
/// Array of outcome patterns.
/// </returns>
public int[][] GetOutcomePatterns()
{
return mOutcomePatterns;
}
/// <summary>
/// Obtains the predicate data for the model produced as a result of training.
/// </summary>
/// <returns>
/// Dictionary containing PatternedPredicate objects.
/// </returns>
public Dictionary<string, PatternedPredicate> GetPredicates()
{
return mPredicates;
}
/// <summary>
/// Returns trained model information for a predicate, given the predicate label.
/// </summary>
/// <param name="predicateLabel">
/// The predicate label to fetch information for.
/// </param>
/// <param name="featureCounts">
/// Array to be passed in to the method; it should have a length equal to the number of outcomes
/// in the model. The method increments the count of each outcome that is active in the specified
/// predicate.
/// </param>
/// <param name="outcomeSums">
/// Array to be passed in to the method; it should have a length equal to the number of outcomes
/// in the model. The method adds the parameter values for each of the active outcomes in the
/// predicate.
/// </param>
public void GetPredicateData(string predicateLabel, int[] featureCounts, double[] outcomeSums)
{
if (mPredicates.ContainsKey(predicateLabel))
{
PatternedPredicate predicate = mPredicates[predicateLabel];
if (predicate != null)
{
int[] activeOutcomes = mOutcomePatterns[predicate.OutcomePattern];
for (int currentActiveOutcome = 1; currentActiveOutcome < activeOutcomes.Length; currentActiveOutcome++)
{
int outcomeIndex = activeOutcomes[currentActiveOutcome];
featureCounts[outcomeIndex]++;
outcomeSums[outcomeIndex] += predicate.GetParameter(currentActiveOutcome - 1);
}
}
}
}
private class OutcomePatternComparer : IComparer<int[]>
{
internal OutcomePatternComparer()
{
}
/// <summary>
/// Compare two outcome patterns and determines which comes first,
/// based on the outcome ids (lower outcome ids first)
/// </summary>
/// <param name="firstPattern">
/// First outcome pattern to compare.
/// </param>
/// <param name="secondPattern">
/// Second outcome pattern to compare.
/// </param>
/// <returns></returns>
public virtual int Compare(int[] firstPattern, int[] secondPattern)
{
int smallerLength = (firstPattern.Length > secondPattern.Length ? secondPattern.Length : firstPattern.Length);
for (int currentOutcome = 0; currentOutcome < smallerLength; currentOutcome++)
{
if (firstPattern[currentOutcome] < secondPattern[currentOutcome])
{
return - 1;
}
else if (firstPattern[currentOutcome] > secondPattern[currentOutcome])
{
return 1;
}
}
if (firstPattern.Length < secondPattern.Length)
{
return - 1;
}
else if (firstPattern.Length > secondPattern.Length)
{
return 1;
}
return 0;
}
}
}
/// <summary>
/// Event arguments class for training progress events.
/// </summary>
public class TrainingProgressEventArgs : EventArgs
{
private string mMessage;
/// <summary>
/// Constructor for the training progress event arguments.
/// </summary>
/// <param name="message">
/// Information message about the progress of training.
/// </param>
public TrainingProgressEventArgs(string message)
{
mMessage = message;
}
/// <summary>
/// Information message about the progress of training.
/// </summary>
public string Message
{
get
{
return mMessage;
}
}
}
/// <summary>
/// Event handler delegate for the training progress event.
/// </summary>
public delegate void TrainingProgressEventHandler(object sender, TrainingProgressEventArgs e);
}
| |
using System.Runtime.CompilerServices;
using GraphQLParser.AST;
namespace GraphQLParser;
internal static class NodeHelper
{
#region ASTNodes that can not have comments, only locations
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLComment CreateGraphQLComment(IgnoreOptions options, ROM value)
{
return options switch
{
IgnoreOptions.All => new GraphQLComment(value),
IgnoreOptions.Comments => new GraphQLCommentWithLocation(value),
IgnoreOptions.Locations => new GraphQLComment(value),
_ => new GraphQLCommentWithLocation(value),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLDocument CreateGraphQLDocument(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLDocument(),
IgnoreOptions.Comments => new GraphQLDocumentWithLocation(),
IgnoreOptions.Locations => new GraphQLDocument(),
_ => new GraphQLDocumentWithLocation(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLDescription CreateGraphQLDescription(IgnoreOptions options, ROM value)
{
return options switch
{
IgnoreOptions.All => new GraphQLDescription(value),
IgnoreOptions.Comments => new GraphQLDescriptionWithLocation(value),
IgnoreOptions.Locations => new GraphQLDescription(value),
_ => new GraphQLDescriptionWithLocation(value),
};
}
// Directives go one after another without any "list prefix", so it is impossible
// to distinguish the comment of the first directive from the comment to the entire
// list of directives. Therefore, a comment for the directive itself is used.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLDirectives CreateGraphQLDirectives(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLDirectives(),
IgnoreOptions.Comments => new GraphQLDirectivesWithLocation(),
IgnoreOptions.Locations => new GraphQLDirectives(),
_ => new GraphQLDirectivesWithLocation(),
};
}
#endregion
#region ASTNodes that can have comments and locations
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLArgument CreateGraphQLArgument(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLArgument(),
IgnoreOptions.Comments => new GraphQLArgumentWithLocation(),
IgnoreOptions.Locations => new GraphQLArgumentWithComment(),
_ => new GraphQLArgumentFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLDirective CreateGraphQLDirective(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLDirective(),
IgnoreOptions.Comments => new GraphQLDirectiveWithLocation(),
IgnoreOptions.Locations => new GraphQLDirectiveWithComment(),
_ => new GraphQLDirectiveFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLVariableDefinition CreateGraphQLVariableDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLVariableDefinition(),
IgnoreOptions.Comments => new GraphQLVariableDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLVariableDefinitionWithComment(),
_ => new GraphQLVariableDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLEnumTypeDefinition CreateGraphQLEnumTypeDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLEnumTypeDefinition(),
IgnoreOptions.Comments => new GraphQLEnumTypeDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLEnumTypeDefinitionWithComment(),
_ => new GraphQLEnumTypeDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLEnumValueDefinition CreateGraphQLEnumValueDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLEnumValueDefinition(),
IgnoreOptions.Comments => new GraphQLEnumValueDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLEnumValueDefinitionWithComment(),
_ => new GraphQLEnumValueDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLFieldDefinition CreateGraphQLFieldDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLFieldDefinition(),
IgnoreOptions.Comments => new GraphQLFieldDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLFieldDefinitionWithComment(),
_ => new GraphQLFieldDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLSelectionSet CreateGraphQLSelectionSet(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLSelectionSet(),
IgnoreOptions.Comments => new GraphQLSelectionSetWithLocation(),
IgnoreOptions.Locations => new GraphQLSelectionSetWithComment(),
_ => new GraphQLSelectionSetFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLVariable CreateGraphQLVariable(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLVariable(),
IgnoreOptions.Comments => new GraphQLVariableWithLocation(),
IgnoreOptions.Locations => new GraphQLVariableWithComment(),
_ => new GraphQLVariableFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLRootOperationTypeDefinition CreateGraphQLOperationTypeDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLRootOperationTypeDefinition(),
IgnoreOptions.Comments => new GraphQLRootOperationTypeDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLRootOperationTypeDefinitionWithComment(),
_ => new GraphQLRootOperationTypeDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLNamedType CreateGraphQLNamedType(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLNamedType(),
IgnoreOptions.Comments => new GraphQLNamedTypeWithLocation(),
IgnoreOptions.Locations => new GraphQLNamedTypeWithComment(),
_ => new GraphQLNamedTypeFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLName CreateGraphQLName(IgnoreOptions options, ROM value)
{
return options switch
{
IgnoreOptions.All => new GraphQLName(value),
IgnoreOptions.Comments => new GraphQLNameWithLocation(value),
IgnoreOptions.Locations => new GraphQLNameWithComment(value),
_ => new GraphQLNameFull(value),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLListValue CreateGraphQLListValue(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLListValue(),
IgnoreOptions.Comments => new GraphQLListValueWithLocation(),
IgnoreOptions.Locations => new GraphQLListValueWithComment(),
_ => new GraphQLListValueFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLListType CreateGraphQLListType(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLListType(),
IgnoreOptions.Comments => new GraphQLListTypeWithLocation(),
IgnoreOptions.Locations => new GraphQLListTypeWithComment(),
_ => new GraphQLListTypeFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLDirectiveDefinition CreateGraphQLDirectiveDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLDirectiveDefinition(),
IgnoreOptions.Comments => new GraphQLDirectiveDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLDirectiveDefinitionWithComment(),
_ => new GraphQLDirectiveDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLField CreateGraphQLField(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLField(),
IgnoreOptions.Comments => new GraphQLFieldWithLocation(),
IgnoreOptions.Locations => new GraphQLFieldWithComment(),
_ => new GraphQLFieldFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLFragmentDefinition CreateGraphQLFragmentDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLFragmentDefinition(),
IgnoreOptions.Comments => new GraphQLFragmentDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLFragmentDefinitionWithComment(),
_ => new GraphQLFragmentDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLUnionTypeDefinition CreateGraphQLUnionTypeDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLUnionTypeDefinition(),
IgnoreOptions.Comments => new GraphQLUnionTypeDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLUnionTypeDefinitionWithComment(),
_ => new GraphQLUnionTypeDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLObjectTypeExtension CreateGraphQLObjectTypeExtension(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLObjectTypeExtension(),
IgnoreOptions.Comments => new GraphQLObjectTypeExtensionWithLocation(),
IgnoreOptions.Locations => new GraphQLObjectTypeExtensionWithComment(),
_ => new GraphQLObjectTypeExtensionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLScalarTypeExtension CreateGraphQLScalarTypeExtension(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLScalarTypeExtension(),
IgnoreOptions.Comments => new GraphQLScalarTypeExtensionWithLocation(),
IgnoreOptions.Locations => new GraphQLScalarTypeExtensionWithComment(),
_ => new GraphQLScalarTypeExtensionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLInterfaceTypeExtension CreateGraphQLInterfaceTypeExtension(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLInterfaceTypeExtension(),
IgnoreOptions.Comments => new GraphQLInterfaceTypeExtensionWithLocation(),
IgnoreOptions.Locations => new GraphQLInterfaceTypeExtensionWithComment(),
_ => new GraphQLInterfaceTypeExtensionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLUnionTypeExtension CreateGraphQLUnionTypeExtension(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLUnionTypeExtension(),
IgnoreOptions.Comments => new GraphQLUnionTypeExtensionWithLocation(),
IgnoreOptions.Locations => new GraphQLUnionTypeExtensionWithComment(),
_ => new GraphQLUnionTypeExtensionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLEnumTypeExtension CreateGraphQLEnumTypeExtension(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLEnumTypeExtension(),
IgnoreOptions.Comments => new GraphQLEnumTypeExtensionWithLocation(),
IgnoreOptions.Locations => new GraphQLEnumTypeExtensionWithComment(),
_ => new GraphQLEnumTypeExtensionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLInputObjectTypeExtension CreateGraphQLInputObjectTypeExtension(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLInputObjectTypeExtension(),
IgnoreOptions.Comments => new GraphQLInputObjectTypeExtensionWithLocation(),
IgnoreOptions.Locations => new GraphQLInputObjectTypeExtensionWithComment(),
_ => new GraphQLInputObjectTypeExtensionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLSchemaExtension CreateGraphQLSchemaExtension(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLSchemaExtension(),
IgnoreOptions.Comments => new GraphQLSchemaExtensionWithLocation(),
IgnoreOptions.Locations => new GraphQLSchemaExtensionWithComment(),
_ => new GraphQLSchemaExtensionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLFragmentSpread CreateGraphQLFragmentSpread(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLFragmentSpread(),
IgnoreOptions.Comments => new GraphQLFragmentSpreadWithLocation(),
IgnoreOptions.Locations => new GraphQLFragmentSpreadWithComment(),
_ => new GraphQLFragmentSpreadFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLInlineFragment CreateGraphQLInlineFragment(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLInlineFragment(),
IgnoreOptions.Comments => new GraphQLInlineFragmentWithLocation(),
IgnoreOptions.Locations => new GraphQLInlineFragmentWithComment(),
_ => new GraphQLInlineFragmentFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLInputObjectTypeDefinition CreateGraphQLInputObjectTypeDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLInputObjectTypeDefinition(),
IgnoreOptions.Comments => new GraphQLInputObjectTypeDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLInputObjectTypeDefinitionWithComment(),
_ => new GraphQLInputObjectTypeDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLInterfaceTypeDefinition CreateGraphQLInterfaceTypeDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLInterfaceTypeDefinition(),
IgnoreOptions.Comments => new GraphQLInterfaceTypeDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLInterfaceTypeDefinitionWithComment(),
_ => new GraphQLInterfaceTypeDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLNonNullType CreateGraphQLNonNullType(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLNonNullType(),
IgnoreOptions.Comments => new GraphQLNonNullTypeWithLocation(),
IgnoreOptions.Locations => new GraphQLNonNullTypeWithComment(),
_ => new GraphQLNonNullTypeFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLSchemaDefinition CreateGraphQLSchemaDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLSchemaDefinition(),
IgnoreOptions.Comments => new GraphQLSchemaDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLSchemaDefinitionWithComment(),
_ => new GraphQLSchemaDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLScalarTypeDefinition CreateGraphQLScalarTypeDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLScalarTypeDefinition(),
IgnoreOptions.Comments => new GraphQLScalarTypeDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLScalarTypeDefinitionWithComment(),
_ => new GraphQLScalarTypeDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLOperationDefinition CreateGraphQLOperationDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLOperationDefinition(),
IgnoreOptions.Comments => new GraphQLOperationDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLOperationDefinitionWithComment(),
_ => new GraphQLOperationDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLObjectTypeDefinition CreateGraphQLObjectTypeDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLObjectTypeDefinition(),
IgnoreOptions.Comments => new GraphQLObjectTypeDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLObjectTypeDefinitionWithComment(),
_ => new GraphQLObjectTypeDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLObjectField CreateGraphQLObjectField(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLObjectField(),
IgnoreOptions.Comments => new GraphQLObjectFieldWithLocation(),
IgnoreOptions.Locations => new GraphQLObjectFieldWithComment(),
_ => new GraphQLObjectFieldFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLObjectValue CreateGraphQLObjectValue(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLObjectValue(),
IgnoreOptions.Comments => new GraphQLObjectValueWithLocation(),
IgnoreOptions.Locations => new GraphQLObjectValueWithComment(),
_ => new GraphQLObjectValueFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLInputValueDefinition CreateGraphQLInputValueDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLInputValueDefinition(),
IgnoreOptions.Comments => new GraphQLInputValueDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLInputValueDefinitionWithComment(),
_ => new GraphQLInputValueDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLTypeCondition CreateGraphQLTypeCondition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLTypeCondition(),
IgnoreOptions.Comments => new GraphQLTypeConditionWithLocation(),
IgnoreOptions.Locations => new GraphQLTypeConditionWithComment(),
_ => new GraphQLTypeConditionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLAlias CreateGraphQLAlias(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLAlias(),
IgnoreOptions.Comments => new GraphQLAliasWithLocation(),
IgnoreOptions.Locations => new GraphQLAliasWithComment(),
_ => new GraphQLAliasFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLArgumentsDefinition CreateGraphQLArgumentsDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLArgumentsDefinition(),
IgnoreOptions.Comments => new GraphQLArgumentsDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLArgumentsDefinitionWithComment(),
_ => new GraphQLArgumentsDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLArguments CreateGraphQLArguments(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLArguments(),
IgnoreOptions.Comments => new GraphQLArgumentsWithLocation(),
IgnoreOptions.Locations => new GraphQLArgumentsWithComment(),
_ => new GraphQLArgumentsFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLInputFieldsDefinition CreateGraphQLInputFieldsDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLInputFieldsDefinition(),
IgnoreOptions.Comments => new GraphQLInputFieldsDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLInputFieldsDefinitionWithComment(),
_ => new GraphQLInputFieldsDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLVariablesDefinition CreateGraphQLVariablesDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLVariablesDefinition(),
IgnoreOptions.Comments => new GraphQLVariablesDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLVariablesDefinitionWithComment(),
_ => new GraphQLVariablesDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLEnumValuesDefinition CreateGraphQLEnumValuesDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLEnumValuesDefinition(),
IgnoreOptions.Comments => new GraphQLEnumValuesDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLEnumValuesDefinitionWithComment(),
_ => new GraphQLEnumValuesDefinitionFull(),
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GraphQLFieldsDefinition CreateGraphQLFieldsDefinition(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLFieldsDefinition(),
IgnoreOptions.Comments => new GraphQLFieldsDefinitionWithLocation(),
IgnoreOptions.Locations => new GraphQLFieldsDefinitionWithComment(),
_ => new GraphQLFieldsDefinitionFull(),
};
}
public static GraphQLImplementsInterfaces CreateGraphQLImplementsInterfaces(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLImplementsInterfaces(),
IgnoreOptions.Comments => new GraphQLImplementsInterfacesWithLocation(),
IgnoreOptions.Locations => new GraphQLImplementsInterfacesWithComment(),
_ => new GraphQLImplementsInterfacesFull(),
};
}
public static GraphQLDirectiveLocations CreateGraphQLDirectiveLocations(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLDirectiveLocations(),
IgnoreOptions.Comments => new GraphQLDirectiveLocationsWithLocation(),
IgnoreOptions.Locations => new GraphQLDirectiveLocationsWithComment(),
_ => new GraphQLDirectiveLocationsFull(),
};
}
public static GraphQLUnionMemberTypes CreateGraphQLUnionMemberTypes(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLUnionMemberTypes(),
IgnoreOptions.Comments => new GraphQLUnionMemberTypesWithLocation(),
IgnoreOptions.Locations => new GraphQLUnionMemberTypesWithComment(),
_ => new GraphQLUnionMemberTypesFull(),
};
}
public static GraphQLEnumValue CreateGraphQLEnumValue(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLEnumValue(),
IgnoreOptions.Comments => new GraphQLEnumValueWithLocation(),
IgnoreOptions.Locations => new GraphQLEnumValueWithComment(),
_ => new GraphQLEnumValueFull(),
};
}
public static GraphQLNullValue CreateGraphQLNullValue(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLNullValue(),
IgnoreOptions.Comments => new GraphQLNullValueWithLocation(),
IgnoreOptions.Locations => new GraphQLNullValueWithComment(),
_ => new GraphQLNullValueFull(),
};
}
public static GraphQLBooleanValue CreateGraphQLBooleanValue(IgnoreOptions options, bool value)
{
return value switch
{
true => options switch
{
IgnoreOptions.All => new GraphQLTrueBooleanValue(),
IgnoreOptions.Comments => new GraphQLTrueBooleanValueWithLocation(),
IgnoreOptions.Locations => new GraphQLTrueBooleanValueWithComment(),
_ => new GraphQLTrueBooleanValueFull(),
},
false => options switch
{
IgnoreOptions.All => new GraphQLFalseBooleanValue(),
IgnoreOptions.Comments => new GraphQLFalseBooleanValueWithLocation(),
IgnoreOptions.Locations => new GraphQLFalseBooleanValueWithComment(),
_ => new GraphQLFalseBooleanValueFull(),
}
};
}
public static GraphQLFloatValue CreateGraphQLFloatValue(IgnoreOptions options, ROM value)
{
return options switch
{
IgnoreOptions.All => new GraphQLFloatValue(value),
IgnoreOptions.Comments => new GraphQLFloatValueWithLocation(value),
IgnoreOptions.Locations => new GraphQLFloatValueWithComment(value),
_ => new GraphQLFloatValueFull(value),
};
}
public static GraphQLIntValue CreateGraphQLIntValue(IgnoreOptions options, ROM value)
{
return options switch
{
IgnoreOptions.All => new GraphQLIntValue(value),
IgnoreOptions.Comments => new GraphQLIntValueWithLocation(value),
IgnoreOptions.Locations => new GraphQLIntValueWithComment(value),
_ => new GraphQLIntValueFull(value),
};
}
public static GraphQLStringValue CreateGraphQLStringValue(IgnoreOptions options, ROM value)
{
return options switch
{
IgnoreOptions.All => new GraphQLStringValue(value),
IgnoreOptions.Comments => new GraphQLStringValueWithLocation(value),
IgnoreOptions.Locations => new GraphQLStringValueWithComment(value),
_ => new GraphQLStringValueFull(value),
};
}
public static GraphQLFragmentName CreateGraphQLFragmentName(IgnoreOptions options)
{
return options switch
{
IgnoreOptions.All => new GraphQLFragmentName(),
IgnoreOptions.Comments => new GraphQLFragmentNameWithLocation(),
IgnoreOptions.Locations => new GraphQLFragmentNameWithComment(),
_ => new GraphQLFragmentNameFull(),
};
}
#endregion
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.