context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Linq;
using System.Text;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators.C;
using CppSharp.Types;
using Delegate = CppSharp.AST.Delegate;
using Type = CppSharp.AST.Type;
namespace CppSharp.Generators.CLI
{
public class CLIMarshalNativeToManagedPrinter : MarshalPrinter<MarshalContext>
{
public CLIMarshalNativeToManagedPrinter(MarshalContext marshalContext)
: base(marshalContext)
{
}
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.CLIMarshalToManaged(Context);
return false;
}
return true;
}
public override bool VisitTagType(TagType tag, TypeQualifiers quals)
{
if (!VisitType(tag, quals))
return false;
var decl = tag.Declaration;
return decl.Visit(this);
}
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
string value = Generator.GeneratedIdentifier("array") + Context.ParameterIndex;
Context.Before.WriteLine("cli::array<{0}>^ {1} = nullptr;", array.Type, value, array.Size);
Context.Before.WriteLine("if ({0} != 0)", Context.ReturnVarName);
Context.Before.WriteOpenBraceAndIndent();
Context.Before.WriteLine("{0} = gcnew cli::array<{1}>({2});", value, array.Type, array.Size);
Context.Before.WriteLine("for (int i = 0; i < {0}; i++)", array.Size);
if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void))
Context.Before.WriteLineIndent("{0}[i] = new ::System::IntPtr({1}[i]);",
value, Context.ReturnVarName);
else if (!array.Type.IsPrimitiveType())
Context.Before.WriteLineIndent($"{value}[i] = gcnew {array.Type.ToString().TrimEnd('^')}(&{Context.ReturnVarName}[i]);");
else
Context.Before.WriteLineIndent("{0}[i] = {1}[i];", value, Context.ReturnVarName);
Context.Before.UnindentAndWriteCloseBrace();
Context.Return.Write(value);
break;
case ArrayType.ArraySize.Incomplete:
// const char* and const char[] are the same so we can use a string
if (array.Type.Desugar().IsPrimitiveType(PrimitiveType.Char) &&
array.QualifiedType.Qualifiers.IsConst)
{
var pointer = new PointerType { QualifiedPointee = array.QualifiedType };
Context.ReturnType = new QualifiedType(pointer);
return this.VisitPointerType(pointer, quals);
}
goto case ArrayType.ArraySize.Variable;
case ArrayType.ArraySize.Variable:
Context.Return.Write("nullptr");
break;
}
return true;
}
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{
var delegateType = function.ToString();
Context.Return.Write("safe_cast<{0}>(", delegateType + "^");
Context.Return.Write("System::Runtime::InteropServices::Marshal::");
Context.Return.Write("GetDelegateForFunctionPointer(");
Context.Return.Write("System::IntPtr({0}), {1}::typeid))", Context.ReturnVarName,
delegateType.TrimEnd('^'));
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var pointee = pointer.Pointee.Desugar();
if (pointee.IsPrimitiveType(PrimitiveType.Void))
{
Context.Return.Write("::System::IntPtr({0})", Context.ReturnVarName);
return true;
}
PrimitiveType primitive;
var param = Context.Parameter;
if (param != null && (param.IsOut || param.IsInOut) &&
pointee.IsPrimitiveType(out primitive))
{
Context.Return.Write(Context.ReturnVarName);
return true;
}
if (pointee.IsPrimitiveType(out primitive))
{
var returnVarName = Context.ReturnVarName;
if (pointer.GetFinalQualifiedPointee().Qualifiers.IsConst !=
Context.ReturnType.Qualifiers.IsConst)
{
var nativeTypePrinter = new CppTypePrinter(Context.Context) { PrintTypeQualifiers = false };
var returnType = Context.ReturnType.Type.Desugar();
var constlessPointer = new PointerType()
{
IsDependent = pointer.IsDependent,
Modifier = pointer.Modifier,
QualifiedPointee = new QualifiedType(returnType.GetPointee())
};
var nativeConstlessTypeName = constlessPointer.Visit(nativeTypePrinter, new TypeQualifiers());
returnVarName = string.Format("const_cast<{0}>({1})",
nativeConstlessTypeName, Context.ReturnVarName);
}
if (pointer.Pointee is TypedefType)
{
var desugaredPointer = new PointerType()
{
IsDependent = pointer.IsDependent,
Modifier = pointer.Modifier,
QualifiedPointee = new QualifiedType(pointee)
};
var nativeTypePrinter = new CppTypePrinter(Context.Context);
var nativeTypeName = desugaredPointer.Visit(nativeTypePrinter, quals);
Context.Return.Write("reinterpret_cast<{0}>({1})", nativeTypeName,
returnVarName);
}
else
Context.Return.Write(returnVarName);
return true;
}
TypeMap typeMap = null;
Context.Context.TypeMaps.FindTypeMap(pointee, out typeMap);
Class @class;
if (pointee.TryGetClass(out @class) && typeMap == null)
{
var instance = (pointer.IsReference) ? "&" + Context.ReturnVarName
: Context.ReturnVarName;
WriteClassInstance(@class, instance);
return true;
}
return pointer.QualifiedPointee.Visit(this);
}
public override bool VisitMemberPointerType(MemberPointerType member,
TypeQualifiers quals)
{
return false;
}
public override bool VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals)
{
return VisitPrimitiveType(builtin.Type);
}
public bool VisitPrimitiveType(PrimitiveType primitive)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
case PrimitiveType.Char:
case PrimitiveType.Char16:
case PrimitiveType.WideChar:
case PrimitiveType.SChar:
case PrimitiveType.UChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.UInt:
case PrimitiveType.Long:
case PrimitiveType.ULong:
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
case PrimitiveType.Null:
Context.Return.Write(Context.ReturnVarName);
return true;
}
throw new NotSupportedException();
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
var decl = typedef.Declaration;
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(decl.Type, out typeMap) &&
typeMap.DoesMarshalling)
{
typeMap.Type = typedef;
typeMap.CLIMarshalToManaged(Context);
return typeMap.IsValueType;
}
FunctionType function;
if (decl.Type.IsPointerTo(out function))
{
Context.Return.Write($"{Context.ReturnVarName} == nullptr ? nullptr : safe_cast<{typedef}>(");
Context.Return.Write("System::Runtime::InteropServices::Marshal::");
Context.Return.Write("GetDelegateForFunctionPointer(");
Context.Return.Write("IntPtr({0}), {1}::typeid))",Context.ReturnVarName,
typedef.ToString().TrimEnd('^'));
return true;
}
return decl.Type.Visit(this);
}
public override bool VisitTemplateSpecializationType(TemplateSpecializationType template,
TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Type = template;
typeMap.CLIMarshalToManaged(Context);
return true;
}
return template.Template.Visit(this);
}
public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals)
{
throw new NotImplementedException();
}
public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals)
{
throw new NotImplementedException();
}
public override bool VisitDeclaration(Declaration decl, TypeQualifiers quals)
{
throw new NotImplementedException();
}
public override bool VisitClassDecl(Class @class)
{
if (@class.CompleteDeclaration != null)
return VisitClassDecl(@class.CompleteDeclaration as Class);
var instance = string.Empty;
if (!Context.ReturnType.Type.IsPointer())
instance += "&";
instance += Context.ReturnVarName;
var needsCopy = Context.MarshalKind != MarshalKind.NativeField;
bool ownNativeInstance = false;
if (@class.IsRefType && needsCopy)
{
var name = Generator.GeneratedIdentifier(Context.ReturnVarName);
Context.Before.WriteLine("auto {0} = new ::{1}({2});", name,
@class.QualifiedOriginalName, Context.ReturnVarName);
instance = name;
ownNativeInstance = true;
}
WriteClassInstance(@class, instance, ownNativeInstance);
return true;
}
public string QualifiedIdentifier(Declaration decl)
{
if (!string.IsNullOrEmpty(decl.TranslationUnit.Module.OutputNamespace))
return $"{decl.TranslationUnit.Module.OutputNamespace}::{decl.QualifiedName}";
return decl.QualifiedName;
}
public void WriteClassInstance(Class @class, string instance, bool ownNativeInstance = false)
{
if (@class.IsRefType)
Context.Return.Write("({0} == nullptr) ? nullptr : gcnew ",
instance);
Context.Return.Write("::{0}(", QualifiedIdentifier(@class));
Context.Return.Write("(::{0}*)", @class.QualifiedOriginalName);
Context.Return.Write("{0}{1})", instance, ownNativeInstance ? ", true" : "");
}
public override bool VisitFieldDecl(Field field)
{
return field.Type.Visit(this);
}
public override bool VisitFunctionDecl(Function function)
{
throw new NotImplementedException();
}
public override bool VisitMethodDecl(Method method)
{
throw new NotImplementedException();
}
public override bool VisitParameterDecl(Parameter parameter)
{
Context.Parameter = parameter;
var ret = parameter.Type.Visit(this, parameter.QualifiedType.Qualifiers);
Context.Parameter = null;
return ret;
}
public override bool VisitTypedefDecl(TypedefDecl typedef)
{
throw new NotImplementedException();
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write("({0}){1}", ToCLITypeName(@enum),
Context.ReturnVarName);
return true;
}
public override bool VisitVariableDecl(Variable variable)
{
return variable.Type.Visit(this, variable.QualifiedType.Qualifiers);
}
private string ToCLITypeName(Declaration decl)
{
var typePrinter = new CLITypePrinter(Context.Context);
return typePrinter.VisitDeclaration(decl).ToString();
}
public override bool VisitClassTemplateDecl(ClassTemplate template)
{
return template.TemplatedClass.Visit(this);
}
public override bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
return template.TemplatedFunction.Visit(this);
}
public override bool VisitMacroDefinition(MacroDefinition macro)
{
throw new NotImplementedException();
}
public override bool VisitNamespace(Namespace @namespace)
{
throw new NotImplementedException();
}
public override bool VisitEvent(Event @event)
{
throw new NotImplementedException();
}
public bool VisitDelegate(Delegate @delegate)
{
throw new NotImplementedException();
}
}
public class CLIMarshalManagedToNativePrinter : MarshalPrinter<MarshalContext>
{
public readonly TextGenerator VarPrefix;
public readonly TextGenerator ArgumentPrefix;
public CLIMarshalManagedToNativePrinter(MarshalContext ctx)
: base(ctx)
{
VarPrefix = new TextGenerator();
ArgumentPrefix = new TextGenerator();
Context.MarshalToNative = this;
}
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.CLIMarshalToNative(Context);
return false;
}
return true;
}
public override bool VisitTagType(TagType tag, TypeQualifiers quals)
{
if (!VisitType(tag, quals))
return false;
var decl = tag.Declaration;
return decl.Visit(this);
}
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
if (!VisitType(array, quals))
return false;
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
if (string.IsNullOrEmpty(Context.ReturnVarName))
{
string arrayPtrRet = $"__{Context.ParameterIndex}ArrayPtr";
Context.Before.WriteLine($"{array.Type} {arrayPtrRet}[{array.Size}];");
Context.ReturnVarName = arrayPtrRet;
Context.Return.Write(arrayPtrRet);
}
bool isPointerToPrimitive = array.Type.IsPointerToPrimitiveType(PrimitiveType.Void);
bool isPrimitive = array.Type.IsPrimitiveType();
var supportBefore = Context.Before;
supportBefore.WriteLine("if ({0} != nullptr)", Context.Parameter.Name);
supportBefore.WriteOpenBraceAndIndent();
supportBefore.WriteLine($"if ({Context.Parameter.Name}->Length != {array.Size})");
supportBefore.WriteOpenBraceAndIndent();
supportBefore.WriteLine($"throw gcnew System::InvalidOperationException(\"Source array size must equal destination array size.\");");
supportBefore.UnindentAndWriteCloseBrace();
string nativeVal = string.Empty;
if (isPointerToPrimitive)
{
nativeVal = ".ToPointer()";
}
else if (!isPrimitive)
{
nativeVal = "->NativePtr";
}
supportBefore.WriteLine("for (int i = 0; i < {0}; i++)", array.Size);
supportBefore.WriteLineIndent("{0}[i] = {1}{2}[i]{3};",
Context.ReturnVarName,
isPointerToPrimitive || isPrimitive ? string.Empty : "*",
Context.Parameter.Name,
nativeVal);
supportBefore.UnindentAndWriteCloseBrace();
break;
default:
Context.Return.Write("null");
break;
}
return true;
}
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{
var returnType = function.ReturnType;
return returnType.Visit(this);
}
public bool VisitDelegateType(string type)
{
// We marshal function pointer types by calling
// GetFunctionPointerForDelegate to get a native function
// pointer ouf of the delegate. Then we can pass it in the
// native call. Since references are not tracked in the
// native side, we need to be careful and protect it with an
// explicit GCHandle if necessary.
var sb = new StringBuilder();
sb.AppendFormat("static_cast<{0}>(", type);
sb.Append("System::Runtime::InteropServices::Marshal::");
sb.Append("GetFunctionPointerForDelegate(");
sb.AppendFormat("{0}).ToPointer())", Context.Parameter.Name);
Context.Return.Write(sb.ToString());
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var pointee = pointer.Pointee.Desugar();
if (pointee is FunctionType)
{
var cppTypePrinter = new CppTypePrinter(Context.Context);
var cppTypeName = pointer.Visit(cppTypePrinter, quals);
return VisitDelegateType(cppTypeName);
}
Enumeration @enum;
if (pointee.TryGetEnum(out @enum))
{
var isRef = Context.Parameter.Type.IsReference() ||
Context.Parameter.Usage == ParameterUsage.Out ||
Context.Parameter.Usage == ParameterUsage.InOut;
if(!isRef)
{
ArgumentPrefix.Write("&");
}
Context.Return.Write("(::{0}){1}{2}", @enum.QualifiedOriginalName,
isRef ? string.Empty : "*", Context.Parameter.Name);
return true;
}
Class @class;
if (pointee.TryGetClass(out @class) && @class.IsValueType)
{
if (Context.Function == null)
Context.Return.Write("&");
return pointer.QualifiedPointee.Visit(this);
}
var finalPointee = pointer.GetFinalPointee();
if (finalPointee.IsPrimitiveType())
{
var cppTypePrinter = new CppTypePrinter(Context.Context);
var cppTypeName = pointer.Visit(cppTypePrinter, quals);
Context.Return.Write("({0})", cppTypeName);
Context.Return.Write(Context.Parameter.Name);
return true;
}
// Pass address of argument if the parameter is a pointer to the pointer itself.
if (pointee is PointerType && !Context.Parameter.Type.IsReference())
{
ArgumentPrefix.Write("&");
}
return pointer.QualifiedPointee.Visit(this);
}
public override bool VisitMemberPointerType(MemberPointerType member,
TypeQualifiers quals)
{
return false;
}
public override bool VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals)
{
return VisitPrimitiveType(builtin.Type);
}
public bool VisitPrimitiveType(PrimitiveType primitive)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
case PrimitiveType.Char:
case PrimitiveType.UChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.UInt:
case PrimitiveType.Long:
case PrimitiveType.ULong:
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Float:
case PrimitiveType.Double:
Context.Return.Write(Context.Parameter.Name);
return true;
}
return false;
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
var decl = typedef.Declaration;
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(decl.Type, out typeMap) &&
typeMap.DoesMarshalling)
{
typeMap.CLIMarshalToNative(Context);
return typeMap.IsValueType;
}
FunctionType func;
if (decl.Type.IsPointerTo(out func))
{
// Use the original typedef name if available, otherwise just use the function pointer type
string cppTypeName;
if (!decl.IsSynthetized)
cppTypeName = "::" + typedef.Declaration.QualifiedOriginalName;
else
{
var cppTypePrinter = new CppTypePrinter(Context.Context);
cppTypeName = decl.Type.Visit(cppTypePrinter, quals);
}
VisitDelegateType(cppTypeName);
return true;
}
PrimitiveType primitive;
if (decl.Type.IsPrimitiveType(out primitive))
{
Context.Return.Write("(::{0})", typedef.Declaration.QualifiedOriginalName);
}
return decl.Type.Visit(this);
}
public override bool VisitTemplateSpecializationType(TemplateSpecializationType template,
TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Type = template;
typeMap.CLIMarshalToNative(Context);
return true;
}
return template.Template.Visit(this);
}
public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals)
{
Context.Return.Write(param.Parameter.Name);
return true;
}
public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals)
{
throw new NotImplementedException();
}
public override bool VisitDeclaration(Declaration decl, TypeQualifiers quals)
{
throw new NotImplementedException();
}
public override bool VisitClassDecl(Class @class)
{
if (@class.CompleteDeclaration != null)
return VisitClassDecl(@class.CompleteDeclaration as Class);
if (@class.IsValueType)
{
MarshalValueClass(@class);
}
else
{
MarshalRefClass(@class);
}
return true;
}
private void MarshalRefClass(Class @class)
{
var type = Context.Parameter.Type.Desugar();
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) &&
typeMap.DoesMarshalling)
{
typeMap.CLIMarshalToNative(Context);
return;
}
var method = Context.Function as Method;
if (type.IsReference() && (method == null ||
// redundant for comparison operators, they are handled in a special way
(method.OperatorKind != CXXOperatorKind.EqualEqual &&
method.OperatorKind != CXXOperatorKind.ExclaimEqual)))
{
Context.Before.WriteLine("if (ReferenceEquals({0}, nullptr))", Context.Parameter.Name);
Context.Before.WriteLineIndent(
"throw gcnew ::System::ArgumentNullException(\"{0}\", " +
"\"Cannot be null because it is a C++ reference (&).\");",
Context.Parameter.Name);
}
if (!type.SkipPointerRefs().IsPointer())
{
Context.Return.Write("*");
if (Context.Parameter.Type.IsReference())
VarPrefix.Write("&");
else
{
Context.Before.WriteLine($"if (ReferenceEquals({Context.Parameter.Name}, nullptr))");
Context.Before.WriteLineIndent(
$@"throw gcnew ::System::ArgumentNullException(""{
Context.Parameter.Name}"", ""Cannot be null because it is passed by value."");");
}
}
if (method != null
&& method.Conversion == MethodConversionKind.FunctionToInstanceMethod
&& Context.ParameterIndex == 0)
{
Context.Return.Write("(::{0}*)", @class.QualifiedOriginalName);
Context.Return.Write("NativePtr");
return;
}
Context.Return.Write("(::{0}*)", @class.QualifiedOriginalName);
Context.Return.Write("{0}->NativePtr", Context.Parameter.Name);
}
public void MarshalValueClass(Class @class)
{
var marshalVar = Context.MarshalVarPrefix + "_marshal" +
Context.ParameterIndex++;
Context.Before.WriteLine("auto {0} = ::{1}();", marshalVar,
@class.QualifiedOriginalName);
MarshalValueClassProperties(@class, marshalVar);
Context.Return.Write(marshalVar);
var param = Context.Parameter;
if (param.Kind == ParameterKind.OperatorParameter)
return;
if (param.Type.IsPointer())
ArgumentPrefix.Write("&");
}
public void MarshalValueClassProperties(Class @class, string marshalVar)
{
foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared))
{
MarshalValueClassProperties(@base.Class, marshalVar);
}
foreach (var property in @class.Properties.Where( p => !ASTUtils.CheckIgnoreProperty(p)))
{
if (property.Field == null)
continue;
MarshalValueClassProperty(property, marshalVar);
}
}
private void MarshalValueClassProperty(Property property, string marshalVar)
{
var fieldRef = string.Format("{0}.{1}", Context.Parameter.Name,
property.Name);
var marshalCtx = new MarshalContext(Context.Context, Context.Indentation)
{
ArgName = fieldRef,
ParameterIndex = Context.ParameterIndex++,
MarshalVarPrefix = Context.MarshalVarPrefix,
ReturnVarName = $"{marshalVar}.{property.Field.OriginalName}"
};
var marshal = new CLIMarshalManagedToNativePrinter(marshalCtx);
property.Visit(marshal);
Context.ParameterIndex = marshalCtx.ParameterIndex;
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Context.Before.Write(marshal.Context.Before);
if (!string.IsNullOrWhiteSpace(marshal.Context.Return))
{
Type type;
Class @class;
var isRef = property.Type.IsPointerTo(out type) &&
!(type.TryGetClass(out @class) && @class.IsValueType) &&
!type.IsPrimitiveType();
if (isRef)
{
Context.Before.WriteLine("if ({0} != nullptr)", fieldRef);
Context.Before.Indent();
}
Context.Before.WriteLine("{0}.{1} = {2};", marshalVar,
property.Field.OriginalName, marshal.Context.Return);
if (isRef)
Context.Before.Unindent();
}
}
public override bool VisitFieldDecl(Field field)
{
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = field.QualifiedType
};
return field.Type.Visit(this);
}
public override bool VisitProperty(Property property)
{
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = property.QualifiedType
};
return base.VisitProperty(property);
}
public override bool VisitFunctionDecl(Function function)
{
throw new NotImplementedException();
}
public override bool VisitMethodDecl(Method method)
{
throw new NotImplementedException();
}
public override bool VisitParameterDecl(Parameter parameter)
{
return parameter.Type.Visit(this);
}
public override bool VisitTypedefDecl(TypedefDecl typedef)
{
throw new NotImplementedException();
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write("(::{0}){1}", @enum.QualifiedOriginalName,
Context.Parameter.Name);
return true;
}
public override bool VisitVariableDecl(Variable variable)
{
throw new NotImplementedException();
}
public override bool VisitClassTemplateDecl(ClassTemplate template)
{
return template.TemplatedClass.Visit(this);
}
public override bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
return template.TemplatedFunction.Visit(this);
}
public override bool VisitMacroDefinition(MacroDefinition macro)
{
throw new NotImplementedException();
}
public override bool VisitNamespace(Namespace @namespace)
{
throw new NotImplementedException();
}
public override bool VisitEvent(Event @event)
{
throw new NotImplementedException();
}
public bool VisitDelegate(Delegate @delegate)
{
throw new NotImplementedException();
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace Reporting.RdlDesign
{
/// <summary>
/// Summary description for TableColumnCtl.
/// </summary>
internal class TableColumnCtl : System.Windows.Forms.UserControl, IProperty
{
private XmlNode _TableColumn;
private DesignXmlDraw _Draw;
// flags for controlling whether syntax changed for a particular property
private bool fHidden, fToggle, fWidth, fFixedHeader;
private System.Windows.Forms.GroupBox grpBoxVisibility;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox tbHidden;
private System.Windows.Forms.ComboBox cbToggle;
private System.Windows.Forms.Button bHidden;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbColumnWidth;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.CheckBox chkFixedHeader;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal TableColumnCtl(DesignXmlDraw dxDraw, XmlNode tc)
{
_TableColumn = tc;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(tc);
}
private void InitValues(XmlNode node)
{
// Handle Width definition
this.tbColumnWidth.Text = _Draw.GetElementValue(node, "Width", "");
this.chkFixedHeader.Checked = _Draw.GetElementValue(node, "FixedHeader", "false").ToLower() == "true"? true: false;
// Handle Visiblity definition
XmlNode visNode = _Draw.GetNamedChildNode(node, "Visibility");
if (visNode != null)
{
this.tbHidden.Text = _Draw.GetElementValue(visNode, "Hidden", "");
this.cbToggle.Text = _Draw.GetElementValue(visNode, "ToggleItem", "");
}
IEnumerable list = _Draw.GetReportItems("//Textbox");
if (list != null)
{
foreach (XmlNode tNode in list)
{
XmlAttribute name = tNode.Attributes["Name"];
if (name != null && name.Value != null && name.Value.Length > 0)
cbToggle.Items.Add(name.Value);
}
}
// nothing has changed now
fWidth = fHidden = fToggle = fFixedHeader = false;
}
/// <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 Component 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.grpBoxVisibility = new System.Windows.Forms.GroupBox();
this.bHidden = new System.Windows.Forms.Button();
this.cbToggle = new System.Windows.Forms.ComboBox();
this.tbHidden = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tbColumnWidth = new System.Windows.Forms.TextBox();
this.chkFixedHeader = new System.Windows.Forms.CheckBox();
this.label4 = new System.Windows.Forms.Label();
this.grpBoxVisibility.SuspendLayout();
this.SuspendLayout();
//
// grpBoxVisibility
//
this.grpBoxVisibility.Controls.Add(this.bHidden);
this.grpBoxVisibility.Controls.Add(this.cbToggle);
this.grpBoxVisibility.Controls.Add(this.tbHidden);
this.grpBoxVisibility.Controls.Add(this.label3);
this.grpBoxVisibility.Controls.Add(this.label2);
this.grpBoxVisibility.Location = new System.Drawing.Point(8, 8);
this.grpBoxVisibility.Name = "grpBoxVisibility";
this.grpBoxVisibility.Size = new System.Drawing.Size(432, 80);
this.grpBoxVisibility.TabIndex = 1;
this.grpBoxVisibility.TabStop = false;
this.grpBoxVisibility.Text = "Visibility";
//
// bHidden
//
this.bHidden.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bHidden.Location = new System.Drawing.Point(400, 24);
this.bHidden.Name = "bHidden";
this.bHidden.Size = new System.Drawing.Size(24, 21);
this.bHidden.TabIndex = 1;
this.bHidden.Tag = "visibility";
this.bHidden.Text = "fx";
this.bHidden.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bHidden.Click += new System.EventHandler(this.bExpr_Click);
//
// cbToggle
//
this.cbToggle.Location = new System.Drawing.Point(168, 48);
this.cbToggle.Name = "cbToggle";
this.cbToggle.Size = new System.Drawing.Size(152, 21);
this.cbToggle.TabIndex = 2;
this.cbToggle.SelectedIndexChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
this.cbToggle.TextChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
//
// tbHidden
//
this.tbHidden.Location = new System.Drawing.Point(168, 24);
this.tbHidden.Name = "tbHidden";
this.tbHidden.Size = new System.Drawing.Size(224, 20);
this.tbHidden.TabIndex = 0;
this.tbHidden.TextChanged += new System.EventHandler(this.tbHidden_TextChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 48);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(152, 23);
this.label3.TabIndex = 1;
this.label3.Text = "Toggle Item (Textbox name)";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(120, 23);
this.label2.TabIndex = 0;
this.label2.Text = "Hidden (initial visibility)";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 104);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Column Width";
//
// tbColumnWidth
//
this.tbColumnWidth.Location = new System.Drawing.Point(88, 104);
this.tbColumnWidth.Name = "tbColumnWidth";
this.tbColumnWidth.Size = new System.Drawing.Size(100, 20);
this.tbColumnWidth.TabIndex = 3;
this.tbColumnWidth.TextChanged += new System.EventHandler(this.tbWidth_TextChanged);
//
// chkFixedHeader
//
this.chkFixedHeader.Location = new System.Drawing.Point(8, 136);
this.chkFixedHeader.Name = "chkFixedHeader";
this.chkFixedHeader.Size = new System.Drawing.Size(96, 24);
this.chkFixedHeader.TabIndex = 4;
this.chkFixedHeader.Text = "Fixed Header";
this.chkFixedHeader.CheckedChanged += new System.EventHandler(this.cbFixedHeader_CheckedChanged);
//
// label4
//
this.label4.Location = new System.Drawing.Point(112, 136);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(336, 24);
this.label4.TabIndex = 5;
this.label4.Text = "Note: Fixed headers must be contiguous and start at either the left or the right " +
"of the table. Current renderers ignore this parameter.";
//
// TableColumnCtl
//
this.Controls.Add(this.label4);
this.Controls.Add(this.chkFixedHeader);
this.Controls.Add(this.tbColumnWidth);
this.Controls.Add(this.label1);
this.Controls.Add(this.grpBoxVisibility);
this.Name = "TableColumnCtl";
this.Size = new System.Drawing.Size(472, 288);
this.grpBoxVisibility.ResumeLayout(false);
this.grpBoxVisibility.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public bool IsValid()
{
try
{
if (fWidth)
DesignerUtility.ValidateSize(this.tbColumnWidth.Text, true, false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Width is Invalid");
return false;
}
if (fHidden)
{
string vh = this.tbHidden.Text.Trim();
if (vh.Length > 0)
{
if (vh.StartsWith("="))
{}
else
{
vh = vh.ToLower();
switch (vh)
{
case "true":
case "false":
break;
default:
MessageBox.Show(String.Format("{0} must be an expression or 'true' or 'false'", tbHidden.Text), "Hidden is Invalid");
return false;
}
}
}
}
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
ApplyChanges(this._TableColumn);
// nothing has changed now
fWidth = fHidden = fToggle = false;
}
private void ApplyChanges(XmlNode rNode)
{
if (fHidden || fToggle)
{
XmlNode visNode = _Draw.SetElement(rNode, "Visibility", null);
if (fHidden)
{
string vh = this.tbHidden.Text.Trim();
if (vh.Length > 0)
_Draw.SetElement(visNode, "Hidden", vh);
else
_Draw.RemoveElement(visNode, "Hidden");
}
if (fToggle)
_Draw.SetElement(visNode, "ToggleItem", this.cbToggle.Text);
}
if (fWidth) // already validated
_Draw.SetElement(rNode, "Width", this.tbColumnWidth.Text);
if (fFixedHeader)
{
if (this.chkFixedHeader.Checked)
_Draw.SetElement(rNode, "FixedHeader", "true");
else
_Draw.RemoveElement(rNode, "FixedHeader"); // just get rid of it
}
}
private void tbHidden_TextChanged(object sender, System.EventArgs e)
{
fHidden = true;
}
private void tbWidth_TextChanged(object sender, System.EventArgs e)
{
fWidth = true;
}
private void cbToggle_SelectedIndexChanged(object sender, System.EventArgs e)
{
fToggle = true;
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
switch (b.Tag as string)
{
case "visibility":
c = tbHidden;
break;
}
if (c == null)
return;
using (DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, _TableColumn))
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
}
return;
}
private void cbFixedHeader_CheckedChanged(object sender, System.EventArgs e)
{
fFixedHeader = true;
}
}
}
| |
//from http://www.codeproject.com/cs/internet/SendFileToNET.asp
using System;
using System.Runtime.InteropServices;
using System.IO;
using System.Collections.Generic;
namespace SIL.Email
{
class MAPI
{
public bool AddRecipientTo(string email)
{
return AddRecipient(email, HowTo.MAPI_TO);
}
public bool AddRecipientCc(string email)
{
return AddRecipient(email, HowTo.MAPI_CC);
}
public bool AddRecipientBcc(string email)
{
return AddRecipient(email, HowTo.MAPI_BCC);
}
public void AddAttachment(string strAttachmentFileName)
{
m_attachments.Add(strAttachmentFileName);
}
public bool SendMailPopup(string strSubject, string strBody)
{
return SendMail(strSubject, strBody, MAPI_LOGON_UI | MAPI_DIALOG);
}
public bool SendMailDirect(string strSubject, string strBody)
{
return SendMail(strSubject, strBody, MAPI_LOGON_UI);
}
[DllImport("MAPI32.DLL")]
static extern int MAPISendMail(IntPtr sess, IntPtr hwnd, MapiMessage message, int flg, int rsv);
/// <summary>
///
/// </summary>
/// <param name="strSubject"></param>
/// <param name="strBody"></param>
/// <param name="how"></param>
/// <returns>true if successful</returns>
bool SendMail(string strSubject, string strBody, int how)
{
MapiMessage msg = new MapiMessage();
msg.subject = strSubject;
msg.noteText = strBody;
msg.recips = GetRecipients(out msg.recipCount);
msg.files = GetAttachments(out msg.fileCount);
m_lastError = MAPISendMail(new IntPtr(0), new IntPtr(0), msg, how, 0);
// if (m_lastError > 1)
// MessageBox.Show("MAPISendMail failed! " + GetLastError(), "MAPISendMail");
//todo if(m_lastError==25)
//bad recipient
var success = m_lastError == 0; // m_lastError gets reset by Cleanup()
Cleanup(ref msg);
return success;//NB: doesn't seem to cach user "denial" using outlook's warning dialog
}
bool AddRecipient(string email, HowTo howTo)
{
MapiRecipDesc recipient = new MapiRecipDesc();
recipient.recipClass = (int)howTo;
recipient.name = email;
// Note: For Outlook Express it would be better to also set recipient.address so that it
// shows the email address in the confirmation dialog, but this messes up things in
// Outlook and Windows Mail.
m_recipients.Add(recipient);
return true;
}
IntPtr GetRecipients(out int recipCount)
{
recipCount = 0;
if (m_recipients.Count == 0)
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof(MapiRecipDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_recipients.Count * size);
int ptr = (int)intPtr;
foreach (MapiRecipDesc mapiDesc in m_recipients)
{
Marshal.StructureToPtr(mapiDesc, (IntPtr)ptr, false);
ptr += size;
}
recipCount = m_recipients.Count;
return intPtr;
}
IntPtr GetAttachments(out int fileCount)
{
fileCount = 0;
if (m_attachments == null)
return IntPtr.Zero;
if ((m_attachments.Count <= 0) || (m_attachments.Count > maxAttachments))
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof(MapiFileDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_attachments.Count * size);
MapiFileDesc mapiFileDesc = new MapiFileDesc();
mapiFileDesc.position = -1;
int ptr = (int)intPtr;
foreach (string strAttachment in m_attachments)
{
mapiFileDesc.name = Path.GetFileName(strAttachment);
mapiFileDesc.path = strAttachment;
Marshal.StructureToPtr(mapiFileDesc, (IntPtr)ptr, false);
ptr += size;
}
fileCount = m_attachments.Count;
return intPtr;
}
void Cleanup(ref MapiMessage msg)
{
int size = Marshal.SizeOf(typeof(MapiRecipDesc));
int ptr;
if (msg.recips != IntPtr.Zero)
{
ptr = (int)msg.recips;
for (int i = 0; i < msg.recipCount; i++)
{
Marshal.DestroyStructure((IntPtr)ptr, typeof(MapiRecipDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.recips);
}
if (msg.files != IntPtr.Zero)
{
size = Marshal.SizeOf(typeof(MapiFileDesc));
ptr = (int)msg.files;
for (int i = 0; i < msg.fileCount; i++)
{
Marshal.DestroyStructure((IntPtr)ptr, typeof(MapiFileDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.files);
}
m_recipients.Clear();
m_attachments.Clear();
m_lastError = 0;
}
public string GetLastError()
{
if (m_lastError >= 0 && m_lastError <= 26)
return Errors[m_lastError];
return "MAPI error [" + m_lastError + "]";
}
readonly string[] Errors = new[]
{
"OK [0]", "User abort [1]", "General MAPI failure [2]", "MAPI login failure [3]",
"Disk full [4]", "Insufficient memory [5]", "Access denied [6]", "-unknown- [7]",
"Too many sessions [8]", "Too many files were specified [9]", "Too many recipients were specified [10]", "A specified attachment was not found [11]",
"Attachment open failure [12]", "Attachment write failure [13]", "Unknown recipient [14]", "Bad recipient type [15]",
"No messages [16]", "Invalid message [17]", "Text too large [18]", "Invalid session [19]",
"Type not supported [20]", "A recipient was specified ambiguously [21]", "Message in use [22]", "Network failure [23]",
"Invalid edit fields [24]", "Invalid recipients [25]", "Not supported [26]"
};
readonly List<MapiRecipDesc> m_recipients = new List<MapiRecipDesc>();
readonly List<string> m_attachments = new List<string>();
int m_lastError;
const int MAPI_LOGON_UI = 0x00000001;
const int MAPI_DIALOG = 0x00000008;
const int maxAttachments = 20;
enum HowTo
{
MAPI_ORIG,
MAPI_TO,
MAPI_CC,
MAPI_BCC
};
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiMessage
{
public int reserved;
public string subject;
public string noteText;
public string messageType;
public string dateReceived;
public string conversationID;
public int flags;
public IntPtr originator;
public int recipCount;
public IntPtr recips;
public int fileCount;
public IntPtr files;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiFileDesc
{
public int reserved;
public int flags;
public int position;
public string path;
public string name;
public IntPtr type;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiRecipDesc
{
public int reserved;
public int recipClass;
public string name;
public string address;
public int eIDSize;
public IntPtr entryID;
}
}
| |
using System;
using System.Collections.Generic;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Http.ExceptionHandling;
using AspNet.WebApi.HtmlMicrodataFormatter;
using Autofac;
using Common.Logging;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.Owin.Diagnostics;
using Microsoft.Owin.Extensions;
using Microsoft.Owin.Infrastructure;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NuGet.Lucene.Web.Filters;
using NuGet.Lucene.Web.Formatters;
using NuGet.Lucene.Web.MessageHandlers;
using NuGet.Lucene.Web.SignalR;
using NuGet.Lucene.Web.Util;
using Owin;
namespace NuGet.Lucene.Web
{
public class Startup
{
private static readonly ILog Log = LogManager.GetLogger<Startup>();
protected readonly ManualResetEventSlim shutdownSignal = new ManualResetEventSlim(false);
protected SignalRMapper signalRMapper;
public INuGetWebApiSettings Settings { get; set; }
public void Configuration(IAppBuilder app)
{
SetNuGetNotRunningInVisualStudio();
SignatureConversions.AddConversions(app);
Settings = CreateSettings();
Start(app, CreateContainer(app));
}
public bool WaitForShutdown(TimeSpan timeout)
{
return shutdownSignal.Wait(timeout);
}
protected virtual INuGetWebApiSettings CreateSettings()
{
return new NuGetWebApiSettings();
}
protected virtual void SetNuGetNotRunningInVisualStudio()
{
// wherein "Command Line" means anything other than Visual Studio:
EnvironmentUtility.SetRunningFromCommandLine();
}
protected virtual void Start(IAppBuilder app, IContainer container)
{
var config = CreateHttpConfiguration();
ConfigureWebApi(config, container);
if (Settings.ShowExceptionDetails)
{
app.UseErrorPage(new ErrorPageOptions
{
ShowExceptionDetails = true,
ShowSourceCode = true
});
}
app.UseAutofacMiddleware(container);
app.UseStageMarker(PipelineStage.Authenticate);
app.UseAutofacWebApi(config);
app.UseWebApi(config);
RegisterSignalR(container, app);
app.UseStageMarker(PipelineStage.MapHandler);
RegisterServices(container, app, config);
RegisterShutdown(app, container);
StartIndexingIfConfigured(container);
}
protected virtual HttpConfiguration CreateHttpConfiguration()
{
return new HttpConfiguration();
}
protected virtual void RegisterShutdown(IAppBuilder app, IContainer container)
{
var token = app.GetHostAppDisposing();
if (token.CanBeCanceled)
{
token.Register(() => OnShutdown(container));
}
else
{
Log.Warn(m => m("OWIN property host.OnAppDisposing not available."));
}
}
private async void OnShutdown(IContainer container)
{
try
{
await ShutdownServices(container);
}
finally
{
shutdownSignal.Set();
}
}
protected virtual async Task ShutdownServices(IContainer container)
{
Log.Info(m => m("Received OnAppDisposing event from OWIN container."));
var taskRunner = container.Resolve<ITaskRunner>();
var pendingTasks = taskRunner.PendingTasks;
if (pendingTasks.Length > 0)
{
Log.Info(m => m("Waiting for {0} background tasks.", pendingTasks.Length));
await Task.WhenAll(pendingTasks);
}
Log.Info(m => m("Disposing Autofac application container."));
container.Dispose();
}
protected virtual IContainer CreateContainer(IAppBuilder app)
{
var builder = new ContainerBuilder();
builder.RegisterModule(new OwinAppLifecycleModule(app));
builder.RegisterModule(new NuGetWebApiModule(Settings));
builder.RegisterModule<SignalRModule>();
return builder.Build();
}
protected virtual void RegisterServices(IContainer container, IAppBuilder app, HttpConfiguration config)
{
var apiMapper = container.Resolve<NuGetWebApiRouteMapper>();
apiMapper.MapNuGetClientRedirectRoutes(config);
apiMapper.MapApiRoutes(config);
apiMapper.MapODataRoutes(config);
apiMapper.MapSymbolSourceRoutes(config);
}
protected virtual void RegisterSignalR(IContainer container, IAppBuilder app)
{
signalRMapper = container.Resolve<SignalRMapper>();
var hubConfiguration = AutofacHubConfiguration.CreateHubConfiguration(container, Settings);
signalRMapper.MapSignalR(app, hubConfiguration);
var statusHubBroadcaster = new StatusHubUpdateBroadcaster
{
ConnectionManager = hubConfiguration.Resolver.Resolve<IConnectionManager>(),
Repository = container.Resolve<ILucenePackageRepository>()
};
statusHubBroadcaster.Start();
container.CurrentScopeEnding += (s, e) => statusHubBroadcaster.Dispose();
}
protected virtual void ConfigureWebApi(HttpConfiguration config, IContainer container)
{
config.IncludeErrorDetailPolicy = Settings.ShowExceptionDetails
? IncludeErrorDetailPolicy.Always
: IncludeErrorDetailPolicy.Default;
config.MessageHandlers.Add(new CrossOriginMessageHandler(Settings.EnableCrossDomainRequests));
config.Filters.Add(new DefaultAcceptHeaderFilter());
config.Filters.Add(new ExceptionLoggingFilter());
var documentation = new HtmlDocumentation();
documentation.Load();
config.Services.Replace(typeof(IDocumentationProvider), new WebApiHtmlDocumentationProvider(documentation));
config.Services.Replace(typeof(IExceptionHandler), new LoggingExceptionHandler());
var formatter = CreateMicrodataFormatter();
config.Formatters.Add(formatter);
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.AddRange(container.Resolve<IEnumerable<MediaTypeFormatter>>());
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
}
protected virtual NuGetHtmlMicrodataFormatter CreateMicrodataFormatter()
{
var formatter = new NuGetHtmlMicrodataFormatter();
formatter.SupportedMediaTypes.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
formatter.SupportedMediaTypes.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
return formatter;
}
protected virtual void StartIndexingIfConfigured(IContainer container)
{
if (!Settings.SynchronizeOnStart) return;
var repository = container.Resolve<ILucenePackageRepository>();
var tcs = container.Resolve<StopSynchronizationCancellationTokenSource>();
var taskRunner = container.Resolve<ITaskRunner>();
taskRunner.QueueBackgroundWorkItem(async shutdownCancellationToken =>
{
using (shutdownCancellationToken.Register(tcs.Cancel))
{
await repository.SynchronizeWithFileSystem(SynchronizationMode.Incremental, tcs.Token);
}
});
}
private class LoggingExceptionHandler : IExceptionHandler
{
private static readonly Task CompletedTask;
static LoggingExceptionHandler()
{
var tcs = new TaskCompletionSource<bool>();
tcs.SetResult(true);
CompletedTask = tcs.Task;
}
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
UnhandledExceptionLogger.LogException(context.Exception);
return CompletedTask;
}
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Xunit;
namespace System.CodeDom.Compiler.Tests
{
public class CodeGeneratorTests : RemoteExecutorTestBase
{
public class Generator : CodeGenerator
{
[Fact]
public void Ctor_Default()
{
Generator generator = this;
Assert.Null(generator.CurrentClass);
Assert.Null(generator.CurrentMember);
Assert.Equal("<% unknown %>", generator.CurrentMemberName);
Assert.Equal("<% unknown %>", generator.CurrentTypeName);
Assert.Throws<NullReferenceException>(() => generator.Indent);
Assert.Throws<NullReferenceException>(() => generator.Indent = 1);
Assert.False(generator.IsCurrentClass);
Assert.False(generator.IsCurrentDelegate);
Assert.False(generator.IsCurrentEnum);
Assert.False(generator.IsCurrentInterface);
Assert.False(generator.IsCurrentStruct);
Assert.Null(generator.Options);
Assert.Null(generator.Output);
}
[Fact]
public void ICodeGeneratorCreateEscapedIdentifier_Invoke_ReturnsExpected()
{
ICodeGenerator generator = this;
Assert.Equal("escapedIdentifier", generator.CreateEscapedIdentifier(null));
}
[Fact]
public void ICodeGeneratorCreateValidIdentifier_Invoke_ReturnsExpected()
{
ICodeGenerator generator = this;
Assert.Equal("validIdentifier", generator.CreateValidIdentifier(null));
}
protected override string NullToken => throw new NotImplementedException();
protected override string CreateEscapedIdentifier(string value)
{
return "escapedIdentifier";
}
protected override string CreateValidIdentifier(string value)
{
return "validIdentifier";
}
protected override void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e)
{
Output.Write("argumentReference");
}
protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression e)
{
Output.Write("arrayCreate");
}
protected override void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e)
{
Output.Write("arrayIndexer");
}
protected override void GenerateAssignStatement(CodeAssignStatement e)
{
Output.Write("assign");
}
protected override void GenerateAttachEventStatement(CodeAttachEventStatement e)
{
Output.Write("attachEvent");
}
protected override void GenerateAttributeDeclarationsEnd(CodeAttributeDeclarationCollection attributes)
{
Output.Write("attributeDeclarationsEnd");
}
protected override void GenerateAttributeDeclarationsStart(CodeAttributeDeclarationCollection attributes)
{
Output.Write("attributeDeclarationsStart");
}
protected override void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e)
{
Output.Write("baseReference");
}
protected override void GenerateCastExpression(CodeCastExpression e)
{
Output.Write("cast");
}
protected override void GenerateComment(CodeComment e)
{
Output.Write("comment");
}
protected override void GenerateConditionStatement(CodeConditionStatement e)
{
Output.Write("condition");
}
protected override void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c)
{
Output.Write("constructor");
}
protected override void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e)
{
Output.Write("delegateCreate");
}
protected override void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e)
{
Output.Write("delegateInvoke");
}
protected override void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c)
{
Output.Write("entryPointMethod");
}
protected override void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c)
{
Output.Write("event");
}
protected override void GenerateEventReferenceExpression(CodeEventReferenceExpression e)
{
Output.Write("eventReference");
}
protected override void GenerateExpressionStatement(CodeExpressionStatement e)
{
Output.Write("expression");
}
protected override void GenerateField(CodeMemberField e)
{
Output.Write("field");
}
protected override void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e)
{
Output.Write("fieldReference");
}
protected override void GenerateGotoStatement(CodeGotoStatement e)
{
Output.Write("goto");
}
protected override void GenerateIndexerExpression(CodeIndexerExpression e)
{
Output.Write("indexer");
}
protected override void GenerateIterationStatement(CodeIterationStatement e)
{
Output.Write("iteration");
}
protected override void GenerateLabeledStatement(CodeLabeledStatement e)
{
Output.Write("labelled");
}
protected override void GenerateLinePragmaEnd(CodeLinePragma e)
{
Output.Write("linePragmaEnd");
}
protected override void GenerateLinePragmaStart(CodeLinePragma e)
{
Output.Write("linePragmaStart");
}
protected override void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c)
{
Output.Write("method");
}
protected override void GenerateMethodInvokeExpression(CodeMethodInvokeExpression e)
{
Output.Write("methodInvoke");
}
protected override void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e)
{
Output.Write("methodReference");
}
protected override void GenerateMethodReturnStatement(CodeMethodReturnStatement e)
{
Output.Write("methodReturn");
}
protected override void GenerateNamespaceEnd(CodeNamespace e)
{
Output.Write("namespaceEnd");
}
protected override void GenerateNamespaceImport(CodeNamespaceImport e)
{
Output.Write("namespaceImport");
}
protected override void GenerateNamespaceStart(CodeNamespace e)
{
Output.Write("namespaceStart");
}
protected override void GenerateObjectCreateExpression(CodeObjectCreateExpression e)
{
Output.Write("objectCreate");
}
protected override void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c)
{
Output.Write("property");
}
protected override void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e)
{
Output.Write("propertyReference");
}
protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
{
Output.Write("propertySetValueReference");
}
protected override void GenerateRemoveEventStatement(CodeRemoveEventStatement e)
{
Output.Write("removeEvent");
}
protected override void GenerateSnippetExpression(CodeSnippetExpression e)
{
Output.Write("snippetExpression");
}
protected override void GenerateSnippetMember(CodeSnippetTypeMember e)
{
Output.Write("snippetMember");
}
protected override void GenerateThisReferenceExpression(CodeThisReferenceExpression e)
{
Output.Write("thisReference");
}
protected override void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e)
{
Output.Write("throwException");
}
protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
{
Output.Write("tryCatchFinally");
}
protected override void GenerateTypeConstructor(CodeTypeConstructor e)
{
Output.Write("typeConstructor");
}
protected override void GenerateTypeEnd(CodeTypeDeclaration e)
{
Output.Write("typeEnd");
}
protected override void GenerateTypeStart(CodeTypeDeclaration e)
{
Output.Write("typeStart");
}
protected override void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e)
{
Output.Write("variableDeclarationStatement");
}
protected override void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e)
{
Output.Write("variableReferenceExpression");
}
protected override string GetTypeOutput(CodeTypeReference value)
{
throw new NotImplementedException();
}
protected override bool IsValidIdentifier(string value)
{
return value == "invalid";
}
protected override void OutputType(CodeTypeReference typeRef)
{
throw new NotImplementedException();
}
protected override string QuoteSnippetString(string value)
{
throw new NotImplementedException();
}
protected override bool Supports(GeneratorSupport support)
{
throw new NotImplementedException();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.ApplicationPlugins.RegionModulesController
{
public class RegionModulesControllerPlugin : IRegionModulesController,
IApplicationPlugin
{
// Logger
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// Config access
private OpenSimBase m_openSim;
// Our name
private string m_name;
// Internal lists to collect information about modules present
private List<TypeExtensionNode> m_nonSharedModules =
new List<TypeExtensionNode>();
private List<TypeExtensionNode> m_sharedModules =
new List<TypeExtensionNode>();
// List of shared module instances, for adding to Scenes
private List<ISharedRegionModule> m_sharedInstances =
new List<ISharedRegionModule>();
#region IApplicationPlugin implementation
public void Initialise (OpenSimBase openSim)
{
m_openSim = openSim;
m_openSim.ApplicationRegistry.RegisterInterface<IRegionModulesController>(this);
m_log.DebugFormat("[REGIONMODULES]: Initializing...");
// Who we are
string id = AddinManager.CurrentAddin.Id;
// Make friendly name
int pos = id.LastIndexOf(".");
if (pos == -1)
m_name = id;
else
m_name = id.Substring(pos + 1);
// The [Modules] section in the ini file
IConfig modulesConfig =
m_openSim.ConfigSource.Source.Configs["Modules"];
if (modulesConfig == null)
modulesConfig = m_openSim.ConfigSource.Source.AddConfig("Modules");
Dictionary<RuntimeAddin, IList<int>> loadedModules = new Dictionary<RuntimeAddin, IList<int>>();
// Scan modules and load all that aren't disabled
foreach (TypeExtensionNode node in
AddinManager.GetExtensionNodes("/OpenSim/RegionModules"))
{
IList<int> loadedModuleData;
if (!loadedModules.ContainsKey(node.Addin))
loadedModules.Add(node.Addin, new List<int> { 0, 0, 0 });
loadedModuleData = loadedModules[node.Addin];
if (node.Type.GetInterface(typeof(ISharedRegionModule).ToString()) != null)
{
if (CheckModuleEnabled(node, modulesConfig))
{
m_log.DebugFormat("[REGIONMODULES]: Found shared region module {0}, class {1}", node.Id, node.Type);
m_sharedModules.Add(node);
loadedModuleData[0]++;
}
}
else if (node.Type.GetInterface(typeof(INonSharedRegionModule).ToString()) != null)
{
if (CheckModuleEnabled(node, modulesConfig))
{
m_log.DebugFormat("[REGIONMODULES]: Found non-shared region module {0}, class {1}", node.Id, node.Type);
m_nonSharedModules.Add(node);
loadedModuleData[1]++;
}
}
else
{
m_log.WarnFormat("[REGIONMODULES]: Found unknown type of module {0}, class {1}", node.Id, node.Type);
loadedModuleData[2]++;
}
}
foreach (KeyValuePair<RuntimeAddin, IList<int>> loadedModuleData in loadedModules)
{
m_log.InfoFormat(
"[REGIONMODULES]: From plugin {0}, (version {1}), loaded {2} modules, {3} shared, {4} non-shared {5} unknown",
loadedModuleData.Key.Id,
loadedModuleData.Key.Version,
loadedModuleData.Value[0] + loadedModuleData.Value[1] + loadedModuleData.Value[2],
loadedModuleData.Value[0], loadedModuleData.Value[1], loadedModuleData.Value[2]);
}
// Load and init the module. We try a constructor with a port
// if a port was given, fall back to one without if there is
// no port or the more specific constructor fails.
// This will be removed, so that any module capable of using a port
// must provide a constructor with a port in the future.
// For now, we do this so migration is easy.
//
foreach (TypeExtensionNode node in m_sharedModules)
{
Object[] ctorArgs = new Object[] { (uint)0 };
// Read the config again
string moduleString =
modulesConfig.GetString("Setup_" + node.Id, String.Empty);
// Get the port number, if there is one
if (moduleString != String.Empty)
{
// Get the port number from the string
string[] moduleParts = moduleString.Split(new char[] { '/' },
2);
if (moduleParts.Length > 1)
ctorArgs[0] = Convert.ToUInt32(moduleParts[0]);
}
// Try loading and initilaizing the module, using the
// port if appropriate
ISharedRegionModule module = null;
try
{
module = (ISharedRegionModule)Activator.CreateInstance(
node.Type, ctorArgs);
}
catch
{
module = (ISharedRegionModule)Activator.CreateInstance(
node.Type);
}
// OK, we're up and running
m_sharedInstances.Add(module);
module.Initialise(m_openSim.ConfigSource.Source);
}
}
public void PostInitialise ()
{
m_log.DebugFormat("[REGIONMODULES]: PostInitializing...");
// Immediately run PostInitialise on shared modules
foreach (ISharedRegionModule module in m_sharedInstances)
{
module.PostInitialise();
}
}
#endregion
#region IPlugin implementation
// We don't do that here
//
public void Initialise ()
{
throw new System.NotImplementedException();
}
#endregion
#region IDisposable implementation
// Cleanup
//
public void Dispose ()
{
// We expect that all regions have been removed already
while (m_sharedInstances.Count > 0)
{
m_sharedInstances[0].Close();
m_sharedInstances.RemoveAt(0);
}
m_sharedModules.Clear();
m_nonSharedModules.Clear();
}
#endregion
public string Version
{
get
{
return AddinManager.CurrentAddin.Version;
}
}
public string Name
{
get
{
return m_name;
}
}
#region Region Module interfacesController implementation
/// <summary>
/// Check that the given module is no disabled in the [Modules] section of the config files.
/// </summary>
/// <param name="node"></param>
/// <param name="modulesConfig">The config section</param>
/// <returns>true if the module is enabled, false if it is disabled</returns>
protected bool CheckModuleEnabled(TypeExtensionNode node, IConfig modulesConfig)
{
// Get the config string
string moduleString =
modulesConfig.GetString("Setup_" + node.Id, String.Empty);
// We have a selector
if (moduleString != String.Empty)
{
// Allow disabling modules even if they don't have
// support for it
if (moduleString == "disabled")
return false;
// Split off port, if present
string[] moduleParts = moduleString.Split(new char[] { '/' }, 2);
// Format is [port/][class]
string className = moduleParts[0];
if (moduleParts.Length > 1)
className = moduleParts[1];
// Match the class name if given
if (className != String.Empty &&
node.Type.ToString() != className)
return false;
}
return true;
}
// The root of all evil.
// This is where we handle adding the modules to scenes when they
// load. This means that here we deal with replaceable interfaces,
// nonshared modules, etc.
//
public void AddRegionToModules (Scene scene)
{
Dictionary<Type, ISharedRegionModule> deferredSharedModules =
new Dictionary<Type, ISharedRegionModule>();
Dictionary<Type, INonSharedRegionModule> deferredNonSharedModules =
new Dictionary<Type, INonSharedRegionModule>();
// We need this to see if a module has already been loaded and
// has defined a replaceable interface. It's a generic call,
// so this can't be used directly. It will be used later
Type s = scene.GetType();
MethodInfo mi = s.GetMethod("RequestModuleInterface");
// This will hold the shared modules we actually load
List<ISharedRegionModule> sharedlist =
new List<ISharedRegionModule>();
// Iterate over the shared modules that have been loaded
// Add them to the new Scene
foreach (ISharedRegionModule module in m_sharedInstances)
{
// Here is where we check if a replaceable interface
// is defined. If it is, the module is checked against
// the interfaces already defined. If the interface is
// defined, we simply skip the module. Else, if the module
// defines a replaceable interface, we add it to the deferred
// list.
Type replaceableInterface = module.ReplaceableInterface;
if (replaceableInterface != null)
{
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
continue;
}
deferredSharedModules[replaceableInterface] = module;
m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name);
continue;
}
m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1}",
scene.RegionInfo.RegionName, module.Name);
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
sharedlist.Add(module);
}
IConfig modulesConfig =
m_openSim.ConfigSource.Source.Configs["Modules"];
// Scan for, and load, nonshared modules
List<INonSharedRegionModule> list = new List<INonSharedRegionModule>();
foreach (TypeExtensionNode node in m_nonSharedModules)
{
Object[] ctorArgs = new Object[] {0};
// Read the config
string moduleString =
modulesConfig.GetString("Setup_" + node.Id, String.Empty);
// Get the port number, if there is one
if (moduleString != String.Empty)
{
// Get the port number from the string
string[] moduleParts = moduleString.Split(new char[] {'/'},
2);
if (moduleParts.Length > 1)
ctorArgs[0] = Convert.ToUInt32(moduleParts[0]);
}
// Actually load it
INonSharedRegionModule module = null;
Type[] ctorParamTypes = new Type[ctorArgs.Length];
for (int i = 0; i < ctorParamTypes.Length; i++)
ctorParamTypes[i] = ctorArgs[i].GetType();
if (node.Type.GetConstructor(ctorParamTypes) != null)
module = (INonSharedRegionModule)Activator.CreateInstance(node.Type, ctorArgs);
else
module = (INonSharedRegionModule)Activator.CreateInstance(node.Type);
// Check for replaceable interfaces
Type replaceableInterface = module.ReplaceableInterface;
if (replaceableInterface != null)
{
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
continue;
}
deferredNonSharedModules[replaceableInterface] = module;
m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name);
continue;
}
m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1}",
scene.RegionInfo.RegionName, module.Name);
// Initialise the module
module.Initialise(m_openSim.ConfigSource.Source);
list.Add(module);
}
// Now add the modules that we found to the scene. If a module
// wishes to override a replaceable interface, it needs to
// register it in Initialise, so that the deferred module
// won't load.
foreach (INonSharedRegionModule module in list)
{
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
}
// Now all modules without a replaceable base interface are loaded
// Replaceable modules have either been skipped, or omitted.
// Now scan the deferred modules here
foreach (ISharedRegionModule module in deferredSharedModules.Values)
{
// Determine if the interface has been replaced
Type replaceableInterface = module.ReplaceableInterface;
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
continue;
}
m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1} (deferred)",
scene.RegionInfo.RegionName, module.Name);
// Not replaced, load the module
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
sharedlist.Add(module);
}
// Same thing for nonshared modules, load them unless overridden
List<INonSharedRegionModule> deferredlist =
new List<INonSharedRegionModule>();
foreach (INonSharedRegionModule module in deferredNonSharedModules.Values)
{
// Check interface override
Type replaceableInterface = module.ReplaceableInterface;
if (replaceableInterface != null)
{
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
continue;
}
}
m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1} (deferred)",
scene.RegionInfo.RegionName, module.Name);
module.Initialise(m_openSim.ConfigSource.Source);
list.Add(module);
deferredlist.Add(module);
}
// Finally, load valid deferred modules
foreach (INonSharedRegionModule module in deferredlist)
{
module.AddRegion(scene);
scene.AddRegionModule(module.Name, module);
}
// This is needed for all module types. Modules will register
// Interfaces with scene in AddScene, and will also need a means
// to access interfaces registered by other modules. Without
// this extra method, a module attempting to use another modules's
// interface would be successful only depending on load order,
// which can't be depended upon, or modules would need to resort
// to ugly kludges to attempt to request interfaces when needed
// and unneccessary caching logic repeated in all modules.
// The extra function stub is just that much cleaner
//
foreach (ISharedRegionModule module in sharedlist)
{
module.RegionLoaded(scene);
}
foreach (INonSharedRegionModule module in list)
{
module.RegionLoaded(scene);
}
}
public void RemoveRegionFromModules (Scene scene)
{
foreach (IRegionModuleBase module in scene.RegionModules.Values)
{
m_log.DebugFormat("[REGIONMODULE]: Removing scene {0} from module {1}",
scene.RegionInfo.RegionName, module.Name);
module.RemoveRegion(scene);
if (module is INonSharedRegionModule)
{
// as we were the only user, this instance has to die
module.Close();
}
}
scene.RegionModules.Clear();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Data;
using EDEngineer.Localization;
using EDEngineer.Models;
using EDEngineer.Models.Operations;
using EDEngineer.Models.State;
using EDEngineer.Models.Utils;
using EDEngineer.Properties;
using EDEngineer.Utils;
using EDEngineer.Utils.System;
using EDEngineer.Views.Notifications;
using Newtonsoft.Json;
using NodaTime;
namespace EDEngineer.Views
{
public class CommanderViewModel : INotifyPropertyChanged, IDisposable
{
public string CommanderName { get; }
public State State { get; }
public BlueprintFilters Filters { get; private set; }
public ObservableCollection<Entry> HighlightedEntryData { get; } = new ObservableCollection<Entry>();
public ShoppingListViewModel ShoppingList { get; private set; }
private readonly JournalEntryConverter journalEntryConverter;
public JsonSerializerSettings JsonSettings { get; }
private readonly HashSet<Blueprint> favoritedBlueprints = new HashSet<Blueprint>();
private Instant lastUpdate = Instant.MinValue;
private readonly CommanderNotifications commanderNotifications;
public Instant LastUpdate
{
get => lastUpdate;
set
{
if (value == lastUpdate)
return;
lastUpdate = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void LoadLogs(IEnumerable<string> events)
{
commanderNotifications?.UnsubscribeNotifications();
State.Cargo.InitLoad();
// Clear state:
State.Cargo.Ingredients.ToList().ForEach(k => State.Cargo.IncrementCargo(k.Value.Data.Name, -1 * k.Value.Count));
LastUpdate = Instant.MinValue;
ApplyEventsToSate(events);
commanderNotifications?.SubscribeNotifications();
State.Cargo.Ingredients.RefreshSort();
State.Cargo.CompleteLoad();
}
public CommanderViewModel(string commanderName, Action<CommanderViewModel> loadAction, Languages languages, List<EntryData> entryDatas, List<Equipment> equipments)
{
CommanderName = commanderName;
var equipmentByName = equipments.ToDictionary(x => x.Code, StringComparer.OrdinalIgnoreCase);
var converter = new ItemNameConverter(entryDatas, equipmentByName);
State = new State(new StateCargo(entryDatas, equipments, languages, SettingsManager.Comparer));
commanderNotifications = new CommanderNotifications(State);
var blueprintConverter = new BlueprintConverter(State.Cargo.Ingredients);
var blueprintsJson = Helpers.GetBlueprintsJson();
var blueprints =
JsonConvert.DeserializeObject<List<Blueprint>>(blueprintsJson, blueprintConverter)
.Where(b => b.Ingredients.Any())
.ToList();
journalEntryConverter = new JournalEntryConverter(converter, State.Cargo.Ingredients, languages, blueprints);
JsonSettings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { journalEntryConverter },
Error = (o, e) => e.ErrorContext.Handled = true
};
LoadBlueprints(languages, blueprints);
languages.PropertyChanged += (o, e) => OnPropertyChanged(nameof(Filters));
loadAction(this);
State.BlueprintCrafted += (o, e) =>
{
TryRemoveFromShoppingListByIngredients(e.Category, e.TechnicalType,
e.IngredientsConsumed);
State.ApplyCraft(e);
};
ShoppingList.SynchronizeWithLogs = SettingsManager.SyncShoppingList;
languages.PropertyChanged += (o, e) =>
{
OnPropertyChanged(nameof(ShoppingList));
OnPropertyChanged(nameof(ShoppingListItem));
};
var datas = State.Cargo.Ingredients.Select(c => c.Value.Data);
var ingredientUsed = State.Blueprints.SelectMany(blueprint => blueprint.Ingredients);
var ingredientUsedNames = ingredientUsed.Select(ingredient => ingredient.Entry.Data.Name).Distinct();
var unusedIngredients = datas.Where(data => !ingredientUsedNames.Contains(data.Name));
foreach (var data in unusedIngredients)
{
data.Unused = true;
}
}
public JournalEntry UserChange(Entry entry, int change)
{
var logEntry = new JournalEntry
{
JournalOperation = new ManualChangeOperation
{
Count = change,
JournalEvent = JournalEvent.ManualUserChange,
Name = entry.Data.Name
},
Timestamp = SystemClock.Instance.GetCurrentInstant()
};
var json = JsonConvert.SerializeObject(logEntry, journalEntryConverter);
logEntry.OriginalJson = json;
MutateState(logEntry);
return logEntry;
}
public void ApplyEventsToSate(IEnumerable<string> allLogs)
{
var entries = allLogs.Select(l => JsonConvert.DeserializeObject<JournalEntry>(l, JsonSettings))
.Where(e => e?.Relevant == true);
foreach (var entry in entries.Where(entry => entry.Timestamp >= LastUpdate).ToList())
{
MutateState(entry);
}
}
private void MutateState(JournalEntry entry)
{
State.Operations.AddLast(entry);
entry.JournalOperation.Mutate(State);
LastUpdate = Instant.Max(LastUpdate, entry.Timestamp);
}
public ICollectionView FilterView(MainWindowViewModel parentViewModel, Kind kind, CollectionViewSource source)
{
source.Filter += (o, e) =>
{
var entry = ((KeyValuePair<string, Entry>)e.Item).Value;
e.Accepted = ((entry.Data.Kind & kind) == entry.Data.Kind || entry.Data.Kind == Kind.Unknown) &&
(parentViewModel.MaterialSubkindFilter == null || entry.Data.Kind == Kind.Data || parentViewModel.MaterialSubkindFilter == entry.Data.Subkind) &&
(parentViewModel.ShowZeroes || entry.Count != 0) &&
(!parentViewModel.ShowOnlyForFavorites || favoritedBlueprints.Any(b => b.Ingredients.Any(i => i.Entry == entry)));
};
parentViewModel.PropertyChanged += (o, e) =>
{
if (e.PropertyName == nameof(parentViewModel.ShowZeroes) || e.PropertyName == nameof(parentViewModel.ShowOnlyForFavorites))
{
source.View.Refresh();
}
};
State.Blueprints.ForEach(b => b.PropertyChanged += (o, e) =>
{
if (parentViewModel.ShowOnlyForFavorites && e.PropertyName == "Favorite")
{
Application.Current.Dispatcher.Invoke(source.View.Refresh);
}
});
if (parentViewModel.IngredientsGrouped)
{
source.View.GroupDescriptions.Add(new PropertyGroupDescription("Value.Data.Group"));
}
return source.View;
}
private void LoadBlueprints(ILanguage languages, IEnumerable<Blueprint> blueprints)
{
State.Blueprints = new List<Blueprint>(blueprints);
if (Settings.Default.Favorites == null)
{
Settings.Default.Favorites = new StringCollection();
}
if (Settings.Default.Ignored == null)
{
Settings.Default.Ignored = new StringCollection();
}
if (Settings.Default.ShoppingList == null)
{
Settings.Default.ShoppingList = new StringCollection();
}
if (Settings.Default.ShowAllGrades == null)
{
Settings.Default.ShowAllGrades = new StringCollection();
}
if (Settings.Default.CollapsedIngredientGroups == null)
{
Settings.Default.CollapsedIngredientGroups = new StringCollection();
}
foreach (var blueprint in State.Blueprints)
{
var text = $"{CommanderName}:{blueprint}";
if (Settings.Default.Favorites.Contains(text))
{
blueprint.Favorite = true;
favoritedBlueprints.Add(blueprint);
if (Settings.Default.Favorites.Contains($"{blueprint}"))
{
Settings.Default.Favorites.Remove($"{blueprint}");
Settings.Default.Save();
}
}
else if (Settings.Default.Favorites.Contains($"{blueprint}"))
{
blueprint.Favorite = true;
favoritedBlueprints.Add(blueprint);
Settings.Default.Favorites.Remove($"{blueprint}");
Settings.Default.Favorites.Add(text);
Settings.Default.Save();
}
if (Settings.Default.Ignored.Contains(text))
{
blueprint.Ignored = true;
if (Settings.Default.Ignored.Contains($"{blueprint}"))
{
Settings.Default.Ignored.Remove($"{blueprint}");
Settings.Default.Save();
}
}
else if (Settings.Default.Ignored.Contains($"{blueprint}"))
{
blueprint.Ignored = true;
Settings.Default.Ignored.Remove($"{blueprint}");
Settings.Default.Ignored.Add(text);
Settings.Default.Save();
}
blueprint.ShoppingListCount = Settings.Default.ShoppingList.Cast<string>().Count(l => l == text);
blueprint.PropertyChanged += (o, e) =>
{
if (e.PropertyName == "Favorite")
{
if (blueprint.Favorite)
{
Settings.Default.Favorites.Add($"{CommanderName}:{blueprint}");
favoritedBlueprints.Add(blueprint);
}
else
{
Settings.Default.Favorites.Remove($"{CommanderName}:{blueprint}");
favoritedBlueprints.Remove(blueprint);
}
Settings.Default.Save();
}
else if (e.PropertyName == "Ignored")
{
if (blueprint.Ignored)
{
Settings.Default.Ignored.Add($"{CommanderName}:{blueprint}");
}
else
{
Settings.Default.Ignored.Remove($"{CommanderName}:{blueprint}");
}
Settings.Default.Save();
}
else if (e.PropertyName == "ShoppingListCount")
{
while (Settings.Default.ShoppingList.Contains(text))
{
Settings.Default.ShoppingList.Remove(text);
}
for (var i = 0; i < blueprint.ShoppingListCount; i++)
{
Settings.Default.ShoppingList.Add(text);
}
Settings.Default.Save();
}
};
}
Filters = new BlueprintFilters(languages, State.Blueprints);
ShoppingList = new ShoppingListViewModel(State.Cargo, State.Blueprints, languages);
}
public void TryRemoveFromShoppingListByIngredients(BlueprintCategory category, string technicalModuleName, List<BlueprintIngredient> blueprintIngredients)
{
if (!ShoppingList.SynchronizeWithLogs)
{
return;
}
var blueprints = ShoppingList
.Composition
.Select(x => x.Item1)
.ToList();
if (category == BlueprintCategory.Module)
{
var blueprint = blueprints.FirstOrDefault(b => b.Category == BlueprintCategory.Module &&
b.TechnicalType.IsIn(technicalModuleName) &&
b.HasSameIngredients(blueprintIngredients));
if (blueprint == null)
{
var experimentals = blueprints.Where(b => b.Category == BlueprintCategory.Experimental).ToList();
foreach (var experimental in experimentals)
{
foreach (var module in blueprints.Where(
b => b.Category == BlueprintCategory.Module && b.TechnicalType.IsIn(technicalModuleName)))
{
var mergedIngredients = experimental.Ingredients.Concat(module.Ingredients).ToList();
if (mergedIngredients.Count == blueprintIngredients.Count &&
mergedIngredients.All(blueprintIngredients.Contains))
{
ShoppingListChange(experimental, -1);
ShoppingListChange(module, -1);
return;
}
}
}
blueprint = blueprints.FirstOrDefault(b => b.HasSameIngredients(blueprintIngredients));
}
if (blueprint != null)
{
ShoppingListChange(blueprint, -1);
}
}
else
{
var blueprint = blueprints.FirstOrDefault(b =>
{
if (b.Category != category)
{
return false;
}
switch (b.Category)
{
case BlueprintCategory.Synthesis:
case BlueprintCategory.Technology:
return b.HasSameIngredients(blueprintIngredients);
default:
return false;
}
});
if (blueprint != null)
{
ShoppingListChange(blueprint, -1);
}
}
}
public void ShoppingListChange(Blueprint blueprint, int i)
{
if (i != 0 && blueprint.ShoppingListCount + i >= 0)
{
blueprint.ShoppingListCount += i;
OnPropertyChanged(nameof(ShoppingList));
OnPropertyChanged(nameof(ShoppingListItem));
}
}
public void ImportShoppingList()
{
if (Helpers.TryRetrieveShoppingList(out var shoppingListItems))
{
var blueprints = State.Blueprints;
if (shoppingListItems != null && shoppingListItems.Count > 0)
{
// Configure the message box to be displayed
var messageBoxText = "Do you want to clear the shopping list before import?";
var caption = "Shopping List Import";
var button = MessageBoxButton.YesNoCancel;
var icon = MessageBoxImage.Warning;
// Display message box
var result = MessageBox.Show(messageBoxText, caption, button, icon);
// Process message box results
switch (result)
{
case MessageBoxResult.Yes:
ClearShoppingList();
break;
case MessageBoxResult.No:
// User pressed No, so just load into shopping list without clearing
break;
case MessageBoxResult.Cancel:
// User pressed Cancel button so skip out of Import
return;
}
LoadShoppingListItems(shoppingListItems, blueprints);
Settings.Default.Save();
}
RefreshShoppingList();
}
}
private void LoadShoppingListItems(StringCollection shoppingListItems, List<Blueprint> blueprints)
{
var blueprintsByString = blueprints.ToDictionary(b => b.ToString(), b => b);
foreach (var item in shoppingListItems)
{
if (item == null)
{
continue;
}
var itemName = item.Split(':');
if (blueprintsByString.TryGetValue(itemName[1], out var blueprint))
{
ShoppingListChange(blueprint, 1);
}
}
}
public void ExportShoppingList()
{
try
{
Helpers.SaveShoppingList(CommanderName);
}
catch(Exception e)
{
MessageBox.Show("Shopping list could not be saved." + Environment.NewLine + Environment.NewLine + e, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public void ClearShoppingList()
{
foreach (var tuple in ShoppingList.Composition.ToList())
{
ShoppingListChange(tuple.Item1, tuple.Item2 * -1);
}
}
public int ShoppingListItem => 0;
public override string ToString()
{
return $"CMDR {CommanderName}";
}
public void Dispose()
{
commanderNotifications?.Dispose();
}
public void ToggleHighlight(Entry entry)
{
entry.Highlighted = !entry.Highlighted;
if (entry.Highlighted)
{
HighlightedEntryData.Add(entry);
}
else
{
HighlightedEntryData.Remove(entry);
}
Settings.Default.Save();
}
public void HighlightShoppingListIngredient(List<BlueprintIngredient> ingredients, Blueprint blueprint, bool highlighted)
{
if (ingredients == null)
{
return;
}
foreach (
var ingredient in
blueprint.Ingredients.Join(ingredients,
ingredient => ingredient.Entry.Data.Name,
ingredient => ingredient.Entry.Data.Name,
(_, ingredient) => ingredient))
{
ingredient.ShoppingListHighlighted = highlighted;
}
blueprint.ShoppingListHighlighted = highlighted;
}
public void HighlightShoppingListBlueprint(List<Tuple<Blueprint, int>> blueprints, BlueprintIngredient ingredient, bool highlighted)
{
foreach (var blueprint in blueprints.Select(i => i.Item1).Where(b => b.Ingredients.Any(i => i.Entry.Data.Name == ingredient.Entry.Data.Name)))
{
blueprint.ShoppingListHighlighted = highlighted;
}
ingredient.ShoppingListHighlighted = highlighted;
}
public void RefreshShoppingList()
{
// relevant when live reloading a commander, because WPF didn't bind upon creating the object:
OnPropertyChanged(nameof(ShoppingList));
OnPropertyChanged(nameof(ShoppingListItem));
}
public void RefreshShoppingList( StringCollection shoppingList)
{
var blueprints = State.Blueprints;
LoadShoppingListItems(shoppingList, blueprints);
Settings.Default.Save();
}
public void ShowAllGradeChanges(ShoppingListBlock shoppingListBlock)
{
shoppingListBlock.ShowAllGrades = !shoppingListBlock.ShowAllGrades;
if (shoppingListBlock.ShowAllGrades)
{
SettingsManager.AddToAllGrades(shoppingListBlock.Label);
}
else
{
SettingsManager.RemoveFromAllGrades(shoppingListBlock.Label);
}
OnPropertyChanged(nameof(ShoppingList));
OnPropertyChanged(nameof(ShoppingListItem));
}
public void LoadAggregation(StateAggregation aggregation)
{
State.ApplyAggregation(aggregation);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
internal class WinHttpWebSocket : WebSocket
{
#region Constants
// TODO (#7893): This code needs to be shared with WinHttpClientHandler
private const string HeaderNameCookie = "Cookie";
private const string HeaderNameWebSocketProtocol = "Sec-WebSocket-Protocol";
#endregion
// TODO (Issue 2503): move System.Net.* strings to resources as appropriate.
// NOTE: All WinHTTP operations must be called while holding the _operation.Lock.
// It is critical that no handle gets closed while a WinHTTP function is running.
private WebSocketCloseStatus? _closeStatus = null;
private string _closeStatusDescription = null;
private string _subProtocol = null;
private bool _disposed = false;
private WinHttpWebSocketState _operation = new WinHttpWebSocketState();
public WinHttpWebSocket()
{
}
#region Properties
public override WebSocketCloseStatus? CloseStatus
{
get
{
return _closeStatus;
}
}
public override string CloseStatusDescription
{
get
{
return _closeStatusDescription;
}
}
public override WebSocketState State
{
get
{
return _operation.State;
}
}
public override string SubProtocol
{
get
{
return _subProtocol;
}
}
#endregion
static readonly WebSocketState[] s_validConnectStates = { WebSocketState.None };
static readonly WebSocketState[] s_validConnectingStates = { WebSocketState.Connecting };
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validConnectingStates);
// Must grab lock until RequestHandle is populated, otherwise we risk resource leaks on Abort.
//
// TODO (Issue 2506): Alternatively, release the lock between WinHTTP operations and check, under lock, that the
// state is still valid to continue operation.
_operation.SessionHandle = InitializeWinHttp(options);
_operation.ConnectionHandle = Interop.WinHttp.WinHttpConnectWithCallback(
_operation.SessionHandle,
uri.IdnHost,
(ushort)uri.Port,
0);
ThrowOnInvalidHandle(_operation.ConnectionHandle);
bool secureConnection = uri.Scheme == UriScheme.Https || uri.Scheme == UriScheme.Wss;
_operation.RequestHandle = Interop.WinHttp.WinHttpOpenRequestWithCallback(
_operation.ConnectionHandle,
"GET",
uri.PathAndQuery,
null,
Interop.WinHttp.WINHTTP_NO_REFERER,
null,
secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0);
ThrowOnInvalidHandle(_operation.RequestHandle);
_operation.IncrementHandlesOpenWithCallback();
if (!Interop.WinHttp.WinHttpSetOption(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET,
IntPtr.Zero,
0))
{
WinHttpException.ThrowExceptionUsingLastError();
}
// We need the address of the IntPtr to the GCHandle.
IntPtr context = _operation.ToIntPtr();
IntPtr contextAddress;
unsafe
{
contextAddress = (IntPtr)(void*)&context;
}
if (!Interop.WinHttp.WinHttpSetOption(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE,
contextAddress,
(uint)IntPtr.Size))
{
WinHttpException.ThrowExceptionUsingLastError();
}
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SECURE_FAILURE;
if (Interop.WinHttp.WinHttpSetStatusCallback(
_operation.RequestHandle,
WinHttpWebSocketCallback.s_StaticCallbackDelegate,
notificationFlags,
IntPtr.Zero) == (IntPtr)Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK)
{
WinHttpException.ThrowExceptionUsingLastError();
}
_operation.RequestHandle.AttachCallback();
// We need to pin the operation object at this point in time since the WinHTTP callback
// has been fully wired to the request handle and the operation object has been set as
// the context value of the callback. Any notifications from activity on the handle will
// result in the callback being called with the context value.
_operation.Pin();
AddRequestHeaders(uri, options);
_operation.TcsUpgrade = new TaskCompletionSource<bool>();
}
await InternalSendWsUpgradeRequestAsync().ConfigureAwait(false);
await InternalReceiveWsUpgradeResponse().ConfigureAwait(false);
lock (_operation.Lock)
{
VerifyUpgradeResponse();
ThrowOnInvalidConnectState();
_operation.WebSocketHandle =
Interop.WinHttp.WinHttpWebSocketCompleteUpgrade(_operation.RequestHandle, IntPtr.Zero);
ThrowOnInvalidHandle(_operation.WebSocketHandle);
_operation.IncrementHandlesOpenWithCallback();
// We need the address of the IntPtr to the GCHandle.
IntPtr context = _operation.ToIntPtr();
IntPtr contextAddress;
unsafe
{
contextAddress = (IntPtr)(void*)&context;
}
if (!Interop.WinHttp.WinHttpSetOption(
_operation.WebSocketHandle,
Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE,
contextAddress,
(uint)IntPtr.Size))
{
WinHttpException.ThrowExceptionUsingLastError();
}
_operation.WebSocketHandle.AttachCallback();
_operation.UpdateState(WebSocketState.Open);
if (_operation.RequestHandle != null)
{
_operation.RequestHandle.Dispose();
// RequestHandle will be set to null in the callback.
}
_operation.TcsUpgrade = null;
ctr.Dispose();
}
}
}
// Requires lock taken.
private Interop.WinHttp.SafeWinHttpHandle InitializeWinHttp(ClientWebSocketOptions options)
{
Interop.WinHttp.SafeWinHttpHandle sessionHandle;
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
null,
null,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle);
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)sizeof(uint)))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return sessionHandle;
}
private Task<bool> InternalSendWsUpgradeRequestAsync()
{
lock (_operation.Lock)
{
ThrowOnInvalidConnectState();
if (!Interop.WinHttp.WinHttpSendRequest(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_NO_ADDITIONAL_HEADERS,
0,
IntPtr.Zero,
0,
0,
_operation.ToIntPtr()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return _operation.TcsUpgrade.Task;
}
private Task<bool> InternalReceiveWsUpgradeResponse()
{
// TODO (Issue 2507): Potential optimization: move this in WinHttpWebSocketCallback.
lock (_operation.Lock)
{
ThrowOnInvalidConnectState();
_operation.TcsUpgrade = new TaskCompletionSource<bool>();
if (!Interop.WinHttp.WinHttpReceiveResponse(_operation.RequestHandle, IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return _operation.TcsUpgrade.Task;
}
private void ThrowOnInvalidConnectState()
{
// A special behavior for WebSocket upgrade: throws ConnectFailure instead of other Abort messages.
if (_operation.State != WebSocketState.Connecting)
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
}
private static readonly WebSocketState[] s_validSendStates = { WebSocketState.Open, WebSocketState.CloseReceived };
public override Task SendAsync(
ArraySegment<byte> buffer,
WebSocketMessageType messageType,
bool endOfMessage,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckValidStates(s_validSendStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
var bufferType = WebSocketMessageTypeAdapter.GetWinHttpMessageType(messageType, endOfMessage);
_operation.PinSendBuffer(buffer);
bool sendOperationAlreadyPending = false;
if (_operation.PendingWriteOperation == false)
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validSendStates);
if (_operation.PendingWriteOperation == false)
{
_operation.PendingWriteOperation = true;
_operation.TcsSend = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
uint ret = Interop.WinHttp.WinHttpWebSocketSend(
_operation.WebSocketHandle,
bufferType,
buffer.Count > 0 ? Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset) : IntPtr.Zero,
(uint)buffer.Count);
if (Interop.WinHttp.ERROR_SUCCESS != ret)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
else
{
sendOperationAlreadyPending = true;
}
}
}
else
{
sendOperationAlreadyPending = true;
}
if (sendOperationAlreadyPending)
{
var exception = new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "SendAsync"));
_operation.TcsSend.TrySetException(exception);
Abort();
}
return _operation.TcsSend.Task;
}
}
private static readonly WebSocketState[] s_validReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent };
private static readonly WebSocketState[] s_validAfterReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent, WebSocketState.CloseReceived };
public override async Task<WebSocketReceiveResult> ReceiveAsync(
ArraySegment<byte> buffer,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckValidStates(s_validReceiveStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
_operation.PinReceiveBuffer(buffer);
await InternalReceiveAsync(buffer).ConfigureAwait(false);
// Check for abort.
_operation.InterlockedCheckValidStates(s_validAfterReceiveStates);
WebSocketMessageType bufferType;
bool endOfMessage;
bufferType = WebSocketMessageTypeAdapter.GetWebSocketMessageType(_operation.BufferType, out endOfMessage);
int bytesTransferred = 0;
checked
{
bytesTransferred = (int)_operation.BytesTransferred;
}
WebSocketReceiveResult ret;
if (bufferType == WebSocketMessageType.Close)
{
UpdateServerCloseStatus();
ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage, _closeStatus, _closeStatusDescription);
}
else
{
ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage);
}
return ret;
}
}
private Task<bool> InternalReceiveAsync(ArraySegment<byte> buffer)
{
bool receiveOperationAlreadyPending = false;
if (_operation.PendingReadOperation == false)
{
lock (_operation.Lock)
{
if (_operation.PendingReadOperation == false)
{
_operation.CheckValidState(s_validReceiveStates);
// Prevent continuations from running on the same thread as the callback to prevent re-entrance deadlocks
_operation.TcsReceive = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_operation.PendingReadOperation = true;
uint bytesRead = 0;
Interop.WinHttp.WINHTTP_WEB_SOCKET_BUFFER_TYPE winHttpBufferType = 0;
uint status = Interop.WinHttp.WinHttpWebSocketReceive(
_operation.WebSocketHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset),
(uint)buffer.Count,
out bytesRead, // Unused in async mode: ignore.
out winHttpBufferType); // Unused in async mode: ignore.
if (Interop.WinHttp.ERROR_SUCCESS != status)
{
throw WinHttpException.CreateExceptionUsingError((int)status);
}
}
else
{
receiveOperationAlreadyPending = true;
}
}
}
else
{
receiveOperationAlreadyPending = true;
}
if (receiveOperationAlreadyPending)
{
var exception = new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "ReceiveAsync"));
_operation.TcsReceive.TrySetException(exception);
Abort();
}
return _operation.TcsReceive.Task;
}
private static readonly WebSocketState[] s_validCloseStates = { WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent };
public override async Task CloseAsync(
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
_operation.TcsClose = new TaskCompletionSource<bool>();
await InternalCloseAsync(closeStatus, statusDescription).ConfigureAwait(false);
UpdateServerCloseStatus();
}
}
private Task<bool> InternalCloseAsync(WebSocketCloseStatus closeStatus, string statusDescription)
{
uint ret;
_operation.TcsClose = new TaskCompletionSource<bool>();
lock (_operation.Lock)
{
_operation.CheckValidState(s_validCloseStates);
if (!string.IsNullOrEmpty(statusDescription))
{
byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription);
ret = Interop.WinHttp.WinHttpWebSocketClose(
_operation.WebSocketHandle,
(ushort)closeStatus,
statusDescriptionBuffer,
(uint)statusDescriptionBuffer.Length);
}
else
{
ret = Interop.WinHttp.WinHttpWebSocketClose(
_operation.WebSocketHandle,
(ushort)closeStatus,
IntPtr.Zero,
0);
}
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
return _operation.TcsClose.Task;
}
private void UpdateServerCloseStatus()
{
uint ret;
ushort serverStatus;
var closeDescription = new byte[WebSocketValidate.MaxControlFramePayloadLength];
uint closeDescriptionConsumed;
lock (_operation.Lock)
{
ret = Interop.WinHttp.WinHttpWebSocketQueryCloseStatus(
_operation.WebSocketHandle,
out serverStatus,
closeDescription,
(uint)closeDescription.Length,
out closeDescriptionConsumed);
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
_closeStatus = (WebSocketCloseStatus)serverStatus;
_closeStatusDescription = Encoding.UTF8.GetString(closeDescription, 0, (int)closeDescriptionConsumed);
}
}
private static readonly WebSocketState[] s_validCloseOutputStates = { WebSocketState.Open, WebSocketState.CloseReceived };
private static readonly WebSocketState[] s_validCloseOutputStatesAfterUpdate = { WebSocketState.CloseReceived, WebSocketState.CloseSent };
public override Task CloseOutputAsync(
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseOutputStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validCloseOutputStatesAfterUpdate);
uint ret;
_operation.TcsCloseOutput = new TaskCompletionSource<bool>();
if (!string.IsNullOrEmpty(statusDescription))
{
byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription);
ret = Interop.WinHttp.WinHttpWebSocketShutdown(
_operation.WebSocketHandle,
(ushort)closeStatus,
statusDescriptionBuffer,
(uint)statusDescriptionBuffer.Length);
}
else
{
ret = Interop.WinHttp.WinHttpWebSocketShutdown(
_operation.WebSocketHandle,
(ushort)closeStatus,
IntPtr.Zero,
0);
}
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
return _operation.TcsCloseOutput.Task;
}
}
private void VerifyUpgradeResponse()
{
// Check the status code
var statusCode = GetHttpStatusCode();
if (statusCode != HttpStatusCode.SwitchingProtocols)
{
Abort();
return;
}
_subProtocol = GetResponseHeader(HeaderNameWebSocketProtocol);
}
private void AddRequestHeaders(Uri uri, ClientWebSocketOptions options)
{
var requestHeadersBuffer = new StringBuilder();
// Manually add cookies.
if (options.Cookies != null)
{
AppendCookieHeaderLine(uri, options.Cookies, requestHeadersBuffer);
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(options.RequestHeaders.ToString());
using (List<string>.Enumerator e = options.RequestedSubProtocols.GetEnumerator())
{
if (e.MoveNext())
{
requestHeadersBuffer.Append(HeaderNameWebSocketProtocol + ": ");
requestHeadersBuffer.Append(e.Current);
while (e.MoveNext())
{
requestHeadersBuffer.Append(", ");
requestHeadersBuffer.Append(e.Current);
}
requestHeadersBuffer.AppendLine();
}
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
_operation.RequestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static void AppendCookieHeaderLine(Uri uri, CookieContainer cookies, StringBuilder requestHeadersBuffer)
{
Debug.Assert(cookies != null);
Debug.Assert(requestHeadersBuffer != null);
string cookieValues = cookies.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
requestHeadersBuffer.Append(HeaderNameCookie + ": ");
requestHeadersBuffer.AppendLine(cookieValues);
}
}
private HttpStatusCode GetHttpStatusCode()
{
uint infoLevel = Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER;
uint result = 0;
uint resultSize = sizeof(uint);
if (!Interop.WinHttp.WinHttpQueryHeaders(
_operation.RequestHandle,
infoLevel,
Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX,
ref result,
ref resultSize,
IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return (HttpStatusCode)result;
}
private unsafe string GetResponseHeader(string headerName, char[] buffer = null)
{
const int StackLimit = 128;
Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit));
int bufferLength;
if (buffer == null)
{
bufferLength = StackLimit;
char* pBuffer = stackalloc char[bufferLength];
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
else
{
bufferLength = buffer.Length;
fixed (char* pBuffer = &buffer[0])
{
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
}
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
return null;
}
if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
{
buffer = new char[bufferLength];
return GetResponseHeader(headerName, buffer);
}
throw WinHttpException.CreateExceptionUsingError(lastError);
}
private unsafe bool QueryHeaders(string headerName, char* buffer, ref int bufferLength)
{
Debug.Assert(bufferLength >= 0, "bufferLength must not be negative.");
uint index = 0;
// Convert the char buffer length to the length in bytes.
uint bufferLengthInBytes = (uint)bufferLength * sizeof(char);
// The WinHttpQueryHeaders buffer length is in bytes,
// but the API actually returns Unicode characters.
bool result = Interop.WinHttp.WinHttpQueryHeaders(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_QUERY_CUSTOM,
headerName,
new IntPtr(buffer),
ref bufferLengthInBytes,
ref index);
// Convert the byte buffer length back to the length in chars.
bufferLength = (int)bufferLengthInBytes / sizeof(char);
return result;
}
public override void Dispose()
{
if (!_disposed)
{
lock (_operation.Lock)
{
// Disposing will involve calling WinHttpClose on handles. It is critical that no other WinHttp
// function is running at the same time.
if (!_disposed)
{
_operation.Dispose();
_disposed = true;
}
}
}
// No need to suppress finalization since the finalizer is not overridden.
}
public override void Abort()
{
lock (_operation.Lock)
{
if ((State != WebSocketState.None) && (State != WebSocketState.Connecting))
{
_operation.UpdateState(WebSocketState.Aborted);
}
else
{
// ClientWebSocket Desktop behavior: a ws that was not connected will not switch state to Aborted.
_operation.UpdateState(WebSocketState.Closed);
}
Dispose();
}
CancelAllOperations();
}
private void CancelAllOperations()
{
if (_operation.TcsClose != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsClose.TrySetException(exception);
}
if (_operation.TcsCloseOutput != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsCloseOutput.TrySetException(exception);
}
if (_operation.TcsReceive != null)
{
_operation.TcsReceive.TrySetCanceled();
}
if (_operation.TcsSend != null)
{
var exception = new OperationCanceledException();
_operation.TcsSend.TrySetException(exception);
}
if (_operation.TcsUpgrade != null)
{
var exception = new WebSocketException(SR.net_webstatus_ConnectFailure);
_operation.TcsUpgrade.TrySetException(exception);
}
}
private void ThrowOnInvalidHandle(Interop.WinHttp.SafeWinHttpHandle value)
{
if (value.IsInvalid)
{
Abort();
throw new WebSocketException(
SR.net_webstatus_ConnectFailure,
WinHttpException.CreateExceptionUsingLastError());
}
}
private CancellationTokenRegistration ThrowOrRegisterCancellation(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
Abort();
cancellationToken.ThrowIfCancellationRequested();
}
CancellationTokenRegistration cancellationRegistration =
cancellationToken.Register(s => ((WinHttpWebSocket)s).Abort(), this);
return cancellationRegistration;
}
}
}
| |
using System;
using System.Text;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Routing
{
public sealed class UriUtility
{
static string _appPath;
static string _appPathPrefix;
public UriUtility(IHostingEnvironment hostingEnvironment)
{
if (hostingEnvironment is null) throw new ArgumentNullException(nameof(hostingEnvironment));
ResetAppDomainAppVirtualPath(hostingEnvironment);
}
// internal for unit testing only
internal void SetAppDomainAppVirtualPath(string appPath)
{
_appPath = appPath ?? "/";
_appPathPrefix = _appPath;
if (_appPathPrefix == "/")
_appPathPrefix = String.Empty;
}
internal void ResetAppDomainAppVirtualPath(IHostingEnvironment hostingEnvironment)
{
SetAppDomainAppVirtualPath(hostingEnvironment.ApplicationVirtualPath);
}
// will be "/" or "/foo"
public string AppPath => _appPath;
// will be "" or "/foo"
public string AppPathPrefix => _appPathPrefix;
// adds the virtual directory if any
// see also VirtualPathUtility.ToAbsolute
// TODO: Does this do anything differently than IHostingEnvironment.ToAbsolute? Seems it does less, maybe should be removed?
public string ToAbsolute(string url)
{
//return ResolveUrl(url);
url = url.TrimStart(Constants.CharArrays.Tilde);
return _appPathPrefix + url;
}
// strips the virtual directory if any
// see also VirtualPathUtility.ToAppRelative
public string ToAppRelative(string virtualPath)
{
if (virtualPath.InvariantStartsWith(_appPathPrefix)
&& (virtualPath.Length == _appPathPrefix.Length || virtualPath[_appPathPrefix.Length] == '/'))
{
virtualPath = virtualPath.Substring(_appPathPrefix.Length);
}
if (virtualPath.Length == 0)
{
virtualPath = "/";
}
return virtualPath;
}
// maps an internal umbraco uri to a public uri
// ie with virtual directory, .aspx if required...
public Uri UriFromUmbraco(Uri uri, RequestHandlerSettings requestConfig)
{
var path = uri.GetSafeAbsolutePath();
if (path != "/" && requestConfig.AddTrailingSlash)
path = path.EnsureEndsWith("/");
path = ToAbsolute(path);
return uri.Rewrite(path);
}
// maps a media umbraco uri to a public uri
// ie with virtual directory - that is all for media
public Uri MediaUriFromUmbraco(Uri uri)
{
var path = uri.GetSafeAbsolutePath();
path = ToAbsolute(path);
return uri.Rewrite(path);
}
// maps a public uri to an internal umbraco uri
// ie no virtual directory, no .aspx, lowercase...
public Uri UriToUmbraco(Uri uri)
{
// TODO: This is critical code that executes on every request, we should
// look into if all of this is necessary? not really sure we need ToLower?
// note: no need to decode uri here because we're returning a uri
// so it will be re-encoded anyway
var path = uri.GetSafeAbsolutePath();
path = path.ToLower();
path = ToAppRelative(path); // strip vdir if any
if (path != "/")
{
path = path.TrimEnd(Constants.CharArrays.ForwardSlash);
}
return uri.Rewrite(path);
}
#region ResolveUrl
// http://www.codeproject.com/Articles/53460/ResolveUrl-in-ASP-NET-The-Perfect-Solution
// note
// if browsing http://example.com/sub/page1.aspx then
// ResolveUrl("page2.aspx") returns "/page2.aspx"
// Page.ResolveUrl("page2.aspx") returns "/sub/page2.aspx" (relative...)
//
public string ResolveUrl(string relativeUrl)
{
if (relativeUrl == null) throw new ArgumentNullException("relativeUrl");
if (relativeUrl.Length == 0 || relativeUrl[0] == '/' || relativeUrl[0] == '\\')
return relativeUrl;
int idxOfScheme = relativeUrl.IndexOf(@"://", StringComparison.Ordinal);
if (idxOfScheme != -1)
{
int idxOfQM = relativeUrl.IndexOf('?');
if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl;
}
StringBuilder sbUrl = new StringBuilder();
sbUrl.Append(_appPathPrefix);
if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/');
// found question mark already? query string, do not touch!
bool foundQM = false;
bool foundSlash; // the latest char was a slash?
if (relativeUrl.Length > 1
&& relativeUrl[0] == '~'
&& (relativeUrl[1] == '/' || relativeUrl[1] == '\\'))
{
relativeUrl = relativeUrl.Substring(2);
foundSlash = true;
}
else foundSlash = false;
foreach (char c in relativeUrl)
{
if (!foundQM)
{
if (c == '?') foundQM = true;
else
{
if (c == '/' || c == '\\')
{
if (foundSlash) continue;
else
{
sbUrl.Append('/');
foundSlash = true;
continue;
}
}
else if (foundSlash) foundSlash = false;
}
}
sbUrl.Append(c);
}
return sbUrl.ToString();
}
#endregion
/// <summary>
/// Returns an full URL with the host, port, etc...
/// </summary>
/// <param name="absolutePath">An absolute path (i.e. starts with a '/' )</param>
/// <param name="curentRequestUrl"> </param>
/// <returns></returns>
/// <remarks>
/// Based on http://stackoverflow.com/questions/3681052/get-absolute-url-from-relative-path-refactored-method
/// </remarks>
internal Uri ToFullUrl(string absolutePath, Uri curentRequestUrl)
{
if (string.IsNullOrEmpty(absolutePath))
throw new ArgumentNullException(nameof(absolutePath));
if (!absolutePath.StartsWith("/"))
throw new FormatException("The absolutePath specified does not start with a '/'");
return new Uri(absolutePath, UriKind.Relative).MakeAbsolute(curentRequestUrl);
}
}
}
| |
/*
* 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 OpenMetaverse;
using OpenMetaverse.StructuredData;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace OpenSim.Region.Framework.Scenes.Animation
{
[Serializable]
public class AnimationSet
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<OpenSim.Framework.Animation> m_animations = new List<OpenSim.Framework.Animation>();
private OpenSim.Framework.Animation m_defaultAnimation = new OpenSim.Framework.Animation();
private OpenSim.Framework.Animation m_implicitDefaultAnimation = new OpenSim.Framework.Animation();
private ReaderWriterLock m_AnimationsLock = new ReaderWriterLock();
public AnimationSet()
{
ResetDefaultAnimation();
}
public AnimationSet(OSDArray pArray)
{
ResetDefaultAnimation();
FromOSDArray(pArray);
}
public OpenSim.Framework.Animation DefaultAnimation
{
get { return m_defaultAnimation; }
}
public OpenSim.Framework.Animation ImplicitDefaultAnimation
{
get { return m_implicitDefaultAnimation; }
}
public bool Add(UUID animID, int sequenceNum, UUID objectID)
{
m_AnimationsLock.AcquireWriterLock(-1);
try
{
if (!HasAnimation(animID))
{
m_animations.Add(new OpenSim.Framework.Animation(animID, sequenceNum, objectID));
return true;
}
}
finally
{
m_AnimationsLock.ReleaseWriterLock();
}
return false;
}
public void Clear()
{
ResetDefaultAnimation();
m_animations.Clear();
}
// Compare two AnimationSets and return 'true' if the default animations are the same
// and all of the animations in the list are equal.
public override bool Equals(object obj)
{
AnimationSet other = obj as AnimationSet;
if (other != null)
{
if (this.DefaultAnimation.Equals(other.DefaultAnimation)
&& this.ImplicitDefaultAnimation.Equals(other.ImplicitDefaultAnimation))
{
// The defaults are the same. Is the list of animations the same?
OpenSim.Framework.Animation[] thisAnims = this.ToArray();
OpenSim.Framework.Animation[] otherAnims = other.ToArray();
if (thisAnims.Length == 0 && otherAnims.Length == 0)
return true; // the common case
if (thisAnims.Length == otherAnims.Length)
{
// Do this the hard way but since the list is usually short this won't take long.
foreach (OpenSim.Framework.Animation thisAnim in thisAnims)
{
bool found = false;
foreach (OpenSim.Framework.Animation otherAnim in otherAnims)
{
if (thisAnim.Equals(otherAnim))
{
found = true;
break;
}
}
if (!found)
{
// If anything is not in the other list, these are not equal
return false;
}
}
// Found everything in the other list. Since lists are equal length, they must be equal.
return true;
}
}
return false;
}
// Don't know what was passed, but the base system will figure it out for me.
return base.Equals(obj);
}
public void FromArray(OpenSim.Framework.Animation[] theArray)
{
foreach (OpenSim.Framework.Animation anim in theArray)
m_animations.Add(anim);
}
public void FromOSDArray(OSDArray pArray)
{
this.Clear();
if (pArray.Count >= 1)
{
m_defaultAnimation = new OpenSim.Framework.Animation((OSDMap)pArray[0]);
}
if (pArray.Count >= 2)
{
m_implicitDefaultAnimation = new OpenSim.Framework.Animation((OSDMap)pArray[1]);
}
for (int ii = 2; ii < pArray.Count; ii++)
{
m_animations.Add(new OpenSim.Framework.Animation((OSDMap)pArray[ii]));
}
}
public void GetArrays(out UUID[] animIDs, out int[] sequenceNums, out UUID[] objectIDs)
{
m_AnimationsLock.AcquireReaderLock(-1);
try
{
int defaultSize = 0;
if (m_defaultAnimation.AnimID != UUID.Zero)
defaultSize++;
animIDs = new UUID[m_animations.Count + defaultSize];
sequenceNums = new int[m_animations.Count + defaultSize];
objectIDs = new UUID[m_animations.Count + defaultSize];
if (m_defaultAnimation.AnimID != UUID.Zero)
{
animIDs[0] = m_defaultAnimation.AnimID;
sequenceNums[0] = m_defaultAnimation.SequenceNum;
objectIDs[0] = m_defaultAnimation.ObjectID;
}
for (int i = 0; i < m_animations.Count; ++i)
{
animIDs[i + defaultSize] = m_animations[i].AnimID;
sequenceNums[i + defaultSize] = m_animations[i].SequenceNum;
objectIDs[i + defaultSize] = m_animations[i].ObjectID;
}
}
finally
{
m_AnimationsLock.ReleaseReaderLock();
}
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public bool HasAnimation(UUID animID)
{
if (m_defaultAnimation.AnimID == animID)
return true;
m_AnimationsLock.AcquireReaderLock(-1);
try
{
for (int i = 0; i < m_animations.Count; ++i)
{
if (m_animations[i].AnimID == animID)
return true;
}
}
finally
{
m_AnimationsLock.ReleaseReaderLock();
}
return false;
}
/// <summary>
/// Remove the specified animation
/// </summary>
/// <param name='animID'></param>
/// <param name='allowNoDefault'>
/// If true, then the default animation can be entirely removed.
/// If false, then removing the default animation will reset it to the simulator default (currently STAND).
/// </param>
public bool Remove(UUID animID, bool allowNoDefault)
{
m_AnimationsLock.AcquireWriterLock(-1);
try
{
if (m_defaultAnimation.AnimID == animID)
{
if (allowNoDefault)
m_defaultAnimation = new OpenSim.Framework.Animation(UUID.Zero, 1, UUID.Zero);
else
ResetDefaultAnimation();
}
else if (HasAnimation(animID))
{
for (int i = 0; i < m_animations.Count; i++)
{
if (m_animations[i].AnimID == animID)
{
m_animations.RemoveAt(i);
return true;
}
}
}
}
finally
{
m_AnimationsLock.ReleaseWriterLock();
}
return false;
}
/// <summary>
/// The default animation is reserved for "main" animations
/// that are mutually exclusive, e.g. flying and sitting.
/// </summary>
public bool SetDefaultAnimation(UUID animID, int sequenceNum, UUID objectID)
{
if (m_defaultAnimation.AnimID != animID)
{
m_defaultAnimation = new OpenSim.Framework.Animation(animID, sequenceNum, objectID);
m_implicitDefaultAnimation = m_defaultAnimation;
return true;
}
return false;
}
// Called from serialization only
public void SetImplicitDefaultAnimation(UUID animID, int sequenceNum, UUID objectID)
{
m_implicitDefaultAnimation = new OpenSim.Framework.Animation(animID, sequenceNum, objectID);
}
public OpenSim.Framework.Animation[] ToArray()
{
OpenSim.Framework.Animation[] theArray = new OpenSim.Framework.Animation[m_animations.Count];
uint i = 0;
try
{
foreach (OpenSim.Framework.Animation anim in m_animations)
theArray[i++] = anim;
}
catch
{
/* S%^t happens. Ignore. */
}
return theArray;
}
// Create representation of this AnimationSet as an OSDArray.
// First two entries in the array are the default and implicitDefault animations
// followed by the other animations.
public OSDArray ToOSDArray()
{
OSDArray ret = new OSDArray();
ret.Add(DefaultAnimation.PackUpdateMessage());
ret.Add(ImplicitDefaultAnimation.PackUpdateMessage());
foreach (OpenSim.Framework.Animation anim in m_animations)
ret.Add(anim.PackUpdateMessage());
return ret;
}
public override string ToString()
{
StringBuilder buff = new StringBuilder();
buff.Append("dflt=");
buff.Append(DefaultAnimation.ToString());
buff.Append(",iDflt=");
if (DefaultAnimation.Equals(ImplicitDefaultAnimation))
buff.Append("same");
else
buff.Append(ImplicitDefaultAnimation.ToString());
if (m_animations.Count > 0)
{
buff.Append(",anims=");
bool firstTime = true;
foreach (OpenSim.Framework.Animation anim in m_animations)
{
if (!firstTime)
buff.Append(",");
buff.Append("<");
buff.Append(anim.ToString());
buff.Append(">");
firstTime = false;
}
}
return buff.ToString();
}
/// <summary>
/// Set the animation as the default animation if it's known
/// </summary>
public bool TrySetDefaultAnimation(string anim, int sequenceNum, UUID objectID)
{
// m_log.DebugFormat(
// "[ANIMATION SET]: Setting default animation {0}, sequence number {1}, object id {2}",
// anim, sequenceNum, objectID);
if (DefaultAvatarAnimations.AnimsUUID.ContainsKey(anim))
{
return SetDefaultAnimation(DefaultAvatarAnimations.AnimsUUID[anim], sequenceNum, objectID);
}
return false;
}
protected bool ResetDefaultAnimation()
{
return TrySetDefaultAnimation("STAND", 1, UUID.Zero);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Threading;
using Orleans.AzureUtils;
using Orleans.Runtime.Configuration;
using System.Threading.Tasks;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Wrapper class for an Orleans silo running in the current host process.
/// </summary>
public class AzureSilo
{
/// <summary>
/// Amount of time to pause before retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 5 seconds.
/// </summary>
public TimeSpan StartupRetryPause { get; set; }
/// <summary>
/// Number of times to retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 120 times.
/// </summary>
public int MaxRetries { get; set; }
/// <summary>
/// The name of the configuration key value for locating the DataConnectionString setting from the Azure configuration for this role.
/// Defaults to <c>DataConnectionString</c>
/// </summary>
public string DataConnectionConfigurationSettingName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansSiloEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansSiloEndpoint</c>
/// </summary>
public string SiloEndpointConfigurationKeyName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansProxyEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansProxyEndpoint</c>
/// </summary>
public string ProxyEndpointConfigurationKeyName { get; set; }
private SiloHost host;
private OrleansSiloInstanceManager siloInstanceManager;
private SiloInstanceTableEntry myEntry;
private readonly Logger logger;
private readonly IServiceRuntimeWrapper serviceRuntimeWrapper;
/// <summary>
/// Constructor
/// </summary>
public AzureSilo()
: this(new ServiceRuntimeWrapper())
{
}
internal AzureSilo(IServiceRuntimeWrapper serviceRuntimeWrapper)
{
this.serviceRuntimeWrapper = serviceRuntimeWrapper;
DataConnectionConfigurationSettingName = AzureConstants.DataConnectionConfigurationSettingName;
SiloEndpointConfigurationKeyName = AzureConstants.SiloEndpointConfigurationKeyName;
ProxyEndpointConfigurationKeyName = AzureConstants.ProxyEndpointConfigurationKeyName;
StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
logger = LogManager.GetLogger("OrleansAzureSilo", LoggerType.Runtime);
}
/// <summary>
/// Async method to validate specific cluster configuration
/// </summary>
/// <param name="config"></param>
/// <returns>Task object of boolean type for this async method </returns>
public async Task<bool> ValidateConfiguration(ClusterConfiguration config)
{
if (config.Globals.LivenessType == GlobalConfiguration.LivenessProviderType.AzureTable)
{
string deploymentId = config.Globals.DeploymentId ?? serviceRuntimeWrapper.DeploymentId;
string connectionString = config.Globals.DataConnectionString ??
serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
var manager = siloInstanceManager ?? await OrleansSiloInstanceManager.GetManager(deploymentId, connectionString);
var instances = await manager.DumpSiloInstanceTable();
logger.Verbose(instances);
}
catch (Exception exc)
{
var error = String.Format("Connecting to the storage table has failed with {0}", LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error(ErrorCode.AzureTable_34, error, exc);
return false;
}
}
return true;
}
/// <summary>
/// Default cluster configuration
/// </summary>
/// <returns>Default ClusterConfiguration </returns>
public static ClusterConfiguration DefaultConfiguration()
{
return DefaultConfiguration(new ServiceRuntimeWrapper());
}
internal static ClusterConfiguration DefaultConfiguration(IServiceRuntimeWrapper serviceRuntimeWrapper)
{
var config = new ClusterConfiguration();
config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable;
config.Globals.DeploymentId = serviceRuntimeWrapper.DeploymentId;
try
{
config.Globals.DataConnectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(AzureConstants.DataConnectionConfigurationSettingName);
}
catch (Exception exc)
{
if (exc.GetType().Name.Contains("RoleEnvironmentException"))
{
config.Globals.DataConnectionString = null;
}
else
{
throw;
}
}
return config;
}
#region Azure RoleEntryPoint methods
/// <summary>
/// Initialize this Orleans silo for execution. Config data will be read from silo config file as normal
/// </summary>
/// <param name="deploymentId">Azure DeploymentId this silo is running under. If null, defaults to the value from the configuration.</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(string deploymentId = null, string connectionString = null)
{
return Start(null, deploymentId, connectionString);
}
/// <summary>
/// Initialize this Orleans silo for execution
/// </summary>
/// <param name="config">Use the specified config data.</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(ClusterConfiguration config, string connectionString = null)
{
if (config == null)
throw new ArgumentNullException(nameof(config));
return Start(config, null, connectionString);
}
/// <summary>
/// Initialize this Orleans silo for execution with the specified Azure deploymentId
/// </summary>
/// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
/// <param name="deploymentId">Azure DeploymentId this silo is running under</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> if the silo startup was successful</returns>
internal bool Start(ClusterConfiguration config, string deploymentId, string connectionString)
{
if (config != null && deploymentId != null)
throw new ArgumentException("Cannot use config and deploymentId on the same time");
// Program ident
Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);
// Read endpoint info for this instance from Azure config
string instanceName = serviceRuntimeWrapper.InstanceName;
// Configure this Orleans silo instance
if (config == null)
{
host = new SiloHost(instanceName);
host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations
}
else
{
host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
}
IPEndPoint myEndpoint = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName);
IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName);
host.SetSiloType(Silo.SiloType.Secondary);
int generation = SiloAddress.AllocateNewGeneration();
// Bootstrap this Orleans silo instance
// If deploymentId was not direclty provided, take the value in the config. If it is not
// in the config too, just take the DeploymentId from Azure
if (deploymentId == null)
deploymentId = string.IsNullOrWhiteSpace(host.Config.Globals.DeploymentId)
? serviceRuntimeWrapper.DeploymentId
: host.Config.Globals.DeploymentId;
myEntry = new SiloInstanceTableEntry
{
DeploymentId = deploymentId,
Address = myEndpoint.Address.ToString(),
Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
Generation = generation.ToString(CultureInfo.InvariantCulture),
HostName = host.Config.GetOrCreateNodeConfigurationForSilo(host.Name).DNSHostName,
ProxyPort = (proxyEndpoint != null ? proxyEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture),
RoleName = serviceRuntimeWrapper.RoleName,
SiloName = instanceName,
UpdateZone = serviceRuntimeWrapper.UpdateDomain.ToString(CultureInfo.InvariantCulture),
FaultZone = serviceRuntimeWrapper.FaultDomain.ToString(CultureInfo.InvariantCulture),
StartTime = LogFormatter.PrintDate(DateTime.UtcNow),
PartitionKey = deploymentId,
RowKey = myEndpoint.Address + "-" + myEndpoint.Port + "-" + generation
};
if (connectionString == null)
connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
siloInstanceManager = OrleansSiloInstanceManager.GetManager(
deploymentId, connectionString).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result;
}
catch (Exception exc)
{
var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}",
LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error(ErrorCode.AzureTable_34, error, exc);
throw new OrleansException(error, exc);
}
// Always use Azure table for membership when running silo in Azure
host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
if (host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified ||
host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain)
{
host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
}
host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount);
siloInstanceManager.RegisterSiloInstance(myEntry);
// Initialize this Orleans silo instance
host.SetDeploymentId(deploymentId, connectionString);
host.SetSiloEndpoint(myEndpoint, generation);
host.SetProxyEndpoint(proxyEndpoint);
host.InitializeOrleansSilo();
return StartSilo();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown.
/// </summary>
public void Run()
{
RunImpl();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
public void Run(CancellationToken cancellationToken)
{
RunImpl(cancellationToken);
}
/// <summary>
/// Stop this Orleans silo executing.
/// </summary>
public void Stop()
{
logger.Info(ErrorCode.Runtime_Error_100290, "Stopping {0}", this.GetType().FullName);
serviceRuntimeWrapper.UnsubscribeFromStoppingNotification(this, HandleAzureRoleStopping);
host.ShutdownOrleansSilo();
logger.Info(ErrorCode.Runtime_Error_100291, "Orleans silo '{0}' shutdown.", host.Name);
}
#endregion
private bool StartSilo()
{
logger.Info(ErrorCode.Runtime_Error_100292, "Starting Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
bool ok = host.StartOrleansSilo();
if (ok)
logger.Info(ErrorCode.Runtime_Error_100293, "Successfully started Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
else
logger.Error(ErrorCode.Runtime_Error_100285, string.Format("Failed to start Orleans silo '{0}' as a {1} node.", host.Name, host.Type));
return ok;
}
private void HandleAzureRoleStopping(object sender, object e)
{
// Try to perform gracefull shutdown of Silo when we detect Azure role instance is being stopped
logger.Info(ErrorCode.SiloStopping, "HandleAzureRoleStopping - starting to shutdown silo");
host.ShutdownOrleansSilo();
}
/// <summary>
/// Run method helper.
/// </summary>
/// <remarks>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
/// <param name="cancellationToken">Optional cancellation token.</param>
private void RunImpl(CancellationToken? cancellationToken = null)
{
logger.Info(ErrorCode.Runtime_Error_100289, "OrleansAzureHost entry point called");
// Hook up to receive notification of Azure role stopping events
serviceRuntimeWrapper.SubscribeForStoppingNotification(this, HandleAzureRoleStopping);
if (host.IsStarted)
{
if (cancellationToken.HasValue)
host.WaitForOrleansSiloShutdown(cancellationToken.Value);
else
host.WaitForOrleansSiloShutdown();
}
else
throw new Exception("Silo failed to start correctly - aborting");
}
}
}
| |
using System;
using Csla;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// InvoiceEdit (editable root object).<br/>
/// This is a generated <see cref="InvoiceEdit"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="InvoiceLines"/> of type <see cref="InvoiceLineCollection"/> (1:M relation to <see cref="InvoiceLineItem"/>)
/// </remarks>
[Serializable]
public partial class InvoiceEdit : BusinessBase<InvoiceEdit>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="InvoiceId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<Guid> InvoiceIdProperty = RegisterProperty<Guid>(p => p.InvoiceId, "Invoice Id");
/// <summary>
/// The invoice internal identification
/// </summary>
/// <value>The Invoice Id.</value>
public Guid InvoiceId
{
get { return GetProperty(InvoiceIdProperty); }
set { SetProperty(InvoiceIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="InvoiceNumber"/> property.
/// </summary>
public static readonly PropertyInfo<string> InvoiceNumberProperty = RegisterProperty<string>(p => p.InvoiceNumber, "Invoice Number");
/// <summary>
/// The public invoice number
/// </summary>
/// <value>The Invoice Number.</value>
public string InvoiceNumber
{
get { return GetProperty(InvoiceNumberProperty); }
set { SetProperty(InvoiceNumberProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CustomerId"/> property.
/// </summary>
public static readonly PropertyInfo<string> CustomerIdProperty = RegisterProperty<string>(p => p.CustomerId, "Customer Id");
/// <summary>
/// Gets or sets the Customer Id.
/// </summary>
/// <value>The Customer Id.</value>
public string CustomerId
{
get { return GetProperty(CustomerIdProperty); }
set { SetProperty(CustomerIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="InvoiceDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> InvoiceDateProperty = RegisterProperty<SmartDate>(p => p.InvoiceDate, "Invoice Date");
/// <summary>
/// Gets or sets the Invoice Date.
/// </summary>
/// <value>The Invoice Date.</value>
public string InvoiceDate
{
get { return GetPropertyConvert<SmartDate, string>(InvoiceDateProperty); }
set { SetPropertyConvert<SmartDate, string>(InvoiceDateProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="TotalAmount"/> property.
/// </summary>
public static readonly PropertyInfo<decimal> TotalAmountProperty = RegisterProperty<decimal>(p => p.TotalAmount, "Total Amount");
/// <summary>
/// Computed invoice total amount
/// </summary>
/// <value>The Total Amount.</value>
public decimal TotalAmount
{
get { return GetProperty(TotalAmountProperty); }
set { SetProperty(TotalAmountProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Gets the Create Date.
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUser"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> CreateUserProperty = RegisterProperty<int>(p => p.CreateUser, "Create User");
/// <summary>
/// Gets the Create User.
/// </summary>
/// <value>The Create User.</value>
public int CreateUser
{
get { return GetProperty(CreateUserProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Gets the Change Date.
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUser"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> ChangeUserProperty = RegisterProperty<int>(p => p.ChangeUser, "Change User");
/// <summary>
/// Gets the Change User.
/// </summary>
/// <value>The Change User.</value>
public int ChangeUser
{
get { return GetProperty(ChangeUserProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Gets the Row Version.
/// </summary>
/// <value>The Row Version.</value>
public byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
/// <summary>
/// Maintains metadata about child <see cref="InvoiceLines"/> property.
/// </summary>
public static readonly PropertyInfo<InvoiceLineCollection> InvoiceLinesProperty = RegisterProperty<InvoiceLineCollection>(p => p.InvoiceLines, "Invoice Lines", RelationshipTypes.Child);
/// <summary>
/// Gets the Invoice Lines ("parent load" child property).
/// </summary>
/// <value>The Invoice Lines.</value>
public InvoiceLineCollection InvoiceLines
{
get { return GetProperty(InvoiceLinesProperty); }
private set { LoadProperty(InvoiceLinesProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="InvoiceEdit"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="InvoiceEdit"/> object.</returns>
public static InvoiceEdit NewInvoiceEdit()
{
return DataPortal.Create<InvoiceEdit>();
}
/// <summary>
/// Factory method. Loads a <see cref="InvoiceEdit"/> object, based on given parameters.
/// </summary>
/// <param name="invoiceId">The InvoiceId parameter of the InvoiceEdit to fetch.</param>
/// <returns>A reference to the fetched <see cref="InvoiceEdit"/> object.</returns>
public static InvoiceEdit GetInvoiceEdit(Guid invoiceId)
{
return DataPortal.Fetch<InvoiceEdit>(invoiceId);
}
/// <summary>
/// Factory method. Deletes a <see cref="InvoiceEdit"/> object, based on given parameters.
/// </summary>
/// <param name="invoiceId">The InvoiceId of the InvoiceEdit to delete.</param>
public static void DeleteInvoiceEdit(Guid invoiceId)
{
DataPortal.Delete<InvoiceEdit>(invoiceId);
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="InvoiceEdit"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewInvoiceEdit(EventHandler<DataPortalResult<InvoiceEdit>> callback)
{
DataPortal.BeginCreate<InvoiceEdit>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="InvoiceEdit"/> object, based on given parameters.
/// </summary>
/// <param name="invoiceId">The InvoiceId parameter of the InvoiceEdit to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetInvoiceEdit(Guid invoiceId, EventHandler<DataPortalResult<InvoiceEdit>> callback)
{
DataPortal.BeginFetch<InvoiceEdit>(invoiceId, callback);
}
/// <summary>
/// Factory method. Asynchronously deletes a <see cref="InvoiceEdit"/> object, based on given parameters.
/// </summary>
/// <param name="invoiceId">The InvoiceId of the InvoiceEdit to delete.</param>
/// <param name="callback">The completion callback method.</param>
public static void DeleteInvoiceEdit(Guid invoiceId, EventHandler<DataPortalResult<InvoiceEdit>> callback)
{
DataPortal.BeginDelete<InvoiceEdit>(invoiceId, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="InvoiceEdit"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public InvoiceEdit()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="InvoiceEdit"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(InvoiceIdProperty, Guid.NewGuid());
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CreateUserProperty, Security.UserInformation.UserId);
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
LoadProperty(ChangeUserProperty, ReadProperty(CreateUserProperty));
LoadProperty(InvoiceLinesProperty, DataPortal.CreateChild<InvoiceLineCollection>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="InvoiceEdit"/> object from the database, based on given criteria.
/// </summary>
/// <param name="invoiceId">The Invoice Id.</param>
protected void DataPortal_Fetch(Guid invoiceId)
{
var args = new DataPortalHookArgs(invoiceId);
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<IInvoiceEditDal>();
var data = dal.Fetch(invoiceId);
Fetch(data);
FetchChildren(dal);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Loads a <see cref="InvoiceEdit"/> object from the given <see cref="InvoiceEditDto"/>.
/// </summary>
/// <param name="data">The InvoiceEditDto to use.</param>
private void Fetch(InvoiceEditDto data)
{
// Value properties
LoadProperty(InvoiceIdProperty, data.InvoiceId);
LoadProperty(InvoiceNumberProperty, data.InvoiceNumber);
LoadProperty(CustomerIdProperty, data.CustomerId);
LoadProperty(InvoiceDateProperty, data.InvoiceDate);
LoadProperty(CreateDateProperty, data.CreateDate);
LoadProperty(CreateUserProperty, data.CreateUser);
LoadProperty(ChangeDateProperty, data.ChangeDate);
LoadProperty(ChangeUserProperty, data.ChangeUser);
LoadProperty(RowVersionProperty, data.RowVersion);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects from the given DAL provider.
/// </summary>
/// <param name="dal">The DAL provider to use.</param>
private void FetchChildren(IInvoiceEditDal dal)
{
LoadProperty(InvoiceLinesProperty, DataPortal.FetchChild<InvoiceLineCollection>(dal.InvoiceLineCollection));
}
/// <summary>
/// Inserts a new <see cref="InvoiceEdit"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
SimpleAuditTrail();
var dto = new InvoiceEditDto();
dto.InvoiceId = InvoiceId;
dto.InvoiceNumber = InvoiceNumber;
dto.CustomerId = CustomerId;
dto.InvoiceDate = ReadProperty(InvoiceDateProperty);
dto.CreateDate = CreateDate;
dto.CreateUser = CreateUser;
dto.ChangeDate = ChangeDate;
dto.ChangeUser = ChangeUser;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IInvoiceEditDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(RowVersionProperty, resultDto.RowVersion);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="InvoiceEdit"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
SimpleAuditTrail();
var dto = new InvoiceEditDto();
dto.InvoiceId = InvoiceId;
dto.InvoiceNumber = InvoiceNumber;
dto.CustomerId = CustomerId;
dto.InvoiceDate = ReadProperty(InvoiceDateProperty);
dto.ChangeDate = ChangeDate;
dto.ChangeUser = ChangeUser;
dto.RowVersion = RowVersion;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IInvoiceEditDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
LoadProperty(RowVersionProperty, resultDto.RowVersion);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
LoadProperty(ChangeUserProperty, Security.UserInformation.UserId);
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
LoadProperty(CreateUserProperty, ReadProperty(ChangeUserProperty));
}
}
/// <summary>
/// Self deletes the <see cref="InvoiceEdit"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(InvoiceId);
}
/// <summary>
/// Deletes the <see cref="InvoiceEdit"/> object from database.
/// </summary>
/// <param name="invoiceId">The delete criteria.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(Guid invoiceId)
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IInvoiceEditDal>();
using (BypassPropertyChecks)
{
dal.Delete(invoiceId);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Party Consent Feed
///<para>SObject Name: PartyConsentFeed</para>
///<para>Custom Object: False</para>
///</summary>
public class SfPartyConsentFeed : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "PartyConsentFeed"; }
}
///<summary>
/// Feed Item ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(false)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: PartyConsent
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfPartyConsent Parent { get; set; }
///<summary>
/// Feed Item Type
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Comment Count
/// <para>Name: CommentCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "commentCount")]
[Updateable(false), Createable(false)]
public int? CommentCount { get; set; }
///<summary>
/// Like Count
/// <para>Name: LikeCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "likeCount")]
[Updateable(false), Createable(false)]
public int? LikeCount { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "title")]
[Updateable(false), Createable(false)]
public string Title { get; set; }
///<summary>
/// Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
[Updateable(false), Createable(false)]
public string Body { get; set; }
///<summary>
/// Link Url
/// <para>Name: LinkUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "linkUrl")]
[Updateable(false), Createable(false)]
public string LinkUrl { get; set; }
///<summary>
/// Is Rich Text
/// <para>Name: IsRichText</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRichText")]
[Updateable(false), Createable(false)]
public bool? IsRichText { get; set; }
///<summary>
/// Related Record ID
/// <para>Name: RelatedRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedRecordId")]
[Updateable(false), Createable(false)]
public string RelatedRecordId { get; set; }
///<summary>
/// InsertedBy ID
/// <para>Name: InsertedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "insertedById")]
[Updateable(false), Createable(false)]
public string InsertedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: InsertedBy</para>
///</summary>
[JsonProperty(PropertyName = "insertedBy")]
[Updateable(false), Createable(false)]
public SfUser InsertedBy { get; set; }
///<summary>
/// Best Comment ID
/// <para>Name: BestCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestCommentId")]
[Updateable(false), Createable(false)]
public string BestCommentId { get; set; }
///<summary>
/// ReferenceTo: FeedComment
/// <para>RelationshipName: BestComment</para>
///</summary>
[JsonProperty(PropertyName = "bestComment")]
[Updateable(false), Createable(false)]
public SfFeedComment BestComment { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementInt321()
{
var test = new VectorGetAndWithElement__GetAndWithElementInt321();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementInt321
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Int32[] values = new Int32[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetInt32();
}
Vector64<Int32> value = Vector64.Create(values[0], values[1]);
bool succeeded = !expectedOutOfRangeException;
try
{
Int32 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Int32.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Int32 insertedValue = TestLibrary.Generator.GetInt32();
try
{
Vector64<Int32> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Int32.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Int32[] values = new Int32[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetInt32();
}
Vector64<Int32> value = Vector64.Create(values[0], values[1]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.GetElement))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Int32)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Int32.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Int32 insertedValue = TestLibrary.Generator.GetInt32();
try
{
object result2 = typeof(Vector64)
.GetMethod(nameof(Vector64.WithElement))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector64<Int32>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Int32.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Int32 result, Int32[] values, [CallerMemberName] string method = "")
{
if (result != values[1])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector64<Int32.GetElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector64<Int32> result, Int32[] values, Int32 insertedValue, [CallerMemberName] string method = "")
{
Int32[] resultElements = new Int32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Int32[] result, Int32[] values, Int32 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 1) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[1] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Int32.WithElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
namespace Microsoft.DotNet.CodeFormatting.Rules
{
[SyntaxRuleOrder(SyntaxRuleOrder.CopyrightHeaderRule)]
internal sealed partial class CopyrightHeaderRule : SyntaxFormattingRule, ISyntaxFormattingRule
{
private abstract class CommonRule
{
/// <summary>
/// This is the normalized copyright header that has no comment delimiters.
/// </summary>
private readonly ImmutableArray<string> _header;
protected CommonRule(ImmutableArray<string> header)
{
_header = header;
}
internal SyntaxNode Process(SyntaxNode syntaxNode)
{
if (_header.IsDefaultOrEmpty)
{
return syntaxNode;
}
if (HasCopyrightHeader(syntaxNode))
return syntaxNode;
return AddCopyrightHeader(syntaxNode);
}
private bool HasCopyrightHeader(SyntaxNode syntaxNode)
{
var existingHeader = GetExistingHeader(syntaxNode.GetLeadingTrivia());
return SequnceStartsWith(_header, existingHeader);
}
private bool SequnceStartsWith(ImmutableArray<string> header, List<string> existingHeader)
{
// Only try if the existing header is at least as long as the new copyright header
if (existingHeader.Count >= header.Count())
{
return !header.Where((headerLine, i) => existingHeader[i] != headerLine).Any();
}
return false;
}
private SyntaxNode AddCopyrightHeader(SyntaxNode syntaxNode)
{
var list = new List<SyntaxTrivia>();
foreach (var headerLine in _header)
{
list.Add(CreateLineComment(headerLine));
list.Add(CreateNewLine());
}
list.Add(CreateNewLine());
var triviaList = RemoveExistingHeader(syntaxNode.GetLeadingTrivia());
var i = 0;
MovePastBlankLines(triviaList, ref i);
while (i < triviaList.Count)
{
list.Add(triviaList[i]);
i++;
}
return syntaxNode.WithLeadingTrivia(CreateTriviaList(list));
}
private List<string> GetExistingHeader(SyntaxTriviaList triviaList)
{
var i = 0;
MovePastBlankLines(triviaList, ref i);
var headerList = new List<string>();
while (i < triviaList.Count && IsLineComment(triviaList[i]))
{
headerList.Add(GetCommentText(triviaList[i].ToFullString()));
i++;
MoveToNextLineOrTrivia(triviaList, ref i);
}
return headerList;
}
/// <summary>
/// Remove any copyright header that already exists.
/// </summary>
private SyntaxTriviaList RemoveExistingHeader(SyntaxTriviaList oldList)
{
var foundHeader = false;
var i = 0;
MovePastBlankLines(oldList, ref i);
while (i < oldList.Count && IsLineComment(oldList[i]))
{
if (oldList[i].ToFullString().IndexOf("copyright", StringComparison.OrdinalIgnoreCase) >= 0)
{
foundHeader = true;
}
i++;
}
if (!foundHeader)
{
return oldList;
}
MovePastBlankLines(oldList, ref i);
return CreateTriviaList(oldList.Skip(i));
}
private void MovePastBlankLines(SyntaxTriviaList list, ref int index)
{
while (index < list.Count && (IsWhitespace(list[index]) || IsNewLine(list[index])))
{
index++;
}
}
private void MoveToNextLineOrTrivia(SyntaxTriviaList list, ref int index)
{
MovePastWhitespaces(list, ref index);
if (index < list.Count && IsNewLine(list[index]))
{
index++;
}
}
private void MovePastWhitespaces(SyntaxTriviaList list, ref int index)
{
while (index < list.Count && IsWhitespace(list[index]))
{
index++;
}
}
protected abstract SyntaxTriviaList CreateTriviaList(IEnumerable<SyntaxTrivia> e);
protected abstract bool IsLineComment(SyntaxTrivia trivia);
protected abstract bool IsWhitespace(SyntaxTrivia trivia);
protected abstract bool IsNewLine(SyntaxTrivia trivia);
protected abstract SyntaxTrivia CreateLineComment(string commentText);
protected abstract SyntaxTrivia CreateNewLine();
}
private readonly Options _options;
private ImmutableArray<string> _cachedHeader;
private ImmutableArray<string> _cachedHeaderSource;
[ImportingConstructor]
internal CopyrightHeaderRule(Options options)
{
_options = options;
}
private ImmutableArray<string> GetHeader()
{
if (_cachedHeaderSource != _options.CopyrightHeader)
{
_cachedHeaderSource = _options.CopyrightHeader;
_cachedHeader = _options.CopyrightHeader.Select(GetCommentText).ToImmutableArray();
}
return _cachedHeader;
}
private static string GetCommentText(string line)
{
if (line.StartsWith("'"))
{
return line.Substring(1).TrimStart();
}
if (line.StartsWith("//"))
{
return line.Substring(2).TrimStart();
}
return line;
}
public override bool SupportsLanguage(string languageName)
{
return languageName == LanguageNames.CSharp || languageName == LanguageNames.VisualBasic;
}
public override SyntaxNode ProcessCSharp(SyntaxNode syntaxNode)
{
return (new CSharpRule(GetHeader())).Process(syntaxNode);
}
public override SyntaxNode ProcessVisualBasic(SyntaxNode syntaxNode)
{
return (new VisualBasicRule(GetHeader())).Process(syntaxNode);
}
}
}
| |
// <copyright file="PrintOptions.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
namespace OpenQA.Selenium
{
/// <summary>
/// Represents the orientation of the page in the printed document.
/// </summary>
public enum PrintOrientation
{
/// <summary>
/// Print the document in portrait mode.
/// </summary>
Portrait,
/// <summary>
/// Print the document in landscape mode.
/// </summary>
Landscape
}
/// <summary>
/// Represents the options to send for printing a page.
/// </summary>
public class PrintOptions
{
private const double DefaultMarginSize = 1.0;
private const double DefaultPageHeight = 21.59;
private const double DefaultPageWidth = 27.94;
private const double CentimetersPerInch = 2.54;
private PrintOrientation orientation = PrintOrientation.Portrait;
private double scale = 1.0;
private bool background = false;
private bool shrinkToFit = true;
private PageSize pageSize = new PageSize();
private Margins margins = new Margins();
private HashSet<object> pageRanges = new HashSet<object>();
/// <summary>
/// Gets or sets the orientation of the pages in the printed document.
/// </summary>
public PrintOrientation Orientation
{
get { return orientation; }
set { orientation = value; }
}
/// <summary>
/// Gets or sets the amount which the printed content is zoomed. Valid values are 0.1 to 2.0.
/// </summary>
public double ScaleFactor
{
get { return scale; }
set
{
if (value < 0.1 || value > 2.0)
{
throw new ArgumentException("Scale factor must be between 0.1 and 2.0.");
}
scale = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether to print background images in the printed document.
/// </summary>
public bool OutputBackgroundImages
{
get { return background; }
set { background = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to shrink the content to fit the printed page size.
/// </summary>
public bool ShrinkToFit
{
get { return shrinkToFit; }
set { shrinkToFit = value; }
}
/// <summary>
/// Gets the dimensions for each page in the printed document.
/// </summary>
public PageSize PageDimensions
{
get { return pageSize; }
}
/// <summary>
/// Gets the margins for each page in the doucment.
/// </summary>
public Margins PageMargins
{
get { return margins; }
}
/// <summary>
/// Adds a page to the list of pages to be included in the document.
/// </summary>
/// <param name="pageNumber">The page number to be included in the document.</param>
public void AddPageToPrint(int pageNumber)
{
if (pageNumber < 0)
{
throw new ArgumentException("Page number must be greater than or equal to zero");
}
if (this.pageRanges.Contains(pageNumber))
{
throw new ArgumentException("Cannot add the same page number twice");
}
this.pageRanges.Add(pageNumber);
}
/// <summary>
/// Adds a range of pages to be included in the document.
/// </summary>
/// <param name="pageRange">A string of the form "x-y" representing the page numbers to include.</param>
public void AddPageRangeToPrint(string pageRange)
{
if (string.IsNullOrEmpty(pageRange))
{
throw new ArgumentException("Page range cannot be null or the empty string");
}
if (this.pageRanges.Contains(pageRange))
{
throw new ArgumentException("Cannot add the same page range twice");
}
string[] pageRangeParts = pageRange.Trim().Split('-');
if (pageRangeParts.Length > 2)
{
throw new ArgumentException("Page range cannot have multiple separators");
}
int startPage = ParsePageRangePart(pageRangeParts[0], 1);
if (startPage < 1)
{
throw new ArgumentException("Start of a page range must be greater than or equal to 1");
}
if (pageRangeParts.Length == 2)
{
int endPage = ParsePageRangePart(pageRangeParts[1], int.MaxValue);
if (endPage < startPage)
{
throw new ArgumentException("End of a page range must be greater than or equal to the start of the page range");
}
}
this.pageRanges.Add(pageRange);
}
internal Dictionary<string, object> ToDictionary()
{
Dictionary<string, object> toReturn = new Dictionary<string, object>();
if (this.orientation != PrintOrientation.Portrait)
{
toReturn["orientation"] = this.orientation.ToString().ToLowerInvariant();
}
if (this.scale != 1.0)
{
toReturn["scale"] = this.scale;
}
if (this.background)
{
toReturn["background"] = this.background;
}
if (!this.shrinkToFit)
{
toReturn["shrinkToFit"] = this.shrinkToFit;
}
if (this.pageSize.Height != DefaultPageHeight || this.pageSize.Width != DefaultPageWidth)
{
Dictionary<string, object> pageSizeDictionary = new Dictionary<string, object>();
pageSizeDictionary["width"] = this.pageSize.Width;
pageSizeDictionary["height"] = this.pageSize.Height;
toReturn["page"] = pageSizeDictionary;
}
if (this.margins.Top != DefaultMarginSize || this.margins.Bottom != DefaultMarginSize || this.margins.Left != DefaultMarginSize || this.margins.Right != DefaultMarginSize)
{
Dictionary<string, object> marginsDictionary = new Dictionary<string, object>();
marginsDictionary["top"] = this.margins.Top;
marginsDictionary["bottom"] = this.margins.Bottom;
marginsDictionary["left"] = this.margins.Left;
marginsDictionary["right"] = this.margins.Right;
toReturn["margin"] = marginsDictionary;
}
if (this.pageRanges.Count > 0)
{
toReturn["pageRanges"] = new List<object>(this.pageRanges);
}
return toReturn;
}
private static int ParsePageRangePart(string pageRangePart, int defaultValue)
{
pageRangePart = pageRangePart.Trim();
int pageRangePartValue = defaultValue;
if (!string.IsNullOrEmpty(pageRangePart))
{
if (!int.TryParse(pageRangePart, NumberStyles.Integer, CultureInfo.InvariantCulture, out pageRangePartValue))
{
throw new ArgumentException("Parts of a page range must be an empty string or an integer");
}
}
return pageRangePartValue;
}
public class PageSize
{
private double height = DefaultPageHeight;
private double width = DefaultPageWidth;
/// <summary>
/// Gets or sets the height of each page in centimeters.
/// </summary>
public double Height
{
get { return height; }
set
{
if (value < 0)
{
throw new ArgumentException("Height must be greater than or equal to zero.");
}
height = value;
}
}
/// <summary>
/// Gets or sets the width of each page in centimeters.
/// </summary>
public double Width
{
get { return width; }
set
{
if (value < 0)
{
throw new ArgumentException("Width must be greater than or equal to zero.");
}
width = value;
}
}
/// <summary>
/// Gets or sets the height of each page in inches.
/// </summary>
public double HeightInInches
{
get { return Height / CentimetersPerInch; }
set { Height = value * CentimetersPerInch; }
}
/// <summary>
/// Gets or sets the width of each page in inches.
/// </summary>
public double WidthInInches
{
get { return Width / CentimetersPerInch; }
set { Width = value * CentimetersPerInch; }
}
}
public class Margins
{
private double top = DefaultMarginSize;
private double bottom = DefaultMarginSize;
private double left = DefaultMarginSize;
private double right = DefaultMarginSize;
public double Top
{
get { return top; }
set
{
if (value < 0)
{
throw new ArgumentException("Top margin must be greater than or equal to zero.");
}
top = value;
}
}
public double Bottom
{
get { return bottom; }
set
{
if (value < 0)
{
throw new ArgumentException("Bottom margin must be greater than or equal to zero.");
}
bottom = value;
}
}
public double Left
{
get { return left; }
set
{
if (value < 0)
{
throw new ArgumentException("Left margin must be greater than or equal to zero.");
}
left = value;
}
}
public double Right
{
get { return right; }
set
{
if (value < 0)
{
throw new ArgumentException("Right margin must be greater than or equal to zero.");
}
right = value;
}
}
}
}
}
| |
// 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.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup
{
internal partial class EventHookupCommandHandler : ICommandHandler<TabKeyCommandArgs>
{
public void ExecuteCommand(TabKeyCommandArgs args, Action nextHandler)
{
AssertIsForeground();
if (!args.SubjectBuffer.GetOption(InternalFeatureOnOffOptions.EventHookup))
{
nextHandler();
return;
}
if (EventHookupSessionManager.CurrentSession == null)
{
nextHandler();
return;
}
// Handling tab is currently uncancellable.
HandleTabWorker(args.TextView, args.SubjectBuffer, nextHandler, CancellationToken.None);
}
public CommandState GetCommandState(TabKeyCommandArgs args, Func<CommandState> nextHandler)
{
AssertIsForeground();
if (EventHookupSessionManager.CurrentSession != null)
{
return CommandState.Available;
}
else
{
return nextHandler();
}
}
private void HandleTabWorker(ITextView textView, ITextBuffer subjectBuffer, Action nextHandler, CancellationToken cancellationToken)
{
AssertIsForeground();
// For test purposes only!
if (EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex != null)
{
try
{
EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex.ReleaseMutex();
}
catch (ApplicationException)
{
}
}
// Blocking wait (if necessary) to determine whether to consume the tab and
// generate the event handler.
EventHookupSessionManager.CurrentSession.GetEventNameTask.Wait(cancellationToken);
string eventHandlerMethodName = null;
if (EventHookupSessionManager.CurrentSession.GetEventNameTask.Status == TaskStatus.RanToCompletion)
{
eventHandlerMethodName = EventHookupSessionManager.CurrentSession.GetEventNameTask.WaitAndGetResult(cancellationToken);
}
if (eventHandlerMethodName == null ||
EventHookupSessionManager.CurrentSession.TextView != textView)
{
nextHandler();
EventHookupSessionManager.CancelAndDismissExistingSessions();
return;
}
// If QuickInfoSession is null, then Tab was pressed before the background task
// finished (that is, the Wait call above actually needed to wait). Since we know an
// event hookup was found, we should set everything up now because the background task
// will not have a chance to set things up until after this Tab has been handled, and
// by then it's too late. When the background task alerts that it found an event hookup
// nothing will change because QuickInfoSession will already be set.
EventHookupSessionManager.EventHookupFoundInSession(EventHookupSessionManager.CurrentSession);
// This tab means we should generate the event handler method. Begin the code
// generation process.
GenerateAndAddEventHandler(textView, subjectBuffer, eventHandlerMethodName, nextHandler, cancellationToken);
}
private void GenerateAndAddEventHandler(ITextView textView, ITextBuffer subjectBuffer, string eventHandlerMethodName, Action nextHandler, CancellationToken cancellationToken)
{
AssertIsForeground();
using (Logger.LogBlock(FunctionId.EventHookup_Generate_Handler, cancellationToken))
{
EventHookupSessionManager.CancelAndDismissExistingSessions();
var workspace = textView.TextSnapshot.TextBuffer.GetWorkspace();
if (workspace == null)
{
nextHandler();
EventHookupSessionManager.CancelAndDismissExistingSessions();
return;
}
Document document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
Contract.Fail("Event Hookup could not find the document for the IBufferView.");
}
var position = textView.GetCaretPoint(subjectBuffer).Value.Position;
int plusEqualTokenEndPosition;
var solutionWithEventHandler = CreateSolutionWithEventHandler(
document,
eventHandlerMethodName,
position,
out plusEqualTokenEndPosition,
cancellationToken);
if (solutionWithEventHandler == null)
{
Contract.Fail("Event Hookup could not create solution with event handler.");
}
// The new solution is created, so start user observable changes
if (!workspace.TryApplyChanges(solutionWithEventHandler))
{
Contract.Fail("Event Hookup could not update the solution.");
}
// The += token will not move during this process, so it is safe to use that
// position as a location from which to find the identifier we're renaming.
BeginInlineRename(workspace, textView, subjectBuffer, plusEqualTokenEndPosition, cancellationToken);
}
}
private Solution CreateSolutionWithEventHandler(
Document document,
string eventHandlerMethodName,
int position,
out int plusEqualTokenEndPosition,
CancellationToken cancellationToken)
{
AssertIsForeground();
// Mark the += token with an annotation so we can find it after formatting
var plusEqualsTokenAnnotation = new SyntaxAnnotation();
var documentWithNameAndAnnotationsAdded = AddMethodNameAndAnnotationsToSolution(document, eventHandlerMethodName, position, plusEqualsTokenAnnotation, cancellationToken);
var semanticDocument = SemanticDocument.CreateAsync(documentWithNameAndAnnotationsAdded, cancellationToken).WaitAndGetResult(cancellationToken);
var updatedRoot = AddGeneratedHandlerMethodToSolution(semanticDocument, eventHandlerMethodName, plusEqualsTokenAnnotation, cancellationToken);
if (updatedRoot == null)
{
plusEqualTokenEndPosition = 0;
return null;
}
var simplifiedDocument = Simplifier.ReduceAsync(documentWithNameAndAnnotationsAdded.WithSyntaxRoot(updatedRoot), Simplifier.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
var formattedDocument = Formatter.FormatAsync(simplifiedDocument, Formatter.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
plusEqualTokenEndPosition = formattedDocument
.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken)
.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation)
.Single().Span.End;
return document.Project.Solution.WithDocumentText(formattedDocument.Id, formattedDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken));
}
private Document AddMethodNameAndAnnotationsToSolution(
Document document,
string eventHandlerMethodName,
int position,
SyntaxAnnotation plusEqualsTokenAnnotation,
CancellationToken cancellationToken)
{
// First find the event hookup to determine if we are in a static context.
var syntaxTree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var plusEqualsToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
var eventHookupExpression = plusEqualsToken.GetAncestor<AssignmentExpressionSyntax>();
var textToInsert = eventHandlerMethodName + ";";
if (!eventHookupExpression.IsInStaticContext())
{
// This will be simplified later if it's not needed.
textToInsert = "this." + textToInsert;
}
// Next, perform a textual insertion of the event handler method name.
var textChange = new TextChange(new TextSpan(position, 0), textToInsert);
var newText = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).WithChanges(textChange);
var documentWithNameAdded = document.WithText(newText);
// Now find the event hookup again to add the appropriate annotations.
syntaxTree = documentWithNameAdded.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
plusEqualsToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
eventHookupExpression = plusEqualsToken.GetAncestor<AssignmentExpressionSyntax>();
var updatedEventHookupExpression = eventHookupExpression
.ReplaceToken(plusEqualsToken, plusEqualsToken.WithAdditionalAnnotations(plusEqualsTokenAnnotation))
.WithRight(eventHookupExpression.Right.WithAdditionalAnnotations(Simplifier.Annotation))
.WithAdditionalAnnotations(Formatter.Annotation);
var rootWithUpdatedEventHookupExpression = syntaxTree.GetRoot(cancellationToken).ReplaceNode(eventHookupExpression, updatedEventHookupExpression);
return documentWithNameAdded.WithSyntaxRoot(rootWithUpdatedEventHookupExpression);
}
private SyntaxNode AddGeneratedHandlerMethodToSolution(
SemanticDocument document,
string eventHandlerMethodName,
SyntaxAnnotation plusEqualsTokenAnnotation,
CancellationToken cancellationToken)
{
var root = document.Root as SyntaxNode;
var eventHookupExpression = root.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation).Single().AsToken().GetAncestor<AssignmentExpressionSyntax>();
var generatedMethodSymbol = GetMethodSymbol(document, eventHandlerMethodName, eventHookupExpression, cancellationToken);
if (generatedMethodSymbol == null)
{
return null;
}
var typeDecl = eventHookupExpression.GetAncestor<TypeDeclarationSyntax>();
var typeDeclWithMethodAdded = CodeGenerator.AddMethodDeclaration(typeDecl, generatedMethodSymbol, document.Project.Solution.Workspace, new CodeGenerationOptions(afterThisLocation: eventHookupExpression.GetLocation()));
return root.ReplaceNode(typeDecl, typeDeclWithMethodAdded);
}
private IMethodSymbol GetMethodSymbol(
SemanticDocument document,
string eventHandlerMethodName,
AssignmentExpressionSyntax eventHookupExpression,
CancellationToken cancellationToken)
{
var semanticModel = document.SemanticModel as SemanticModel;
var symbolInfo = semanticModel.GetSymbolInfo(eventHookupExpression.Left, cancellationToken);
var symbol = symbolInfo.Symbol;
if (symbol == null || symbol.Kind != SymbolKind.Event)
{
return null;
}
var typeInference = document.Project.LanguageServices.GetService<ITypeInferenceService>();
var delegateType = typeInference.InferDelegateType(semanticModel, eventHookupExpression.Right, cancellationToken);
if (delegateType == null || delegateType.DelegateInvokeMethod == null)
{
return null;
}
var syntaxFactory = document.Project.LanguageServices.GetService<SyntaxGenerator>();
return CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: null,
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isStatic: eventHookupExpression.IsInStaticContext()),
returnType: delegateType.DelegateInvokeMethod.ReturnType,
explicitInterfaceSymbol: null,
name: eventHandlerMethodName,
typeParameters: null,
parameters: delegateType.DelegateInvokeMethod.Parameters,
statements: new List<SyntaxNode>
{
CodeGenerationHelpers.GenerateThrowStatement(syntaxFactory, document, "System.NotImplementedException", cancellationToken)
});
}
private void BeginInlineRename(Workspace workspace, ITextView textView, ITextBuffer subjectBuffer, int plusEqualTokenEndPosition, CancellationToken cancellationToken)
{
AssertIsForeground();
if (_inlineRenameService.ActiveSession == null)
{
var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
// In the middle of a user action, cannot cancel.
var syntaxTree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var token = syntaxTree.FindTokenOnRightOfPosition(plusEqualTokenEndPosition, cancellationToken);
var editSpan = token.Span;
var memberAccessExpression = token.GetAncestor<MemberAccessExpressionSyntax>();
if (memberAccessExpression != null)
{
// the event hookup might look like `MyEvent += this.GeneratedHandlerName;`
editSpan = memberAccessExpression.Name.Span;
}
_inlineRenameService.StartInlineSession(document, editSpan, cancellationToken);
textView.SetSelection(editSpan.ToSnapshotSpan(textView.TextSnapshot));
}
}
}
}
}
| |
// Copyright (c) 2011-2012 Smarkets Limited
//
// 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.Threading;
using IronSmarkets.Data;
using IronSmarkets.Events;
using IronSmarkets.Exceptions;
using IronSmarkets.Messages;
using IronSmarkets.Sessions;
using IronSmarkets.Sockets;
#if NET35
using IronSmarkets.System;
#endif
using PS = IronSmarkets.Proto.Seto;
using PE = IronSmarkets.Proto.Eto;
namespace IronSmarkets.Clients
{
public interface ISmarketsClient :
IDisposable,
IPayloadEvents<PS.Payload>,
IPayloadEndpoint<PS.Payload>,
IQuoteSink
{
string SessionId { get; }
bool IsDisposed { get; }
ulong Login();
ulong Logout();
ulong Ping();
IEventMap EventMap { get; }
IOrderMap OrderMap { get; }
IMarketMap MarketMap { get; }
IContractMap ContractMap { get; }
IResponse<IEventMap> GetEvents(EventQuery query);
IResponse<AccountState> GetAccountState();
IResponse<AccountState> GetAccountState(Uid account);
IResponse<MarketQuotes> GetQuotesByMarket(Uid market);
IResponse<IOrderMap> GetOrders();
IResponse<IOrderMap> GetOrdersByMarket(Uid market);
IResponse<OrderCancelledReason> CancelOrder(Order order);
IResponse<Order> CreateOrder(NewOrder order);
}
public sealed class SmarketsClient : ISmarketsClient
{
private readonly ISession<PS.Payload> _session;
private readonly Receiver<PS.Payload> _receiver;
private readonly EventMap _eventMap = new EventMap();
private readonly OrderMap _orderMap = new OrderMap();
private readonly MarketMap _marketMap = new MarketMap();
private readonly ContractMap _contractMap = new ContractMap();
private readonly IRpcHandler<IEventMap, EventMap> _eventsRequestHandler;
private readonly IRpcHandler<AccountState, object> _accountStateRequestHandler;
private readonly IRpcHandler<MarketQuotes, object> _marketQuotesRequestHandler;
private readonly IRpcHandler<IOrderMap, OrderMap> _ordersForAccountRequestHandler;
private readonly IRpcHandler<IOrderMap, OrderMap> _ordersForMarketRequestHandler;
private readonly IRpcHandler<Order, Tuple<NewOrder, OrderMap>> _orderCreateRequestHandler;
private readonly IRpcHandler<OrderCancelledReason, OrderMap> _orderCancelRequestHandler;
private readonly IAsyncHttpFoundHandler<PS.Events> _httpHandler;
private readonly QuoteHandler<PS.MarketQuotes> _marketQuotesHandler = new MarketQuoteHandler();
private readonly QuoteHandler<PS.ContractQuotes> _contractQuotesHandler = new ContractQuoteHandler();
private int _disposed;
private SmarketsClient(
ISession<PS.Payload> session,
IAsyncHttpFoundHandler<PS.Events> httpHandler)
{
if (session == null)
throw new ArgumentNullException("session cannot be null");
_session = session;
_session.PayloadReceived += (sender, args) =>
OnPayloadReceived(args.Payload);
_session.PayloadSent += (sender, args) =>
OnPayloadSent(args.Payload);
AddPayloadHandler(HandlePayload);
_receiver = new Receiver<PS.Payload>(_session);
_httpHandler = httpHandler;
_eventsRequestHandler = new EventsRequestHandler(this, _httpHandler);
_accountStateRequestHandler = new AccountStateRequestHandler(this);
_marketQuotesRequestHandler = new MarketQuotesRequestHandler(this);
_ordersForAccountRequestHandler = new OrdersForAccountRequestHandler(this);
_ordersForMarketRequestHandler = new OrdersForMarketRequestHandler(this);
_orderCreateRequestHandler = new OrderCreateRequestHandler(this);
_orderCancelRequestHandler = new OrderCancelRequestHandler(this);
}
public static ISmarketsClient Create(IClientSettings settings)
{
return Create(settings, null, null);
}
public static ISmarketsClient Create(
IClientSettings settings,
ISession<PS.Payload> session)
{
return Create(settings, session, null);
}
public static ISmarketsClient Create(
IClientSettings settings,
IAsyncHttpFoundHandler<PS.Events> httpHandler)
{
return Create(settings, null, httpHandler);
}
public static ISmarketsClient Create(
IClientSettings settings,
ISession<PS.Payload> session,
IAsyncHttpFoundHandler<PS.Events> httpHandler)
{
if (session == null)
session = new SeqSession(
new SessionSocket(settings.SocketSettings),
settings.SessionSettings);
if (httpHandler == null)
httpHandler = new HttpFoundHandler<PS.Events>(
settings.HttpRequestTimeout);
var client = new SmarketsClient(session, httpHandler);
httpHandler.SetClient(client);
return client;
}
public string SessionId
{
get
{
return _session.SessionId;
}
}
public bool IsDisposed
{
get
{
return Thread.VolatileRead(ref _disposed) == 1;
}
}
public IEventMap EventMap
{
get
{
return _eventMap;
}
}
public IOrderMap OrderMap
{
get
{
return _orderMap;
}
}
public IMarketMap MarketMap
{
get
{
return _marketMap;
}
}
public IContractMap ContractMap
{
get
{
return _contractMap;
}
}
public event EventHandler<PayloadReceivedEventArgs<PS.Payload>> PayloadReceived;
public event EventHandler<PayloadReceivedEventArgs<PS.Payload>> PayloadSent;
~SmarketsClient()
{
Dispose(false);
}
public void AddPayloadHandler(Predicate<PS.Payload> predicate)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called AddPayloadHandler on disposed object");
_session.AddPayloadHandler(predicate);
}
public void RemovePayloadHandler(Predicate<PS.Payload> predicate)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called RemovePayloadHandler on disposed object");
_session.RemovePayloadHandler(predicate);
}
public void AddMarketQuotesHandler(Uid uid, EventHandler<QuotesReceivedEventArgs<PS.MarketQuotes>> handler)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called AddMarketQuotesHandler on disposed object");
_marketQuotesHandler.AddHandler(uid, handler);
}
public void RemoveMarketQuotesHandler(Uid uid, EventHandler<QuotesReceivedEventArgs<PS.MarketQuotes>> handler)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called RemoveMarketQuotesHandler on disposed object");
_marketQuotesHandler.RemoveHandler(uid, handler);
}
public void AddContractQuotesHandler(Uid uid, EventHandler<QuotesReceivedEventArgs<PS.ContractQuotes>> handler)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called AddContractQuotesHandler on disposed object");
_contractQuotesHandler.AddHandler(uid, handler);
}
public void RemoveContractQuotesHandler(Uid uid, EventHandler<QuotesReceivedEventArgs<PS.ContractQuotes>> handler)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called RemoveContractQuotesHandler on disposed object");
_contractQuotesHandler.RemoveHandler(uid, handler);
}
public void SendPayload(PS.Payload payload)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called SendPayload on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"SendPayload called from receiver thread "
+ "which would result in a deadlock");
_session.SendPayload(payload);
}
public ulong Login()
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called Login on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"Login called from receiver thread "
+ "which would result in a deadlock");
ulong seq = _session.Login();
_receiver.Start();
return seq;
}
public ulong Logout()
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called Logout on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"Logout called from receiver thread "
+ "which would result in a deadlock");
ulong seq = _session.Logout();
_receiver.Stop();
return seq;
}
public ulong Ping()
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called Ping on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"Ping called from receiver thread "
+ "which would result in a deadlock");
var payload = Payloads.Ping();
SendPayload(payload);
return payload.EtoPayload.Seq;
}
public ulong SubscribeMarket(Uid market)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called SubscribeMarket on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"SubscribeMarket called from receiver thread "
+ "which would result in a deadlock");
var payload = Payloads.MarketSubscribe(market);
SendPayload(payload);
return payload.EtoPayload.Seq;
}
public ulong UnsubscribeMarket(Uid market)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called UnsubscribeMarket on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"UnsubscribeMarket called from receiver thread "
+ "which would result in a deadlock");
var payload = Payloads.MarketUnsubscribe(market);
SendPayload(payload);
return payload.EtoPayload.Seq;
}
public IResponse<IEventMap> GetEvents(EventQuery query)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called GetEvents on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"GetEvents called from receiver thread "
+ "which would result in a deadlock");
return _eventsRequestHandler.BeginRequest(
Payloads.EventsRequest(query), _eventMap);
}
public IResponse<AccountState> GetAccountState()
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called GetAccountState on disposed object");
return GetAccountStateInternal(null);
}
public IResponse<AccountState> GetAccountState(Uid account)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called GetAccountState on disposed object");
return GetAccountStateInternal(account);
}
private IResponse<AccountState> GetAccountStateInternal(Uid? account)
{
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"GetAccountState called from receiver thread "
+ "which would result in a deadlock");
return _accountStateRequestHandler.BeginRequest(
Payloads.AccountStateRequest(account), null);
}
public IResponse<MarketQuotes> GetQuotesByMarket(Uid market)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called GetQuotesByMarket on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"GetQuotesByMarket called from receiver thread "
+ "which would result in a deadlock");
return _marketQuotesRequestHandler.BeginRequest(
Payloads.MarketQuotesRequest(market), null);
}
public IResponse<IOrderMap> GetOrders()
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called GetOrdersByAccount on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"GetOrders called from receiver thread "
+ "which would result in a deadlock");
return _ordersForAccountRequestHandler.BeginRequest(
Payloads.OrdersForAccountRequest(), _orderMap);
}
public IResponse<IOrderMap> GetOrdersByMarket(Uid market)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called GetOrdersByMarket on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"GetOrdersByMarket called from receiver thread "
+ "which would result in a deadlock");
return _ordersForMarketRequestHandler.BeginRequest(
Payloads.OrdersForMarketRequest(market), _orderMap);
}
public IResponse<OrderCancelledReason> CancelOrder(Order order)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called CancelOrder on disposed object");
if (!order.Cancellable)
throw new InvalidOperationException(
string.Format(
"Order cannot be cancelled: {0}", order.State.Status));
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"CancelOrder called from receiver thread "
+ "which would result in a deadlock");
return _orderCancelRequestHandler.BeginRequest(
Payloads.OrderCancel(order.Uid), _orderMap);
}
public IResponse<Order> CreateOrder(NewOrder order)
{
if (IsDisposed)
throw new ObjectDisposedException(
"SmarketsClient",
"Called CreateOrder on disposed object");
if (_receiver.IsCurrentThread)
throw new ReceiverDeadlockException(
"CreateOrder called from receiver thread "
+ "which would result in a deadlock");
return _orderCreateRequestHandler.BeginRequest(
Payloads.OrderCreate(order),
new Tuple<NewOrder, OrderMap>(order, _orderMap));
}
private void OnPayloadReceived(PS.Payload payload)
{
EventHandler<PayloadReceivedEventArgs<PS.Payload>> ev = PayloadReceived;
if (ev != null)
ev(this, new PayloadReceivedEventArgs<PS.Payload>(
payload.EtoPayload.Seq,
payload));
}
private void OnPayloadSent(PS.Payload payload)
{
EventHandler<PayloadReceivedEventArgs<PS.Payload>> ev = PayloadSent;
if (ev != null)
ev(this, new PayloadReceivedEventArgs<PS.Payload>(
payload.EtoPayload.Seq,
payload));
}
private bool HandlePayload(PS.Payload payload)
{
switch (payload.Type)
{
case PS.PayloadType.PAYLOADINVALIDREQUEST:
case PS.PayloadType.PAYLOADHTTPFOUND:
_eventsRequestHandler.Handle(payload);
break;
case PS.PayloadType.PAYLOADACCOUNTSTATE:
_accountStateRequestHandler.Handle(payload);
break;
case PS.PayloadType.PAYLOADMARKETQUOTES:
// First, respond to a possible synchronous request
var marketUid = Uid.FromUuid128(payload.MarketQuotes.Market);
_marketQuotesRequestHandler.Handle(payload);
// Dispatch updates to markets in identity map
var marketPair = _marketQuotesHandler.Extract(payload);
Market market;
if (_marketMap.TryGetValue(marketUid, out market))
{
var args = QuoteHandler<PS.MarketQuotes>.PayloadArgs(marketPair, payload);
market.OnMarketQuotesReceived(this, args);
}
// Dispatch updates to all listeners
_marketQuotesHandler.Handle(marketPair, payload);
break;
case PS.PayloadType.PAYLOADCONTRACTQUOTES:
var contractUid = Uid.FromUuid128(payload.ContractQuotes.Contract);
// Dispatch updates to markets in identity map
var contractPair = _contractQuotesHandler.Extract(payload);
Contract contract;
if (_contractMap.TryGetValue(contractUid, out contract))
{
var args = QuoteHandler<PS.ContractQuotes>.PayloadArgs(contractPair, payload);
contract.OnContractQuotesReceived(this, args);
}
// Dispatch to all other listeners
_contractQuotesHandler.Handle(contractPair, payload);
break;
case PS.PayloadType.PAYLOADORDERSFORMARKET:
_ordersForMarketRequestHandler.Handle(payload);
break;
case PS.PayloadType.PAYLOADORDERSFORACCOUNT:
_ordersForAccountRequestHandler.Handle(payload);
break;
case PS.PayloadType.PAYLOADORDERACCEPTED:
case PS.PayloadType.PAYLOADORDERREJECTED:
case PS.PayloadType.PAYLOADORDERINVALID:
_orderCreateRequestHandler.Handle(payload);
break;
case PS.PayloadType.PAYLOADORDEREXECUTED:
var orderUid = Uid.FromUuid128(payload.OrderExecuted.Order);
Order order;
if (_orderMap.TryGetValue(orderUid, out order))
{
order.Update(payload.OrderExecuted);
}
break;
case PS.PayloadType.PAYLOADORDERCANCELLED:
orderUid = Uid.FromUuid128(payload.OrderCancelled.Order);
if (_orderMap.TryGetValue(orderUid, out order))
{
order.Update(payload.OrderCancelled);
}
_orderCancelRequestHandler.Handle(payload);
break;
case PS.PayloadType.PAYLOADORDERCANCELREJECTED:
_orderCancelRequestHandler.Handle(payload);
break;
}
return true;
}
private void Dispose(bool disposing)
{
if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0)
{
if (disposing)
{
var dispSession = _session as IDisposable;
if (dispSession != null)
dispSession.Dispose();
}
}
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using FarseerPhysics.TestBed.Framework;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace FarseerPhysics.TestBed.Tests
{
public class RayCastTest : Test
{
private const int MaxBodies = 256;
private float _angle;
private Body[] _bodies = new Body[MaxBodies];
private int _bodyIndex;
private CircleShape _circle;
private RayCastMode _mode;
private PolygonShape[] _polygons = new PolygonShape[4];
private RayCastTest()
{
{
Vertices vertices = new Vertices(3);
vertices.Add(new Vector2(-0.5f, 0.0f));
vertices.Add(new Vector2(0.5f, 0.0f));
vertices.Add(new Vector2(0.0f, 1.5f));
_polygons[0] = new PolygonShape(vertices, 1);
}
{
Vertices vertices2 = new Vertices(3);
vertices2.Add(new Vector2(-0.1f, 0.0f));
vertices2.Add(new Vector2(0.1f, 0.0f));
vertices2.Add(new Vector2(0.0f, 1.5f));
_polygons[1] = new PolygonShape(vertices2, 1);
}
{
const float w = 1.0f;
float b = w / (2.0f + (float)Math.Sqrt(2.0));
float s = (float)Math.Sqrt(2.0) * b;
Vertices vertices3 = new Vertices(8);
vertices3.Add(new Vector2(0.5f * s, 0.0f));
vertices3.Add(new Vector2(0.5f * w, b));
vertices3.Add(new Vector2(0.5f * w, b + s));
vertices3.Add(new Vector2(0.5f * s, w));
vertices3.Add(new Vector2(-0.5f * s, w));
vertices3.Add(new Vector2(-0.5f * w, b + s));
vertices3.Add(new Vector2(-0.5f * w, b));
vertices3.Add(new Vector2(-0.5f * s, 0.0f));
_polygons[2] = new PolygonShape(vertices3, 1);
}
{
_polygons[3] = new PolygonShape(1);
_polygons[3].SetAsBox(0.5f, 0.5f);
}
{
_circle = new CircleShape(0.5f, 1);
}
_bodyIndex = 0;
_angle = 0.0f;
_mode = RayCastMode.Closest;
}
public override void Keyboard(KeyboardManager keyboardManager)
{
if (keyboardManager.IsNewKeyPress(Keys.D1))
{
Create(0);
}
if (keyboardManager.IsNewKeyPress(Keys.D2))
{
Create(1);
}
if (keyboardManager.IsNewKeyPress(Keys.D3))
{
Create(2);
}
if (keyboardManager.IsNewKeyPress(Keys.D4))
{
Create(3);
}
if (keyboardManager.IsNewKeyPress(Keys.D5))
{
Create(4);
}
if (keyboardManager.IsNewKeyPress(Keys.D))
{
DestroyBody();
}
if (keyboardManager.IsNewKeyPress(Keys.M))
{
switch (_mode)
{
case RayCastMode.Closest:
_mode = RayCastMode.Any;
break;
case RayCastMode.Any:
_mode = RayCastMode.Multiple;
break;
case RayCastMode.Multiple:
_mode = RayCastMode.Closest;
break;
default:
break;
}
}
}
private void DestroyBody()
{
for (int i = 0; i < MaxBodies; ++i)
{
if (_bodies[i] != null)
{
World.RemoveBody(_bodies[i]);
_bodies[i] = null;
return;
}
}
}
public override void Update(GameSettings settings, GameTime gameTime)
{
bool advanceRay = settings.Pause == false || settings.SingleStep;
base.Update(settings, gameTime);
DebugView.DrawString(50, TextLine, "Press 1-5 to drop stuff, m to change the mode");
TextLine += 15;
DebugView.DrawString(50, TextLine, string.Format("Mode = {0}", _mode));
TextLine += 15;
const float l = 11.0f;
Vector2 point1 = new Vector2(0.0f, 10.0f);
Vector2 d = new Vector2(l * (float)Math.Cos(_angle), l * (float)Math.Sin(_angle));
Vector2 point2 = point1 + d;
Vector2 point = Vector2.Zero, normal = Vector2.Zero;
switch (_mode)
{
case RayCastMode.Closest:
bool hitClosest = false;
World.RayCast((f, p, n, fr) =>
{
Body body = f.Body;
if (body.UserData != null)
{
int index = (int)body.UserData;
if (index == 0)
{
// filter
return -1.0f;
}
}
hitClosest = true;
point = p;
normal = n;
return fr;
}, point1, point2);
if (hitClosest)
{
DebugView.BeginCustomDraw();
DebugView.DrawPoint(point, .5f, new Color(0.4f, 0.9f, 0.4f));
DebugView.DrawSegment(point1, point, new Color(0.8f, 0.8f, 0.8f));
Vector2 head = point + 0.5f * normal;
DebugView.DrawSegment(point, head, new Color(0.9f, 0.9f, 0.4f));
DebugView.EndCustomDraw();
}
else
{
DebugView.BeginCustomDraw();
DebugView.DrawSegment(point1, point2, new Color(0.8f, 0.8f, 0.8f));
DebugView.EndCustomDraw();
}
break;
case RayCastMode.Any:
bool hitAny = false;
World.RayCast((f, p, n, fr) =>
{
Body body = f.Body;
if (body.UserData != null)
{
int index = (int)body.UserData;
if (index == 0)
{
// filter
return -1.0f;
}
}
hitAny = true;
point = p;
normal = n;
return 0;
}, point1, point2);
if (hitAny)
{
DebugView.BeginCustomDraw();
DebugView.DrawPoint(point, .5f, new Color(0.4f, 0.9f, 0.4f));
DebugView.DrawSegment(point1, point, new Color(0.8f, 0.8f, 0.8f));
Vector2 head = point + 0.5f * normal;
DebugView.DrawSegment(point, head, new Color(0.9f, 0.9f, 0.4f));
DebugView.EndCustomDraw();
}
else
{
DebugView.BeginCustomDraw();
DebugView.DrawSegment(point1, point2, new Color(0.8f, 0.8f, 0.8f));
DebugView.EndCustomDraw();
}
break;
case RayCastMode.Multiple:
List<Vector2> points = new List<Vector2>();
List<Vector2> normals = new List<Vector2>();
World.RayCast((f, p, n, fr) =>
{
Body body = f.Body;
if (body.UserData != null)
{
int index = (int)body.UserData;
if (index == 0)
{
// filter
return -1.0f;
}
}
points.Add(p);
normals.Add(n);
return 1.0f;
}, point1, point2);
DebugView.BeginCustomDraw();
DebugView.DrawSegment(point1, point2, new Color(0.8f, 0.8f, 0.8f));
for (int i = 0; i < points.Count; i++)
{
DebugView.DrawPoint(points[i], .5f, new Color(0.4f, 0.9f, 0.4f));
DebugView.DrawSegment(point1, points[i], new Color(0.8f, 0.8f, 0.8f));
Vector2 head = points[i] + 0.5f * normals[i];
DebugView.DrawSegment(points[i], head, new Color(0.9f, 0.9f, 0.4f));
}
DebugView.EndCustomDraw();
break;
default:
break;
}
if (advanceRay)
{
_angle += 0.25f * Settings.Pi / 180.0f;
}
}
private void Create(int index)
{
if (_bodies[_bodyIndex] != null)
{
World.RemoveBody(_bodies[_bodyIndex]);
_bodies[_bodyIndex] = null;
}
float x = Rand.RandomFloat(-10.0f, 10.0f);
float y = Rand.RandomFloat(0.0f, 20.0f);
_bodies[_bodyIndex] = BodyFactory.CreateBody(World);
_bodies[_bodyIndex].Position = new Vector2(x, y);
_bodies[_bodyIndex].Rotation = Rand.RandomFloat(-Settings.Pi, Settings.Pi);
_bodies[_bodyIndex].UserData = index;
if (index == 4)
{
_bodies[_bodyIndex].AngularDamping = 0.02f;
}
if (index < 4)
{
Fixture fixture = _bodies[_bodyIndex].CreateFixture(_polygons[index]);
fixture.Friction = 0.3f;
}
else
{
Fixture fixture = _bodies[_bodyIndex].CreateFixture(_circle);
fixture.Friction = 0.3f;
}
_bodyIndex = (_bodyIndex + 1) % MaxBodies;
}
internal static Test Create()
{
return new RayCastTest();
}
#region Nested type: RayCastMode
private enum RayCastMode
{
Closest,
Any,
Multiple,
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure.Management.Insights;
using Microsoft.Azure.Management.Insights.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Insights
{
/// <summary>
/// Operations for managing service diagnostic settings.
/// </summary>
internal partial class ServiceDiagnosticSettingsOperations : IServiceOperations<InsightsManagementClient>, IServiceDiagnosticSettingsOperations
{
/// <summary>
/// Initializes a new instance of the
/// ServiceDiagnosticSettingsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ServiceDiagnosticSettingsOperations(InsightsManagementClient client)
{
this._client = client;
}
private InsightsManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Insights.InsightsManagementClient.
/// </summary>
public InsightsManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Deletes the diagnostic settings for the specified resource.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource identifier of the configuration.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Generic empty response. We only pass it to ensure json error
/// handling
/// </returns>
public async Task<EmptyResponse> DeleteAsync(string resourceUri, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(resourceUri);
url = url + "/providers/microsoft.insights/diagnosticSettings/service";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-07-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
EmptyResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EmptyResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the active diagnostic settings. To get the diagnostic settings
/// being applied, use GetStatus.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource identifier of the configuration.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<ServiceDiagnosticSettingsGetResponse> GetAsync(string resourceUri, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(resourceUri);
url = url + "/providers/microsoft.insights/diagnosticSettings/service";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-07-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServiceDiagnosticSettingsGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServiceDiagnosticSettingsGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
result.Location = locationInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServiceDiagnosticSettings propertiesInstance = new ServiceDiagnosticSettings();
result.Properties = propertiesInstance;
JToken storageAccountIdValue = propertiesValue["storageAccountId"];
if (storageAccountIdValue != null && storageAccountIdValue.Type != JTokenType.Null)
{
string storageAccountIdInstance = ((string)storageAccountIdValue);
propertiesInstance.StorageAccountId = storageAccountIdInstance;
}
JToken serviceBusRuleIdValue = propertiesValue["serviceBusRuleId"];
if (serviceBusRuleIdValue != null && serviceBusRuleIdValue.Type != JTokenType.Null)
{
string serviceBusRuleIdInstance = ((string)serviceBusRuleIdValue);
propertiesInstance.ServiceBusRuleId = serviceBusRuleIdInstance;
}
JToken storageAccountNameValue = propertiesValue["storageAccountName"];
if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
{
string storageAccountNameInstance = ((string)storageAccountNameValue);
propertiesInstance.StorageAccountName = storageAccountNameInstance;
}
JToken metricsArray = propertiesValue["metrics"];
if (metricsArray != null && metricsArray.Type != JTokenType.Null)
{
foreach (JToken metricsValue in ((JArray)metricsArray))
{
MetricSettings metricSettingsInstance = new MetricSettings();
propertiesInstance.Metrics.Add(metricSettingsInstance);
JToken timeGrainValue = metricsValue["timeGrain"];
if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
{
TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue));
metricSettingsInstance.TimeGrain = timeGrainInstance;
}
JToken enabledValue = metricsValue["enabled"];
if (enabledValue != null && enabledValue.Type != JTokenType.Null)
{
bool enabledInstance = ((bool)enabledValue);
metricSettingsInstance.Enabled = enabledInstance;
}
JToken retentionPolicyValue = metricsValue["retentionPolicy"];
if (retentionPolicyValue != null && retentionPolicyValue.Type != JTokenType.Null)
{
RetentionPolicy retentionPolicyInstance = new RetentionPolicy();
metricSettingsInstance.RetentionPolicy = retentionPolicyInstance;
JToken enabledValue2 = retentionPolicyValue["enabled"];
if (enabledValue2 != null && enabledValue2.Type != JTokenType.Null)
{
bool enabledInstance2 = ((bool)enabledValue2);
retentionPolicyInstance.Enabled = enabledInstance2;
}
JToken daysValue = retentionPolicyValue["days"];
if (daysValue != null && daysValue.Type != JTokenType.Null)
{
int daysInstance = ((int)daysValue);
retentionPolicyInstance.Days = daysInstance;
}
}
}
}
JToken logsArray = propertiesValue["logs"];
if (logsArray != null && logsArray.Type != JTokenType.Null)
{
foreach (JToken logsValue in ((JArray)logsArray))
{
LogSettings logSettingsInstance = new LogSettings();
propertiesInstance.Logs.Add(logSettingsInstance);
JToken categoryValue = logsValue["category"];
if (categoryValue != null && categoryValue.Type != JTokenType.Null)
{
string categoryInstance = ((string)categoryValue);
logSettingsInstance.Category = categoryInstance;
}
JToken enabledValue3 = logsValue["enabled"];
if (enabledValue3 != null && enabledValue3.Type != JTokenType.Null)
{
bool enabledInstance3 = ((bool)enabledValue3);
logSettingsInstance.Enabled = enabledInstance3;
}
JToken retentionPolicyValue2 = logsValue["retentionPolicy"];
if (retentionPolicyValue2 != null && retentionPolicyValue2.Type != JTokenType.Null)
{
RetentionPolicy retentionPolicyInstance2 = new RetentionPolicy();
logSettingsInstance.RetentionPolicy = retentionPolicyInstance2;
JToken enabledValue4 = retentionPolicyValue2["enabled"];
if (enabledValue4 != null && enabledValue4.Type != JTokenType.Null)
{
bool enabledInstance4 = ((bool)enabledValue4);
retentionPolicyInstance2.Enabled = enabledInstance4;
}
JToken daysValue2 = retentionPolicyValue2["days"];
if (daysValue2 != null && daysValue2.Type != JTokenType.Null)
{
int daysInstance2 = ((int)daysValue2);
retentionPolicyInstance2.Days = daysInstance2;
}
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create or update new diagnostic settings for the specified
/// resource. This operation is long running. Use GetStatus to check
/// the status of this operation.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource identifier of the configuration.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Generic empty response. We only pass it to ensure json error
/// handling
/// </returns>
public async Task<EmptyResponse> PutAsync(string resourceUri, ServiceDiagnosticSettingsPutParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PutAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(resourceUri);
url = url + "/providers/microsoft.insights/diagnosticSettings/service";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-07-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject serviceDiagnosticSettingsPutParametersValue = new JObject();
requestDoc = serviceDiagnosticSettingsPutParametersValue;
if (parameters.Properties != null)
{
JObject propertiesValue = new JObject();
serviceDiagnosticSettingsPutParametersValue["properties"] = propertiesValue;
if (parameters.Properties.StorageAccountId != null)
{
propertiesValue["storageAccountId"] = parameters.Properties.StorageAccountId;
}
if (parameters.Properties.ServiceBusRuleId != null)
{
propertiesValue["serviceBusRuleId"] = parameters.Properties.ServiceBusRuleId;
}
if (parameters.Properties.StorageAccountName != null)
{
propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName;
}
if (parameters.Properties.Metrics != null)
{
if (parameters.Properties.Metrics is ILazyCollection == false || ((ILazyCollection)parameters.Properties.Metrics).IsInitialized)
{
JArray metricsArray = new JArray();
foreach (MetricSettings metricsItem in parameters.Properties.Metrics)
{
JObject metricSettingsValue = new JObject();
metricsArray.Add(metricSettingsValue);
metricSettingsValue["timeGrain"] = XmlConvert.ToString(metricsItem.TimeGrain);
metricSettingsValue["enabled"] = metricsItem.Enabled;
if (metricsItem.RetentionPolicy != null)
{
JObject retentionPolicyValue = new JObject();
metricSettingsValue["retentionPolicy"] = retentionPolicyValue;
retentionPolicyValue["enabled"] = metricsItem.RetentionPolicy.Enabled;
retentionPolicyValue["days"] = metricsItem.RetentionPolicy.Days;
}
}
propertiesValue["metrics"] = metricsArray;
}
}
if (parameters.Properties.Logs != null)
{
if (parameters.Properties.Logs is ILazyCollection == false || ((ILazyCollection)parameters.Properties.Logs).IsInitialized)
{
JArray logsArray = new JArray();
foreach (LogSettings logsItem in parameters.Properties.Logs)
{
JObject logSettingsValue = new JObject();
logsArray.Add(logSettingsValue);
if (logsItem.Category != null)
{
logSettingsValue["category"] = logsItem.Category;
}
logSettingsValue["enabled"] = logsItem.Enabled;
if (logsItem.RetentionPolicy != null)
{
JObject retentionPolicyValue2 = new JObject();
logSettingsValue["retentionPolicy"] = retentionPolicyValue2;
retentionPolicyValue2["enabled"] = logsItem.RetentionPolicy.Enabled;
retentionPolicyValue2["days"] = logsItem.RetentionPolicy.Days;
}
}
propertiesValue["logs"] = logsArray;
}
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
EmptyResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EmptyResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using POESKillTree.Model;
using POESKillTree.Views;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace POESKillTree.ViewModels
{
public class MetroMessageBoxViewModel : Notifier, INotifyPropertyChanged
{
#region fields
private string _title;
private string _message;
private MessageBoxButton _buttons;
private MessageBoxImage _image;
private ImageSource _imageSource;
private MetroMessageBoxView _view;
private bool _isYesVisible;
private bool _isNoVisible;
private bool _isOKVisible;
private bool _isCancelVisible;
private bool _isYesDefault;
private bool _isNoDefault;
private bool _isOKDefault;
private bool _isCancelDefault;
private ICommand _yesCommand;
private ICommand _noCommand;
private ICommand _okCommand;
private ICommand _cancelCommand;
private ICommand _escapeCommand;
private ICommand _closeCommand;
#endregion
public MetroMessageBoxViewModel(MetroMessageBoxView mmbView, string message, string title, MessageBoxButton buttons, ImageSource imageSource)
{
_view = mmbView;
Message = message;
BoxTitle = title;
Buttons = buttons;
NotificationImageSource = imageSource;
}
#region properties
public MessageBoxButton Buttons
{
get { return _buttons; }
set
{
_buttons = value;
switch (_buttons)
{
case MessageBoxButton.YesNo:
IsYesVisible = IsNoVisible = true;
IsYesDefault = true;
break;
case MessageBoxButton.YesNoCancel:
IsYesVisible = IsNoVisible = IsCancelVisible = true;
IsYesDefault = true;
break;
case MessageBoxButton.OK:
IsOKVisible = true;
IsOKDefault = true;
break;
case MessageBoxButton.OKCancel:
IsOKVisible = IsCancelVisible = true;
IsOKDefault = true;
break;
}
}
}
#region commands
public ICommand YesCommand
{
get
{
if (_yesCommand == null)
{
_yesCommand = new RelayCommand(args =>
{
this.Result = MessageBoxResult.Yes;
_view.Close();
});
}
return _yesCommand;
}
}
public ICommand NoCommand
{
get
{
if (_noCommand == null)
{
_noCommand = new RelayCommand(args =>
{
this.Result = MessageBoxResult.No;
_view.Close();
});
}
return _noCommand;
}
}
public ICommand CancelCommand
{
get
{
if (_cancelCommand == null)
{
_cancelCommand = new RelayCommand(args =>
{
this.Result = MessageBoxResult.Cancel;
_view.Close();
});
}
return _cancelCommand;
}
}
public ICommand OKCommand
{
get
{
if (_okCommand == null)
{
_okCommand = new RelayCommand(args =>
{
this.Result = MessageBoxResult.OK;
_view.Close();
});
}
return _okCommand;
}
}
public ICommand EscapeCommand
{
get
{
if (_escapeCommand == null)
{
_escapeCommand = new RelayCommand(args =>
{
this.Result = IsCancelVisible ? MessageBoxResult.Cancel :
(IsNoVisible ? MessageBoxResult.No : MessageBoxResult.OK);
_view.Close();
});
}
return _escapeCommand;
}
}
#endregion
#region elements content
public string Message
{
get { return _message; }
set
{
_message = value;
NotifyPropertyChanged("Message");
}
}
public string BoxTitle
{
get { return _title; }
set
{
_title = value;
NotifyPropertyChanged("BoxTitle");
}
}
public MessageBoxResult Result
{
get;
set;
}
public ImageSource NotificationImageSource
{
get { return _imageSource; }
set
{
_imageSource = value;
NotifyPropertyChanged("NotificationImageSource");
}
}
public string ImageColumnWidth
{
get { return _imageSource == null ? "0" : "Auto"; }
}
#endregion
#region buttons visibility
public bool IsYesVisible
{
get { return _isYesVisible; }
set
{
_isYesVisible = value;
NotifyPropertyChanged("IsYesVisible");
}
}
public bool IsNoVisible
{
get { return _isNoVisible; }
set
{
_isNoVisible = value;
NotifyPropertyChanged("IsNoVisible");
}
}
public bool IsOKVisible
{
get { return _isOKVisible; }
set
{
_isOKVisible = value;
NotifyPropertyChanged("IsOKVisible");
}
}
public bool IsCancelVisible
{
get { return _isCancelVisible; }
set
{
_isCancelVisible = value;
NotifyPropertyChanged("IsCancelVisible");
}
}
#endregion
#region buttons defaults
public bool IsYesDefault
{
get { return _isYesDefault; }
set
{
_isYesDefault = value;
NotifyPropertyChanged("IsYesDefault");
}
}
public bool IsNoDefault
{
get { return _isNoDefault; }
set
{
_isNoDefault = value;
NotifyPropertyChanged("IsNoDefault");
}
}
public bool IsOKDefault
{
get { return _isOKDefault; }
set
{
_isOKDefault = value;
NotifyPropertyChanged("IsOKDefault");
}
}
public bool IsCancelDefault
{
get { return _isCancelDefault; }
set
{
_isCancelDefault = value;
NotifyPropertyChanged("IsCancelDefault");
}
}
#endregion
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osuTK;
namespace osu.Game.Overlays.BeatmapSet.Scores
{
public class TopScoreStatisticsSection : CompositeDrawable
{
private const float margin = 10;
private const float top_columns_min_width = 64;
private const float bottom_columns_min_width = 45;
private readonly FontUsage smallFont = OsuFont.GetFont(size: 16);
private readonly FontUsage largeFont = OsuFont.GetFont(size: 22, weight: FontWeight.Light);
private readonly TextColumn totalScoreColumn;
private readonly TextColumn accuracyColumn;
private readonly TextColumn maxComboColumn;
private readonly TextColumn ppColumn;
private readonly FillFlowContainer<InfoColumn> statisticsColumns;
private readonly ModsInfoColumn modsColumn;
public TopScoreStatisticsSection()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChild = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new FillFlowContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(margin, 0),
Children = new Drawable[]
{
totalScoreColumn = new TextColumn("total score", largeFont, top_columns_min_width),
accuracyColumn = new TextColumn("accuracy", largeFont, top_columns_min_width),
maxComboColumn = new TextColumn("max combo", largeFont, top_columns_min_width)
}
},
new FillFlowContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(margin, 0),
Children = new Drawable[]
{
statisticsColumns = new FillFlowContainer<InfoColumn>
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(margin, 0),
},
ppColumn = new TextColumn("pp", smallFont, bottom_columns_min_width),
modsColumn = new ModsInfoColumn(),
}
},
}
};
}
/// <summary>
/// Sets the score to be displayed.
/// </summary>
public ScoreInfo Score
{
set
{
totalScoreColumn.Text = $@"{value.TotalScore:N0}";
accuracyColumn.Text = value.DisplayAccuracy;
maxComboColumn.Text = $@"{value.MaxCombo:N0}x";
ppColumn.Text = $@"{value.PP:N0}";
statisticsColumns.ChildrenEnumerable = value.SortedStatistics.Select(kvp => createStatisticsColumn(kvp.Key, kvp.Value));
modsColumn.Mods = value.Mods;
}
}
private TextColumn createStatisticsColumn(HitResult hitResult, int count) => new TextColumn(hitResult.GetDescription(), smallFont, bottom_columns_min_width)
{
Text = count.ToString()
};
private class InfoColumn : CompositeDrawable
{
private readonly Box separator;
private readonly OsuSpriteText text;
public InfoColumn(string title, Drawable content, float? minWidth = null)
{
AutoSizeAxes = Axes.Both;
Margin = new MarginPadding { Vertical = 5 };
InternalChild = new GridContainer
{
AutoSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize, minSize: minWidth ?? 0)
},
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.Absolute, 2),
new Dimension(GridSizeMode.AutoSize)
},
Content = new[]
{
new Drawable[]
{
text = new OsuSpriteText
{
Font = OsuFont.GetFont(size: 10, weight: FontWeight.Bold),
Text = title.ToUpper(),
// 2px padding bottom + 1px vertical to compensate for the additional spacing because of 1.25 line-height in osu-web
Padding = new MarginPadding { Top = 1, Bottom = 3 }
}
},
new Drawable[]
{
separator = new Box
{
Anchor = Anchor.TopLeft,
RelativeSizeAxes = Axes.X,
Height = 2,
},
},
new[]
{
// osu-web has 4px margin here but also uses 0.9 line-height, reducing margin to 2px seems like a good alternative to that
content.With(c => c.Margin = new MarginPadding { Top = 2 })
}
}
};
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
text.Colour = colourProvider.Foreground1;
separator.Colour = colourProvider.Background3;
}
}
private class TextColumn : InfoColumn
{
private readonly SpriteText text;
public TextColumn(string title, FontUsage font, float? minWidth = null)
: this(title, new OsuSpriteText { Font = font }, minWidth)
{
}
private TextColumn(string title, SpriteText text, float? minWidth = null)
: base(title, text, minWidth)
{
this.text = text;
}
public LocalisedString Text
{
set => text.Text = value;
}
}
private class ModsInfoColumn : InfoColumn
{
private readonly FillFlowContainer modsContainer;
public ModsInfoColumn()
: this(new FillFlowContainer
{
AutoSizeAxes = Axes.X,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(1),
Height = 18f
})
{
}
private ModsInfoColumn(FillFlowContainer modsContainer)
: base("mods", modsContainer)
{
this.modsContainer = modsContainer;
}
public IEnumerable<Mod> Mods
{
set
{
modsContainer.Clear();
modsContainer.Children = value.Select(mod => new ModIcon(mod)
{
AutoSizeAxes = Axes.Both,
Scale = new Vector2(0.25f),
}).ToList();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
using Palmmedia.ReportGenerator.Core.Logging;
using Palmmedia.ReportGenerator.Core.Parser.Analysis;
using Palmmedia.ReportGenerator.Core.Parser.Filtering;
using Palmmedia.ReportGenerator.Core.Properties;
namespace Palmmedia.ReportGenerator.Core.Parser
{
/// <summary>
/// Parser for XML reports generated by Visual Studio.
/// </summary>
internal class VisualStudioParser : ParserBase
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(VisualStudioParser));
/// <summary>
/// Regex to analyze if a method name belongs to a lamda expression.
/// </summary>
private static readonly Regex LambdaMethodNameRegex = new Regex("<.+>.+__", RegexOptions.Compiled);
/// <summary>
/// Regex to analyze if a method name is generated by compiler.
/// </summary>
private static readonly Regex CompilerGeneratedMethodNameRegex = new Regex(@"^.*<(?<CompilerGeneratedName>.+)>.+__.+!MoveNext\(\)!.+$", RegexOptions.Compiled);
/// <summary>
/// Regex to extract short method name.
/// </summary>
private static readonly Regex MethodRegex = new Regex(@"^(?<MethodName>.+)\((?<Arguments>.*)\).*$", RegexOptions.Compiled);
/// <summary>
/// Initializes a new instance of the <see cref="VisualStudioParser" /> class.
/// </summary>
/// <param name="assemblyFilter">The assembly filter.</param>
/// <param name="classFilter">The class filter.</param>
/// <param name="fileFilter">The file filter.</param>
internal VisualStudioParser(IFilter assemblyFilter, IFilter classFilter, IFilter fileFilter)
: base(assemblyFilter, classFilter, fileFilter)
{
}
/// <summary>
/// Parses the given XML report.
/// </summary>
/// <param name="report">The XML report.</param>
/// <returns>The parser result.</returns>
public ParserResult Parse(XContainer report)
{
if (report == null)
{
throw new ArgumentNullException(nameof(report));
}
var assemblies = new List<Assembly>();
var modules = report.Descendants("Module").ToArray();
var files = report.Descendants("SourceFileNames").ToArray();
var assemblyNames = modules
.Select(m => m.Element("ModuleName").Value)
.Distinct()
.Where(a => this.AssemblyFilter.IsElementIncludedInReport(a))
.OrderBy(a => a)
.ToArray();
foreach (var assemblyName in assemblyNames)
{
assemblies.Add(this.ProcessAssembly(modules, files, assemblyName));
}
var result = new ParserResult(assemblies.OrderBy(a => a.Name).ToList(), false, this.ToString());
return result;
}
/// <summary>
/// Processes the given assembly.
/// </summary>
/// <param name="modules">The modules.</param>
/// <param name="files">The files.</param>
/// <param name="assemblyName">Name of the assembly.</param>
/// <returns>The <see cref="Assembly"/>.</returns>
private Assembly ProcessAssembly(XElement[] modules, XElement[] files, string assemblyName)
{
Logger.DebugFormat(Resources.CurrentAssembly, assemblyName);
var classNames = modules
.Where(m => m.Element("ModuleName").Value.Equals(assemblyName))
.Elements("NamespaceTable")
.Elements("Class")
.Elements("ClassName")
.Where(c => !c.Value.Contains("<>")
&& !c.Value.StartsWith("$", StringComparison.OrdinalIgnoreCase))
.Select(c =>
{
string fullname = c.Value;
int nestedClassSeparatorIndex = fullname.IndexOf('.');
fullname = nestedClassSeparatorIndex > -1 ? fullname.Substring(0, nestedClassSeparatorIndex) : fullname;
return c.Parent.Parent.Element("NamespaceName").Value + "." + fullname;
})
.Distinct()
.Where(c => this.ClassFilter.IsElementIncludedInReport(c))
.OrderBy(name => name)
.ToArray();
var assembly = new Assembly(assemblyName);
Parallel.ForEach(classNames, className => this.ProcessClass(modules, files, assembly, className));
return assembly;
}
/// <summary>
/// Processes the given class.
/// </summary>
/// <param name="modules">The modules.</param>
/// <param name="files">The files.</param>
/// <param name="assembly">The assembly.</param>
/// <param name="className">Name of the class.</param>
private void ProcessClass(XElement[] modules, XElement[] files, Assembly assembly, string className)
{
var fileIdsOfClass = modules
.Where(m => m.Element("ModuleName").Value.Equals(assembly.Name))
.Elements("NamespaceTable")
.Elements("Class")
.Where(c => (c.Parent.Element("NamespaceName").Value + "." + c.Element("ClassName").Value).Equals(className, StringComparison.Ordinal)
|| (c.Parent.Element("NamespaceName").Value + "." + c.Element("ClassName").Value).StartsWith(className + ".", StringComparison.Ordinal))
.Elements("Method")
.Elements("Lines")
.Elements("SourceFileID")
.Select(m => m.Value)
.Distinct()
.ToArray();
var filteredFilesOfClass = fileIdsOfClass
.Select(fileId =>
new
{
FileId = fileId,
FilePath = files.First(f => f.Element("SourceFileID").Value == fileId).Element("SourceFileName").Value
})
.Where(f => this.FileFilter.IsElementIncludedInReport(f.FilePath))
.ToArray();
// If all files are removed by filters, then the whole class is omitted
if ((fileIdsOfClass.Length == 0 && !this.FileFilter.HasCustomFilters) || filteredFilesOfClass.Length > 0)
{
var @class = new Class(className, assembly);
foreach (var file in filteredFilesOfClass)
{
@class.AddFile(ProcessFile(modules, file.FileId, @class, file.FilePath));
}
assembly.AddClass(@class);
}
}
/// <summary>
/// Processes the file.
/// </summary>
/// <param name="modules">The modules.</param>
/// <param name="fileId">The file id.</param>
/// <param name="class">The class.</param>
/// <param name="filePath">The file path.</param>
/// <returns>The <see cref="CodeFile"/>.</returns>
private static CodeFile ProcessFile(XElement[] modules, string fileId, Class @class, string filePath)
{
var methods = modules
.Where(m => m.Element("ModuleName").Value.Equals(@class.Assembly.Name))
.Elements("NamespaceTable")
.Elements("Class")
.Where(c => (c.Parent.Element("NamespaceName").Value + "." + c.Element("ClassName").Value).Equals(@class.Name, StringComparison.Ordinal)
|| (c.Parent.Element("NamespaceName").Value + "." + c.Element("ClassName").Value).StartsWith(@class.Name + ".", StringComparison.Ordinal))
.Elements("Method")
.Where(m => m.Elements("Lines").Elements("SourceFileID").Any(s => s.Value == fileId))
.ToArray();
var linesOfFile = methods
.Elements("Lines")
.Select(l => new
{
LineNumberStart = int.Parse(l.Element("LnStart").Value, CultureInfo.InvariantCulture),
LineNumberEnd = int.Parse(l.Element("LnEnd").Value, CultureInfo.InvariantCulture),
Coverage = int.Parse(l.Element("Coverage").Value, CultureInfo.InvariantCulture)
})
.OrderBy(seqpnt => seqpnt.LineNumberEnd)
.ToArray();
int[] coverage = new int[] { };
LineVisitStatus[] lineVisitStatus = new LineVisitStatus[] { };
if (linesOfFile.Length > 0)
{
coverage = new int[linesOfFile[linesOfFile.LongLength - 1].LineNumberEnd + 1];
lineVisitStatus = new LineVisitStatus[linesOfFile[linesOfFile.LongLength - 1].LineNumberEnd + 1];
for (int i = 0; i < coverage.Length; i++)
{
coverage[i] = -1;
}
foreach (var seqpnt in linesOfFile)
{
for (int lineNumber = seqpnt.LineNumberStart; lineNumber <= seqpnt.LineNumberEnd; lineNumber++)
{
int visits = seqpnt.Coverage < 2 ? 1 : 0;
coverage[lineNumber] = coverage[lineNumber] == -1 ? visits : Math.Min(coverage[lineNumber] + visits, 1);
lineVisitStatus[lineNumber] = lineVisitStatus[lineNumber] == LineVisitStatus.Covered || visits > 0 ? LineVisitStatus.Covered : LineVisitStatus.NotCovered;
}
}
}
var codeFile = new CodeFile(filePath, coverage, lineVisitStatus);
SetMethodMetrics(codeFile, methods);
SetCodeElements(codeFile, methods);
return codeFile;
}
/// <summary>
/// Extracts the metrics from the given <see cref="XElement">XElements</see>.
/// </summary>
/// <param name="codeFile">The code file.</param>
/// <param name="methodsOfFile">The methods of the file.</param>
private static void SetMethodMetrics(CodeFile codeFile, IEnumerable<XElement> methodsOfFile)
{
foreach (var method in methodsOfFile)
{
string fullName = method.Element("MethodName").Value;
// Exclude properties and lambda expressions
if (fullName.StartsWith("get_", StringComparison.Ordinal)
|| fullName.StartsWith("set_", StringComparison.Ordinal)
|| LambdaMethodNameRegex.IsMatch(fullName))
{
continue;
}
fullName = ExtractMethodName(fullName, method.Element("MethodKeyName").Value);
string shortName = MethodRegex.Replace(fullName, m => string.Format(CultureInfo.InvariantCulture, "{0}({1})", m.Groups["MethodName"].Value, m.Groups["Arguments"].Value.Length > 0 ? "..." : string.Empty));
var metrics = new[]
{
new Metric(
ReportResources.BlocksCovered,
ParserBase.CodeCoverageUri,
MetricType.CoverageAbsolute,
int.Parse(method.Element("BlocksCovered").Value, CultureInfo.InvariantCulture)),
new Metric(
ReportResources.BlocksNotCovered,
ParserBase.CodeCoverageUri,
MetricType.CoverageAbsolute,
int.Parse(method.Element("BlocksNotCovered").Value, CultureInfo.InvariantCulture),
MetricMergeOrder.LowerIsBetter)
};
var methodMetric = new MethodMetric(fullName, shortName, metrics);
var seqpnt = method
.Elements("Lines")
.Elements("LnStart")
.FirstOrDefault();
if (seqpnt != null)
{
methodMetric.Line = int.Parse(seqpnt.Value, CultureInfo.InvariantCulture);
}
codeFile.AddMethodMetric(methodMetric);
}
}
/// <summary>
/// Extracts the methods/properties of the given <see cref="XElement">XElements</see>.
/// </summary>
/// <param name="codeFile">The code file.</param>
/// <param name="methodsOfFile">The methods of the file.</param>
private static void SetCodeElements(CodeFile codeFile, IEnumerable<XElement> methodsOfFile)
{
foreach (var method in methodsOfFile)
{
if (LambdaMethodNameRegex.IsMatch(method.Element("MethodName").Value))
{
continue;
}
string methodName = ExtractMethodName(method.Element("MethodName").Value, method.Element("MethodKeyName").Value);
CodeElementType type = CodeElementType.Method;
if (methodName.StartsWith("get_", StringComparison.OrdinalIgnoreCase)
|| methodName.StartsWith("set_", StringComparison.OrdinalIgnoreCase))
{
type = CodeElementType.Property;
methodName = methodName.Substring(4);
}
var seqpnts = method
.Elements("Lines")
.Select(l => new
{
LineNumberStart = int.Parse(l.Element("LnStart").Value, CultureInfo.InvariantCulture),
LineNumberEnd = int.Parse(l.Element("LnEnd").Value, CultureInfo.InvariantCulture)
})
.ToArray();
if (seqpnts.Length > 0)
{
int firstLine = seqpnts.Min(s => s.LineNumberStart);
int lastLine = seqpnts.Max(s => s.LineNumberEnd);
codeFile.AddCodeElement(new CodeElement(
methodName,
type,
firstLine,
lastLine,
codeFile.CoverageQuota(firstLine, lastLine)));
}
}
}
/// <summary>
/// Extracts the method name. For async methods the original name is returned.
/// </summary>
/// <param name="methodName">The full method name.</param>
/// <param name="methodKeyName">The method key name.</param>
/// <returns>The method name.</returns>
private static string ExtractMethodName(string methodName, string methodKeyName)
{
// Quick check before expensive regex is called
if (methodKeyName.Contains("MoveNext()"))
{
Match match = CompilerGeneratedMethodNameRegex.Match(methodKeyName);
if (match.Success)
{
methodName = match.Groups["CompilerGeneratedName"].Value + "()";
}
}
return methodName;
}
}
}
| |
// 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.Generic;
using System.IO;
using System.Linq;
namespace Scriban.Syntax
{
/// <summary>
/// A script variable
/// </summary>
/// <remarks>This class is immutable as all variable object are being shared across all templates</remarks>
[ScriptSyntax("variable", "<variable_name>")]
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
abstract partial class ScriptVariable : ScriptExpression, IScriptVariablePath, IEquatable<ScriptVariable>, IScriptTerminal
{
private int _hashCode;
public static readonly ScriptVariableLocal Arguments = new ScriptVariableLocal(string.Empty);
public static readonly ScriptVariableLocal BlockDelegate = new ScriptVariableLocal("$");
public static readonly ScriptVariableLocal Continue = new ScriptVariableLocal("continue"); // Used by liquid offset:continue
public static readonly ScriptVariableLoop ForObject = new ScriptVariableLoop("for");
public static readonly ScriptVariableLoop TablerowObject = new ScriptVariableLoop("tablerow");
public static readonly ScriptVariableLoop WhileObject = new ScriptVariableLoop("while");
protected ScriptVariable(string name, ScriptVariableScope scope)
{
BaseName = name;
Scope = scope;
switch (scope)
{
case ScriptVariableScope.Global:
case ScriptVariableScope.Loop:
Name = name;
break;
case ScriptVariableScope.Local:
Name = $"${name}";
break;
}
unchecked
{
_hashCode = (BaseName.GetHashCode() * 397) ^ (int)Scope;
}
}
public ScriptTrivias Trivias { get; set; }
/// <summary>
/// Creates a <see cref="ScriptVariable"/> according to the specified name and <see cref="ScriptVariableScope"/>
/// </summary>
/// <param name="name">Name of the variable</param>
/// <param name="scope">Scope of the variable</param>
/// <returns>The script variable</returns>
public static ScriptVariable Create(string name, ScriptVariableScope scope)
{
switch (scope)
{
case ScriptVariableScope.Global:
return new ScriptVariableGlobal(name);
case ScriptVariableScope.Local:
return new ScriptVariableLocal(name);
case ScriptVariableScope.Loop:
return new ScriptVariableLoop(name);
default:
throw new InvalidOperationException($"Scope `{scope}` is not supported");
}
}
public string BaseName { get; }
/// <summary>
/// Gets or sets the name of the variable (without the $ sign for local variable)
/// </summary>
public string Name { get; }
/// <summary>
/// Gets or sets a boolean indicating whether this variable is a local variable (starting with $ in the template ) or global.
/// </summary>
public ScriptVariableScope Scope { get; }
public string GetFirstPath()
{
return Name;
}
public virtual bool Equals(ScriptVariable other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(Name, other.Name) && Scope == other.Scope;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj is ScriptVariable && Equals((ScriptVariable) obj);
}
public override int GetHashCode()
{
return _hashCode;
}
public static bool operator ==(ScriptVariable left, ScriptVariable right)
{
return Equals(left, right);
}
public static bool operator !=(ScriptVariable left, ScriptVariable right)
{
return !Equals(left, right);
}
public override object Evaluate(TemplateContext context)
{
return context.GetValue((ScriptExpression)this);
}
public virtual object GetValue(TemplateContext context)
{
return context.GetValue(this);
}
public void SetValue(TemplateContext context, object valueToSet)
{
context.SetValue(this, valueToSet);
}
public override void PrintTo(ScriptPrinter printer)
{
printer.Write(Name);
}
}
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
partial class ScriptVariableGlobal : ScriptVariable
{
public ScriptVariableGlobal(string name) : base(name, ScriptVariableScope.Global)
{
}
public override object GetValue(TemplateContext context)
{
// Used a specialized overrides on contxet for ScriptVariableGlobal
return context.GetValue(this);
}
}
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
partial class ScriptVariableLocal : ScriptVariable
{
public ScriptVariableLocal(string name) : base(name, ScriptVariableScope.Local)
{
}
}
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
partial class ScriptVariableLoop : ScriptVariable
{
public ScriptVariableLoop(string name) : base(name, ScriptVariableScope.Loop)
{
}
public override void PrintTo(ScriptPrinter printer)
{
if (printer.IsInWhileLoop)
{
// TODO: Not efficient
printer.Write(Name == "for" ? "while" : Name);
}
else
{
base.PrintTo(printer);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UDPMeshLib;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayer
{
public class DebugWindow
{
private bool safeDisplay = false;
private bool initialized = false;
private bool isWindowLocked = false;
//private parts
private bool displayFast;
private bool displayVectors;
private bool displayNTP;
private bool displayConnectionQueue;
private bool displayDynamicTickStats;
private bool displayRequestedRates;
private bool displayVesselRecorder;
private bool displayVesselTimeDelay;
private bool displayMeshStats;
private bool displayVesselCache;
private bool displayRecycler;
private bool dumpRecycler;
private string vectorText = "";
private string ntpText = "";
private string connectionText = "";
private string dynamicTickText = "";
private string requestedRateText = "";
private string vesselworkerTimeDelay = "0";
private string recyclerText = "";
private float lastUpdateTime;
//GUI Layout
private Rect windowRect;
private Rect moveRect;
private GUILayoutOption[] layoutOptions;
private GUILayoutOption[] textAreaOptions;
private GUIStyle windowStyle;
private GUIStyle buttonStyle;
private GUIStyle labelStyle;
//const
private const float WINDOW_HEIGHT = 450;
private const float WINDOW_WIDTH = 350;
private const float DISPLAY_UPDATE_INTERVAL = .2f;
//Services
private DMPGame dmpGame;
private Settings dmpSettings;
private TimeSyncer timeSyncer;
private NetworkWorker networkWorker;
private VesselWorker vesselWorker;
private DynamicTickWorker dynamicTickWorker;
private WarpWorker warpWorker;
private VesselRecorder vesselRecorder;
private PosistionStatistics posistionStatistics;
private OptionsWindow optionsWindow;
private Profiler profiler;
private NamedAction updateAction;
private NamedAction drawAction;
public DebugWindow(DMPGame dmpGame, Settings dmpSettings, TimeSyncer timeSyncer, NetworkWorker networkWorker, VesselWorker vesselWorker, DynamicTickWorker dynamicTickWorker, WarpWorker warpWorker, VesselRecorder vesselRecorder, PosistionStatistics posistionStatistics, OptionsWindow optionsWindow, Profiler profiler)
{
this.dmpGame = dmpGame;
this.dmpSettings = dmpSettings;
this.timeSyncer = timeSyncer;
this.networkWorker = networkWorker;
this.vesselWorker = vesselWorker;
this.dynamicTickWorker = dynamicTickWorker;
this.warpWorker = warpWorker;
this.vesselRecorder = vesselRecorder;
this.posistionStatistics = posistionStatistics;
this.optionsWindow = optionsWindow;
this.profiler = profiler;
updateAction = new NamedAction(Update);
drawAction = new NamedAction(Draw);
dmpGame.updateEvent.Add(updateAction);
dmpGame.drawEvent.Add(drawAction);
}
private void InitGUI()
{
//Setup GUI stuff
windowRect = new Rect(Screen.width - (WINDOW_WIDTH + 50), (Screen.height / 2f) - (WINDOW_HEIGHT / 2f), WINDOW_WIDTH, WINDOW_HEIGHT);
moveRect = new Rect(0, 0, 10000, 20);
layoutOptions = new GUILayoutOption[4];
layoutOptions[0] = GUILayout.MinWidth(WINDOW_WIDTH);
layoutOptions[1] = GUILayout.MaxWidth(WINDOW_WIDTH);
layoutOptions[2] = GUILayout.MinHeight(WINDOW_HEIGHT);
layoutOptions[3] = GUILayout.MaxHeight(WINDOW_HEIGHT);
windowStyle = new GUIStyle(GUI.skin.window);
buttonStyle = new GUIStyle(GUI.skin.button);
textAreaOptions = new GUILayoutOption[1];
textAreaOptions[0] = GUILayout.ExpandWidth(true);
labelStyle = new GUIStyle(GUI.skin.label);
}
public void Draw()
{
if (safeDisplay)
{
if (!initialized)
{
initialized = true;
InitGUI();
}
windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6705 + Client.WINDOW_OFFSET, windowRect, DrawContent, "DarkMultiPlayer - Debug", windowStyle, layoutOptions));
}
CheckWindowLock();
}
private void DrawContent(int windowID)
{
GUILayout.BeginVertical();
GUI.DragWindow(moveRect);
GameEvents.debugEvents = GUILayout.Toggle(GameEvents.debugEvents, "Debug GameEvents", buttonStyle);
displayFast = GUILayout.Toggle(displayFast, "Fast debug update", buttonStyle);
displayVectors = GUILayout.Toggle(displayVectors, "Display vessel vectors", buttonStyle);
if (displayVectors)
{
GUILayout.Label(vectorText, labelStyle);
}
displayNTP = GUILayout.Toggle(displayNTP, "Display NTP/Subspace statistics", buttonStyle);
if (displayNTP)
{
GUILayout.Label(ntpText, labelStyle);
}
displayConnectionQueue = GUILayout.Toggle(displayConnectionQueue, "Display connection statistics", buttonStyle);
if (displayConnectionQueue)
{
GUILayout.Label(connectionText, labelStyle);
}
displayDynamicTickStats = GUILayout.Toggle(displayDynamicTickStats, "Display dynamic tick statistics", buttonStyle);
if (displayDynamicTickStats)
{
GUILayout.Label(dynamicTickText, labelStyle);
}
displayRequestedRates = GUILayout.Toggle(displayRequestedRates, "Display requested rates", buttonStyle);
if (displayRequestedRates)
{
GUILayout.Label(requestedRateText, labelStyle);
}
profiler.samplingEnabled = GUILayout.Toggle(profiler.samplingEnabled, "Record Profiler Samples", buttonStyle);
displayVesselRecorder = GUILayout.Toggle(displayVesselRecorder, "Display Vessel Recorder", buttonStyle);
if (displayVesselRecorder)
{
if (!vesselRecorder.active)
{
if (GUILayout.Button("Start Recording", buttonStyle))
{
vesselRecorder.StartRecord();
}
if (GUILayout.Button("Playback", buttonStyle))
{
vesselRecorder.StartPlayback();
}
}
else
{
if (GUILayout.Button("Stop Recording", buttonStyle))
{
vesselRecorder.StopRecord();
}
if (GUILayout.Button("Cancel Recording", buttonStyle))
{
vesselRecorder.CancelRecord();
}
}
}
posistionStatistics.active = GUILayout.Toggle(posistionStatistics.active, "Display Posistional Error", buttonStyle);
if (posistionStatistics.active)
{
if (posistionStatistics.selectedVessel != Guid.Empty)
{
GUILayout.Label("Posistional Error: " + Math.Round(posistionStatistics.distanceError, 2), labelStyle);
GUILayout.Label("Velocity Error: " + Math.Round(posistionStatistics.velocityError, 2), labelStyle);
GUILayout.Label("Rotational Error: " + Math.Round(posistionStatistics.rotationError, 2), labelStyle);
GUILayout.Label("Update HZ: " + Math.Round(posistionStatistics.updateHz, 2), labelStyle);
}
else
{
GUILayout.Label("(no selected vessel)", labelStyle);
}
}
displayVesselTimeDelay = GUILayout.Toggle(displayVesselTimeDelay, "Vessel Delay Settings", buttonStyle);
if (displayVesselTimeDelay)
{
GUILayout.BeginHorizontal();
vesselworkerTimeDelay = GUILayout.TextArea(vesselworkerTimeDelay, textAreaOptions);
if (GUILayout.Button("Set", buttonStyle))
{
float newDelay = 0f;
if (float.TryParse(vesselworkerTimeDelay, out newDelay))
{
vesselWorker.delayTime = newDelay;
}
else
{
vesselWorker.delayTime = 0f;
vesselworkerTimeDelay = "0";
}
}
GUILayout.EndHorizontal();
}
displayMeshStats = GUILayout.Toggle(displayMeshStats, "Mesh statistics", buttonStyle);
if (displayMeshStats)
{
UdpMeshClient udpMesh = networkWorker.GetMesh();
foreach (UdpPeer peer in udpMesh.GetPeers())
{
if (peer.guid != UdpMeshCommon.GetMeshAddress())
{
string playerName = networkWorker.GetMeshPlayername(peer.guid);
if (playerName != null)
{
GUILayout.Label(playerName + ":", labelStyle);
}
else
{
GUILayout.Label(peer.guid + ":", labelStyle);
}
double latency4 = peer.latency4 / (double)TimeSpan.TicksPerMillisecond;
double latency6 = peer.latency6 / (double)TimeSpan.TicksPerMillisecond;
double offset = peer.offset / (double)TimeSpan.TicksPerSecond;
if (peer.usev4)
{
GUILayout.Label("V4 Latency: " + Math.Round(latency4, 2) + "ms", labelStyle);
}
if (peer.usev6)
{
GUILayout.Label("V6 Latency: " + Math.Round(latency6, 2) + "ms", labelStyle);
}
if (peer.usev4 || peer.usev6)
{
GUILayout.Label("Clock offset: " + Math.Round(offset, 2), labelStyle);
}
else
{
GUILayout.Label("No contact - using server relay", labelStyle);
}
}
}
}
displayVesselCache = GUILayout.Toggle(displayVesselCache, "Display vessel cache", buttonStyle);
if (displayVesselCache)
{
GUILayout.Label("Normal:", labelStyle);
foreach (KeyValuePair<Guid, Queue<VesselUpdate>> kvp in vesselWorker.vesselUpdateQueue)
{
if (kvp.Value.Count > 0)
{
GUILayout.Label(kvp.Key + ": " + kvp.Value.Count, labelStyle);
}
}
GUILayout.Label("Mesh:", labelStyle);
foreach (KeyValuePair<Guid, Queue<VesselUpdate>> kvp in vesselWorker.vesselUpdateMeshQueue)
{
if (kvp.Value.Count > 0)
{
GUILayout.Label(kvp.Key + ": " + kvp.Value.Count, labelStyle);
}
}
}
displayRecycler = GUILayout.Toggle(displayRecycler, "Display recycler", buttonStyle);
if (displayRecycler)
{
GUILayout.Label(recyclerText, labelStyle);
}
if (GUILayout.Button("Dump recycler", buttonStyle))
{
dumpRecycler = true;
}
GUILayout.EndVertical();
}
private void Update()
{
safeDisplay = optionsWindow.showDebugWindow;
if (safeDisplay)
{
if (((Client.realtimeSinceStartup - lastUpdateTime) > DISPLAY_UPDATE_INTERVAL) || displayFast)
{
lastUpdateTime = Client.realtimeSinceStartup;
//Vector text
if (displayVectors)
{
if (HighLogic.LoadedScene == GameScenes.FLIGHT && FlightGlobals.ready && FlightGlobals.fetch.activeVessel != null)
{
Vessel ourVessel = FlightGlobals.fetch.activeVessel;
vectorText = "Forward vector: " + ourVessel.GetFwdVector() + "\n";
vectorText += "Up vector: " + (Vector3)ourVessel.upAxis + "\n";
vectorText += "Srf Rotation: " + ourVessel.srfRelRotation + "\n";
vectorText += "Vessel Rotation: " + ourVessel.transform.rotation + "\n";
vectorText += "Vessel Local Rotation: " + ourVessel.transform.localRotation + "\n";
vectorText += "mainBody Rotation: " + (Quaternion)ourVessel.mainBody.rotation + "\n";
vectorText += "mainBody Transform Rotation: " + (Quaternion)ourVessel.mainBody.bodyTransform.rotation + "\n";
vectorText += "Surface Velocity: " + ourVessel.GetSrfVelocity() + ", |v|: " + ourVessel.GetSrfVelocity().magnitude + "\n";
vectorText += "Orbital Velocity: " + ourVessel.GetObtVelocity() + ", |v|: " + ourVessel.GetObtVelocity().magnitude + "\n";
if (ourVessel.orbitDriver != null && ourVessel.orbitDriver.orbit != null)
{
vectorText += "Frame Velocity: " + (Vector3)ourVessel.orbitDriver.orbit.GetFrameVel() + ", |v|: " + ourVessel.orbitDriver.orbit.GetFrameVel().magnitude + "\n";
}
vectorText += "CoM offset vector: " + ourVessel.CoM.ToString() + "\n";
vectorText += "Angular Velocity: " + ourVessel.angularVelocity + ", |v|: " + ourVessel.angularVelocity.magnitude + "\n";
vectorText += "World Pos: " + (Vector3)ourVessel.GetWorldPos3D() + ", |pos|: " + ourVessel.GetWorldPos3D().magnitude + "\n";
}
else
{
vectorText = "You have to be in flight";
}
}
//NTP text
if (displayNTP)
{
ntpText = "Warp rate: " + Math.Round(Time.timeScale, 3) + "x.\n";
ntpText += "Current subspace: " + timeSyncer.currentSubspace + ".\n";
if (timeSyncer.locked)
{
ntpText += "Current subspace rate: " + Math.Round(timeSyncer.lockedSubspace.subspaceSpeed, 3) + "x.\n";
}
else
{
ntpText += "Current subspace rate: " + Math.Round(timeSyncer.requestedRate, 3) + "x.\n";
}
ntpText += "Current Error: " + Math.Round((timeSyncer.GetCurrentError() * 1000), 0) + " ms.\n";
ntpText += "Current universe time: " + Math.Round(Planetarium.GetUniversalTime(), 3) + " UT\n";
ntpText += "Network latency: " + Math.Round((timeSyncer.networkLatencyAverage / (float)TimeSpan.TicksPerMillisecond), 3) + " ms\n";
ntpText += "Server clock difference: " + Math.Round((timeSyncer.clockOffsetAverage / (float)TimeSpan.TicksPerMillisecond), 3) + " ms\n";
ntpText += "Server lag: " + Math.Round((timeSyncer.serverLag / (float)TimeSpan.TicksPerMillisecond), 3) + " ms\n";
}
//Connection queue text
if (displayConnectionQueue)
{
connectionText = "Last send time: " + networkWorker.GetStatistics("LastSendTime") + "ms.\n";
connectionText += "Last receive time: " + networkWorker.GetStatistics("LastReceiveTime") + "ms.\n";
connectionText += "Queued outgoing messages (High): " + networkWorker.GetStatistics("HighPriorityQueueLength") + ".\n";
connectionText += "Queued outgoing messages (Split): " + networkWorker.GetStatistics("SplitPriorityQueueLength") + ".\n";
connectionText += "Queued outgoing messages (Low): " + networkWorker.GetStatistics("LowPriorityQueueLength") + ".\n";
connectionText += "Queued out bytes: " + networkWorker.GetStatistics("QueuedOutBytes") + ".\n";
connectionText += "Sent bytes: " + networkWorker.GetStatistics("SentBytes") + ".\n";
connectionText += "Received bytes: " + networkWorker.GetStatistics("ReceivedBytes") + ".\n";
connectionText += "Stored future updates: " + vesselWorker.GetStatistics("StoredFutureUpdates") + "\n";
connectionText += "Stored future proto updates: " + vesselWorker.GetStatistics("StoredFutureProtoUpdates") + ".\n";
}
//Dynamic tick text
if (displayDynamicTickStats)
{
dynamicTickText = "Current tick rate: " + DynamicTickWorker.SEND_TICK_RATE + "hz.\n";
dynamicTickText += "Current max secondry vessels: " + dynamicTickWorker.maxSecondryVesselsPerTick + ".\n";
}
//Requested rates text
if (displayRequestedRates)
{
requestedRateText = dmpSettings.playerName + ": " + Math.Round(timeSyncer.requestedRate, 3) + "x.\n";
foreach (KeyValuePair<string, float> playerEntry in warpWorker.clientSkewList)
{
requestedRateText += playerEntry.Key + ": " + Math.Round(playerEntry.Value, 3) + "x.\n";
}
}
//Requested rates text
if (displayRecycler)
{
recyclerText = "16kB: " + ByteRecycler.GetPoolCount(Client.SMALL_MESSAGE_SIZE) + ", free: " + ByteRecycler.GetPoolFreeCount(Client.SMALL_MESSAGE_SIZE) + "\n";
recyclerText += "512kB: " + ByteRecycler.GetPoolCount(Client.MEDIUM_MESSAGE_SIZE) + ", free: " + ByteRecycler.GetPoolFreeCount(Client.MEDIUM_MESSAGE_SIZE) + "\n";
recyclerText += "6MB: " + ByteRecycler.GetPoolCount(Client.LARGE_MESSAGE_SIZE) + ", free: " + ByteRecycler.GetPoolFreeCount(Client.LARGE_MESSAGE_SIZE) + "\n";
recyclerText += "VesselUpdate: " + Recycler<VesselUpdate>.GetPoolCount() + ", free: " + Recycler<VesselUpdate>.GetPoolFreeCount() + "\n";
}
if (dumpRecycler)
{
dumpRecycler = false;
string dumpPath = Path.Combine(KSPUtil.ApplicationRootPath, "DarkMultiPlayer-Recycler");
ByteRecycler.DumpNonFree(dumpPath);
}
}
}
}
private void CheckWindowLock()
{
if (!dmpGame.running)
{
RemoveWindowLock();
return;
}
if (HighLogic.LoadedSceneIsFlight)
{
RemoveWindowLock();
return;
}
if (safeDisplay)
{
Vector2 mousePos = Input.mousePosition;
mousePos.y = Screen.height - mousePos.y;
bool shouldLock = windowRect.Contains(mousePos);
if (shouldLock && !isWindowLocked)
{
InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, "DMP_DebugLock");
isWindowLocked = true;
}
if (!shouldLock && isWindowLocked)
{
RemoveWindowLock();
}
}
if (!safeDisplay && isWindowLocked)
{
RemoveWindowLock();
}
}
private void RemoveWindowLock()
{
if (isWindowLocked)
{
isWindowLocked = false;
InputLockManager.RemoveControlLock("DMP_DebugLock");
}
}
public void Stop()
{
optionsWindow.showDebugWindow = false;
RemoveWindowLock();
dmpGame.updateEvent.Remove(updateAction);
dmpGame.drawEvent.Remove(drawAction);
}
}
}
| |
using System;
using System.Collections;
using Server.Misc;
using Server.Mobiles;
using Server.Network;
using Server.Gumps;
using Server.Regions;
namespace Server.Items
{
[DispellableFieldAttribute]
public class Moongate : Item
{
private Point3D m_Target;
private Map m_TargetMap;
private bool m_bDispellable;
[CommandProperty( AccessLevel.GameMaster )]
public Point3D Target
{
get
{
return m_Target;
}
set
{
m_Target = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public Map TargetMap
{
get
{
return m_TargetMap;
}
set
{
m_TargetMap = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public bool Dispellable
{
get
{
return m_bDispellable;
}
set
{
m_bDispellable = value;
}
}
public virtual bool ShowFeluccaWarning{ get{ return false; } }
[Constructable]
public Moongate() : this( Point3D.Zero, null )
{
m_bDispellable = true;
}
[Constructable]
public Moongate(bool bDispellable) : this( Point3D.Zero, null )
{
m_bDispellable = bDispellable;
}
[Constructable]
public Moongate( Point3D target, Map targetMap ) : base( 0xF6C )
{
Movable = false;
Light = LightType.Circle300;
m_Target = target;
m_TargetMap = targetMap;
}
public Moongate( Serial serial ) : base( serial )
{
}
public override void OnDoubleClick( Mobile from )
{
if ( !from.Player )
return;
if ( from.InRange( GetWorldLocation(), 1 ) )
CheckGate( from, 1 );
else
from.SendLocalizedMessage( 500446 ); // That is too far away.
}
public override bool OnMoveOver( Mobile m )
{
if ( m.Player )
CheckGate( m, 0 );
return true;
}
public virtual void CheckGate( Mobile m, int range )
{
#region Mondain's Legacy
if (m.Hidden && m.AccessLevel == AccessLevel.Player && Core.ML)
m.RevealingAction();
#endregion
new DelayTimer( m, this, range ).Start();
}
public virtual void OnGateUsed( Mobile m )
{
}
public virtual void UseGate( Mobile m )
{
ClientFlags flags = m.NetState == null ? ClientFlags.None : m.NetState.Flags;
if ( Factions.Sigil.ExistsOn( m ) )
{
m.SendLocalizedMessage( 1061632 ); // You can't do that while carrying the sigil.
}
else if ( m_TargetMap == Map.Felucca && m is PlayerMobile && ((PlayerMobile)m).Young )
{
m.SendLocalizedMessage( 1049543 ); // You decide against traveling to Felucca while you are still young.
}
else if ( (m.Kills >= 5 && m_TargetMap != Map.Felucca) || ( m_TargetMap == Map.Tokuno && (flags & ClientFlags.Tokuno) == 0 ) || ( m_TargetMap == Map.Malas && (flags & ClientFlags.Malas) == 0 ) || ( m_TargetMap == Map.Ilshenar && (flags & ClientFlags.Ilshenar) == 0 ) )
{
m.SendLocalizedMessage( 1019004 ); // You are not allowed to travel there.
}
else if ( m.Spell != null )
{
m.SendLocalizedMessage( 1049616 ); // You are too busy to do that at the moment.
}
else if ( m_TargetMap != null && m_TargetMap != Map.Internal )
{
BaseCreature.TeleportPets( m, m_Target, m_TargetMap );
m.MoveToWorld( m_Target, m_TargetMap );
if ( m.AccessLevel == AccessLevel.Player || !m.Hidden )
m.PlaySound( 0x1FE );
OnGateUsed( m );
}
else
{
m.SendMessage( "This moongate does not seem to go anywhere." );
}
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 ); // version
writer.Write( m_Target );
writer.Write( m_TargetMap );
// Version 1
writer.Write( m_bDispellable );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
m_Target = reader.ReadPoint3D();
m_TargetMap = reader.ReadMap();
if ( version >= 1 )
m_bDispellable = reader.ReadBool();
}
public virtual bool ValidateUse( Mobile from, bool message )
{
if ( from.Deleted || this.Deleted )
return false;
if ( from.Map != this.Map || !from.InRange( this, 1 ) )
{
if ( message )
from.SendLocalizedMessage( 500446 ); // That is too far away.
return false;
}
return true;
}
public virtual void BeginConfirmation( Mobile from )
{
if ( IsInTown( from.Location, from.Map ) && !IsInTown( m_Target, m_TargetMap ) || (from.Map != Map.Felucca && TargetMap == Map.Felucca && ShowFeluccaWarning) )
{
if ( from.AccessLevel == AccessLevel.Player || !from.Hidden )
from.Send( new PlaySound( 0x20E, from.Location ) );
from.CloseGump( typeof( MoongateConfirmGump ) );
from.SendGump( new MoongateConfirmGump( from, this ) );
}
else
{
EndConfirmation( from );
}
}
public virtual void EndConfirmation( Mobile from )
{
if ( !ValidateUse( from, true ) )
return;
UseGate( from );
}
public virtual void DelayCallback( Mobile from, int range )
{
if ( !ValidateUse( from, false ) || !from.InRange( this, range ) )
return;
if ( m_TargetMap != null )
BeginConfirmation( from );
else
from.SendMessage( "This moongate does not seem to go anywhere." );
}
public static bool IsInTown( Point3D p, Map map )
{
if ( map == null )
return false;
GuardedRegion reg = (GuardedRegion) Region.Find( p, map ).GetRegion( typeof( GuardedRegion ) );
return ( reg != null && !reg.IsDisabled() );
}
private class DelayTimer : Timer
{
private Mobile m_From;
private Moongate m_Gate;
private int m_Range;
public DelayTimer( Mobile from, Moongate gate, int range ) : base( TimeSpan.FromSeconds( 1.0 ) )
{
m_From = from;
m_Gate = gate;
m_Range = range;
}
protected override void OnTick()
{
m_Gate.DelayCallback( m_From, m_Range );
}
}
}
public class ConfirmationMoongate : Moongate
{
private int m_GumpWidth;
private int m_GumpHeight;
private int m_TitleColor;
private int m_MessageColor;
private int m_TitleNumber;
private int m_MessageNumber;
private string m_MessageString;
[CommandProperty( AccessLevel.GameMaster )]
public int GumpWidth
{
get{ return m_GumpWidth; }
set{ m_GumpWidth = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public int GumpHeight
{
get{ return m_GumpHeight; }
set{ m_GumpHeight = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public int TitleColor
{
get{ return m_TitleColor; }
set{ m_TitleColor = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public int MessageColor
{
get{ return m_MessageColor; }
set{ m_MessageColor = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public int TitleNumber
{
get{ return m_TitleNumber; }
set{ m_TitleNumber = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public int MessageNumber
{
get{ return m_MessageNumber; }
set{ m_MessageNumber = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public string MessageString
{
get{ return m_MessageString; }
set{ m_MessageString = value; }
}
[Constructable]
public ConfirmationMoongate() : this( Point3D.Zero, null )
{
}
[Constructable]
public ConfirmationMoongate( Point3D target, Map targetMap ) : base( target, targetMap )
{
}
public ConfirmationMoongate( Serial serial ) : base( serial )
{
}
public virtual void Warning_Callback( Mobile from, bool okay, object state )
{
if ( okay )
EndConfirmation( from );
}
public override void BeginConfirmation( Mobile from )
{
if ( m_GumpWidth > 0 && m_GumpHeight > 0 && m_TitleNumber > 0 && (m_MessageNumber > 0 || m_MessageString != null) )
{
from.CloseGump( typeof( WarningGump ) );
from.SendGump( new WarningGump( m_TitleNumber, m_TitleColor, m_MessageString == null ? (object)m_MessageNumber : (object)m_MessageString, m_MessageColor, m_GumpWidth, m_GumpHeight, new WarningGumpCallback( Warning_Callback ), from ) );
}
else
{
base.BeginConfirmation( from );
}
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
writer.WriteEncodedInt( m_GumpWidth );
writer.WriteEncodedInt( m_GumpHeight );
writer.WriteEncodedInt( m_TitleColor );
writer.WriteEncodedInt( m_MessageColor );
writer.WriteEncodedInt( m_TitleNumber );
writer.WriteEncodedInt( m_MessageNumber );
writer.Write( m_MessageString );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_GumpWidth = reader.ReadEncodedInt();
m_GumpHeight = reader.ReadEncodedInt();
m_TitleColor = reader.ReadEncodedInt();
m_MessageColor = reader.ReadEncodedInt();
m_TitleNumber = reader.ReadEncodedInt();
m_MessageNumber = reader.ReadEncodedInt();
m_MessageString = reader.ReadString();
break;
}
}
}
}
public class MoongateConfirmGump : Gump
{
private Mobile m_From;
private Moongate m_Gate;
public MoongateConfirmGump( Mobile from, Moongate gate ) : base( Core.AOS ? 110 : 20, Core.AOS ? 100 : 30 )
{
m_From = from;
m_Gate = gate;
if ( Core.AOS )
{
Closable = false;
AddPage( 0 );
AddBackground( 0, 0, 420, 280, 5054 );
AddImageTiled( 10, 10, 400, 20, 2624 );
AddAlphaRegion( 10, 10, 400, 20 );
AddHtmlLocalized( 10, 10, 400, 20, 1062051, 30720, false, false ); // Gate Warning
AddImageTiled( 10, 40, 400, 200, 2624 );
AddAlphaRegion( 10, 40, 400, 200 );
if ( from.Map != Map.Felucca && gate.TargetMap == Map.Felucca && gate.ShowFeluccaWarning )
AddHtmlLocalized( 10, 40, 400, 200, 1062050, 32512, false, true ); // This Gate goes to Felucca... Continue to enter the gate, Cancel to stay here
else
AddHtmlLocalized( 10, 40, 400, 200, 1062049, 32512, false, true ); // Dost thou wish to step into the moongate? Continue to enter the gate, Cancel to stay here
AddImageTiled( 10, 250, 400, 20, 2624 );
AddAlphaRegion( 10, 250, 400, 20 );
AddButton( 10, 250, 4005, 4007, 1, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 40, 250, 170, 20, 1011036, 32767, false, false ); // OKAY
AddButton( 210, 250, 4005, 4007, 0, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 240, 250, 170, 20, 1011012, 32767, false, false ); // CANCEL
}
else
{
AddPage( 0 );
AddBackground( 0, 0, 420, 400, 5054 );
AddBackground( 10, 10, 400, 380, 3000 );
AddHtml( 20, 40, 380, 60, @"Dost thou wish to step into the moongate? Continue to enter the gate, Cancel to stay here", false, false );
AddHtmlLocalized( 55, 110, 290, 20, 1011012, false, false ); // CANCEL
AddButton( 20, 110, 4005, 4007, 0, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 55, 140, 290, 40, 1011011, false, false ); // CONTINUE
AddButton( 20, 140, 4005, 4007, 1, GumpButtonType.Reply, 0 );
}
}
public override void OnResponse( NetState state, RelayInfo info )
{
if ( info.ButtonID == 1 )
m_Gate.EndConfirmation( m_From );
}
}
}
| |
/*
* 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.Tests.Compute
{
using System;
using System.Collections.Generic;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using NUnit.Framework;
/// <summary>
/// Tests class.
/// </summary>
[Category(TestUtils.CategoryIntensive)]
public class ComputeMultithreadedTest : AbstractTaskTest
{
/** */
private static IList<Action<ICompute>> _actions;
/// <summary>
/// Constructor.
/// </summary>
public ComputeMultithreadedTest() : base(false) { }
/// <summary>
/// Set-up routine.
/// </summary>
[SetUp]
public void SetUp()
{
_actions = new List<Action<ICompute>>
{
compute => { compute.Apply(new My1ArgClosure(), "zzzz"); },
compute => { compute.Broadcast(new My1ArgClosure(), "zzzz"); },
compute => { compute.Broadcast(new MyNoArgClosure("zzzz")); },
compute => { compute.Call(new MyNoArgClosure("zzzz")); },
compute => { compute.Execute(new StringLengthEmptyTask(), "zzzz"); },
compute =>
{
compute.Apply(new My1ArgClosure(), new List<string> {"zzzz", "a", "b"}, new MyReducer());
}
};
}
/// <summary>
/// Tear-down routine.
/// </summary>
[TearDown]
public void TearDown()
{
_actions.Clear();
}
/// <summary>
/// Test not-marshalable error occurred during map step.
/// </summary>
[Test]
public void TestAllTaskTypeAtSameTime()
{
Assert.AreEqual(_actions.Count, 6);
var compute = Grid1.Compute();
TestUtils.RunMultiThreaded(() =>
{
_actions[TestUtils.Random.Next(_actions.Count)](compute);
}, 4, 60);
}
/// <summary>
///
/// </summary>
[Test]
public void TestSingleTaskType0()
{
Assert.AreEqual(_actions.Count, 6);
TestUtils.RunMultiThreaded(() => _actions[0](Grid1.Compute()), 4, 20);
}
/// <summary>
///
/// </summary>
[Test]
public void TestSingleTaskType1()
{
Assert.AreEqual(_actions.Count, 6);
TestUtils.RunMultiThreaded(() => _actions[1](Grid1.Compute()), 4, 20);
}
/// <summary>
///
/// </summary>
[Test]
public void TestSingleTaskType2()
{
Assert.AreEqual(_actions.Count, 6);
TestUtils.RunMultiThreaded(() => _actions[2](Grid1.Compute()), 4, 20);
}
/// <summary>
///
/// </summary>
[Test]
public void TestSingleTaskType3()
{
Assert.AreEqual(_actions.Count, 6);
TestUtils.RunMultiThreaded(() => _actions[3](Grid1.Compute()), 4, 20);
}
/// <summary>
///
/// </summary>
[Test]
public void TestSingleTaskType4()
{
Assert.AreEqual(_actions.Count, 6);
TestUtils.RunMultiThreaded(() => _actions[4](Grid1.Compute()), 4, 20);
}
/// <summary>
///
/// </summary>
[Test]
public void TestSingleTaskType5()
{
Assert.AreEqual(_actions.Count, 6);
TestUtils.RunMultiThreaded(() => _actions[5](Grid1.Compute()), 4, 20);
}
}
/// <summary>
/// Test class.
/// </summary>
[Serializable]
public class My1ArgClosure : IComputeFunc<string, int>
{
/** <inheritDoc /> */
public int Invoke(string s)
{
return s.Length;
}
}
/// <summary>
/// Test class.
/// </summary>
[Serializable]
public class MyNoArgClosure : IComputeFunc<int>
{
/** */
private readonly string _s;
/// <summary>
///
/// </summary>
/// <param name="s"></param>
public MyNoArgClosure(string s)
{
_s = s;
}
/** <inheritDoc /> */
public int Invoke()
{
return _s.Length;
}
}
/// <summary>
///
/// </summary>
public class StringLengthEmptyTask : IComputeTask<string, int, int>
{
/** <inheritDoc /> */
public IDictionary<IComputeJob<int>, IClusterNode> Map(IList<IClusterNode> subgrid, string arg)
{
var res = new Dictionary<IComputeJob<int>, IClusterNode>();
var job = new StringLengthEmptyJob(arg);
IClusterNode node = subgrid[TestUtils.Random.Next(subgrid.Count)];
res.Add(job, node);
return res;
}
/** <inheritDoc /> */
public ComputeJobResultPolicy Result(IComputeJobResult<int> res, IList<IComputeJobResult<int>> rcvd)
{
return ComputeJobResultPolicy.Wait;
}
/** <inheritDoc /> */
public int Reduce(IList<IComputeJobResult<int>> results)
{
return results.Count == 0 ? 0 : results[0].Data();
}
}
/// <summary>
/// Test class.
/// </summary>
[Serializable]
public class StringLengthEmptyJob: IComputeJob<int>
{
/** */
private string _s;
/// <summary>
///
/// </summary>
/// <param name="s"></param>
public StringLengthEmptyJob(string s)
{
_s = s;
}
/** <inheritDoc /> */
public int Execute()
{
return _s.Length;
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op
}
}
public class MyReducer : IComputeReducer<int, int>
{
/** */
private int _res;
public bool Collect(int res)
{
_res += res;
return true;
}
public int Reduce()
{
return _res;
}
}
}
| |
// Copyright 2011 Chris Edwards
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using Fluency.DataGeneration;
using Machine.Specifications;
using SharpTestsEx;
// ReSharper disable InconsistentNaming
namespace Fluency.Tests.BuilderTests
{
public class DynamicFluentBuilderSpecs
{
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
public static DynamicFluentBuilder< TestClass > _builder;
Establish context = () =>
{
Fluency.Initialize( x => x.UseDefaultValueConventions() );
_builder = new DynamicFluentBuilder< TestClass >();
};
}
public class TestClass
{
public string StringProperty { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int IntegerProperty { get; set; }
public DateTime DateTimeProperty { get; set; }
public TestClass ReferenceProperty { get; set; }
public IList<TestClass> ListProperty { get; set; }
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
Because of = () => _result = _builder.build();
It should_use_default_convention_for_a_first_name_property = () => _result.FirstName.Satisfy( x => RandomData.FirstNames.Contains( x ) );
It should_use_default_convention_for_a_last_name_property = () => _result.LastName.Satisfy( x => RandomData.LastNames.Contains( x ) );
It should_use_default_convention_for_date_property = () => _result.DateTimeProperty.Should().Not.Be.EqualTo( default( DateTime ) );
It should_use_default_convention_for_integer_property = () => _result.IntegerProperty.Should().Not.Be.EqualTo( 0 );
It should_use_default_convention_for_string_property = () => _result.StringProperty.Length.Should().Be.EqualTo( 20 );
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_dynamic_date_time_property_value : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static DateTime _dateTime;
Establish context = () =>
{
_dateTime = ARandom.DateTime();
_builder.With( x => x.DateTimeProperty, _dateTime );
};
Because of = () => _result = _builder.build();
It should_use_the_provided_date_time = () => _result.DateTimeProperty.Should().Be.EqualTo( _dateTime );
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_dynamic_integer_property_value : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static int _expected;
Establish context = () =>
{
_expected = ARandom.Int();
_builder.With( x => x.IntegerProperty, _expected );
};
Because of = () => _result = _builder.build();
It should_use_the_provided_integer_value = () => _result.IntegerProperty.Should().Be.EqualTo( _expected );
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_dynamic_string_property_value : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static string _expected;
Establish context = () =>
{
_expected = ARandom.String( 20 );
_builder.With( x => x.StringProperty, _expected );
};
Because of = () => _result = _builder.build();
It should_use_the_provided_string_value = () => _result.StringProperty.Should().Be.EqualTo( _expected );
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_dynamic_property_value_using_For : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static string _expected;
Establish context = () =>
{
_expected = ARandom.String( 20 );
_builder.For( x => x.StringProperty, _expected );
};
Because of = () => _result = _builder.build();
It should_use_the_specified_value = () => _result.StringProperty.Should().Be.EqualTo( _expected );
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_dynamic_property_value_using_Having : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static string _expected;
Establish context = () =>
{
_expected = ARandom.String( 20 );
_builder.Having( x => x.StringProperty, _expected );
};
Because of = () => _result = _builder.build();
It should_use_the_specified_value = () => _result.StringProperty.Should().Be.EqualTo( _expected );
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_dynamic_property_builder_using_With : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static TestClass _expectedValue;
Establish context = () =>
{
// Create a builder that will return the expected value.
_expectedValue = new TestClass {FirstName = "Bob", LastName = "Smith"};
FluentBuilder< TestClass > propertyBuilder = new DynamicFluentBuilder< TestClass >().AliasFor( _expectedValue );
_builder.With( x => x.ReferenceProperty, propertyBuilder );
};
Because of = () => _result = _builder.build();
It should_use_the_specified_builder_to_build_the_result = () => _result.ReferenceProperty.Should().Be.EqualTo( _expectedValue );
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_dynamic_property_builder_using_For : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static TestClass _expectedValue;
Establish context = () =>
{
// Create a builder that will return the expected value.
_expectedValue = new TestClass {FirstName = "Bob", LastName = "Smith"};
FluentBuilder< TestClass > propertyBuilder = new DynamicFluentBuilder< TestClass >().AliasFor( _expectedValue );
_builder.For( x => x.ReferenceProperty, propertyBuilder );
};
Because of = () => _result = _builder.build();
It should_use_the_provided_builder_to_build_the_result = () => _result.ReferenceProperty.Should().Be.EqualTo( _expectedValue );
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_dynamic_property_builder_using_Having : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static TestClass _expectedValue;
Establish context = () =>
{
// Create a builder that will return the expected value.
_expectedValue = new TestClass {FirstName = "Bob", LastName = "Smith"};
FluentBuilder< TestClass > propertyBuilder = new DynamicFluentBuilder< TestClass >().AliasFor( _expectedValue );
_builder.Having( x => x.ReferenceProperty, propertyBuilder );
};
Because of = () => _result = _builder.build();
It should_use_the_provided_builder_to_build_the_result = () => _result.ReferenceProperty.Should().Be.EqualTo( _expectedValue );
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_list_property_values_using_WithListOf : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static TestClass _firstExpectedValue;
static TestClass _secondExpectedValue;
Establish context = () =>
{
// Create a builder that will return the expected value.
_firstExpectedValue = new TestClass {FirstName = "Bob", LastName = "Smith"};
_secondExpectedValue = new TestClass {FirstName = "Harry", LastName = "Johnson"};
_builder.WithListOf( x => x.ListProperty , _firstExpectedValue, _secondExpectedValue );
};
Because of = () => _result = _builder.build();
private It should_build_a_list_containing_the_specified_values = () =>
{
_result.ListProperty.Should().Contain( _firstExpectedValue );
_result.ListProperty.Should().Contain( _secondExpectedValue );
};
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_list_property_values_using_HavingListOf : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static TestClass _firstExpectedValue;
static TestClass _secondExpectedValue;
Establish context = () =>
{
// Create a builder that will return the expected value.
_firstExpectedValue = new TestClass {FirstName = "Bob", LastName = "Smith"};
_secondExpectedValue = new TestClass {FirstName = "Harry", LastName = "Johnson"};
_builder.HavingListOf( x => x.ListProperty , _firstExpectedValue, _secondExpectedValue );
};
Because of = () => _result = _builder.build();
private It should_build_a_list_containing_the_specified_values = () =>
{
_result.ListProperty.Should().Contain( _firstExpectedValue );
_result.ListProperty.Should().Contain( _secondExpectedValue );
};
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_list_property_builders_using_WithListOf : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static TestClass _firstExpectedValue;
static TestClass _secondExpectedValue;
Establish context = () =>
{
// Create a builder that will return the expected value.
_firstExpectedValue = new TestClass {FirstName = "Bob", LastName = "Smith"};
FluentBuilder<TestClass> firstValueBuilder = new DynamicFluentBuilder<TestClass>().AliasFor(_firstExpectedValue);
_secondExpectedValue = new TestClass {FirstName = "Harry", LastName = "Johnson"};
FluentBuilder<TestClass> secondValueBuilder = new DynamicFluentBuilder<TestClass>().AliasFor(_secondExpectedValue);
_builder.WithListOf( x => x.ListProperty , firstValueBuilder, secondValueBuilder );
};
Because of = () => _result = _builder.build();
private It should_build_a_list_containing_the_specified_values = () =>
{
_result.ListProperty.Should().Contain( _firstExpectedValue );
_result.ListProperty.Should().Contain( _secondExpectedValue );
};
}
[ Subject( typeof ( DynamicFluentBuilder< > ) ) ]
public class When_building_the_object_after_specifying_list_property_builders_using_HavingListOf : Given_a_DynamicFluentBuilder_that_uses_default_value_conventions
{
static TestClass _result;
static TestClass _firstExpectedValue;
static TestClass _secondExpectedValue;
Establish context = () =>
{
// Create a builder that will return the expected value.
_firstExpectedValue = new TestClass { FirstName = "Bob", LastName = "Smith" };
FluentBuilder<TestClass> firstValueBuilder = new DynamicFluentBuilder<TestClass>().AliasFor(_firstExpectedValue);
_secondExpectedValue = new TestClass { FirstName = "Harry", LastName = "Johnson" };
FluentBuilder<TestClass> secondValueBuilder = new DynamicFluentBuilder<TestClass>().AliasFor(_secondExpectedValue);
_builder.HavingListOf( x => x.ListProperty , firstValueBuilder, secondValueBuilder );
};
Because of = () => _result = _builder.build();
private It should_build_a_list_containing_the_specified_values = () =>
{
_result.ListProperty.Should().Contain( _firstExpectedValue );
_result.ListProperty.Should().Contain( _secondExpectedValue );
};
}
}
}
// ReSharper restore InconsistentNaming
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Material sourced from the bluePortal project (http://blueportal.codeplex.com).
// Licensed under the Microsoft Public License (available at http://www.opensource.org/licenses/ms-pl.html).
using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace CSSFriendly
{
public abstract class CompositeDataBoundControlAdapter : System.Web.UI.WebControls.Adapters.DataBoundControlAdapter
{
private WebControlAdapterExtender _extender = null;
private WebControlAdapterExtender Extender
{
get
{
if (((_extender == null) && (Control != null)) ||
((_extender != null) && (Control != _extender.AdaptedControl)))
{
_extender = new WebControlAdapterExtender(Control);
}
System.Diagnostics.Debug.Assert(_extender != null, "CSS Friendly adapters internal error", "Null extender instance");
return _extender;
}
}
protected string _classMain = "";
protected string _classHeader = "";
protected string _classData = "";
protected string _classFooter = "";
protected string _classPagination = "";
protected string _classOtherPage = "";
protected string _classActivePage = "";
protected CompositeDataBoundControl View
{
get { return Control as CompositeDataBoundControl; }
}
protected DetailsView ControlAsDetailsView
{
get { return Control as DetailsView; }
}
protected bool IsDetailsView
{
get { return ControlAsDetailsView != null; }
}
protected FormView ControlAsFormView
{
get { return Control as FormView; }
}
protected bool IsFormView
{
get { return ControlAsFormView != null; }
}
protected abstract string HeaderText { get; }
protected abstract string FooterText { get; }
protected abstract ITemplate HeaderTemplate { get; }
protected abstract ITemplate FooterTemplate { get; }
protected abstract TableRow HeaderRow { get; }
protected abstract TableRow FooterRow { get; }
protected abstract bool AllowPaging { get; }
protected abstract int DataItemCount { get; }
protected abstract int DataItemIndex { get; }
protected abstract PagerSettings PagerSettings { get; }
/// ///////////////////////////////////////////////////////////////////////////////
/// METHODS
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Extender.AdapterEnabled)
{
RegisterScripts();
}
}
protected override void RenderBeginTag(HtmlTextWriter writer)
{
if (Extender.AdapterEnabled)
{
Extender.RenderBeginTag(writer, _classMain);
}
else
{
base.RenderBeginTag(writer);
}
}
protected override void RenderEndTag(HtmlTextWriter writer)
{
if (Extender.AdapterEnabled)
{
Extender.RenderEndTag(writer);
}
else
{
base.RenderEndTag(writer);
}
}
protected override void RenderContents(HtmlTextWriter writer)
{
if (Extender.AdapterEnabled)
{
if (View != null)
{
writer.Indent++;
BuildRow(HeaderRow, _classHeader, writer);
BuildItem(writer);
BuildRow(FooterRow, _classFooter, writer);
BuildPaging(writer);
writer.Indent--;
writer.WriteLine();
}
}
else
{
base.RenderContents(writer);
}
}
protected virtual void BuildItem(HtmlTextWriter writer)
{
}
protected virtual void BuildRow(TableRow row, string cssClass, HtmlTextWriter writer)
{
if (row != null)
{
// If there isn't any content, don't render anything.
bool bHasContent = false;
TableCell cell = null;
for (int iCell = 0; iCell < row.Cells.Count; iCell++)
{
cell = row.Cells[iCell];
if ((!String.IsNullOrEmpty(cell.Text)) || (cell.Controls.Count > 0))
{
bHasContent = true;
break;
}
}
if (bHasContent)
{
writer.WriteLine();
writer.WriteBeginTag("div");
writer.WriteAttribute("class", cssClass);
writer.Write(HtmlTextWriter.TagRightChar);
writer.Indent++;
writer.WriteLine();
for (int iCell = 0; iCell < row.Cells.Count; iCell++)
{
cell = row.Cells[iCell];
if (!String.IsNullOrEmpty(cell.Text))
{
writer.Write(cell.Text);
}
foreach (Control cellChildControl in cell.Controls)
{
cellChildControl.RenderControl(writer);
}
}
writer.Indent--;
writer.WriteLine();
writer.WriteEndTag("div");
}
}
}
protected virtual void BuildPaging(HtmlTextWriter writer)
{
if (AllowPaging && (DataItemCount > 0))
{
writer.WriteLine();
writer.WriteBeginTag("div");
writer.WriteAttribute("class", _classPagination);
writer.Write(HtmlTextWriter.TagRightChar);
writer.Indent++;
int iStart = 0;
int iEnd = DataItemCount;
int nPages = iEnd - iStart + 1;
bool bExceededPageButtonCount = nPages > PagerSettings.PageButtonCount;
if (bExceededPageButtonCount)
{
iStart = (DataItemIndex / PagerSettings.PageButtonCount) * PagerSettings.PageButtonCount;
iEnd = Math.Min(iStart + PagerSettings.PageButtonCount, DataItemCount);
}
writer.WriteLine();
if (bExceededPageButtonCount && (iStart > 0))
{
writer.WriteBeginTag("a");
writer.WriteAttribute("class", _classOtherPage);
writer.WriteAttribute("href", Page.ClientScript.GetPostBackClientHyperlink(Control, "Page$" + iStart.ToString(), true));
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write("...");
writer.WriteEndTag("a");
}
for (int iDataItem = iStart; iDataItem < iEnd; iDataItem++)
{
string strPage = (iDataItem + 1).ToString();
if (DataItemIndex == iDataItem)
{
writer.WriteBeginTag("span");
writer.WriteAttribute("class", _classActivePage);
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write(strPage);
writer.WriteEndTag("span");
}
else
{
writer.WriteBeginTag("a");
writer.WriteAttribute("class", _classOtherPage);
writer.WriteAttribute("href", Page.ClientScript.GetPostBackClientHyperlink(Control, "Page$" + strPage, true));
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write(strPage);
writer.WriteEndTag("a");
}
}
if (bExceededPageButtonCount && (iEnd < DataItemCount))
{
writer.WriteBeginTag("a");
writer.WriteAttribute("class", _classOtherPage);
writer.WriteAttribute("href", Page.ClientScript.GetPostBackClientHyperlink(Control, "Page$" + (iEnd + 1).ToString(), true));
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write("...");
writer.WriteEndTag("a");
}
writer.Indent--;
writer.WriteLine();
writer.WriteEndTag("div");
}
}
protected virtual void RegisterScripts()
{
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Globalization;
using Xunit;
public class Queue_TrimToSize
{
public bool runTest()
{
//////////// Global Variables used for all tests
String strValue = String.Empty;
int iCountErrors = 0;
int iCountTestcases = 0;
Queue que;
Object dequeuedValue;
try
{
///////////////////////// START TESTS ////////////////////////////
iCountTestcases++;
que = new Queue();
try
{
que.TrimToSize();
}
catch (Exception)
{
iCountErrors++;
}
que = new Queue();
for (int i = 0; i < 1000; i++)
{
que.Enqueue(i);
}
try
{
que.TrimToSize();
}
catch (Exception)
{
iCountErrors++;
}
que = new Queue(100000);
try
{
que.TrimToSize();
}
catch (Exception)
{
iCountErrors++;
}
//[]Empty Queue
iCountTestcases++;
que = new Queue();
que.TrimToSize();
if (que.Count != 0)
{
iCountErrors++;
}
que.Enqueue(100);
if ((int)(dequeuedValue = que.Dequeue()) != 100)
{
iCountErrors++;
}
//[]After Clear
iCountTestcases++;
que = new Queue();
// Insert 50 items in the Queue
for (int i = 0; i < 100; i++)
{
que.Enqueue(i);
}
que.Clear();
que.TrimToSize();
if (que.Count != 0)
{
iCountErrors++;
}
que.Enqueue(100);
if ((int)(dequeuedValue = que.Dequeue()) != 100)
{
iCountErrors++;
}
//[]After Dequeue all items
iCountTestcases++;
que = new Queue();
// Insert 50 items in the Queue
for (int i = 0; i < 100; i++)
{
que.Enqueue(i);
}
for (int i = 0; i < 100; i++)
{
que.Dequeue();
}
que.TrimToSize();
if (que.Count != 0)
{
iCountErrors++;
}
que.Enqueue(100);
if ((int)(dequeuedValue = que.Dequeue()) != 100)
{
iCountErrors++;
}
//[]TrimToSize then Dequeue then EnQueue
iCountTestcases++;
que = new Queue();
// Insert 50 items in the Queue
for (int i = 0; i < 100; i++)
{
que.Enqueue(i);
}
que.TrimToSize();
if (que.Count != 100)
{
iCountErrors++;
}
if ((int)(dequeuedValue = que.Dequeue()) != 0)
{
iCountErrors++;
}
que.Enqueue(100);
if ((int)(dequeuedValue = que.Dequeue()) != 1)
{
iCountErrors++;
Console.WriteLine("Err_51084aheid! wrong value returned Expected={0} Actual={1}", 1, dequeuedValue);
}
//[] Wrap the queue then dequeue and enqueue
iCountTestcases++;
que = new Queue(100);
// Insert 50 items in the Queue
for (int i = 0; i < 50; i++)
{
que.Enqueue(i);
}
// Insert and Remove 75 items in the Queue this should wrap the queue
// Where there is 25 at the end of the array and 25 at the beginning
for (int i = 0; i < 75; i++)
{
que.Enqueue(i + 50);
que.Dequeue();
}
que.TrimToSize();
if (50 != que.Count)
{
iCountErrors++;
Console.WriteLine("Err_154488ahjeid! Count wrong value returned Expected={0} Actual={1}", 50, que.Count);
}
if ((int)(dequeuedValue = que.Dequeue()) != 75)
{
iCountErrors++;
Console.WriteLine("Err_410848ajeid! wrong value returned Expected={0} Actual={1}", 50, dequeuedValue);
}
// Add an item to the Queue
que.Enqueue(100);
if (50 != que.Count)
{
iCountErrors++;
Console.WriteLine("Err_152180ajekd! Count wrong value returned Expected={0} Actual={1}", 50, que.Count);
}
if ((int)(dequeuedValue = que.Dequeue()) != 76)
{
iCountErrors++;
Console.WriteLine("Err_5154ejhae! wrong value returned Expected={0} Actual={1}", 51, dequeuedValue);
}
//[] Wrap the queue then enqueue and dequeue
iCountTestcases++;
que = new Queue(100);
// Insert 50 items in the Queue
for (int i = 0; i < 50; i++)
{
que.Enqueue(i);
}
// Insert and Remove 75 items in the Queue this should wrap the queue
// Where there is 25 at the end of the array and 25 at the beginning
for (int i = 0; i < 75; i++)
{
que.Enqueue(i + 50);
que.Dequeue();
}
que.TrimToSize();
if (50 != que.Count)
{
iCountErrors++;
Console.WriteLine("Err_15418ajioed! Count wrong value returned Expected={0} Actual={1}", 50, que.Count);
}
// Add an item to the Queue
que.Enqueue(100);
if ((int)(dequeuedValue = que.Dequeue()) != 75)
{
iCountErrors++;
Console.WriteLine("Err_211508ajoied! wrong value returned Expected={0} Actual={1}", 50, dequeuedValue);
}
// Add an item to the Queue
que.Enqueue(101);
if (51 != que.Count)
{
iCountErrors++;
Console.WriteLine("Err_4055ajeid! Count wrong value returned Expected={0} Actual={1}", 51, que.Count);
}
if ((int)(dequeuedValue = que.Dequeue()) != 76)
{
iCountErrors++;
Console.WriteLine("Err_440815ajkejid! wrong value returned Expected={0} Actual={1}", 51, dequeuedValue);
}
//[]vanilla SYNCHRONIZED
iCountTestcases++;
que = new Queue();
que = Queue.Synchronized(que);
try
{
que.TrimToSize();
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("Err_1689asdfa! unexpected exception thrown," + ex.GetType().Name);
}
que = new Queue();
que = Queue.Synchronized(que);
for (int i = 0; i < 1000; i++)
{
que.Enqueue(i);
}
try
{
que.TrimToSize();
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("Err_79446jhjk! unexpected exception thrown," + ex.GetType().Name);
}
que = new Queue(100000);
que = Queue.Synchronized(que);
try
{
que.TrimToSize();
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("Err_4156hjkj! unexpected exception thrown," + ex.GetType().Name);
}
///////////////////////////////////////////////////////////////////
/////////////////////////// END TESTS /////////////////////////////
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine(" : Error Err_8888yyy! exc_general==" + exc_general.ToString());
}
//// Finish Diagnostics
return iCountErrors == 0;
}
[Fact]
public static void ExecuteQueue_TrimToSize()
{
bool bResult = false;
var test = new Queue_TrimToSize();
try
{
bResult = test.runTest();
}
catch (Exception exc_main)
{
bResult = false;
Console.WriteLine("Fail! Error Err_main! Uncaught Exception in main(), exc_main==" + exc_main);
}
Assert.True(bResult);
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Runtime.Scheduler;
using Microsoft.Extensions.Logging;
namespace Orleans.Runtime.ReminderService
{
internal class LocalReminderService : GrainService, IReminderService
{
private const int InitialReadRetryCountBeforeFastFailForUpdates = 2;
private static readonly TimeSpan InitialReadMaxWaitTimeForUpdates = TimeSpan.FromSeconds(20);
private static readonly TimeSpan InitialReadRetryPeriod = TimeSpan.FromSeconds(30);
private ILogger logger;
private readonly Dictionary<ReminderIdentity, LocalReminderData> localReminders;
private readonly IReminderTable reminderTable;
private long localTableSequence;
private IGrainTimer listRefreshTimer; // timer that refreshes our list of reminders to reflect global reminder table
private readonly TaskCompletionSource<bool> startedTask;
private uint initialReadCallCount = 0;
private readonly ILogger timerLogger;
private readonly ILoggerFactory loggerFactory;
private readonly AverageTimeSpanStatistic tardinessStat;
private readonly CounterStatistic ticksDeliveredStat;
private readonly TimeSpan initTimeout;
internal LocalReminderService(
Silo silo,
IReminderTable reminderTable,
TimeSpan initTimeout,
ILoggerFactory loggerFactory)
: base(GetGrainId(), silo, loggerFactory)
{
this.timerLogger = loggerFactory.CreateLogger<GrainTimer>();
localReminders = new Dictionary<ReminderIdentity, LocalReminderData>();
this.reminderTable = reminderTable;
this.initTimeout = initTimeout;
localTableSequence = 0;
this.loggerFactory = loggerFactory;
tardinessStat = AverageTimeSpanStatistic.FindOrCreate(StatisticNames.REMINDERS_AVERAGE_TARDINESS_SECONDS);
IntValueStatistic.FindOrCreate(StatisticNames.REMINDERS_NUMBER_ACTIVE_REMINDERS, () => localReminders.Count);
ticksDeliveredStat = CounterStatistic.FindOrCreate(StatisticNames.REMINDERS_COUNTERS_TICKS_DELIVERED);
startedTask = new TaskCompletionSource<bool>();
this.logger = this.loggerFactory.CreateLogger<LocalReminderService>();
}
/// <summary>
/// Attempt to retrieve reminders, that are my responsibility, from the global reminder table when starting this silo (reminder service instance)
/// </summary>
/// <returns></returns>
public override async Task Start()
{
// confirm that it can access the underlying store, as after this the ReminderService will load in the background, without the opportunity to prevent the Silo from starting
await reminderTable.Init().WithTimeout(initTimeout, $"ReminderTable Initialization failed due to timeout {initTimeout}");
await base.Start();
}
public async override Task Stop()
{
await base.Stop();
if (listRefreshTimer != null)
{
listRefreshTimer.Dispose();
listRefreshTimer = null;
}
foreach (LocalReminderData r in localReminders.Values)
r.StopReminder(logger);
// for a graceful shutdown, also handover reminder responsibilities to new owner, and update the ReminderTable
// currently, this is taken care of by periodically reading the reminder table
}
public async Task<IGrainReminder> RegisterOrUpdateReminder(GrainReference grainRef, string reminderName, TimeSpan dueTime, TimeSpan period)
{
var entry = new ReminderEntry
{
GrainRef = grainRef,
ReminderName = reminderName,
StartAt = DateTime.UtcNow.Add(dueTime),
Period = period,
};
if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_RegisterOrUpdate, "RegisterOrUpdateReminder: {0}", entry.ToString());
await DoResponsibilitySanityCheck(grainRef, "RegisterReminder");
var newEtag = await reminderTable.UpsertRow(entry);
if (newEtag != null)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Registered reminder {0} in table, assigned localSequence {1}", entry, localTableSequence);
entry.ETag = newEtag;
StartAndAddTimer(entry);
if (logger.IsEnabled(LogLevel.Trace)) PrintReminders();
return new ReminderData(grainRef, reminderName, newEtag) as IGrainReminder;
}
var msg = string.Format("Could not register reminder {0} to reminder table due to a race. Please try again later.", entry);
logger.Error(ErrorCode.RS_Register_TableError, msg);
throw new ReminderException(msg);
}
/// <summary>
/// Stop the reminder locally, and remove it from the external storage system
/// </summary>
/// <param name="reminder"></param>
/// <returns></returns>
public async Task UnregisterReminder(IGrainReminder reminder)
{
var remData = (ReminderData)reminder;
if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_Unregister, "UnregisterReminder: {0}, LocalTableSequence: {1}", remData, localTableSequence);
GrainReference grainRef = remData.GrainRef;
string reminderName = remData.ReminderName;
string eTag = remData.ETag;
await DoResponsibilitySanityCheck(grainRef, "RemoveReminder");
// it may happen that we dont have this reminder locally ... even then, we attempt to remove the reminder from the reminder
// table ... the periodic mechanism will stop this reminder at any silo's LocalReminderService that might have this reminder locally
// remove from persistent/memory store
var success = await reminderTable.RemoveRow(grainRef, reminderName, eTag);
if (success)
{
bool removed = TryStopPreviousTimer(grainRef, reminderName);
if (removed)
{
if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_Stop, "Stopped reminder {0}", reminder);
if (logger.IsEnabled(LogLevel.Trace)) PrintReminders(string.Format("After removing {0}.", reminder));
}
else
{
// no-op
if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_RemoveFromTable, "Removed reminder from table which I didn't have locally: {0}.", reminder);
}
}
else
{
var msg = string.Format("Could not unregister reminder {0} from the reminder table, due to tag mismatch. You can retry.", reminder);
logger.Error(ErrorCode.RS_Unregister_TableError, msg);
throw new ReminderException(msg);
}
}
public async Task<IGrainReminder> GetReminder(GrainReference grainRef, string reminderName)
{
if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_GetReminder,"GetReminder: GrainReference={0} ReminderName={1}", grainRef.ToDetailedString(), reminderName);
var entry = await reminderTable.ReadRow(grainRef, reminderName);
return entry == null ? null : entry.ToIGrainReminder();
}
public async Task<List<IGrainReminder>> GetReminders(GrainReference grainRef)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_GetReminders, "GetReminders: GrainReference={0}", grainRef.ToDetailedString());
var tableData = await reminderTable.ReadRows(grainRef);
return tableData.Reminders.Select(entry => entry.ToIGrainReminder()).ToList();
}
/// <summary>
/// Attempt to retrieve reminders from the global reminder table
/// </summary>
private async Task ReadAndUpdateReminders()
{
if (StoppedCancellationTokenSource.IsCancellationRequested) return;
RemoveOutOfRangeReminders();
// try to retrieve reminders from all my subranges
var rangeSerialNumberCopy = RangeSerialNumber;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace($"My range= {RingRange}, RangeSerialNumber {RangeSerialNumber}. Local reminders count {localReminders.Count}");
var acks = new List<Task>();
foreach (var range in RangeFactory.GetSubRanges(RingRange))
{
acks.Add(ReadTableAndStartTimers(range, rangeSerialNumberCopy));
}
await Task.WhenAll(acks);
if (logger.IsEnabled(LogLevel.Trace)) PrintReminders();
}
private void RemoveOutOfRangeReminders()
{
var remindersOutOfRange = localReminders.Where(r => !RingRange.InRange(r.Key.GrainRef)).Select(r => r.Value).ToArray();
foreach (var reminder in remindersOutOfRange)
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("Not in my range anymore, so removing. {0}", reminder);
// remove locally
reminder.StopReminder(logger);
localReminders.Remove(reminder.Identity);
}
if (logger.IsEnabled(LogLevel.Information) && remindersOutOfRange.Length > 0) logger.Info($"Removed {remindersOutOfRange.Length} local reminders that are now out of my range.");
}
public override async Task OnRangeChange(IRingRange oldRange, IRingRange newRange, bool increased)
{
await base.OnRangeChange(oldRange, newRange, increased);
if (Status == GrainServiceStatus.Started)
await ReadAndUpdateReminders();
else
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Ignoring range change until ReminderService is Started -- Current status = {0}", Status);
}
protected override async Task StartInBackground()
{
await DoInitialReadAndUpdateReminders();
if (Status == GrainServiceStatus.Booting)
{
var random = new SafeRandom();
listRefreshTimer = GrainTimer.FromTaskCallback(
this.RuntimeClient.Scheduler,
this.timerLogger,
_ => DoInitialReadAndUpdateReminders(),
null,
random.NextTimeSpan(InitialReadRetryPeriod),
InitialReadRetryPeriod,
name: "ReminderService.ReminderListInitialRead");
listRefreshTimer.Start();
}
}
private void PromoteToStarted()
{
if (StoppedCancellationTokenSource.IsCancellationRequested) return;
// Logger.Info(ErrorCode.RS_ServiceStarted, "Reminder system target started OK on: {0} x{1,8:X8}, with range {2}", this.Silo, this.Silo.GetConsistentHashCode(), this.myRange);
var random = new SafeRandom();
var dueTime = random.NextTimeSpan(Constants.RefreshReminderList);
if (listRefreshTimer != null) listRefreshTimer.Dispose();
listRefreshTimer = GrainTimer.FromTaskCallback(
this.RuntimeClient.Scheduler,
this.timerLogger,
_ => ReadAndUpdateReminders(),
null,
dueTime,
Constants.RefreshReminderList,
name: "ReminderService.ReminderListRefresher");
listRefreshTimer.Start();
Status = GrainServiceStatus.Started;
startedTask.TrySetResult(true);
}
private async Task DoInitialReadAndUpdateReminders()
{
try
{
if (StoppedCancellationTokenSource.IsCancellationRequested) return;
initialReadCallCount++;
await this.ReadAndUpdateReminders();
PromoteToStarted();
}
catch (Exception ex)
{
if (StoppedCancellationTokenSource.IsCancellationRequested) return;
if (initialReadCallCount <= InitialReadRetryCountBeforeFastFailForUpdates)
{
logger.Warn(
ErrorCode.RS_ServiceInitialLoadFailing,
string.Format("ReminderService failed initial load of reminders and will retry. Attempt #{0}", this.initialReadCallCount),
ex);
}
else
{
const string baseErrorMsg = "ReminderService failed initial load of reminders and cannot guarantee that the service will be eventually start without manual intervention or restarting the silo.";
var logErrorMessage = string.Format(baseErrorMsg + " Attempt #{0}", this.initialReadCallCount);
logger.Error(ErrorCode.RS_ServiceInitialLoadFailed, logErrorMessage, ex);
startedTask.TrySetException(new OrleansException(baseErrorMsg, ex));
}
}
}
private async Task ReadTableAndStartTimers(IRingRange range, int rangeSerialNumberCopy)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Reading rows from {0}", range.ToString());
localTableSequence++;
long cachedSequence = localTableSequence;
try
{
var srange = range as ISingleRange;
if (srange == null)
throw new InvalidOperationException("LocalReminderService must be dealing with SingleRange");
ReminderTableData table = await reminderTable.ReadRows(srange.Begin, srange.End); // get all reminders, even the ones we already have
if (rangeSerialNumberCopy < RangeSerialNumber)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"My range changed while reading from the table, ignoring the results. Another read has been started. RangeSerialNumber {RangeSerialNumber}, RangeSerialNumberCopy {rangeSerialNumberCopy}.");
return;
}
if (StoppedCancellationTokenSource.IsCancellationRequested) return;
// if null is a valid value, it means that there's nothing to do.
if (null == table && reminderTable is MockReminderTable) return;
var remindersNotInTable = localReminders.Where(r => range.InRange(r.Key.GrainRef)).ToDictionary(r => r.Key, r => r.Value); // shallow copy
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("For range {0}, I read in {1} reminders from table. LocalTableSequence {2}, CachedSequence {3}", range.ToString(), table.Reminders.Count, localTableSequence, cachedSequence);
foreach (ReminderEntry entry in table.Reminders)
{
var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
LocalReminderData localRem;
if (localReminders.TryGetValue(key, out localRem))
{
if (cachedSequence > localRem.LocalSequenceNumber) // info read from table is same or newer than local info
{
if (localRem.Timer != null) // if ticking
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Old, & Ticking {0}", localRem);
// it might happen that our local reminder is different than the one in the table, i.e., eTag is different
// if so, stop the local timer for the old reminder, and start again with new info
if (!localRem.ETag.Equals(entry.ETag))
// this reminder needs a restart
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("{0} Needs a restart", localRem);
localRem.StopReminder(logger);
localReminders.Remove(localRem.Identity);
StartAndAddTimer(entry);
}
}
else // if not ticking
{
// no-op
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Old, & Not Ticking {0}", localRem);
}
}
else // cachedSequence < localRem.LocalSequenceNumber ... // info read from table is older than local info
{
if (localRem.Timer != null) // if ticking
{
// no-op
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Newer, & Ticking {0}", localRem);
}
else // if not ticking
{
// no-op
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Newer, & Not Ticking {0}", localRem);
}
}
}
else // exists in table, but not locally
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, Not in local, {0}", entry);
// create and start the reminder
StartAndAddTimer(entry);
}
// keep a track of extra reminders ... this 'reminder' is useful, so remove it from extra list
remindersNotInTable.Remove(key);
} // foreach reminder read from table
int remindersCountBeforeRemove = localReminders.Count;
// foreach reminder that is not in global table, but exists locally
foreach (var reminder in remindersNotInTable.Values)
{
if (cachedSequence < reminder.LocalSequenceNumber)
{
// no-op
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Not in table, In local, Newer, {0}", reminder);
}
else // cachedSequence > reminder.LocalSequenceNumber
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Not in table, In local, Old, so removing. {0}", reminder);
// remove locally
reminder.StopReminder(logger);
localReminders.Remove(reminder.Identity);
}
}
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"Removed {localReminders.Count - remindersCountBeforeRemove} reminders from local table");
}
catch (Exception exc)
{
logger.Error(ErrorCode.RS_FailedToReadTableAndStartTimer, "Failed to read rows from table.", exc);
throw;
}
}
private void StartAndAddTimer(ReminderEntry entry)
{
// it might happen that we already have a local reminder with a different eTag
// if so, stop the local timer for the old reminder, and start again with new info
// Note: it can happen here that we restart a reminder that has the same eTag as what we just registered ... its a rare case, and restarting it doesn't hurt, so we don't check for it
var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
LocalReminderData prevReminder;
if (localReminders.TryGetValue(key, out prevReminder)) // if found locally
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_LocalStop, "Locally stopping reminder {0} as it is different than newly registered reminder {1}", prevReminder, entry);
prevReminder.StopReminder(logger);
localReminders.Remove(prevReminder.Identity);
}
var newReminder = new LocalReminderData(entry, this.loggerFactory);
localTableSequence++;
newReminder.LocalSequenceNumber = localTableSequence;
localReminders.Add(newReminder.Identity, newReminder);
newReminder.StartTimer(this.RuntimeClient.Scheduler, AsyncTimerCallback, logger);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_Started, "Started reminder {0}.", entry.ToString());
}
// stop without removing it. will remove later.
private bool TryStopPreviousTimer(GrainReference grainRef, string reminderName)
{
// we stop the locally running timer for this reminder
var key = new ReminderIdentity(grainRef, reminderName);
LocalReminderData localRem;
if (!localReminders.TryGetValue(key, out localRem)) return false;
// if we have it locally
localTableSequence++; // move to next sequence
localRem.LocalSequenceNumber = localTableSequence;
localRem.StopReminder(logger);
return true;
}
/// <summary>
/// Local timer expired ... notify it as a 'tick' to the grain who registered this reminder
/// </summary>
/// <param name="rem">Reminder that this timeout represents</param>
private async Task AsyncTimerCallback(object rem)
{
var reminder = (LocalReminderData)rem;
if (!localReminders.ContainsKey(reminder.Identity) // we have already stopped this timer
|| reminder.Timer == null) // this timer was unregistered, and is waiting to be gc-ied
return;
ticksDeliveredStat.Increment();
await reminder.OnTimerTick(tardinessStat, logger);
}
private async Task DoResponsibilitySanityCheck(GrainReference grainRef, string debugInfo)
{
switch (Status)
{
case GrainServiceStatus.Booting:
// if service didn't finish the initial load, it could still be loading normally or it might have already
// failed a few attempts and callers should not be hold waiting for it to complete
var task = this.startedTask.Task;
if (task.IsCompleted)
{
// task at this point is already Faulted
await task;
}
else
{
try
{
// wait for the initial load task to complete (with a timeout)
await task.WithTimeout(InitialReadMaxWaitTimeForUpdates);
}
catch (TimeoutException ex)
{
throw new OrleansException("Reminder Service is still initializing and it is taking a long time. Please retry again later.", ex);
}
}
break;
case GrainServiceStatus.Started:
break;
case GrainServiceStatus.Stopped:
throw new OperationCanceledException("ReminderService has been stopped.");
default:
throw new InvalidOperationException("status");
}
if (!RingRange.InRange(grainRef))
{
logger.Warn(ErrorCode.RS_NotResponsible, "I shouldn't have received request '{0}' for {1}. It is not in my responsibility range: {2}",
debugInfo, grainRef.ToDetailedString(), RingRange);
// For now, we still let the caller proceed without throwing an exception... the periodical mechanism will take care of reminders being registered at the wrong silo
// otherwise, we can either reject the request, or re-route the request
}
}
// Note: The list of reminders can be huge in production!
private void PrintReminders(string msg = null)
{
if (!logger.IsEnabled(LogLevel.Trace)) return;
var str = String.Format("{0}{1}{2}", (msg ?? "Current list of reminders:"), Environment.NewLine,
Utils.EnumerableToString(localReminders, null, Environment.NewLine));
logger.Trace(str);
}
private static GrainId GetGrainId()
{
var typeCode = GrainInterfaceUtils.GetGrainClassTypeCode(typeof(IReminderService));
return GrainId.GetGrainServiceGrainId(0, typeCode);
}
private class LocalReminderData
{
private readonly IRemindable remindable;
private Stopwatch stopwatch;
private readonly DateTime firstTickTime; // time for the first tick of this reminder
private readonly TimeSpan period;
private GrainReference GrainRef { get { return Identity.GrainRef; } }
private string ReminderName { get { return Identity.ReminderName; } }
private readonly ILogger timerLogger;
internal ReminderIdentity Identity { get; private set; }
internal string ETag;
internal IGrainTimer Timer;
internal long LocalSequenceNumber; // locally, we use this for resolving races between the periodic table reader, and any concurrent local register/unregister requests
internal LocalReminderData(ReminderEntry entry, ILoggerFactory loggerFactory)
{
Identity = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
firstTickTime = entry.StartAt;
period = entry.Period;
remindable = entry.GrainRef.Cast<IRemindable>();
ETag = entry.ETag;
LocalSequenceNumber = -1;
this.timerLogger = loggerFactory.CreateLogger<GrainTimer>();
}
public void StartTimer(OrleansTaskScheduler scheduler, Func<object, Task> asyncCallback, ILogger Logger)
{
StopReminder(Logger); // just to make sure.
var dueTimeSpan = CalculateDueTime();
Timer = GrainTimer.FromTaskCallback(scheduler, this.timerLogger, asyncCallback, this, dueTimeSpan, period, name: ReminderName);
if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Reminder {0}, Due time{1}", this, dueTimeSpan);
Timer.Start();
}
public void StopReminder(ILogger Logger)
{
if (Timer != null)
Timer.Dispose();
Timer = null;
}
private TimeSpan CalculateDueTime()
{
TimeSpan dueTimeSpan;
var now = DateTime.UtcNow;
if (now < firstTickTime) // if the time for first tick hasn't passed yet
{
dueTimeSpan = firstTickTime.Subtract(now); // then duetime is duration between now and the first tick time
}
else // the first tick happened in the past ... compute duetime based on the first tick time, and period
{
// formula used:
// due = period - 'time passed since last tick (==sinceLast)'
// due = period - ((Now - FirstTickTime) % period)
// explanation of formula:
// (Now - FirstTickTime) => gives amount of time since first tick happened
// (Now - FirstTickTime) % period => gives amount of time passed since the last tick should have triggered
var sinceFirstTick = now.Subtract(firstTickTime);
var sinceLastTick = TimeSpan.FromTicks(sinceFirstTick.Ticks % period.Ticks);
dueTimeSpan = period.Subtract(sinceLastTick);
// in corner cases, dueTime can be equal to period ... so, take another mod
dueTimeSpan = TimeSpan.FromTicks(dueTimeSpan.Ticks % period.Ticks);
}
return dueTimeSpan;
}
public async Task OnTimerTick(AverageTimeSpanStatistic tardinessStat, ILogger Logger)
{
var before = DateTime.UtcNow;
var status = TickStatus.NewStruct(firstTickTime, period, before);
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Triggering tick for {0}, status {1}, now {2}", this.ToString(), status, before);
try
{
if (null != stopwatch)
{
stopwatch.Stop();
var tardiness = stopwatch.Elapsed - period;
tardinessStat.AddSample(Math.Max(0, tardiness.Ticks));
}
await remindable.ReceiveReminder(ReminderName, status);
if (null == stopwatch)
stopwatch = new Stopwatch();
stopwatch.Restart();
var after = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace))
Logger.Trace("Tick triggered for {0}, dt {1} sec, next@~ {2}", this.ToString(), (after - before).TotalSeconds,
// the next tick isn't actually scheduled until we return control to
// AsyncSafeTimer but we can approximate it by adding the period of the reminder
// to the after time.
after + period);
}
catch (Exception exc)
{
var after = DateTime.UtcNow;
Logger.Error(
ErrorCode.RS_Tick_Delivery_Error,
String.Format("Could not deliver reminder tick for {0}, next {1}.", this.ToString(), after + period),
exc);
// What to do with repeated failures to deliver a reminder's ticks?
}
}
public override string ToString()
{
return string.Format("[{0}, {1}, {2}, {3}, {4}, {5}, {6}]",
ReminderName,
GrainRef.ToDetailedString(),
period,
LogFormatter.PrintDate(firstTickTime),
ETag,
LocalSequenceNumber,
Timer == null ? "Not_ticking" : "Ticking");
}
}
private struct ReminderIdentity : IEquatable<ReminderIdentity>
{
private readonly GrainReference grainRef;
private readonly string reminderName;
public GrainReference GrainRef { get { return grainRef; } }
public string ReminderName { get { return reminderName; } }
public ReminderIdentity(GrainReference grainRef, string reminderName)
{
if (grainRef == null)
throw new ArgumentNullException("grainRef");
if (string.IsNullOrWhiteSpace(reminderName))
throw new ArgumentException("The reminder name is either null or whitespace.", "reminderName");
this.grainRef = grainRef;
this.reminderName = reminderName;
}
public bool Equals(ReminderIdentity other)
{
return grainRef.Equals(other.grainRef) && reminderName.Equals(other.reminderName);
}
public override bool Equals(object other)
{
return (other is ReminderIdentity) && Equals((ReminderIdentity)other);
}
public override int GetHashCode()
{
return unchecked((int)((uint)grainRef.GetHashCode() + (uint)reminderName.GetHashCode()));
}
}
}
}
| |
using System;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Xml;
using MbUnit.Framework;
using Moq;
using Subtext.Extensibility;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Framework.Providers;
using Subtext.Framework.Routing;
using Subtext.Framework.Syndication;
using Subtext.Framework.Web.HttpModules;
using UnitTests.Subtext.Framework.Util;
namespace UnitTests.Subtext.Framework.Syndication
{
/// <summary>
/// Tests of the RssHandler http handler class.
/// </summary>
[TestFixture]
public class RssHandlerTests
{
/// <summary>
/// Tests writing a simple RSS feed from some database entries.
/// </summary>
[Test]
[RollBack]
public void RssWriterProducesValidFeedFromDatabase()
{
string hostName = UnitTestHelper.GenerateUniqueHostname();
Config.CreateBlog("Test", "username", "password", hostName, string.Empty);
UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "");
BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
Config.CurrentBlog.Email = "Subtext@example.com";
Config.CurrentBlog.RFC3229DeltaEncodingEnabled = false;
Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("Author",
"testtitle",
"testbody",
null,
NullValue.NullDateTime);
entry.DateCreated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture);
entry.DateSyndicated = entry.DateCreated;
UnitTestHelper.Create(entry); //persist to db.
string rssOutput = null;
var subtextContext = new Mock<ISubtextContext>();
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
Mock<UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper);
urlHelper.Setup(u => u.BlogUrl()).Returns("/");
urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/archive/2008/01/23/testtitle.aspx");
XmlNodeList itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);
Assert.AreEqual(1, itemNodes.Count, "expected one item nodes.");
string urlFormat = "http://{0}/archive/2008/01/23/{1}.aspx";
string expectedUrl = string.Format(urlFormat, hostName, "testtitle");
Assert.AreEqual("testtitle", itemNodes[0].SelectSingleNode("title").InnerText,
"Not what we expected for the title.");
Assert.AreEqual(expectedUrl, itemNodes[0].SelectSingleNode("link").InnerText,
"Not what we expected for the link.");
Assert.AreEqual(expectedUrl, itemNodes[0].SelectSingleNode("guid").InnerText,
"Not what we expected for the link.");
Assert.AreEqual(expectedUrl + "#feedback", itemNodes[0].SelectSingleNode("comments").InnerText,
"Not what we expected for the link.");
}
[Test]
[RollBack]
public void RssWriterProducesValidFeedWithEnclosureFromDatabase()
{
string hostName = UnitTestHelper.GenerateUniqueString() + ".com";
Config.CreateBlog("Test", "username", "password", hostName, string.Empty);
UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "");
BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
Config.CurrentBlog.Email = "Subtext@example.com";
Config.CurrentBlog.RFC3229DeltaEncodingEnabled = false;
Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("Author", "testtitle", "testbody", null,
NullValue.NullDateTime);
entry.DateCreated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture);
entry.DateSyndicated = entry.DateCreated;
int entryId = UnitTestHelper.Create(entry); //persist to db.
string enclosureUrl = "http://perseus.franklins.net/hanselminutes_0107.mp3";
string enclosureMimeType = "audio/mp3";
long enclosureSize = 26707573;
Enclosure enc =
UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>",
enclosureUrl, enclosureMimeType, entryId, enclosureSize, true, true);
Enclosures.Create(enc);
var subtextContext = new Mock<ISubtextContext>();
string rssOutput = null;
subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
Mock<UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper);
urlHelper.Setup(u => u.BlogUrl()).Returns("/");
urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/archive/2008/01/23/testtitle.aspx");
XmlNodeList itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);
Assert.AreEqual(1, itemNodes.Count, "expected one item nodes.");
string urlFormat = "http://{0}/archive/2008/01/23/{1}.aspx";
string expectedUrl = string.Format(urlFormat, hostName, "testtitle");
Assert.AreEqual("testtitle", itemNodes[0].SelectSingleNode("title").InnerText,
"Not what we expected for the title.");
Assert.AreEqual(expectedUrl, itemNodes[0].SelectSingleNode("link").InnerText,
"Not what we expected for the link.");
Assert.AreEqual(expectedUrl, itemNodes[0].SelectSingleNode("guid").InnerText,
"Not what we expected for the guid.");
Assert.AreEqual(enclosureUrl, itemNodes[0].SelectSingleNode("enclosure/@url").InnerText,
"Not what we expected for the enclosure url.");
Assert.AreEqual(enclosureMimeType, itemNodes[0].SelectSingleNode("enclosure/@type").InnerText,
"Not what we expected for the enclosure mimetype.");
Assert.AreEqual(enclosureSize.ToString(), itemNodes[0].SelectSingleNode("enclosure/@length").InnerText,
"Not what we expected for the enclosure size.");
Assert.AreEqual(expectedUrl + "#feedback", itemNodes[0].SelectSingleNode("comments").InnerText,
"Not what we expected for the link.");
}
/// <summary>
/// Tests that a simple regular RSS feed works.
/// </summary>
[Test]
[RollBack]
public void RssHandlerProducesValidRssFeed()
{
string hostName = UnitTestHelper.GenerateUniqueHostname();
UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "");
Config.CreateBlog("", "username", "password", hostName, string.Empty);
BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
UnitTestHelper.Create(UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test",
"Body Rocking"));
Thread.Sleep(50);
UnitTestHelper.Create(UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test 2",
"Body Rocking Pt 2"));
var subtextContext = new Mock<ISubtextContext>();
string rssOutput = null;
subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
Mock<UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper);
urlHelper.Setup(u => u.BlogUrl()).Returns("/");
urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/whatever");
XmlNodeList itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);
Assert.AreEqual(2, itemNodes.Count, "expected two item nodes.");
Assert.AreEqual("Title Test 2", itemNodes[0].SelectSingleNode("title").InnerText,
"Not what we expected for the second title.");
Assert.AreEqual("Title Test", itemNodes[1].SelectSingleNode("title").InnerText,
"Not what we expected for the first title.");
Assert.AreEqual("Body Rocking Pt 2",
itemNodes[0].SelectSingleNode("description").InnerText.Substring(0,
"Body Rocking pt 2".Length),
"Not what we expected for the second body.");
Assert.AreEqual("Body Rocking",
itemNodes[1].SelectSingleNode("description").InnerText.Substring(0, "Body Rocking".Length),
"Not what we expected for the first body.");
}
/// <summary>
/// Tests that items without a date syndicated are not syndicated.
/// </summary>
[Test]
[RollBack]
public void RssHandlerHandlesDateSyndicatedProperly()
{
// arrange
string hostName = UnitTestHelper.GenerateUniqueHostname();
UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "");
Config.CreateBlog("", "username", "password", hostName, string.Empty);
BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
//Create two entries, but only include one in main syndication.
Entry entryForSyndication = UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test",
"Body Rocking");
UnitTestHelper.Create(entryForSyndication);
Entry entryTwoForSyndication = UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test 2",
"Body Rocking Pt 2");
int id = UnitTestHelper.Create(entryTwoForSyndication);
Entry entry = UnitTestHelper.GetEntry(id, PostConfig.None, false);
DateTime date = entry.DateSyndicated;
entry.IncludeInMainSyndication = false;
entry.Blog = new Blog() { Title = "MyTestBlog" };
var subtextContext = new Mock<ISubtextContext>();
subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog);
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
UnitTestHelper.Update(entry, subtextContext.Object);
Assert.AreEqual(date, entry.DateSyndicated);
string rssOutput = null;
subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
Mock<UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper);
urlHelper.Setup(u => u.BlogUrl()).Returns("/");
urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/whatever");
XmlNodeList itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);
Assert.AreEqual(1, itemNodes.Count, "expected one item node.");
Assert.AreEqual("Title Test", itemNodes[0].SelectSingleNode("title").InnerText,
"Not what we expected for the first title.");
Assert.AreEqual("Body Rocking",
itemNodes[0].SelectSingleNode("description").InnerText.Substring(0, "Body Rocking".Length),
"Not what we expected for the first body.");
//Include the second entry back in the syndication.
entry.IncludeInMainSyndication = true;
UnitTestHelper.Update(entry, subtextContext.Object);
UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "", "");
BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
subtextContext = new Mock<ISubtextContext>();
subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
urlHelper = Mock.Get(subtextContext.Object.UrlHelper);
urlHelper.Setup(u => u.BlogUrl()).Returns("/");
urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/whatever");
itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);
Assert.AreEqual(2, itemNodes.Count, "Expected two items in the feed now.");
}
/// <summary>
/// Tests that the RssHandler orders items by DateSyndicated.
/// </summary>
[Test]
[RollBack]
public void RssHandlerSortsByDateSyndicated()
{
// Setup
string hostName = UnitTestHelper.GenerateUniqueHostname();
UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "");
Config.CreateBlog("", "username", "password", hostName, string.Empty);
BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
//Create two entries.
int firstId =
UnitTestHelper.Create(UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test",
"Body Rocking"));
Thread.Sleep(1000);
UnitTestHelper.Create(UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test 2",
"Body Rocking Pt 2"));
var subtextContext = new Mock<ISubtextContext>();
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
string rssOutput = null;
subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
Mock<UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper);
urlHelper.Setup(u => u.BlogUrl()).Returns("/");
urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/whatever");
XmlNodeList itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);
//Expect the first item to be the second entry.
Assert.AreEqual("Title Test 2", itemNodes[0].SelectSingleNode("title").InnerText,
"Not what we expected for the first title.");
Assert.AreEqual("Title Test", itemNodes[1].SelectSingleNode("title").InnerText,
"Not what we expected for the second title.");
//Remove first entry from syndication.
Entry firstEntry = UnitTestHelper.GetEntry(firstId, PostConfig.None, false);
firstEntry.IncludeInMainSyndication = false;
firstEntry.Blog = new Blog() { Title = "MyTestBlog" };
UnitTestHelper.Update(firstEntry, subtextContext.Object);
UnitTestHelper.SetHttpContextWithBlogRequest(hostName, string.Empty);
BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
subtextContext = new Mock<ISubtextContext>();
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
rssOutput = null;
subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
urlHelper = Mock.Get(subtextContext.Object.UrlHelper);
urlHelper.Setup(u => u.BlogUrl()).Returns("/");
urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/whatever");
itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);
Assert.AreEqual(1, itemNodes.Count, "Here we were expeting only one item");
Thread.Sleep(10);
//Now add it back in changing the DateSyndicated
firstEntry.IncludeInMainSyndication = true;
firstEntry.DateSyndicated = Config.CurrentBlog.TimeZone.Now;
UnitTestHelper.Update(firstEntry, subtextContext.Object);
UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "");
BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
subtextContext = new Mock<ISubtextContext>();
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
rssOutput = null;
subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
urlHelper = Mock.Get(subtextContext.Object.UrlHelper);
urlHelper.Setup(u => u.BlogUrl()).Returns("/");
urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/whatever");
itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);
//Expect the second item to be the second entry.
Assert.AreEqual(2, itemNodes.Count, "Here we were expeting 2 items");
Assert.AreEqual("Title Test", itemNodes[0].SelectSingleNode("title").InnerText,
"Not what we expected for the first title.");
Assert.AreEqual("Title Test 2", itemNodes[1].SelectSingleNode("title").InnerText,
"Not what we expected for the second title.");
}
[Test]
[RollBack]
public void RssHandlerHandlesDoesNotSyndicateFuturePosts()
{
// Setup
string hostName = UnitTestHelper.GenerateUniqueHostname();
UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "");
Config.CreateBlog("", "username", "password", hostName, string.Empty);
BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
Config.CurrentBlog.TimeZoneId = TimeZonesTest.HawaiiTimeZoneId;
//Create two entries, but only include one in main syndication.
UnitTestHelper.Create(UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test",
"Body Rocking", null,
NullValue.NullDateTime));
Entry futureEntry = UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test 2",
"Body Rocking Pt 2", null,
NullValue.NullDateTime);
futureEntry.DateSyndicated = Config.CurrentBlog.TimeZone.Now.AddMinutes(20);
UnitTestHelper.Create(futureEntry);
string rssOutput = null;
var subtextContext = new Mock<ISubtextContext>();
subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
Mock<UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper);
urlHelper.Setup(u => u.BlogUrl()).Returns("/");
urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/whatever");
XmlNodeList itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);
Assert.AreEqual(1, itemNodes.Count, "expected one item node.");
Assert.AreEqual("Title Test", itemNodes[0].SelectSingleNode("title").InnerText,
"Not what we expected for the first title.");
Assert.AreEqual("Body Rocking",
itemNodes[0].SelectSingleNode("description").InnerText.Substring(0, "Body Rocking".Length),
"Not what we expected for the first body.");
Config.CurrentBlog.TimeZoneId = TimeZonesTest.PacificTimeZoneId;
UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "");
BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
subtextContext = new Mock<ISubtextContext>();
rssOutput = null;
subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
urlHelper = Mock.Get(subtextContext.Object.UrlHelper);
urlHelper.Setup(u => u.BlogUrl()).Returns("/");
urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/whatever");
itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);
Assert.AreEqual(2, itemNodes.Count, "Expected two items in the feed now.");
}
private static XmlNodeList GetRssHandlerItemNodes(ISubtextContext context, ref string rssOutput)
{
var handler = new RssHandler(context);
handler.ProcessRequest();
var doc = new XmlDocument();
doc.LoadXml(rssOutput);
return doc.SelectNodes("/rss/channel/item");
}
private static XmlNodeList GetRssHandlerItemNodes(ISubtextContext context, StringBuilder sb)
{
string output = sb.ToString();
return GetRssHandlerItemNodes(context, ref output);
}
/// <summary>
/// Tests that sending a Gzip compressed RSS Feed sends the feed
/// properly compressed. USed the RSS Bandit decompress code
/// to decompress the feed and test it.
/// </summary>
[Test]
[RollBack]
[Ignore("Need to review")]
public void TestCompressedFeedWorks()
{
//string hostName = UnitTestHelper.GenerateUniqueHostname();
//StringBuilder sb = new StringBuilder();
//TextWriter output = new StringWriter(sb);
//SimulatedHttpRequest workerRequest = UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "", "", "", output);
//workerRequest.Headers.Add("Accept-Encoding", "gzip");
//Config.CreateBlog("", "username", "password", hostName, string.Empty);
//Config.CurrentBlog.UseSyndicationCompression = true;
//UnitTestHelper.Create(UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test", "Body Rocking"));
//Thread.Sleep(50);
//UnitTestHelper.Create(UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test 2", "Body Rocking Pt 2"));
//RssHandler handler = new RssHandler();
//Assert.IsNotNull(HttpContext.Current.Request.Headers, "Headers collection is null! Not Good.");
//var subtextContext = new Mock<ISubtextContext>();
//string rssOutput = null;
//subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
//handler.ProcessRequest(subtextContext.Object);
////I'm cheating here!
//MethodInfo method = typeof(HttpResponse).GetMethod("FilterOutput", BindingFlags.NonPublic | BindingFlags.Instance);
//method.Invoke(HttpContext.Current.Response, new object[] {});
//MemoryStream stream = new MemoryStream(Encoding.Default.GetBytes(sb.ToString()));
//Stream deflated = UnitTestHelper.GetDeflatedResponse("gzip", stream);
//using(StreamReader reader = new StreamReader(deflated))
//{
// rssOutput = reader.ReadToEnd();
//}
//XmlDocument doc = new XmlDocument();
//doc.LoadXml(rssOutput);
//XmlNodeList itemNodes = doc.SelectNodes("/rss/channel/item");
//Assert.AreEqual(2, itemNodes.Count, "expected two item nodes.");
//Assert.AreEqual("Title Test 2", itemNodes[0].SelectSingleNode("title").InnerText, "Not what we expected for the second title.");
//Assert.AreEqual("Title Test", itemNodes[1].SelectSingleNode("title").InnerText, "Not what we expected for the first title.");
//Assert.AreEqual("Body Rocking Pt 2", itemNodes[0].SelectSingleNode("description").InnerText.Substring(0, "Body Rocking pt 2".Length), "Not what we expected for the second body.");
//Assert.AreEqual("Body Rocking", itemNodes[1].SelectSingleNode("description").InnerText.Substring(0, "Body Rocking".Length), "Not what we expected for the first body.");
}
}
}
| |
// 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.ObjectModel;
using System.Diagnostics;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed partial class CSharpFormatter : Formatter
{
private void AppendEnumTypeAndName(StringBuilder builder, Type typeToDisplayOpt, string name)
{
if (typeToDisplayOpt != null)
{
AppendQualifiedTypeName(builder, typeToDisplayOpt, escapeKeywordIdentifiers: true);
builder.Append('.');
AppendIdentifierEscapingPotentialKeywords(builder, name);
}
else
{
builder.Append(name);
}
}
internal override string GetArrayDisplayString(Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options)
{
Debug.Assert(lmrType.IsArray);
Type originalLmrType = lmrType;
// Strip off all array types. We'll process them at the end.
while (lmrType.IsArray)
{
lmrType = lmrType.GetElementType();
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append('{');
builder.Append(GetTypeName(lmrType)); // NOTE: call our impl directly, since we're coupled anyway.
var numSizes = sizes.Count;
builder.Append('[');
for (int i = 0; i < numSizes; i++)
{
if (i > 0)
{
builder.Append(", ");
}
var lowerBound = lowerBounds[i];
var size = sizes[i];
if (lowerBound == 0)
{
builder.Append(FormatLiteral(size, options));
}
else
{
builder.Append(FormatLiteral(lowerBound, options));
builder.Append("..");
builder.Append(FormatLiteral(size + lowerBound - 1, options));
}
}
builder.Append(']');
lmrType = originalLmrType.GetElementType(); // Strip off one layer (already handled).
while (lmrType.IsArray)
{
builder.Append('[');
builder.Append(',', lmrType.GetArrayRank() - 1);
builder.Append(']');
lmrType = lmrType.GetElementType();
}
builder.Append('}');
return pooled.ToStringAndFree();
}
internal override string GetArrayIndexExpression(int[] indices)
{
Debug.Assert(indices != null);
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append('[');
bool any = false;
foreach (var index in indices)
{
if (any)
{
builder.Append(", ");
}
builder.Append(index);
any = true;
}
builder.Append(']');
return pooled.ToStringAndFree();
}
internal override string GetCastExpression(string argument, string type, bool parenthesizeArgument = false, bool parenthesizeEntireExpression = false)
{
Debug.Assert(!string.IsNullOrEmpty(argument));
Debug.Assert(!string.IsNullOrEmpty(type));
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
if (parenthesizeEntireExpression)
{
builder.Append('(');
}
var castExpressionFormat = parenthesizeArgument ? "({0})({1})" : "({0}){1}";
builder.AppendFormat(castExpressionFormat, type, argument);
if (parenthesizeEntireExpression)
{
builder.Append(')');
}
return pooled.ToStringAndFree();
}
internal override string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt)
{
var usedFields = ArrayBuilder<EnumField>.GetInstance();
FillUsedEnumFields(usedFields, fields, underlyingValue);
if (usedFields.Count == 0)
{
return null;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
for (int i = usedFields.Count - 1; i >= 0; i--) // Backwards to list smallest first.
{
AppendEnumTypeAndName(builder, typeToDisplayOpt, usedFields[i].Name);
if (i > 0)
{
builder.Append(" | ");
}
}
usedFields.Free();
return pooled.ToStringAndFree();
}
internal override string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt)
{
foreach (var field in fields)
{
// First match wins (deterministic since sorted).
if (underlyingValue == field.Value)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
AppendEnumTypeAndName(builder, typeToDisplayOpt, field.Name);
return pooled.ToStringAndFree();
}
}
return null;
}
internal override string GetObjectCreationExpression(string type, string arguments)
{
Debug.Assert(!string.IsNullOrEmpty(type));
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append("new ");
builder.Append(type);
builder.Append('(');
builder.Append(arguments);
builder.Append(')');
return pooled.ToStringAndFree();
}
internal override string FormatLiteral(char c, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(c, options);
}
internal override string FormatLiteral(int value, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(value, options & ~ObjectDisplayOptions.UseQuotes);
}
internal override string FormatPrimitiveObject(object value, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatPrimitive(value, options);
}
internal override string FormatString(string str, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatString(str, quote: options.IncludesOption(ObjectDisplayOptions.UseQuotes) ? '"' : '\0', escapeNonPrintable: false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using SimpleContainer.Configuration;
using SimpleContainer.Infection;
using SimpleContainer.Interface;
using SimpleContainer.Tests.Helpers;
namespace SimpleContainer.Tests
{
public abstract class InitializeComponentsTest : SimpleContainerTestBase
{
public class Simple : InitializeComponentsTest
{
public class ComponentWrap
{
public readonly Component2 component2;
public ComponentWrap(Component2 component2)
{
this.component2 = component2;
}
}
public class Component2 : IInitializable
{
public readonly IntermediateService intermediateService;
public Component2(IntermediateService intermediateService)
{
this.intermediateService = intermediateService;
LogBuilder.Append("Component2.ctor ");
}
public void Initialize()
{
LogBuilder.Append("Component2.Initialize ");
}
}
public class IntermediateService
{
public Component1 component1;
public IntermediateService(Component1 component1)
{
this.component1 = component1;
LogBuilder.Append("IntermediateService.ctor ");
}
}
public class Component1 : IInitializable
{
public Component0 component0;
public Component1(Component0 component0)
{
this.component0 = component0;
LogBuilder.Append("Component1.ctor ");
}
public void Initialize()
{
LogBuilder.Append("Component1.Initialize ");
}
}
public class Component0 : IInitializable
{
public Component0()
{
LogBuilder.Append("Component0.ctor ");
}
public void Initialize()
{
LogBuilder.Append("Component0.Initialize ");
}
}
[Test]
public void Test()
{
var container = Container();
container.Get<ComponentWrap>();
const string constructorsLog = "Component0.ctor Component1.ctor IntermediateService.ctor Component2.ctor ";
const string runLog = "Component0.Initialize Component1.Initialize Component2.Initialize ";
Assert.That(LogBuilder.ToString(), Is.EqualTo(constructorsLog + runLog));
}
}
public class InitializeComponentsFromCache : InitializeComponentsTest
{
public class A
{
public readonly B b;
public readonly C c;
public A([Optional] B b, C c)
{
this.b = b;
this.c = c;
}
}
public class B
{
public readonly C c;
public readonly D d;
public B(C c, D d)
{
this.c = c;
this.d = d;
}
}
public class C : IInitializable
{
public static bool initializeCalled;
public void Initialize()
{
initializeCalled = true;
}
}
public class D
{
}
[Test]
public void Test()
{
var container = Container(b => b.DontUse<D>());
container.Resolve<A>().EnsureInitialized();
Assert.That(C.initializeCalled);
}
}
public class DoNotInitializeNotUsedComponents : InitializeComponentsTest
{
private static readonly StringBuilder logBuilder = new StringBuilder();
public class A
{
public readonly BWrap b;
public A([Optional] BWrap b)
{
this.b = b;
}
}
public class BWrap
{
public readonly B b;
public readonly FilteredService filteredService;
public BWrap(B b, FilteredService filteredService)
{
this.b = b;
this.filteredService = filteredService;
}
}
public class FilteredService
{
}
public class B : IInitializable
{
public void Initialize()
{
logBuilder.Append("Initialize ");
}
}
[Test]
public void Test()
{
var container = Container(b => b.WithInstanceFilter<FilteredService>(x => false));
var a = container.Get<A>();
Assert.That(a.b, Is.Null);
Assert.That(logBuilder.ToString(), Is.Empty);
}
}
public class InitializeUsesInstancesReachableFromAllResolutionContexts : InitializeComponentsTest
{
private static readonly StringBuilder logBuilder = new StringBuilder();
public class A
{
public readonly B b;
public A(B b)
{
this.b = b;
}
}
public class B
{
public readonly C c;
public B(C c)
{
this.c = c;
}
}
public class C : IInitializable
{
public void Initialize()
{
logBuilder.Append("Run ");
}
}
[Test]
public void Test()
{
var container = Container();
container.Get<B>();
container.Get<A>();
Assert.That(logBuilder.ToString(), Is.EqualTo("Run "));
}
}
public class InitializeUsesInstancesCreatedByFactories : InitializeComponentsTest
{
private static readonly StringBuilder logBuilder = new StringBuilder();
public class A
{
public readonly B b;
public A(Func<B> createB)
{
b = createB();
}
}
public class B
{
public readonly C c;
public B(C c)
{
this.c = c;
}
}
public class C : IInitializable
{
public void Initialize()
{
logBuilder.Append("Run ");
}
}
[Test]
public void Test()
{
var container = Container();
container.Get<A>();
Assert.That(logBuilder.ToString(), Is.EqualTo("Run "));
}
}
public class UnionAllDependencies : InitializeComponentsTest
{
public class A
{
public readonly IEnumerable<IX> instances;
public A([TestContract("u")] IEnumerable<IX> instances)
{
this.instances = instances;
}
}
public interface IX
{
}
public class B : IX, IInitializable
{
public static bool initializeCalled;
public void Initialize()
{
initializeCalled = true;
}
}
public class C : IX, IInitializable
{
public static bool initializeCalled;
public void Initialize()
{
initializeCalled = true;
}
}
[Test]
public void Tets()
{
var container = Container(delegate(ContainerConfigurationBuilder b)
{
b.Contract("a").Bind<IX, B>();
b.Contract("b").Bind<IX, C>();
b.Contract("u").UnionOf("a", "b");
});
container.Get<A>();
Assert.That(B.initializeCalled);
Assert.That(C.initializeCalled);
}
}
public class InterfaceDependencies : InitializeComponentsTest
{
public class A
{
public readonly IX x;
public A(IX x)
{
this.x = x;
}
}
public interface IX
{
}
public class X1 : IX
{
public readonly Initializable initializable;
public X1(Initializable initializable)
{
this.initializable = initializable;
}
}
public class Initializable : IInitializable
{
public static bool initializeCalled;
public void Initialize()
{
initializeCalled = true;
}
}
[Test]
public void Test()
{
var container = Container();
container.Get<A>();
Assert.That(Initializable.initializeCalled);
}
}
public class EnumerableDependencies : InitializeComponentsTest
{
public class A
{
public readonly IEnumerable<IX> dependencies;
public A(IEnumerable<IX> dependencies)
{
this.dependencies = dependencies;
}
}
public interface IX
{
}
public class B : IX, IInitializable
{
public static bool initializeCalled;
public void Initialize()
{
initializeCalled = true;
}
}
public class C : IX, IInitializable
{
public static bool initializeCalled;
public void Initialize()
{
initializeCalled = true;
}
}
[Test]
public void Test()
{
var container = Container();
container.Get<A>();
Assert.That(B.initializeCalled);
Assert.That(C.initializeCalled);
}
}
public class InitializeComponentsCreatedInFactories : InitializeComponentsTest
{
public class A
{
public readonly Func<B> createB;
public A(Func<B> createB)
{
this.createB = createB;
}
}
public class B
{
public readonly C c;
public B(C c)
{
this.c = c;
}
}
public class C : IInitializable
{
public static int initializeCallCount;
public void Initialize()
{
initializeCallCount ++;
}
}
[Test]
public void Test()
{
var container = Container();
var a = container.Get<A>();
Assert.That(C.initializeCallCount, Is.EqualTo(0));
var b1 = a.createB();
Assert.That(C.initializeCallCount, Is.EqualTo(1));
var b2 = a.createB();
Assert.That(C.initializeCallCount, Is.EqualTo(1));
Assert.That(b1, Is.Not.SameAs(b2));
}
}
public class FactoryCallInConstructor_DelayInitializeUntilEntireDependencyTreeIsConstructed : InitializeComponentsTest
{
public class A
{
public readonly B b;
public A(B b = null)
{
this.b = b;
}
}
public class B
{
public readonly C c;
public readonly D d;
public B(C c, D d)
{
this.c = c;
this.d = d;
}
}
public class D
{
}
public class C
{
public readonly E e1;
public readonly E e2;
public C(Func<E> createE)
{
e1 = createE();
e2 = createE();
}
}
public class E : IInitializable
{
public static int initializeCallCount;
public void Initialize()
{
initializeCallCount++;
}
}
[Test]
public void Test()
{
var container = Container(b => b.DontUse<D>());
Assert.That(container.Get<A>().b, Is.Null);
Assert.That(E.initializeCallCount, Is.EqualTo(0));
container.Get<C>();
Assert.That(E.initializeCallCount, Is.EqualTo(2));
}
}
public class InitializeExceptionMustContainServiceContracts : InitializeComponentsTest
{
[TestContract("c1")]
public class A : IInitializable
{
public readonly int parameter;
public A(int parameter)
{
this.parameter = parameter;
}
public void Initialize()
{
throw new InvalidOperationException("test crash");
}
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("c1").BindDependency<A>("parameter", 42));
var resolvedA = container.Resolve<A>();
var exception = Assert.Throws<SimpleContainerException>(resolvedA.EnsureInitialized);
Assert.That(exception.Message, Is.EqualTo("exception initializing A[c1]\r\n\r\nA[c1], initializing ...\r\n\tparameter -> 42"));
Assert.That(exception.InnerException.Message, Is.EqualTo("test crash"));
}
}
public class DontInitiaizeNotOwnedComponents : InitializeComponentsTest
{
public class A : IInitializable
{
public static StringBuilder log = new StringBuilder();
public void Initialize()
{
log.Append("Initialize ");
}
}
[Test]
public void Test()
{
var container = Container(b => b.Bind<A>(new A(), false));
container.Get<A>();
Assert.That(A.log.ToString(), Is.EqualTo(""));
}
}
public class InitializeWithInitializeLogger : InitializeComponentsTest
{
private static StringBuilder log;
protected override void SetUp()
{
base.SetUp();
log = new StringBuilder();
}
public class ComponentA : IInitializable
{
public readonly ComponentB componentB;
public ComponentA(ComponentB componentB)
{
this.componentB = componentB;
}
public void Initialize()
{
log.Append(" ComponentA.Initialize\r\n");
}
}
public class ComponentB : IInitializable
{
public readonly int parameter;
public ComponentB(int parameter)
{
this.parameter = parameter;
}
public void Initialize()
{
log.Append(" ComponentB.Initialize\r\n");
}
}
[Test]
public void Test()
{
LogInfo logInfo = delegate(ServiceName name, string message)
{
log.Append(name);
log.Append(" - ");
log.Append(message);
};
Action<ContainerConfigurationBuilder> configure = b => b
.Contract("my-contract")
.BindDependency<ComponentB>("parameter", 42);
using (var container = Factory().WithInfoLogger(logInfo).WithConfigurator(configure).Build())
{
container.Get<ComponentA>("my-contract");
const string componentALog =
"ComponentA[my-contract] - initialize started ComponentA.Initialize\r\nComponentA[my-contract] - initialize finished";
const string componentBLog =
"ComponentB[my-contract] - initialize started ComponentB.Initialize\r\nComponentB[my-contract] - initialize finished";
Assert.That(log.ToString(), Is.EqualTo(componentBLog + componentALog));
}
}
}
public class EnsireInitializedMustShowServiceDependencies : InitializeComponentsTest
{
public class A
{
public readonly B b;
public A(B b)
{
this.b = b;
}
}
public class B: IInitializable
{
public void Initialize()
{
throw new InvalidOperationException("test-crash");
}
}
[Test]
public void Test()
{
var container = Container();
var exception = Assert.Throws<SimpleContainerException>(() => container.Get<A>());
Assert.That(exception.Message, Is.EqualTo("exception initializing B\r\n\r\nA, initializing ...\r\n\tB, initializing ..."));
Assert.That(exception.InnerException.Message, Is.EqualTo("test-crash"));
}
}
public class InvokeInitializeOnGetOnlyIfItIsTopmost : InitializeComponentsTest
{
public class A
{
public B b;
public A(IContainer container)
{
b = container.Get<B>();
Assert.That(B.initializeCalled, Is.False);
}
}
public class B : IInitializable
{
public static bool initializeCalled;
public void Initialize()
{
initializeCalled = true;
}
}
[Test]
public void Test()
{
var container = Container();
container.Get<A>();
Assert.That(B.initializeCalled, Is.True);
}
}
public class InvokeInitializeOnGetAllOnlyIfItIsTopmost : InitializeComponentsTest
{
public class A
{
public IEnumerable<B> b;
public A(IContainer container)
{
b = container.GetAll<B>();
Assert.That(B.initializeCalled, Is.False);
}
}
public class B : IInitializable
{
public static bool initializeCalled;
public void Initialize()
{
initializeCalled = true;
}
}
[Test]
public void Test()
{
var container = Container();
container.Get<A>();
Assert.That(B.initializeCalled, Is.True);
}
}
public class GetAllCallsInitializeOnAllInstances : InitializeComponentsTest
{
public interface IService : IInitializable
{
bool Initialized { get; set; }
}
public class ImplA : IService
{
public bool Initialized { get; set; }
public void Initialize()
{
Initialized = true;
}
}
public class ImplB : IService
{
public bool Initialized { get; set; }
public void Initialize()
{
Initialized = true;
}
}
[Test]
public void Test()
{
var services = Container().GetAll<IService>().ToArray();
Assert.That(services.Length, Is.EqualTo(2));
foreach (var service in services)
Assert.That(service.Initialized, Is.True);
}
}
public class ResolutionsInInitializeAreProhibited : InitializeComponentsTest
{
public class A : IInitializable
{
private readonly Lazy<B> lazyB;
public A(Lazy<B> lazyB)
{
this.lazyB = lazyB;
}
public B b;
public void Initialize()
{
b = lazyB.Value;
}
}
public class B
{
}
[Test]
public void Test()
{
var container = Container();
var exception = Assert.Throws<SimpleContainerException>(() => container.Get<A>());
const string expectedTopMessage = @"
exception initializing A
A, initializing ...
Lazy<B>";
const string expectedNestedMessage = @"
attempt to resolve [B] is prohibited to prevent possible deadlocks
!B <---------------";
Assert.That(exception.Message, Is.EqualTo(FormatExpectedMessage(expectedTopMessage)));
Assert.That(exception.InnerException.Message, Is.EqualTo(FormatExpectedMessage(expectedNestedMessage)));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.IO
{
// This class implements a TextWriter for writing characters to a Stream.
// This is designed for character output in a particular Encoding,
// whereas the Stream class is designed for byte input and output.
public class StreamWriter : TextWriter
{
// For UTF-8, the values of 1K for the default buffer size and 4K for the
// file stream buffer size are reasonable & give very reasonable
// performance for in terms of construction time for the StreamWriter and
// write perf. Note that for UTF-8, we end up allocating a 4K byte buffer,
// which means we take advantage of adaptive buffering code.
// The performance using UnicodeEncoding is acceptable.
private const int DefaultBufferSize = 1024; // char[]
private const int DefaultFileStreamBufferSize = 4096;
private const int MinBufferSize = 128;
private const int DontCopyOnWriteLineThreshold = 512;
// Bit bucket - Null has no backing store. Non closable.
public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, UTF8NoBOM, MinBufferSize, true);
private Stream _stream;
private Encoding _encoding;
private Encoder _encoder;
private byte[] _byteBuffer;
private char[] _charBuffer;
private int _charPos;
private int _charLen;
private bool _autoFlush;
private bool _haveWrittenPreamble;
private bool _closable;
// We don't guarantee thread safety on StreamWriter, but we should at
// least prevent users from trying to write anything while an Async
// write from the same thread is in progress.
private volatile Task _asyncWriteTask;
private void CheckAsyncTaskInProgress()
{
// We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety.
// We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress.
Task t = _asyncWriteTask;
if (t != null && !t.IsCompleted)
throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress);
}
// The high level goal is to be tolerant of encoding errors when we read and very strict
// when we write. Hence, default StreamWriter encoding will throw on encoding error.
// Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character
// D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the
// internal StreamWriter's state to be irrecoverable as it would have buffered the
// illegal chars and any subsequent call to Flush() would hit the encoding error again.
// Even Close() will hit the exception as it would try to flush the unwritten data.
// Maybe we can add a DiscardBufferedData() method to get out of such situation (like
// StreamReader though for different reason). Either way, the buffered data will be lost!
private static Encoding UTF8NoBOM => EncodingCache.UTF8NoBOM;
internal StreamWriter() : base(null)
{ // Ask for CurrentCulture all the time
}
public StreamWriter(Stream stream)
: this(stream, UTF8NoBOM, DefaultBufferSize, false)
{
}
public StreamWriter(Stream stream, Encoding encoding)
: this(stream, encoding, DefaultBufferSize, false)
{
}
// Creates a new StreamWriter for the given stream. The
// character encoding is set by encoding and the buffer size,
// in number of 16-bit characters, is set by bufferSize.
//
public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
: this(stream, encoding, bufferSize, false)
{
}
public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
: base(null) // Ask for CurrentCulture all the time
{
if (stream == null || encoding == null)
{
throw new ArgumentNullException(stream == null ? nameof(stream) : nameof(encoding));
}
if (!stream.CanWrite)
{
throw new ArgumentException(SR.Argument_StreamNotWritable);
}
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
}
Init(stream, encoding, bufferSize, leaveOpen);
}
public StreamWriter(string path)
: this(path, false, UTF8NoBOM, DefaultBufferSize)
{
}
public StreamWriter(string path, bool append)
: this(path, append, UTF8NoBOM, DefaultBufferSize)
{
}
public StreamWriter(string path, bool append, Encoding encoding)
: this(path, append, encoding, DefaultBufferSize)
{
}
public StreamWriter(string path, bool append, Encoding encoding, int bufferSize)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath);
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
Stream stream = new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read,
DefaultFileStreamBufferSize, FileOptions.SequentialScan);
Init(stream, encoding, bufferSize, shouldLeaveOpen: false);
}
private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
{
_stream = streamArg;
_encoding = encodingArg;
_encoder = _encoding.GetEncoder();
if (bufferSize < MinBufferSize)
{
bufferSize = MinBufferSize;
}
_charBuffer = new char[bufferSize];
_byteBuffer = new byte[_encoding.GetMaxByteCount(bufferSize)];
_charLen = bufferSize;
// If we're appending to a Stream that already has data, don't write
// the preamble.
if (_stream.CanSeek && _stream.Position > 0)
{
_haveWrittenPreamble = true;
}
_closable = !shouldLeaveOpen;
}
public override void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
try
{
// We need to flush any buffered data if we are being closed/disposed.
// Also, we never close the handles for stdout & friends. So we can safely
// write any buffered data to those streams even during finalization, which
// is generally the right thing to do.
if (_stream != null)
{
// Note: flush on the underlying stream can throw (ex., low disk space)
if (disposing /* || (LeaveOpen && stream is __ConsoleStream) */)
{
CheckAsyncTaskInProgress();
Flush(true, true);
}
}
}
finally
{
// Dispose of our resources if this StreamWriter is closable.
// Note: Console.Out and other such non closable streamwriters should be left alone
if (!LeaveOpen && _stream != null)
{
try
{
// Attempt to close the stream even if there was an IO error from Flushing.
// Note that Stream.Close() can potentially throw here (may or may not be
// due to the same Flush error). In this case, we still need to ensure
// cleaning up internal resources, hence the finally block.
if (disposing)
{
_stream.Close();
}
}
finally
{
_stream = null;
_byteBuffer = null;
_charBuffer = null;
_encoding = null;
_encoder = null;
_charLen = 0;
base.Dispose(disposing);
}
}
}
}
public override void Flush()
{
CheckAsyncTaskInProgress();
Flush(true, true);
}
private void Flush(bool flushStream, bool flushEncoder)
{
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
// Perf boost for Flush on non-dirty writers.
if (_charPos == 0 && !flushStream && !flushEncoder)
{
return;
}
if (!_haveWrittenPreamble)
{
_haveWrittenPreamble = true;
ReadOnlySpan<byte> preamble = _encoding.Preamble;
if (preamble.Length > 0)
{
_stream.Write(preamble);
}
}
int count = _encoder.GetBytes(_charBuffer, 0, _charPos, _byteBuffer, 0, flushEncoder);
_charPos = 0;
if (count > 0)
{
_stream.Write(_byteBuffer, 0, count);
}
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
{
_stream.Flush();
}
}
public virtual bool AutoFlush
{
get { return _autoFlush; }
set
{
CheckAsyncTaskInProgress();
_autoFlush = value;
if (value)
{
Flush(true, false);
}
}
}
public virtual Stream BaseStream
{
get { return _stream; }
}
internal bool LeaveOpen
{
get { return !_closable; }
}
internal bool HaveWrittenPreamble
{
set { _haveWrittenPreamble = value; }
}
public override Encoding Encoding
{
get { return _encoding; }
}
public override void Write(char value)
{
CheckAsyncTaskInProgress();
if (_charPos == _charLen)
{
Flush(false, false);
}
_charBuffer[_charPos] = value;
_charPos++;
if (_autoFlush)
{
Flush(true, false);
}
}
public override void Write(char[] buffer)
{
// This may be faster than the one with the index & count since it
// has to do less argument checking.
if (buffer == null)
{
return;
}
CheckAsyncTaskInProgress();
// Threshold of 4 was chosen after running perf tests
if (buffer.Length <= 4)
{
for (int i = 0; i < buffer.Length; i++)
{
if (_charPos == _charLen)
{
Flush(false, false);
}
Debug.Assert(_charLen - _charPos > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race in user code.");
_charBuffer[_charPos] = buffer[i];
_charPos++;
}
}
else
{
int count = buffer.Length;
int index = 0;
while (count > 0)
{
if (_charPos == _charLen)
{
Flush(false, false);
}
int n = _charLen - _charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race in user code.");
Buffer.BlockCopy(buffer, index * sizeof(char), _charBuffer, _charPos * sizeof(char), n * sizeof(char));
_charPos += n;
index += n;
count -= n;
}
}
if (_autoFlush)
{
Flush(true, false);
}
}
public override void Write(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
CheckAsyncTaskInProgress();
// Threshold of 4 was chosen after running perf tests
if (count <= 4)
{
while (count > 0)
{
if (_charPos == _charLen)
{
Flush(false, false);
}
Debug.Assert(_charLen - _charPos > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race in user code.");
_charBuffer[_charPos] = buffer[index];
_charPos++;
index++;
count--;
}
}
else
{
while (count > 0)
{
if (_charPos == _charLen)
{
Flush(false, false);
}
int n = _charLen - _charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.BlockCopy(buffer, index * sizeof(char), _charBuffer, _charPos * sizeof(char), n * sizeof(char));
_charPos += n;
index += n;
count -= n;
}
}
if (_autoFlush)
{
Flush(true, false);
}
}
public override void Write(string value)
{
if (value == null)
{
return;
}
CheckAsyncTaskInProgress();
int count = value.Length;
// Threshold of 4 was chosen after running perf tests
if (count <= 4)
{
for (int i = 0; i < count; i++)
{
if (_charPos == _charLen)
{
Flush(false, false);
}
Debug.Assert(_charLen - _charPos > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
_charBuffer[_charPos] = value[i];
_charPos++;
}
}
else
{
int index = 0;
while (count > 0)
{
if (_charPos == _charLen)
{
Flush(false, false);
}
int n = _charLen - _charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, _charBuffer, _charPos, n);
_charPos += n;
index += n;
count -= n;
}
}
if (_autoFlush)
{
Flush(true, false);
}
}
//
// Optimize the most commonly used WriteLine overload. This optimization is important for System.Console in particular
// because of it will make one WriteLine equal to one call to the OS instead of two in the common case.
//
public override void WriteLine(string value)
{
if (value == null)
{
value = String.Empty;
}
CheckAsyncTaskInProgress();
int count = value.Length;
int index = 0;
while (count > 0)
{
if (_charPos == _charLen)
{
Flush(false, false);
}
int n = _charLen - _charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::WriteLine(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, _charBuffer, _charPos, n);
_charPos += n;
index += n;
count -= n;
}
char[] coreNewLine = CoreNewLine;
for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (_charPos == _charLen)
{
Flush(false, false);
}
_charBuffer[_charPos] = coreNewLine[i];
_charPos++;
}
if (_autoFlush)
{
Flush(true, false);
}
}
#region Task based Async APIs
public override Task WriteAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() 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 Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteAsync(value);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, char value,
char[] charBuffer, int charPos, int charLen, char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
charBuffer[charPos] = value;
charPos++;
if (appendNewLine)
{
for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush)
{
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
public override Task WriteAsync(string value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() 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 Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteAsync(value);
}
if (value != null)
{
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
else
{
return Task.CompletedTask;
}
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, string value,
char[] charBuffer, int charPos, int charLen, char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Debug.Assert(value != null);
int count = value.Length;
int index = 0;
while (count > 0)
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush)
{
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
public override Task WriteAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() 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 Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteAsync(buffer, index, count);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, char[] buffer, int index, int count,
char[] charBuffer, int charPos, int charLen, char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Debug.Assert(count == 0 || (count > 0 && buffer != null));
Debug.Assert(index >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer == null || (buffer != null && buffer.Length - index >= count));
while (count > 0)
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.BlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush)
{
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
public override Task WriteLineAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() 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 Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteLineAsync();
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, null, 0, 0, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
public override Task WriteLineAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() 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 Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteLineAsync(value);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
public override Task WriteLineAsync(string value)
{
if (value == null)
{
return WriteLineAsync();
}
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() 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 Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteLineAsync(value);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() 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 Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteLineAsync(buffer, index, count);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
public override Task FlushAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() 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 Flush) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.FlushAsync();
}
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = FlushAsyncInternal(true, true, _charBuffer, _charPos);
_asyncWriteTask = task;
return task;
}
private int CharPos_Prop
{
set { _charPos = value; }
}
private bool HaveWrittenPreamble_Prop
{
set { _haveWrittenPreamble = value; }
}
private Task FlushAsyncInternal(bool flushStream, bool flushEncoder,
char[] sCharBuffer, int sCharPos)
{
// Perf boost for Flush on non-dirty writers.
if (sCharPos == 0 && !flushStream && !flushEncoder)
{
return Task.CompletedTask;
}
Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, _haveWrittenPreamble,
_encoding, _encoder, _byteBuffer, _stream);
_charPos = 0;
return flushTask;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder,
char[] charBuffer, int charPos, bool haveWrittenPreamble,
Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream)
{
if (!haveWrittenPreamble)
{
_this.HaveWrittenPreamble_Prop = true;
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
{
await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false);
}
}
int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
if (count > 0)
{
await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false);
}
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
{
await stream.FlushAsync().ConfigureAwait(false);
}
}
#endregion
} // class StreamWriter
} // namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestCUInt32()
{
var test = new BooleanBinaryOpTest__TestCUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestCUInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt32> _fld1;
public Vector256<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestCUInt32 testClass)
{
var result = Avx.TestC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestCUInt32 testClass)
{
fixed (Vector256<UInt32>* pFld1 = &_fld1)
fixed (Vector256<UInt32>* pFld2 = &_fld2)
{
var result = Avx.TestC(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector256<UInt32> _clsVar1;
private static Vector256<UInt32> _clsVar2;
private Vector256<UInt32> _fld1;
private Vector256<UInt32> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestCUInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public BooleanBinaryOpTest__TestCUInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestC(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestC(
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestC(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt32>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestC(
Avx.LoadVector256((UInt32*)(pClsVar1)),
Avx.LoadVector256((UInt32*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr);
var result = Avx.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestCUInt32();
var result = Avx.TestC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestCUInt32();
fixed (Vector256<UInt32>* pFld1 = &test._fld1)
fixed (Vector256<UInt32>* pFld2 = &test._fld2)
{
var result = Avx.TestC(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt32>* pFld1 = &_fld1)
fixed (Vector256<UInt32>* pFld2 = &_fld2)
{
var result = Avx.TestC(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestC(
Avx.LoadVector256((UInt32*)(&test._fld1)),
Avx.LoadVector256((UInt32*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt32> op1, Vector256<UInt32> op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((~left[i] & right[i]) == 0);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestC)}<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using TestFirst.Net.Lang;
using TestFirst.Net.Logging;
namespace TestFirst.Net.Performance
{
/// <summary>
/// Generates a report based from listening to the performance test
/// </summary>
[ThreadSafe]
public class PerformanceMetricsWriter : IPerformanceTestRunnerListener
{
private static readonly ILogger Log = Logger.GetLogger<PerformanceMetricsWriter>();
// try to minimise any delays caused by the file system
private readonly QueuedFileWriter m_writer = new QueuedFileWriter();
// ignore any incoming metrics after the test run
private volatile bool m_collectingMetrics;
private string m_workingDir = "perf-metrics/";
private string m_testName;
private DateTime m_startTime;
private string m_metricsFilePath;
public static PerformanceMetricsWriter With()
{
return new PerformanceMetricsWriter();
}
/// <summary>
/// Override the default location to generate metrics and reports in
/// </summary>
/// <param name="dir">The working dir</param>
/// <returns>The PerformanceMetricsWriter</returns>
public PerformanceMetricsWriter WorkingDir(string dir)
{
m_workingDir = dir;
return this;
}
public PerformanceMetricsWriter TestName(object test)
{
TestName(test.GetType().Name);
return this;
}
public PerformanceMetricsWriter TestName(string name)
{
m_testName = name;
return this;
}
public void OnBeginTestSession()
{
m_metricsFilePath = CreateMetricsFile();
Log.InfoFormat("Collecting metrics, writing to '{0}'", m_metricsFilePath);
Console.WriteLine("Writing metrics to " + m_metricsFilePath);
m_writer.Given_filePath = m_metricsFilePath;
m_writer.Start();
m_collectingMetrics = true;
}
public void OnBeginTestRun()
{
m_startTime = DateTime.Now;
}
public void OnMetric(TestId testId, PerformanceMetric metric)
{
if (m_collectingMetrics)
{
m_writer.WriteLine(MetricsFileUtil.ToLine(testId, m_startTime, metric));
}
}
public void OnError(TestId testId, Exception testException)
{
Log.Warn("Test Error in : " + testId + ", exception : " + testException);
}
public void OnEndTestRun()
{
// do nothing
}
public void OnEndTestSession()
{
m_collectingMetrics = false;
m_writer.Stop();
}
public PerformanceReport BuildReport()
{
PreConditions.AssertNotNullOrWhitespace(m_testName, "TestName");
Log.InfoFormat("Generating report, reading metrics from '{0}'", m_metricsFilePath);
// TODO:print a running report every X seconds
var report = new PerformanceReportBuilder
{
ReportTitle = m_testName,
MetricsFilePath = m_metricsFilePath,
LineToMetricsReader = ReadLineToMetrics
}
.Build();
Log.Debug("Done generating report");
WriteReportToDisk(report);
return report;
}
private string CreateMetricsFile()
{
var path = string.Format(
"{0}metrics_{1}{2}.csv",
m_workingDir,
m_testName == null ? string.Empty : m_testName + "_",
DateTime.Now.ToString("yyyyMMdd-HHmmss"));
path = Path.GetFullPath(path);
Directory.CreateDirectory(m_workingDir);
using (File.CreateText(path))
{
if (!File.Exists(path))
{
throw new InvalidOperationException(string.Format("Couldn't create the metrics file path: {0}", path));
}
}
using (var writer = File.AppendText(path))
{
writer.WriteLine(MetricsFileUtil.Header());
}
return path;
}
private PerformanceMetric ReadLineToMetrics(string metricLineEntry)
{
if (metricLineEntry.StartsWith("#"))
{
return null;
}
PerformanceMetric metric;
if (MetricsFileUtil.TryRead(metricLineEntry, out metric))
{
return metric;
}
return null;
}
private void WriteReportToDisk(PerformanceReport report)
{
var reportFile = m_metricsFilePath + ".report." + report.GeneratedAt.ToString("yyyy-MM-dd_HHmm.ss") + ".txt";
using (var writer = File.CreateText(reportFile))
{
writer.WriteLine(report.ToString());
}
Log.InfoFormat("Printed report to '{0}'", reportFile);
}
private static class MetricsFileUtil
{
private const string DateFormat = "yyyyMMdd-HHmm:ss.fff";
private static readonly char[] SplitChars = { ',' };
private enum Col
{
MachineId = 0,
AgentId = 1,
ThreadId = 2,
TimeFromStartMs = 3,
MetricCallId = 4,
MetricName = 5,
MetricTImeStamp = 6,
MetricValue = 7,
MetricIsError = 8,
MetricData = 9
}
internal static string Header()
{
return "# MachineId, AgentId, ThreadId, TimeFromStartMs, Metric.CallId, Metric.Name, Metric.Timestamp, Metric.Value, Metric.IsError, Metric.Data";
}
internal static string ToLine(TestId testId, DateTime testRunStartTime, PerformanceMetric metric)
{
return string.Format(
"{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}",
testId.MachineId,
testId.AgentId,
testId.ThreadId,
(metric.Timestamp - testRunStartTime).TotalMilliseconds,
metric.CallId ?? string.Empty,
metric.Name,
metric.Timestamp.ToString(DateFormat),
metric.Value,
metric.IsError ? "t" : "f",
metric.Data ?? string.Empty);
}
internal static bool TryRead(string line, out PerformanceMetric metric)
{
if (!line.StartsWith("#"))
{
var parts = line.Split(SplitChars, (int)Col.MetricData + 1); // leave the Data bit as it is, including seperator chars
if (parts.Length >= (int)Col.MetricData - 1)
{
// testId = new TestId(
// machineId:parts[0],
// agentId:parts[1],
// threadId:parts[2]
// );
metric = new PerformanceMetric
{
CallId = NullIfEmpty(parts[(int)Col.MetricCallId]),
Name = parts[(int)Col.MetricName],
Timestamp = DateTime.ParseExact(parts[(int)Col.MetricTImeStamp], DateFormat, null),
Value = double.Parse(parts[(int)Col.MetricValue]),
IsError = StringToBool(parts[(int)Col.MetricIsError]),
Data = NullIfEmpty(parts[(int)Col.MetricData])
};
return true;
}
}
// testId = default(TestId);
metric = default(PerformanceMetric);
return false;
}
private static string NullIfEmpty(string s)
{
return s.Length == 0 ? null : s;
}
private static bool StringToBool(string s)
{
if (string.IsNullOrEmpty(s))
{
return false;
}
return s.Equals("t");
}
}
/// <summary>
/// Maintains a queues of strings to write to file. reads lines from many threads and writes in a single background thread
/// </summary>
[ThreadSafe]
private class QueuedFileWriter
{
private const int WritePollIntervalMs = 300;
private readonly ConcurrentQueue<string> m_queue = new ConcurrentQueue<string>();
private volatile string m_pathToFile;
private bool m_running;
private bool m_shouldRun;
private Thread m_writerThread;
public string Given_filePath
{
get { return m_pathToFile; }
set { m_pathToFile = value; }
}
public void Start()
{
PreConditions.AssertNotNullOrWhitespace(m_pathToFile, "MetricFilePath");
ClearQueue();
StartWriteTask();
}
public void WriteLine(string line)
{
m_queue.Enqueue(line);
}
public void Stop()
{
StopWriteTask();
}
private void ClearQueue()
{
string item;
while (m_queue.TryDequeue(out item))
{
// do nothing, queue is emptying
}
}
private void StartWriteTask()
{
if (!m_running)
{
m_shouldRun = true;
m_writerThread = new Thread(() =>
{
using (var writer = File.AppendText(m_pathToFile))
{
while (m_shouldRun)
{
WriteItemsTo(writer);
if (m_shouldRun)
{
Thread.Sleep(WritePollIntervalMs);
}
}
}
});
m_writerThread.Start();
m_running = true;
}
}
private void StopWriteTask()
{
if (m_running)
{
// kill the polling thread.
m_shouldRun = false;
m_writerThread.Join(TimeSpan.FromSeconds(30));
// complete the last poll to clear the queue
using (var writer = File.AppendText(m_pathToFile))
{
WriteItemsTo(writer);
}
m_running = false;
}
}
private void WriteItemsTo(StreamWriter writer)
{
var linesToWrite = TakeItemsFromQueue();
foreach (var line in linesToWrite)
{
writer.WriteLine(line);
}
writer.Flush();
}
private IEnumerable<string> TakeItemsFromQueue()
{
string line;
while (m_queue.TryDequeue(out line))
{
yield return line;
}
}
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Text;
namespace DiscUtils.PowerShell.VirtualDiskProvider
{
internal sealed class FileContentReaderWriter : IContentWriter, IContentReader
{
private Provider _provider;
private Stream _contentStream;
private ContentEncoding _encoding;
private StreamReader _reader;
private StreamWriter _writer;
public FileContentReaderWriter(Provider provider, Stream contentStream, ContentParameters dynParams)
{
_provider = provider;
_contentStream = contentStream;
_contentStream.Position = 0;
if (dynParams != null)
{
_encoding = dynParams.Encoding;
}
}
public void Close()
{
if (_writer != null)
{
_writer.Flush();
}
try
{
_contentStream.Close();
}
catch (Exception e)
{
_provider.WriteError(
new ErrorRecord(
new IOException("Failure using virtual disk", e),
"CloseFailed",
ErrorCategory.WriteError,
null));
}
}
public void Seek(long offset, SeekOrigin origin)
{
_contentStream.Seek(offset, origin);
}
public IList Read(long readCount)
{
try
{
if (_encoding == ContentEncoding.Byte)
{
if (readCount <= 0)
{
readCount = long.MaxValue;
}
int maxToRead = (int)Math.Min(Math.Min(readCount, _contentStream.Length - _contentStream.Position), int.MaxValue);
byte[] fileContent = new byte[maxToRead];
int numRead = _contentStream.Read(fileContent, 0, maxToRead);
object[] result = new object[numRead];
for (int i = 0; i < numRead; ++i)
{
result[i] = fileContent[i];
}
return result;
}
else
{
List<object> result = new List<object>();
if (_reader == null)
{
if (_encoding == ContentEncoding.Unknown)
{
_reader = new StreamReader(_contentStream, Encoding.ASCII, true);
}
else
{
_reader = new StreamReader(_contentStream, GetEncoding(Encoding.ASCII));
}
}
while ((result.Count < readCount || readCount <= 0) && !_reader.EndOfStream)
{
result.Add(_reader.ReadLine());
}
return result;
}
}
catch (Exception e)
{
_provider.WriteError(
new ErrorRecord(
new IOException("Failure reading from virtual disk" + e, e),
"ReadFailed",
ErrorCategory.ReadError,
null));
return null;
}
}
public IList Write(IList content)
{
try
{
if (content == null || content.Count == 0)
{
return content;
}
if (content[0].GetType() == typeof(byte))
{
byte[] buffer = new byte[content.Count];
for (int i = 0; i < buffer.Length; ++i)
{
buffer[i] = (byte)content[i];
}
_contentStream.Write(buffer, 0, buffer.Length);
return content;
}
else if ((content[0] as string) != null)
{
if (_writer == null)
{
string initialContent = (string)content[0];
bool foundExtended = false;
int toInspect = Math.Min(20, initialContent.Length);
for (int i = 0; i < toInspect; ++i)
{
if (((ushort)initialContent[i]) > 127)
{
foundExtended = true;
}
}
_writer = new StreamWriter(_contentStream, GetEncoding(foundExtended ? Encoding.Unicode : Encoding.ASCII));
}
string lastLine = null;
foreach (string s in content)
{
_writer.WriteLine(s);
lastLine = s;
}
_writer.Flush();
return content;
}
else
{
return null;
}
}
catch (Exception e)
{
_provider.WriteError(
new ErrorRecord(
new IOException("Failure writing to virtual disk", e),
"WriteFailed",
ErrorCategory.WriteError,
null));
return null;
}
}
public void Dispose()
{
if (_writer != null)
{
_writer.Dispose();
}
if (_reader != null)
{
_reader.Dispose();
}
if (_contentStream != null)
{
_contentStream.Dispose();
}
}
private Encoding GetEncoding(Encoding defEncoding)
{
switch (_encoding)
{
case ContentEncoding.BigEndianUnicode:
return Encoding.BigEndianUnicode;
case ContentEncoding.UTF8:
return Encoding.UTF8;
case ContentEncoding.UTF7:
return Encoding.UTF7;
case ContentEncoding.Unicode:
return Encoding.Unicode;
case ContentEncoding.Ascii:
return Encoding.ASCII;
default:
return defEncoding;
}
}
}
}
| |
using System;
using System.IO;
using NuGet;
using Orchard.Environment.Extensions;
using Orchard.Environment.Extensions.Models;
using Orchard.FileSystems.VirtualPath;
using Orchard.Localization;
using Orchard.Packaging.Extensions;
using Orchard.Packaging.Models;
using Orchard.UI.Notify;
using NuGetPackageManager = NuGet.PackageManager;
namespace Orchard.Packaging.Services {
[OrchardFeature("PackagingServices")]
public class PackageInstaller : IPackageInstaller {
private const string PackagesPath = "packages";
private const string SolutionFilename = "Orchard.sln";
private readonly INotifier _notifier;
private readonly IVirtualPathProvider _virtualPathProvider;
private readonly IExtensionManager _extensionManager;
private readonly IFolderUpdater _folderUpdater;
public PackageInstaller(
INotifier notifier,
IVirtualPathProvider virtualPathProvider,
IExtensionManager extensionManager,
IFolderUpdater folderUpdater) {
_notifier = notifier;
_virtualPathProvider = virtualPathProvider;
_extensionManager = extensionManager;
_folderUpdater = folderUpdater;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public PackageInfo Install(string packageId, string version, string location, string applicationPath) {
// instantiates the appropriate package repository
IPackageRepository packageRepository = PackageRepositoryFactory.Default.CreateRepository(new PackageSource(location, "Default"));
// gets an IPackage instance from the repository
var packageVersion = String.IsNullOrEmpty(version) ? null : new Version(version);
var package = packageRepository.FindPackage(packageId, packageVersion);
if (package == null) {
throw new ArgumentException(T("The specified package could not be found, id:{0} version:{1}", packageId, String.IsNullOrEmpty(version) ? T("No version").Text : version).Text);
}
return InstallPackage(package, packageRepository, location, applicationPath);
}
public PackageInfo Install(IPackage package, string location, string applicationPath) {
// instantiates the appropriate package repository
IPackageRepository packageRepository = PackageRepositoryFactory.Default.CreateRepository(new PackageSource(location, "Default"));
return InstallPackage(package, packageRepository, location, applicationPath);
}
protected PackageInfo InstallPackage(IPackage package, IPackageRepository packageRepository, string location, string applicationPath) {
bool previousInstalled;
// 1. See if extension was previous installed and backup its folder if so
try {
previousInstalled = BackupExtensionFolder(package.ExtensionFolder(), package.ExtensionId());
}
catch (Exception exception) {
throw new OrchardException(T("Unable to backup existing local package directory."), exception);
}
if (previousInstalled) {
// 2. If extension is installed, need to un-install first
try {
UninstallExtensionIfNeeded(package);
}
catch (Exception exception) {
throw new OrchardException(T("Unable to un-install local package before updating."), exception);
}
}
return ExecuteInstall(package, packageRepository, location, applicationPath);
}
/// <summary>
/// Executes a package installation.
/// </summary>
/// <param name="package">The package to install.</param>
/// <param name="packageRepository">The repository for the package.</param>
/// <param name="sourceLocation">The source location.</param>
/// <param name="targetPath">The path where to install the package.</param>
/// <returns>The package information.</returns>
protected PackageInfo ExecuteInstall(IPackage package, IPackageRepository packageRepository, string sourceLocation, string targetPath) {
// this logger is used to render NuGet's log on the notifier
var logger = new NugetLogger(_notifier);
bool installed = false;
// if we can access the parent directory, and the solution is inside, NuGet-install the package here
string solutionPath;
var installedPackagesPath = String.Empty;
if (TryGetSolutionPath(targetPath, out solutionPath)) {
installedPackagesPath = Path.Combine(solutionPath, PackagesPath);
try {
var packageManager = new NuGetPackageManager(
packageRepository,
new DefaultPackagePathResolver(sourceLocation),
new PhysicalFileSystem(installedPackagesPath) {Logger = logger}
) {Logger = logger};
packageManager.InstallPackage(package, true);
installed = true;
}
catch {
// installing the package at the solution level failed
}
}
// if the package got installed successfully, use it, otherwise use the previous repository
var sourceRepository = installed
? new LocalPackageRepository(installedPackagesPath)
: packageRepository;
var project = new FileBasedProjectSystem(targetPath) { Logger = logger };
var projectManager = new ProjectManager(
sourceRepository, // source repository for the package to install
new DefaultPackagePathResolver(targetPath),
project,
new ExtensionReferenceRepository(project, sourceRepository, _extensionManager)
) { Logger = logger };
// add the package to the project
projectManager.AddPackageReference(package.Id, package.Version);
return new PackageInfo {
ExtensionName = package.Title ?? package.Id,
ExtensionVersion = package.Version.ToString(),
ExtensionType = package.Id.StartsWith(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Theme)) ? DefaultExtensionTypes.Theme : DefaultExtensionTypes.Module,
ExtensionPath = targetPath
};
}
/// <summary>
/// Uninstalls a package.
/// </summary>
/// <param name="packageId">The package identifier for the package to be uninstalled.</param>
/// <param name="applicationPath">The application path.</param>
public void Uninstall(string packageId, string applicationPath) {
string solutionPath;
string extensionFullPath = string.Empty;
if (packageId.StartsWith(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Theme))) {
extensionFullPath = _virtualPathProvider.MapPath("~/Themes/" + packageId.Substring(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Theme).Length));
} else if (packageId.StartsWith(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Module))) {
extensionFullPath = _virtualPathProvider.MapPath("~/Modules/" + packageId.Substring(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Module).Length));
}
if (string.IsNullOrEmpty(extensionFullPath) ||
!Directory.Exists(extensionFullPath)) {
throw new OrchardException(T("Package not found: {0}", packageId));
}
// if we can access the parent directory, and the solution is inside, NuGet-uninstall the package here
if (TryGetSolutionPath(applicationPath, out solutionPath)) {
// this logger is used to render NuGet's log on the notifier
var logger = new NugetLogger(_notifier);
var installedPackagesPath = Path.Combine(solutionPath, PackagesPath);
var sourcePackageRepository = new LocalPackageRepository(installedPackagesPath);
try {
var project = new FileBasedProjectSystem(applicationPath) {Logger = logger};
var projectManager = new ProjectManager(
sourcePackageRepository,
new DefaultPackagePathResolver(installedPackagesPath),
project,
new ExtensionReferenceRepository(project, sourcePackageRepository, _extensionManager)
) {Logger = logger};
// add the package to the project
projectManager.RemovePackageReference(packageId);
}
catch {
// Uninstalling the package at the solution level failed
}
try {
var packageManager = new NuGetPackageManager(
sourcePackageRepository,
new DefaultPackagePathResolver(applicationPath),
new PhysicalFileSystem(installedPackagesPath) {Logger = logger}
) {Logger = logger};
packageManager.UninstallPackage(packageId);
}
catch {
// Package doesnt exist anymore
}
}
// If the package was not installed through nuget we still need to try to uninstall it by removing its directory
if (Directory.Exists(extensionFullPath)) {
Directory.Delete(extensionFullPath, true);
}
}
private static bool TryGetSolutionPath(string applicationPath, out string parentPath) {
try {
parentPath = Directory.GetParent(applicationPath).Parent.FullName;
var solutionPath = Path.Combine(parentPath, SolutionFilename);
return File.Exists(solutionPath);
}
catch {
// Either solution does not exist or we are running under medium trust
parentPath = null;
return false;
}
}
private bool BackupExtensionFolder(string extensionFolder, string extensionId) {
var source = new DirectoryInfo(_virtualPathProvider.MapPath(_virtualPathProvider.Combine("~", extensionFolder, extensionId)));
if (source.Exists) {
var tempPath = _virtualPathProvider.Combine("~", extensionFolder, "_Backup", extensionId);
string localTempPath = null;
for (int i = 0; i < 1000; i++) {
localTempPath = _virtualPathProvider.MapPath(tempPath) + (i == 0 ? "" : "." + i.ToString());
if (!Directory.Exists(localTempPath)) {
Directory.CreateDirectory(localTempPath);
break;
}
localTempPath = null;
}
if (localTempPath == null) {
throw new OrchardException(T("Backup folder {0} has too many backups subfolder (limit is 1,000)", tempPath));
}
var backupFolder = new DirectoryInfo(localTempPath);
_folderUpdater.Backup(source, backupFolder);
_notifier.Information(T("Successfully backed up local package to local folder \"{0}\"", backupFolder));
return true;
}
return false;
}
private void UninstallExtensionIfNeeded(IPackage package) {
// Nuget requires to un-install the currently installed packages if the new
// package is the same version or an older version
try {
Uninstall(package.Id, _virtualPathProvider.MapPath("~\\"));
_notifier.Information(T("Successfully un-installed local package {0}", package.ExtensionId()));
}
catch {}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ElasticPoolsOperations.
/// </summary>
public static partial class ElasticPoolsOperationsExtensions
{
/// <summary>
/// Creates a new elastic pool or updates an existing elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be operated on (updated or created).
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating an elastic pool.
/// </param>
public static ElasticPool CreateOrUpdate(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, elasticPoolName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new elastic pool or updates an existing elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be operated on (updated or created).
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating an elastic pool.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ElasticPool> CreateOrUpdateAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be deleted.
/// </param>
public static void Delete(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName)
{
operations.DeleteAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets an elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be retrieved.
/// </param>
public static ElasticPool Get(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName)
{
return operations.GetAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets an elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ElasticPool> GetAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns a list of elastic pools in a server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static IEnumerable<ElasticPool> ListByServer(this IElasticPoolsOperations operations, string resourceGroupName, string serverName)
{
return operations.ListByServerAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of elastic pools in a server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<ElasticPool>> ListByServerAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns elastic pool activities.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool for which to get the current activity.
/// </param>
public static IEnumerable<ElasticPoolActivity> ListActivity(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName)
{
return operations.ListActivityAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns elastic pool activities.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool for which to get the current activity.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<ElasticPoolActivity>> ListActivityAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListActivityWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns activity on databases inside of an elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool.
/// </param>
public static IEnumerable<ElasticPoolDatabaseActivity> ListDatabaseActivity(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName)
{
return operations.ListDatabaseActivityAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns activity on databases inside of an elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<ElasticPoolDatabaseActivity>> ListDatabaseActivityAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListDatabaseActivityWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a database inside of an elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be retrieved.
/// </param>
/// <param name='databaseName'>
/// The name of the database to be retrieved.
/// </param>
public static Database GetDatabase(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, string databaseName)
{
return operations.GetDatabaseAsync(resourceGroupName, serverName, elasticPoolName, databaseName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a database inside of an elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be retrieved.
/// </param>
/// <param name='databaseName'>
/// The name of the database to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Database> GetDatabaseAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, string databaseName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDatabaseWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, databaseName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns a list of databases in an elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be retrieved.
/// </param>
public static IEnumerable<Database> ListDatabases(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName)
{
return operations.ListDatabasesAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of databases in an elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<Database>> ListDatabasesAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListDatabasesWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new elastic pool or updates an existing elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be operated on (updated or created).
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating an elastic pool.
/// </param>
public static ElasticPool BeginCreateOrUpdate(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, elasticPoolName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new elastic pool or updates an existing elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be operated on (updated or created).
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating an elastic pool.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ElasticPool> BeginCreateOrUpdateAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
/// <summary>
/// ToInt16(System.Object)
/// </summary>
public class ConvertToInt16_9
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify methos ToInt16((object)random).");
try
{
object random = TestLibrary.Generator.GetInt16(-55);
Int16 actual = Convert.ToInt16(random);
Int16 expected = (Int16)random;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt16((object)0)");
try
{
object obj = 0;
Int16 actual = Convert.ToInt16(obj);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt16((object)int16.max)");
try
{
object obj = Int16.MaxValue;
Int16 actual = Convert.ToInt16(obj);
Int16 expected = Int16.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt16((object)int16.min)");
try
{
object obj = Int16.MinValue;
Int16 actual = Convert.ToInt16(obj);
Int16 expected = Int16.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt16(true)");
try
{
object obj = true;
Int16 actual = Convert.ToInt16(obj);
Int16 expected = 1;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("005.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest6: Verify method ToInt16(false)");
try
{
object obj = false;
Int16 actual = Convert.ToInt16(obj);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("006.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest7: Verify method ToInt16(null)");
try
{
object obj = null;
Int16 actual = Convert.ToInt16(obj);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("007.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: InvalidCastException is not thrown.");
try
{
object obj = new object();
Int16 r = Convert.ToInt16(obj);
TestLibrary.TestFramework.LogError("101.1", "InvalidCastException is not thrown.");
retVal = false;
}
catch (InvalidCastException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToInt16_9 test = new ConvertToInt16_9();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt16_9");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
// Prexonite
//
// Copyright (c) 2014, Christian Klauser
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// The names of the contributors may be used to endorse or
// promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using Prexonite.Modular;
namespace Prexonite.Internal
{
/// <summary>
/// Wraps a SymbolicTable<PFunction> to ensure that a function is stored with it's Id as the key.
/// </summary>
public class PFunctionTableImpl : PFunctionTable
{
#region table
private readonly SymbolTable<PFunction> _table;
public PFunctionTableImpl()
{
_table = new SymbolTable<PFunction>();
_idChangingHandler = _onIdChanging;
}
public PFunctionTableImpl(int capacity)
{
_table = new SymbolTable<PFunction>(capacity);
_idChangingHandler = _onIdChanging;
}
public override bool Contains(string id)
{
return _table.ContainsKey(id);
}
public override bool TryGetValue(string id, out PFunction func)
{
return _table.TryGetValue(id, out func);
}
public override PFunction this[string id]
{
get { return _table.GetDefault(id, null); }
}
#endregion
#region Storage
public override void Store(TextWriter writer)
{
foreach (var kvp in _table)
kvp.Value.Store(writer);
}
#endregion
#region ICollection<PFunction> Members
private readonly EventHandler<FunctionIdChangingEventArgs> _idChangingHandler;
[EditorBrowsable(EditorBrowsableState.Never)]
private void _onIdChanging(object o, FunctionIdChangingEventArgs args)
{
var sender = (FunctionDeclaration)o;
PFunction func;
if(TryGetValue(sender.Id,out func))
{
_table.Remove(func.Id);
_table.Add(args.NewId,func);
}
else
{
Debug.Assert(false,
string.Format(
"PFunction table is still registered to function declaration {0} even though it is no longer in the table.",
sender));
}
}
public override void Add(PFunction item)
{
if (_table.ContainsKey(item.Id))
throw new ArgumentException(
"The function table already contains a function named " + item.Id);
item.Declaration.IdChanging += _idChangingHandler;
_table.Add(item.Id, item);
}
public override void AddOverride(PFunction item)
{
PFunction oldFunc;
if (_table.TryGetValue(item.Id,out oldFunc))
{
oldFunc.Declaration.IdChanging -= _idChangingHandler;
_table.Remove(oldFunc.Id);
}
item.Declaration.IdChanging += _idChangingHandler;
_table.Add(item.Id, item);
}
public override void Clear()
{
foreach (var func in _table)
func.Value.Declaration.IdChanging -= _idChangingHandler;
_table.Clear();
}
public override bool Contains(PFunction item)
{
return _table.ContainsKey(item.Id);
}
public override void CopyTo(PFunction[] array, int arrayIndex)
{
if (_table.Count + arrayIndex > array.Length)
throw new ArgumentException("Array to copy functions into is not long enough.");
var i = arrayIndex;
foreach (var kvp in _table)
{
if (i >= array.Length)
break;
array[i++] = kvp.Value;
}
}
public override int Count
{
get { return _table.Count; }
}
public override bool IsReadOnly
{
get { return _table.IsReadOnly; }
}
public override bool Remove(PFunction item)
{
PFunction f;
if(_table.TryGetValue(item.Id,out f) && ReferenceEquals(f,item))
{
f.Declaration.IdChanging -= _idChangingHandler;
_table.Remove(item.Id);
return true;
}
else
return false;
}
public override bool Remove(string id)
{
PFunction oldFunc;
if (_table.TryGetValue(id,out oldFunc))
{
oldFunc.Declaration.IdChanging -= _idChangingHandler;
return _table.Remove(id);
}
else
return false;
}
#endregion
#region IEnumerable<PFunction> Members
public override IEnumerator<PFunction> GetEnumerator()
{
foreach (var kvp in _table)
yield return kvp.Value;
}
#endregion
#region IEnumerable Members
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
** Purpose: Implements a generic, dynamically sized list as an
** array.
**
**
===========================================================*/
namespace System.Collections.Generic {
using System;
using System.Runtime;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.ObjectModel;
using System.Security.Permissions;
// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length
// of the internal array. As elements are added to a List, the capacity
// of the List is automatically increased as required by reallocating the
// internal array.
//
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
{
private const int _defaultCapacity = 4;
private T[] _items;
[ContractPublicPropertyName("Count")]
private int _size;
private int _version;
[NonSerialized]
private Object _syncRoot;
static readonly T[] _emptyArray = new T[0];
// Constructs a List. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
// increased to _defaultCapacity, and then increased in multiples of two
// as required.
public List() {
_items = _emptyArray;
}
// Constructs a List with a given initial capacity. The list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required.
//
public List(int capacity) {
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (capacity == 0)
_items = _emptyArray;
else
_items = new T[capacity];
}
// Constructs a List, copying the contents of the given collection. The
// size and capacity of the new list will both be equal to the size of the
// given collection.
//
public List(IEnumerable<T> collection) {
if (collection==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if( c != null) {
int count = c.Count;
if (count == 0)
{
_items = _emptyArray;
}
else {
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
else {
_size = 0;
_items = _emptyArray;
// This enumerable could be empty. Let Add allocate a new array, if needed.
// Note it will also go to _defaultCapacity first, not 1, then 2, etc.
using(IEnumerator<T> en = collection.GetEnumerator()) {
while(en.MoveNext()) {
Add(en.Current);
}
}
}
}
// Gets and sets the capacity of this list. The capacity is the size of
// the internal array used to hold items. When set, the internal
// array of the list is reallocated to the given capacity.
//
public int Capacity {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
return _items.Length;
}
set {
if (value < _size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
}
Contract.EndContractBlock();
if (value != _items.Length) {
if (value > 0) {
T[] newItems = new T[value];
if (_size > 0) {
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
else {
_items = _emptyArray;
}
}
}
}
// Read-only property describing how many elements are in the List.
public int Count {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
return _size;
}
}
bool System.Collections.IList.IsFixedSize {
get { return false; }
}
// Is this List read-only?
bool ICollection<T>.IsReadOnly {
get { return false; }
}
bool System.Collections.IList.IsReadOnly {
get { return false; }
}
// Is this List synchronized (thread-safe)?
bool System.Collections.ICollection.IsSynchronized {
get { return false; }
}
// Synchronization root for this object.
Object System.Collections.ICollection.SyncRoot {
get {
if( _syncRoot == null) {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Sets or Gets the element at the given index.
//
public T this[int index] {
get {
// Following trick can reduce the range check by one
if ((uint) index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
Contract.EndContractBlock();
return _items[index];
}
set {
if ((uint) index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
Contract.EndContractBlock();
_items[index] = value;
_version++;
}
}
private static bool IsCompatibleObject(object value) {
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
Object System.Collections.IList.this[int index] {
get {
return this[index];
}
set {
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
try {
this[index] = (T)value;
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
}
}
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
//
public void Add(T item) {
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size++] = item;
_version++;
}
int System.Collections.IList.Add(Object item)
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
try {
Add((T) item);
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
}
return Count - 1;
}
// Adds the elements of the given collection to the end of this list. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger.
//
public void AddRange(IEnumerable<T> collection) {
Contract.Ensures(Count >= Contract.OldValue(Count));
InsertRange(_size, collection);
}
public ReadOnlyCollection<T> AsReadOnly() {
Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null);
return new ReadOnlyCollection<T>(this);
}
// Searches a section of the list for a given element using a binary search
// algorithm. Elements of the list are compared to the search value using
// the given IComparer interface. If comparer is null, elements of
// the list are compared to the search value using the IComparable
// interface, which in that case must be implemented by all elements of the
// list and the given search value. This method assumes that the given
// section of the list is already sorted; if this is not the case, the
// result will be incorrect.
//
// The method returns the index of the given value in the list. If the
// list does not contain the given value, the method returns a negative
// integer. The bitwise complement operator (~) can be applied to a
// negative result to produce the index of the first element (if any) that
// is larger than the given search value. This is also the index at which
// the search value should be inserted into the list in order for the list
// to remain sorted.
//
// The method uses the Array.BinarySearch method to perform the
// search.
//
public int BinarySearch(int index, int count, T item, IComparer<T> comparer) {
if (index < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.Ensures(Contract.Result<int>() <= index + count);
Contract.EndContractBlock();
return Array.BinarySearch<T>(_items, index, count, item, comparer);
}
public int BinarySearch(T item)
{
Contract.Ensures(Contract.Result<int>() <= Count);
return BinarySearch(0, Count, item, null);
}
public int BinarySearch(T item, IComparer<T> comparer)
{
Contract.Ensures(Contract.Result<int>() <= Count);
return BinarySearch(0, Count, item, comparer);
}
// Clears the contents of List.
public void Clear() {
if (_size > 0)
{
Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
}
_version++;
}
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// EqualityComparer<T>.Default.Equals().
public bool Contains(T item)
{
// PERF: IndexOf calls Array.IndexOf, which internally
// calls EqualityComparer<T>.Default.IndexOf, which
// is specialized for different types. This
// boosts performance since instead of making a
// virtual method call each iteration of the loop,
// via EqualityComparer<T>.Default.Equals, we
// only make one virtual call to EqualityComparer.IndexOf.
return _size != 0 && IndexOf(item) != -1;
}
bool System.Collections.IList.Contains(Object item)
{
if(IsCompatibleObject(item)) {
return Contains((T) item);
}
return false;
}
public List<TOutput> ConvertAll<TOutput>(Converter<T,TOutput> converter) {
if( converter == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
Contract.EndContractBlock();
List<TOutput> list = new List<TOutput>(_size);
for( int i = 0; i< _size; i++) {
list._items[i] = converter(_items[i]);
}
list._size = _size;
return list;
}
// Copies this List into array, which must be of a
// compatible array type.
//
public void CopyTo(T[] array) {
CopyTo(array, 0);
}
// Copies this List into array, which must be of a
// compatible array type.
//
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) {
if ((array != null) && (array.Rank != 1)) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
Contract.EndContractBlock();
try {
// Array.Copy will check for NULL.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
catch(ArrayTypeMismatchException){
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
// Copies a section of this list to the given array at the given index.
//
// The method uses the Array.Copy method to copy the elements.
//
public void CopyTo(int index, T[] array, int arrayIndex, int count) {
if (_size - index < count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
Contract.EndContractBlock();
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, index, array, arrayIndex, count);
}
public void CopyTo(T[] array, int arrayIndex) {
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
// Ensures that the capacity of this list is at least the given minimum
// value. If the currect capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
private void EnsureCapacity(int min) {
if (_items.Length < min) {
int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
public bool Exists(Predicate<T> match) {
return FindIndex(match) != -1;
}
public T Find(Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
for(int i = 0 ; i < _size; i++) {
if(match(_items[i])) {
return _items[i];
}
}
return default(T);
}
public List<T> FindAll(Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
List<T> list = new List<T>();
for(int i = 0 ; i < _size; i++) {
if(match(_items[i])) {
list.Add(_items[i]);
}
}
return list;
}
public int FindIndex(Predicate<T> match) {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return FindIndex(0, _size, match);
}
public int FindIndex(int startIndex, Predicate<T> match) {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < startIndex + Count);
return FindIndex(startIndex, _size - startIndex, match);
}
public int FindIndex(int startIndex, int count, Predicate<T> match) {
if( (uint)startIndex > (uint)_size ) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (count < 0 || startIndex > _size - count) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
}
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < startIndex + count);
Contract.EndContractBlock();
int endIndex = startIndex + count;
for( int i = startIndex; i < endIndex; i++) {
if( match(_items[i])) return i;
}
return -1;
}
public T FindLast(Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
for(int i = _size - 1 ; i >= 0; i--) {
if(match(_items[i])) {
return _items[i];
}
}
return default(T);
}
public int FindLastIndex(Predicate<T> match) {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return FindLastIndex(_size - 1, _size, match);
}
public int FindLastIndex(int startIndex, Predicate<T> match) {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() <= startIndex);
return FindLastIndex(startIndex, startIndex + 1, match);
}
public int FindLastIndex(int startIndex, int count, Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() <= startIndex);
Contract.EndContractBlock();
if(_size == 0) {
// Special case for 0 length List
if( startIndex != -1) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
}
else {
// Make sure we're not out of range
if ( (uint)startIndex >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
}
int endIndex = startIndex - count;
for( int i = startIndex; i > endIndex; i--) {
if( match(_items[i])) {
return i;
}
}
return -1;
}
public void ForEach(Action<T> action) {
if( action == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
}
Contract.EndContractBlock();
int version = _version;
for(int i = 0 ; i < _size; i++) {
if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) {
break;
}
action(_items[i]);
}
if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
// Returns an enumerator for this list with the given
// permission for removal of elements. If modifications made to the list
// while an enumeration is in progress, the MoveNext and
// GetObject methods of the enumerator will throw an exception.
//
public Enumerator GetEnumerator() {
return new Enumerator(this);
}
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return new Enumerator(this);
}
public List<T> GetRange(int index, int count) {
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
Contract.Ensures(Contract.Result<List<T>>() != null);
Contract.EndContractBlock();
List<T> list = new List<T>(count);
Array.Copy(_items, index, list._items, 0, count);
list._size = count;
return list;
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards from beginning to end.
// The elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item) {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return Array.IndexOf(_items, item, 0, _size);
}
int System.Collections.IList.IndexOf(Object item)
{
if(IsCompatibleObject(item)) {
return IndexOf((T)item);
}
return -1;
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and ending at count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index) {
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, _size - index);
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and upto count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index, int count) {
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
if (count <0 || index > _size - count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, count);
}
// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
//
public void Insert(int index, T item) {
// Note that insertions at the end are legal.
if ((uint) index > (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
}
Contract.EndContractBlock();
if (_size == _items.Length) EnsureCapacity(_size + 1);
if (index < _size) {
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
void System.Collections.IList.Insert(int index, Object item)
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
try {
Insert(index, (T) item);
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
}
}
// Inserts the elements of the given collection at a given index. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger. Ranges may be added
// to the end of the list by setting index to the List's size.
//
public void InsertRange(int index, IEnumerable<T> collection) {
if (collection==null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
if ((uint)index > (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if( c != null ) { // if collection is ICollection<T>
int count = c.Count;
if (count > 0) {
EnsureCapacity(_size + count);
if (index < _size) {
Array.Copy(_items, index, _items, index + count, _size - index);
}
// If we're inserting a List into itself, we want to be able to deal with that.
if (this == c) {
// Copy first part of _items to insert location
Array.Copy(_items, 0, _items, index, index);
// Copy last part of _items back to inserted location
Array.Copy(_items, index+count, _items, index*2, _size-index);
}
else {
T[] itemsToInsert = new T[count];
c.CopyTo(itemsToInsert, 0);
itemsToInsert.CopyTo(_items, index);
}
_size += count;
}
}
else {
using(IEnumerator<T> en = collection.GetEnumerator()) {
while(en.MoveNext()) {
Insert(index++, en.Current);
}
}
}
_version++;
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at the end
// and ending at the first element in the list. The elements of the list
// are compared to the given value using the Object.Equals method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
if (_size == 0) { // Special case for empty list
return -1;
}
else {
return LastIndexOf(item, _size - 1, _size);
}
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at index
// index and ending at the first element in the list. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item, int index)
{
if (index >= _size)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
Contract.EndContractBlock();
return LastIndexOf(item, index, index + 1);
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at index
// index and upto count elements. The elements of
// the list are compared to the given value using the Object.Equals
// method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item, int index, int count) {
if ((Count != 0) && (index < 0)) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if ((Count !=0) && (count < 0)) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
Contract.EndContractBlock();
if (_size == 0) { // Special case for empty list
return -1;
}
if (index >= _size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);
}
if (count > index + 1) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);
}
return Array.LastIndexOf(_items, item, index, count);
}
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public bool Remove(T item) {
int index = IndexOf(item);
if (index >= 0) {
RemoveAt(index);
return true;
}
return false;
}
void System.Collections.IList.Remove(Object item)
{
if(IsCompatibleObject(item)) {
Remove((T) item);
}
}
// This method removes all items which matches the predicate.
// The complexity is O(n).
public int RemoveAll(Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count));
Contract.EndContractBlock();
int freeIndex = 0; // the first free slot in items array
// Find the first item which needs to be removed.
while( freeIndex < _size && !match(_items[freeIndex])) freeIndex++;
if( freeIndex >= _size) return 0;
int current = freeIndex + 1;
while( current < _size) {
// Find the first item which needs to be kept.
while( current < _size && match(_items[current])) current++;
if( current < _size) {
// copy item to the free slot.
_items[freeIndex++] = _items[current++];
}
}
Array.Clear(_items, freeIndex, _size - freeIndex);
int result = _size - freeIndex;
_size = freeIndex;
_version++;
return result;
}
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public void RemoveAt(int index) {
if ((uint)index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
Contract.EndContractBlock();
_size--;
if (index < _size) {
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
// Removes a range of elements from this list.
//
public void RemoveRange(int index, int count) {
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (count > 0) {
int i = _size;
_size -= count;
if (index < _size) {
Array.Copy(_items, index + count, _items, index, _size - index);
}
Array.Clear(_items, _size, count);
_version++;
}
}
// Reverses the elements in this list.
public void Reverse() {
Reverse(0, Count);
}
// Reverses the elements in a range of this list. Following a call to this
// method, an element in the range given by index and count
// which was previously located at index i will now be located at
// index index + (index + count - i - 1).
//
public void Reverse(int index, int count) {
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
// The non-generic Array.Reverse is not used because it does not perform
// well for non-primitive value types.
// If/when a generic Array.Reverse<T> becomes available, the below code
// can be deleted and replaced with a call to Array.Reverse<T>.
int i = index;
int j = index + count - 1;
T[] array = _items;
while (i < j)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
_version++;
}
// Sorts the elements in this list. Uses the default comparer and
// Array.Sort.
public void Sort()
{
Sort(0, Count, null);
}
// Sorts the elements in this list. Uses Array.Sort with the
// provided comparer.
public void Sort(IComparer<T> comparer)
{
Sort(0, Count, comparer);
}
// Sorts the elements in a section of this list. The sort compares the
// elements to each other using the given IComparer interface. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented by all
// elements of the list.
//
// This method uses the Array.Sort method to sort the elements.
//
public void Sort(int index, int count, IComparer<T> comparer) {
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
Array.Sort<T>(_items, index, count, comparer);
_version++;
}
public void Sort(Comparison<T> comparison) {
if( comparison == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
}
Contract.EndContractBlock();
if( _size > 0) {
IComparer<T> comparer = Comparer<T>.Create(comparison);
Array.Sort(_items, 0, _size, comparer);
}
}
// ToArray returns an array containing the contents of the List.
// This requires copying the List, which is an O(n) operation.
public T[] ToArray() {
Contract.Ensures(Contract.Result<T[]>() != null);
Contract.Ensures(Contract.Result<T[]>().Length == Count);
#if FEATURE_CORECLR
if (_size == 0)
{
return _emptyArray;
}
#endif
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
// Sets the capacity of this list to the size of the list. This method can
// be used to minimize a list's memory overhead once it is known that no
// new elements will be added to the list. To completely clear a list and
// release all memory referenced by the list, execute the following
// statements:
//
// list.Clear();
// list.TrimExcess();
//
public void TrimExcess() {
int threshold = (int)(((double)_items.Length) * 0.9);
if( _size < threshold ) {
Capacity = _size;
}
}
public bool TrueForAll(Predicate<T> match) {
if( match == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
for(int i = 0 ; i < _size; i++) {
if( !match(_items[i])) {
return false;
}
}
return true;
}
[Serializable]
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private List<T> list;
private int index;
private int version;
private T current;
internal Enumerator(List<T> list) {
this.list = list;
index = 0;
version = list._version;
current = default(T);
}
public void Dispose() {
}
public bool MoveNext() {
List<T> localList = list;
if (version == localList._version && ((uint)index < (uint)localList._size))
{
current = localList._items[index];
index++;
return true;
}
return MoveNextRare();
}
private bool MoveNextRare()
{
if (version != list._version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
index = list._size + 1;
current = default(T);
return false;
}
public T Current {
get {
return current;
}
}
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || index == list._size + 1) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return Current;
}
}
void System.Collections.IEnumerator.Reset() {
if (version != list._version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
index = 0;
current = default(T);
}
}
}
}
| |
using System;
using De.Osthus.Ambeth.Util;
using System.Reflection;
using De.Osthus.Ambeth.Ioc.Config;
using De.Osthus.Ambeth.Ioc.Extendable;
using De.Osthus.Ambeth.Log;
using De.Osthus.Ambeth.Proxy;
using De.Osthus.Ambeth.Config;
namespace De.Osthus.Ambeth.Ioc.Link
{
public class LinkController : ILinkController, IInitializingBean
{
[LogInstance]
public ILogger Log { private get; set; }
protected static readonly Object[] emptyArgs = new Object[0];
public IExtendableRegistry ExtendableRegistry { protected get; set; }
public IProxyFactory ProxyFactory { protected get; set; }
public IProperties Props { protected get; set; }
public void AfterPropertiesSet()
{
ParamChecker.AssertNotNull(ExtendableRegistry, "ExtendableRegistry");
ParamChecker.AssertNotNull(Props, "Props");
ParamChecker.AssertNotNull(ProxyFactory, "ProxyFactory");
}
protected Object[] createArgumentArray(Object[] args)
{
Object[] realArguments = new Object[args.Length + 1];
Array.Copy(args, 0, realArguments, 1, args.Length);
return realArguments;
}
public ILinkRegistryNeededRuntime Link(IServiceContext serviceContext, String listenerBeanName)
{
return Link(serviceContext, listenerBeanName, (String)null);
}
public ILinkRegistryNeededRuntime Link(IServiceContext serviceContext, String listenerBeanName, String methodName)
{
LinkRuntime<LinkContainer> linkRuntime = new LinkRuntime<LinkContainer>((ServiceContext)serviceContext, typeof(LinkContainer));
linkRuntime.Listener(listenerBeanName);
if (methodName != null)
{
linkRuntime.ListenerMethod(methodName);
}
return linkRuntime;
}
public ILinkRegistryNeededRuntime Link(IServiceContext serviceContext, IBeanConfiguration listenerBean)
{
return Link(serviceContext, listenerBean, (String)null);
}
public ILinkRegistryNeededRuntime Link(IServiceContext serviceContext, IBeanConfiguration listenerBean, String methodName)
{
LinkRuntime<LinkContainer> linkRuntime = new LinkRuntime<LinkContainer>((ServiceContext)serviceContext, typeof(LinkContainer));
linkRuntime.Listener(listenerBean);
if (methodName != null)
{
linkRuntime.ListenerMethod(methodName);
}
return linkRuntime;
}
public ILinkRegistryNeededRuntime Link(IServiceContext serviceContext, Object listener, String methodName)
{
if (listener is String)
{
return Link(serviceContext, (String)listener);
}
else if (listener is IBeanConfiguration)
{
return Link(serviceContext, (IBeanConfiguration)listener);
}
LinkRuntime<LinkContainer> linkRuntime = new LinkRuntime<LinkContainer>((ServiceContext)serviceContext, typeof(LinkContainer));
linkRuntime.Listener(listener);
if (methodName != null)
{
linkRuntime.ListenerMethod(methodName);
}
return linkRuntime;
}
public ILinkRegistryNeededRuntime<D> Link<D>(IServiceContext serviceContext, D listener)
{
LinkRuntime<D> linkRuntime = new LinkRuntime<D>((ServiceContext)serviceContext, typeof(LinkContainer));
linkRuntime.Listener(listener);
return linkRuntime;
}
public LinkConfiguration<Object> CreateLinkConfiguration(String listenerBeanName, String methodName)
{
LinkConfiguration<Object> linkConfiguration = new LinkConfiguration<Object>(typeof(LinkContainer), ProxyFactory, Props);
linkConfiguration.PropertyValue(LinkContainer.PROPERTY_LISTENER_NAME, listenerBeanName);
if (methodName != null)
{
linkConfiguration.PropertyValue(LinkContainer.PROPERTY_LISTENER_METHOD_NAME, methodName);
}
return linkConfiguration;
}
public LinkConfiguration<Object> CreateLinkConfiguration(IBeanConfiguration listenerBean, String methodName)
{
LinkConfiguration<Object> linkConfiguration = new LinkConfiguration<Object>(typeof(LinkContainer), ProxyFactory, Props);
linkConfiguration.PropertyValue(LinkContainer.PROPERTY_LISTENER_BEAN, listenerBean);
if (methodName != null)
{
linkConfiguration.PropertyValue(LinkContainer.PROPERTY_LISTENER_METHOD_NAME, methodName);
}
return linkConfiguration;
}
public LinkConfiguration<Object> CreateLinkConfiguration(Object listener, String methodName)
{
if (listener is String)
{
return CreateLinkConfiguration((String)listener, methodName);
}
else if (listener is IBeanConfiguration)
{
return CreateLinkConfiguration((IBeanConfiguration)listener, methodName);
}
// else if (listener is Delegate)
// {
// throw new Exception("Illegal state: Delegate can not have an additional methodName");
// }
LinkConfiguration<Object> linkConfiguration = new LinkConfiguration<Object>(typeof(LinkContainer), ProxyFactory, Props);
linkConfiguration.PropertyValue(LinkContainer.PROPERTY_LISTENER, listener);
if (methodName != null)
{
linkConfiguration.PropertyValue(LinkContainer.PROPERTY_LISTENER_METHOD_NAME, methodName);
}
return linkConfiguration;
}
public LinkConfiguration<D> CreateLinkConfiguration<D>(D listener)
{
LinkConfiguration<D> linkConfiguration = new LinkConfiguration<D>(typeof(LinkContainer), ProxyFactory, Props);
linkConfiguration.PropertyValue(LinkContainer.PROPERTY_LISTENER, listener);
return linkConfiguration;
}
[Obsolete]
protected AbstractLinkContainerOld createLinkContainer(Type registryType, Object[] arguments)
{
Object[] linkArguments;
MethodInfo[] methods = ExtendableRegistry.GetAddRemoveMethods(registryType, arguments, out linkArguments);
LinkContainerOld linkContainer = new LinkContainerOld();
linkContainer.AddMethod = methods[0];
linkContainer.RemoveMethod = methods[1];
linkContainer.Arguments = linkArguments;
return linkContainer;
}
[Obsolete]
protected AbstractLinkContainerOld createLinkContainer(Type registryType, String methodName)
{
Object[] linkArguments;
MethodInfo[] methods = ExtendableRegistry.GetAddRemoveMethods(registryType, null, out linkArguments);
LinkContainerOld linkContainer = new LinkContainerOld();
linkContainer.AddMethod = methods[0];
linkContainer.RemoveMethod = methods[1];
linkContainer.Arguments = linkArguments;
if (methodName != null)
{
linkContainer.Listener = new LateDelegate(methods[0].GetParameters()[0].ParameterType, methodName);
}
return linkContainer;
}
[Obsolete]
protected AbstractLinkContainerOld createLinkContainer(String eventName, String methodName)
{
PropertyChangedLinkContainerOld linkContainer = new PropertyChangedLinkContainerOld();
linkContainer.PropertyName = eventName;
linkContainer.Arguments = new Object[1];
if (methodName != null)
{
linkContainer.MethodName = methodName;
//linkContainer.Listener = new LateDelegate(null, methodName);
}
return linkContainer;
}
[Obsolete]
protected BeanConfiguration createLinkContainerConfiguration(Type registryType, Object[] arguments)
{
Object[] linkArguments;
MethodInfo[] methods = ExtendableRegistry.GetAddRemoveMethods(registryType, arguments, out linkArguments);
BeanConfiguration beanConfiguration = new BeanConfiguration(typeof(LinkContainerOld), null, ProxyFactory, Props);
beanConfiguration.PropertyValue("AddMethod", methods[0]);
beanConfiguration.PropertyValue("RemoveMethod", methods[1]);
beanConfiguration.PropertyValue("Arguments", linkArguments);
return beanConfiguration;
}
[Obsolete]
protected BeanConfiguration createLinkContainerConfiguration(Type registryType, String methodName)
{
Object[] linkArguments;
MethodInfo[] methods = ExtendableRegistry.GetAddRemoveMethods(registryType, null, out linkArguments);
BeanConfiguration beanConfiguration = new BeanConfiguration(typeof(LinkContainerOld), null, ProxyFactory, Props);
beanConfiguration.PropertyValue("AddMethod", methods[0]);
beanConfiguration.PropertyValue("RemoveMethod", methods[1]);
beanConfiguration.PropertyValue("Arguments", linkArguments);
if (methodName != null)
{
beanConfiguration.PropertyValue("Listener", new LateDelegate(methods[0].GetParameters()[0].ParameterType, methodName));
}
return beanConfiguration;
}
[Obsolete]
protected BeanConfiguration createLinkContainerConfiguration(String eventName)
{
BeanConfiguration beanConfiguration = new BeanConfiguration(typeof(PropertyChangedLinkContainerOld), null, ProxyFactory, Props);
beanConfiguration.PropertyValue("PropertyName", eventName);
beanConfiguration.PropertyValue("Arguments", new Object[1]);
return beanConfiguration;
}
[Obsolete]
public void Link<R>(IServiceContext serviceContext, String registryBeanName, String listenerBeanName, Object[] arguments)
{
Link(serviceContext, registryBeanName, listenerBeanName, typeof(R), arguments);
}
[Obsolete]
public void Link(IServiceContext serviceContext, String registryBeanName, String listenerBeanName, Type registryClass, Object[] arguments)
{
ParamChecker.AssertParamNotNull(serviceContext, "serviceContext");
ParamChecker.AssertParamNotNull(registryBeanName, "registryBeanName");
ParamChecker.AssertParamNotNull(listenerBeanName, "listenerBeanName");
ParamChecker.AssertParamNotNull(registryClass, "registryClass");
ParamChecker.AssertParamNotNull(arguments, "arguments");
AbstractLinkContainerOld linkContainer = createLinkContainer(registryClass, arguments);
linkContainer.RegistryBeanName = registryBeanName;
linkContainer.ListenerBeanName = listenerBeanName;
linkContainer.BeanContext = serviceContext;
serviceContext.RegisterWithLifecycle(linkContainer).Finish();
}
[Obsolete]
public void Link<R>(IServiceContext serviceContext, String registryBeanName, String listenerBeanName)
{
Link(serviceContext, registryBeanName, listenerBeanName, typeof(R), emptyArgs);
}
[Obsolete]
public void Link(IServiceContext serviceContext, String registryBeanName, String listenerBeanName, Type registryClass)
{
Link(serviceContext, registryBeanName, listenerBeanName, registryClass, emptyArgs);
}
[Obsolete]
public void Link<R>(IServiceContext serviceContext, IBeanConfiguration listenerBean)
{
Link(serviceContext, listenerBean, typeof(R), emptyArgs);
}
[Obsolete]
public void Link(IServiceContext serviceContext, IBeanConfiguration listenerBean, Type autowiredRegistryClass)
{
Link(serviceContext, listenerBean, autowiredRegistryClass, emptyArgs);
}
[Obsolete]
public void Link<R>(IServiceContext serviceContext, IBeanConfiguration listenerBean, Object[] arguments)
{
Link(serviceContext, listenerBean, typeof(R), arguments);
}
[Obsolete]
public void Link(IServiceContext serviceContext, IBeanConfiguration listenerBean, Type autowiredRegistryClass, Object[] arguments)
{
ParamChecker.AssertParamNotNull(serviceContext, "serviceContext");
ParamChecker.AssertParamNotNull(listenerBean, "listenerBean");
ParamChecker.AssertParamNotNull(autowiredRegistryClass, "autowiredRegistryClass");
ParamChecker.AssertParamNotNull(arguments, "arguments");
AbstractLinkContainerOld linkContainer = createLinkContainer(autowiredRegistryClass, arguments);
linkContainer.RegistryBeanAutowiredType = autowiredRegistryClass;
linkContainer.ListenerBean = listenerBean;
linkContainer.BeanContext = serviceContext;
serviceContext.RegisterWithLifecycle(linkContainer).Finish();
}
[Obsolete]
public void Link<R>(IServiceContext serviceContext, String listenerBeanName)
{
Link(serviceContext, listenerBeanName, typeof(R), emptyArgs);
}
[Obsolete]
public void Link(IServiceContext serviceContext, String listenerBeanName, Type autowiredRegistryClass)
{
Link(serviceContext, listenerBeanName, autowiredRegistryClass, emptyArgs);
}
[Obsolete]
public void Link<R>(IServiceContext serviceContext, String listenerBeanName, Object[] arguments)
{
Link(serviceContext, listenerBeanName, typeof(R), arguments);
}
[Obsolete]
public void Link(IServiceContext serviceContext, String listenerBeanName, Type autowiredRegistryClass, Object[] arguments)
{
ParamChecker.AssertParamNotNull(serviceContext, "serviceContext");
ParamChecker.AssertParamNotNull(listenerBeanName, "listenerBeanName");
ParamChecker.AssertParamNotNull(autowiredRegistryClass, "autowiredRegistryClass");
ParamChecker.AssertParamNotNull(arguments, "arguments");
AbstractLinkContainerOld linkContainer = createLinkContainer(autowiredRegistryClass, arguments);
linkContainer.RegistryBeanAutowiredType = autowiredRegistryClass;
linkContainer.ListenerBeanName = listenerBeanName;
linkContainer.BeanContext = serviceContext;
serviceContext.RegisterWithLifecycle(linkContainer).Finish();
}
[Obsolete]
public IBeanConfiguration createLinkConfiguration(String registryBeanName, String listenerBeanName, Type registryClass)
{
return createLinkConfiguration(registryBeanName, listenerBeanName, registryClass, emptyArgs);
}
[Obsolete]
public IBeanConfiguration createLinkConfiguration(String registryBeanName, String listenerBeanName, Type registryClass, Object[] arguments)
{
ParamChecker.AssertParamNotNull(registryBeanName, "registryBeanName");
ParamChecker.AssertParamNotNull(listenerBeanName, "listenerBeanName");
ParamChecker.AssertParamNotNull(registryClass, "registryClass");
ParamChecker.AssertParamNotNull(arguments, "arguments");
BeanConfiguration linkContainer = createLinkContainerConfiguration(registryClass, arguments);
linkContainer.PropertyValue("RegistryBeanName", registryBeanName);
linkContainer.PropertyValue("ListenerBeanName", listenerBeanName);
return linkContainer;
}
[Obsolete]
public IBeanConfiguration createLinkConfiguration(String listenerBeanName, Type autowiredRegistryClass)
{
return createLinkConfiguration(listenerBeanName, autowiredRegistryClass, emptyArgs);
}
[Obsolete]
public IBeanConfiguration createLinkConfiguration(String listenerBeanName, Type autowiredRegistryClass, Object[] arguments)
{
ParamChecker.AssertParamNotNull(listenerBeanName, "listenerBeanName");
ParamChecker.AssertParamNotNull(autowiredRegistryClass, "autowiredRegistryClass");
ParamChecker.AssertParamNotNull(arguments, "arguments");
BeanConfiguration linkContainer = createLinkContainerConfiguration(autowiredRegistryClass, arguments);
linkContainer.PropertyValue("RegistryBeanAutowiredType", autowiredRegistryClass);
linkContainer.PropertyValue("ListenerBeanName", listenerBeanName);
return linkContainer;
}
[Obsolete]
public IBeanConfiguration createEventLinkConfiguration(String eventProviderBeanName, Type eventInterface, String listenerBeanName, String methodName)
{
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(eventInterface, "eventInterface");
ParamChecker.AssertParamNotNull(listenerBeanName, "listenerBeanName");
ParamChecker.AssertParamNotNull(methodName, "methodName");
BeanConfiguration linkContainer = createLinkContainerConfiguration(eventInterface, methodName);
linkContainer.PropertyValue("RegistryBeanName", eventProviderBeanName);
linkContainer.PropertyValue("ListenerBeanName", listenerBeanName);
return linkContainer;
}
[Obsolete]
public IBeanConfiguration createEventLinkConfiguration(String eventProviderBeanName, Type eventInterface, String handlerDelegateBeanName)
{
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(eventInterface, "eventInterface");
ParamChecker.AssertParamNotNull(handlerDelegateBeanName, "handlerDelegateBeanName");
BeanConfiguration linkContainer = createLinkContainerConfiguration(eventInterface, (String)null);
linkContainer.PropertyValue("RegistryBeanName", eventProviderBeanName);
linkContainer.PropertyValue("ListenerBeanName", handlerDelegateBeanName);
return linkContainer;
}
[Obsolete]
public IBeanConfiguration createEventLinkConfiguration(String eventProviderBeanName, Type eventInterface, Delegate handlerDelegate)
{
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(eventInterface, "eventInterface");
ParamChecker.AssertParamNotNull(handlerDelegate, "handlerDelegate");
BeanConfiguration linkContainer = createLinkContainerConfiguration(eventInterface, (String)null);
linkContainer.PropertyValue("RegistryBeanName", eventProviderBeanName);
linkContainer.PropertyValue("Listener", handlerDelegate);
return linkContainer;
}
[Obsolete]
public IBeanConfiguration createEventLinkConfiguration<D>(String eventProviderBeanName, IEventDelegate<D> eventName, String listenerBeanName, String methodName)
{
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(eventName, "eventName");
ParamChecker.AssertParamNotNull(listenerBeanName, "listenerBeanName");
ParamChecker.AssertParamNotNull(methodName, "methodName");
BeanConfiguration linkContainer = createLinkContainerConfiguration(eventName.EventName);
linkContainer.PropertyValue("RegistryBeanName", eventProviderBeanName);
linkContainer.PropertyValue("ListenerBeanName", listenerBeanName);
linkContainer.PropertyValue("MethodName", methodName);
return linkContainer;
}
[Obsolete]
public IBeanConfiguration createEventLinkConfiguration<D>(String eventProviderBeanName, IEventDelegate<D> eventName, String handlerDelegateBeanName)
{
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(eventName, "eventName");
ParamChecker.AssertParamNotNull(handlerDelegateBeanName, "handlerDelegateBeanName");
BeanConfiguration linkContainer = createLinkContainerConfiguration(eventName.EventName);
linkContainer.PropertyValue("RegistryBeanName", eventProviderBeanName);
linkContainer.PropertyValue("ListenerBeanName", handlerDelegateBeanName);
return linkContainer;
}
[Obsolete]
public IBeanConfiguration createEventLinkConfiguration<D>(String eventProviderBeanName, IEventDelegate<D> eventName, D handlerDelegate)
{
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(eventName, "eventName");
ParamChecker.AssertParamNotNull(handlerDelegate, "handlerDelegate");
BeanConfiguration linkContainer = createLinkContainerConfiguration(eventName.EventName);
linkContainer.PropertyValue("RegistryBeanName", eventProviderBeanName);
linkContainer.PropertyValue("Listener", handlerDelegate);
return linkContainer;
}
[Obsolete]
public void LinkToEvent<D>(IServiceContext serviceContext, String eventProviderBeanName, IEventDelegate<D> eventName, String listenerBeanName, String methodName)
{
ParamChecker.AssertParamNotNull(serviceContext, "serviceContext");
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(eventName, "eventName");
ParamChecker.AssertParamNotNull(listenerBeanName, "listenerBeanName");
ParamChecker.AssertParamNotNull(methodName, "methodName");
AbstractLinkContainerOld linkContainer = createLinkContainer(eventName.EventName, methodName);
linkContainer.RegistryBeanName = eventProviderBeanName;
linkContainer.ListenerBeanName = listenerBeanName;
serviceContext.RegisterWithLifecycle(linkContainer).Finish();
}
[Obsolete]
public void LinkToEvent<D>(IServiceContext serviceContext, String eventProviderBeanName, IEventDelegate<D> eventName, String handlerDelegateBeanName)
{
ParamChecker.AssertParamNotNull(serviceContext, "serviceContext");
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(eventName, "eventName");
ParamChecker.AssertParamNotNull(handlerDelegateBeanName, "handlerDelegateBeanName");
AbstractLinkContainerOld linkContainer = createLinkContainer(eventName.EventName, (String)null);
linkContainer.RegistryBeanName = eventProviderBeanName;
linkContainer.ListenerBeanName = handlerDelegateBeanName;
serviceContext.RegisterWithLifecycle(linkContainer).Finish();
}
[Obsolete]
public void LinkToEvent<D>(IServiceContext serviceContext, String eventProviderBeanName, IEventDelegate<D> eventName, D handlerDelegate)
{
ParamChecker.AssertParamNotNull(serviceContext, "serviceContext");
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(eventName, "eventName");
ParamChecker.AssertParamNotNull(handlerDelegate, "handlerDelegate");
AbstractLinkContainerOld linkContainer = createLinkContainer(eventName.EventName, (String)null);
linkContainer.RegistryBeanName = eventProviderBeanName;
linkContainer.Listener = handlerDelegate;
serviceContext.RegisterWithLifecycle(linkContainer).Finish();
}
[Obsolete]
public void LinkToEvent<R>(IServiceContext serviceContext, String eventProviderBeanName, String listenerBeanName, String methodName)
{
ParamChecker.AssertParamNotNull(serviceContext, "serviceContext");
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(listenerBeanName, "listenerBeanName");
ParamChecker.AssertParamNotNull(methodName, "methodName");
AbstractLinkContainerOld linkContainer = createLinkContainer(typeof(R), methodName);
linkContainer.RegistryBeanName = eventProviderBeanName;
linkContainer.ListenerBeanName = listenerBeanName;
serviceContext.RegisterWithLifecycle(linkContainer).Finish();
}
[Obsolete]
public void LinkToEvent<R>(IServiceContext serviceContext, String eventProviderBeanName, String handlerDelegateBeanName)
{
ParamChecker.AssertParamNotNull(serviceContext, "serviceContext");
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(handlerDelegateBeanName, "handlerDelegateBeanName");
AbstractLinkContainerOld linkContainer = createLinkContainer(typeof(R), (String)null);
linkContainer.RegistryBeanName = eventProviderBeanName;
linkContainer.ListenerBeanName = handlerDelegateBeanName;
serviceContext.RegisterWithLifecycle(linkContainer).Finish();
}
[Obsolete]
public void LinkToEvent<R>(IServiceContext serviceContext, String eventProviderBeanName, Delegate handlerDelegate)
{
ParamChecker.AssertParamNotNull(serviceContext, "serviceContext");
ParamChecker.AssertParamNotNull(eventProviderBeanName, "eventProviderBeanName");
ParamChecker.AssertParamNotNull(handlerDelegate, "handlerDelegate");
AbstractLinkContainerOld linkContainer = createLinkContainer(typeof(R), (String)null);
linkContainer.RegistryBeanName = eventProviderBeanName;
linkContainer.Listener = handlerDelegate;
serviceContext.RegisterWithLifecycle(linkContainer).Finish();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Xml;
using Nop.Core;
using Nop.Core.Domain.Blogs;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Forums;
using Nop.Core.Domain.News;
using Nop.Core.Domain.Security;
using Nop.Services.Catalog;
using Nop.Services.Topics;
namespace Nop.Services.Seo
{
/// <summary>
/// Represents a sitemap generator
/// </summary>
public partial class SitemapGenerator : ISitemapGenerator
{
#region Constants
private const string DateFormat = @"yyyy-MM-dd";
/// <summary>
/// At now each provided sitemap file must have no more than 50000 URLs
/// </summary>
private const int maxSitemapUrlNumber = 50000;
#endregion
#region Fields
private readonly IStoreContext _storeContext;
private readonly ICategoryService _categoryService;
private readonly IProductService _productService;
private readonly IManufacturerService _manufacturerService;
private readonly ITopicService _topicService;
private readonly IWebHelper _webHelper;
private readonly CommonSettings _commonSettings;
private readonly BlogSettings _blogSettings;
private readonly NewsSettings _newsSettings;
private readonly ForumSettings _forumSettings;
private readonly SecuritySettings _securitySettings;
#endregion
#region Ctor
public SitemapGenerator(IStoreContext storeContext,
ICategoryService categoryService,
IProductService productService,
IManufacturerService manufacturerService,
ITopicService topicService,
IWebHelper webHelper,
CommonSettings commonSettings,
BlogSettings blogSettings,
NewsSettings newsSettings,
ForumSettings forumSettings,
SecuritySettings securitySettings)
{
this._storeContext = storeContext;
this._categoryService = categoryService;
this._productService = productService;
this._manufacturerService = manufacturerService;
this._topicService = topicService;
this._webHelper = webHelper;
this._commonSettings = commonSettings;
this._blogSettings = blogSettings;
this._newsSettings = newsSettings;
this._forumSettings = forumSettings;
this._securitySettings = securitySettings;
}
#endregion
#region Nested class
/// <summary>
/// Represents sitemap URL entry
/// </summary>
protected class SitemapUrl
{
public SitemapUrl(string location, UpdateFrequency frequency, DateTime updatedOn)
{
Location = location;
UpdateFrequency = frequency;
UpdatedOn = updatedOn;
}
/// <summary>
/// Gets or sets URL of the page
/// </summary>
public string Location { get; set; }
/// <summary>
/// Gets or sets a value indicating how frequently the page is likely to change
/// </summary>
public UpdateFrequency UpdateFrequency { get; set; }
/// <summary>
/// Gets or sets the date of last modification of the file
/// </summary>
public DateTime UpdatedOn { get; set; }
}
#endregion
#region Utilities
/// <summary>
/// Get HTTP protocol
/// </summary>
/// <returns>Protocol name as string</returns>
protected virtual string GetHttpProtocol()
{
return _securitySettings.ForceSslForAllPages ? "https" : "http";
}
/// <summary>
/// Generate URLs for the sitemap
/// </summary>
/// <param name="urlHelper">URL helper</param>
/// <returns>List of URL for the sitemap</returns>
protected virtual IList<SitemapUrl> GenerateUrls(UrlHelper urlHelper)
{
var sitemapUrls = new List<SitemapUrl>();
//home page
var homePageUrl = urlHelper.RouteUrl("HomePage", null, GetHttpProtocol());
sitemapUrls.Add(new SitemapUrl(homePageUrl, UpdateFrequency.Weekly, DateTime.UtcNow));
//search products
var productSearchUrl = urlHelper.RouteUrl("ProductSearch", null, GetHttpProtocol());
sitemapUrls.Add(new SitemapUrl(productSearchUrl, UpdateFrequency.Weekly, DateTime.UtcNow));
//contact us
var contactUsUrl = urlHelper.RouteUrl("ContactUs", null, GetHttpProtocol());
sitemapUrls.Add(new SitemapUrl(contactUsUrl, UpdateFrequency.Weekly, DateTime.UtcNow));
//news
if (_newsSettings.Enabled)
{
var url = urlHelper.RouteUrl("NewsArchive", null, GetHttpProtocol());
sitemapUrls.Add(new SitemapUrl(url, UpdateFrequency.Weekly, DateTime.UtcNow));
}
//blog
if (_blogSettings.Enabled)
{
var url = urlHelper.RouteUrl("Blog", null, GetHttpProtocol());
sitemapUrls.Add(new SitemapUrl(url, UpdateFrequency.Weekly, DateTime.UtcNow));
}
//blog
if (_forumSettings.ForumsEnabled)
{
var url = urlHelper.RouteUrl("Boards", null, GetHttpProtocol());
sitemapUrls.Add(new SitemapUrl(url, UpdateFrequency.Weekly, DateTime.UtcNow));
}
//categories
if (_commonSettings.SitemapIncludeCategories)
sitemapUrls.AddRange(GetCategoryUrls(urlHelper, 0));
//manufacturers
if (_commonSettings.SitemapIncludeManufacturers)
sitemapUrls.AddRange(GetManufacturerUrls(urlHelper));
//products
if (_commonSettings.SitemapIncludeProducts)
sitemapUrls.AddRange(GetProductUrls(urlHelper));
//topics
sitemapUrls.AddRange(GetTopicUrls(urlHelper));
//custom URLs
sitemapUrls.AddRange(GetCustomUrls());
return sitemapUrls;
}
/// <summary>
/// Get category URLs for the sitemap
/// </summary>
/// <param name="urlHelper">URL helper</param>
/// <param name="parentCategoryId">Parent category identifier</param>
/// <returns>Collection of sitemap URLs</returns>
protected virtual IEnumerable<SitemapUrl> GetCategoryUrls(UrlHelper urlHelper, int parentCategoryId)
{
return _categoryService.GetAllCategoriesByParentCategoryId(parentCategoryId).SelectMany(category =>
{
var sitemapUrls = new List<SitemapUrl>();
var url = urlHelper.RouteUrl("Category", new { SeName = category.GetSeName() }, GetHttpProtocol());
sitemapUrls.Add(new SitemapUrl(url, UpdateFrequency.Weekly, category.UpdatedOnUtc));
sitemapUrls.AddRange(GetCategoryUrls(urlHelper, category.Id));
return sitemapUrls;
});
}
/// <summary>
/// Get manufacturer URLs for the sitemap
/// </summary>
/// <param name="urlHelper">URL helper</param>
/// <returns>Collection of sitemap URLs</returns>
protected virtual IEnumerable<SitemapUrl> GetManufacturerUrls(UrlHelper urlHelper)
{
return _manufacturerService.GetAllManufacturers(storeId: _storeContext.CurrentStore.Id).Select(manufacturer =>
{
var url = urlHelper.RouteUrl("Manufacturer", new { SeName = manufacturer.GetSeName() }, GetHttpProtocol());
return new SitemapUrl(url, UpdateFrequency.Weekly, manufacturer.UpdatedOnUtc);
});
}
/// <summary>
/// Get product URLs for the sitemap
/// </summary>
/// <param name="urlHelper">URL helper</param>
/// <returns>Collection of sitemap URLs</returns>
protected virtual IEnumerable<SitemapUrl> GetProductUrls(UrlHelper urlHelper)
{
return _productService.SearchProducts(storeId: _storeContext.CurrentStore.Id,
visibleIndividuallyOnly: true, orderBy: ProductSortingEnum.CreatedOn).Select(product =>
{
var url = urlHelper.RouteUrl("Product", new { SeName = product.GetSeName() }, GetHttpProtocol());
return new SitemapUrl(url, UpdateFrequency.Weekly, product.UpdatedOnUtc);
});
}
/// <summary>
/// Get topic URLs for the sitemap
/// </summary>
/// <param name="urlHelper">URL helper</param>
/// <returns>Collection of sitemap URLs</returns>
protected virtual IEnumerable<SitemapUrl> GetTopicUrls(UrlHelper urlHelper)
{
return _topicService.GetAllTopics(_storeContext.CurrentStore.Id).Where(t => t.IncludeInSitemap).Select(topic =>
{
var url = urlHelper.RouteUrl("Topic", new { SeName = topic.GetSeName() }, GetHttpProtocol());
return new SitemapUrl(url, UpdateFrequency.Weekly, DateTime.UtcNow);
});
}
/// <summary>
/// Get custom URLs for the sitemap
/// </summary>
/// <returns>Collection of sitemap URLs</returns>
protected virtual IEnumerable<SitemapUrl> GetCustomUrls()
{
var storeLocation = _webHelper.GetStoreLocation();
return _commonSettings.SitemapCustomUrls.Select(customUrl =>
new SitemapUrl(string.Concat(storeLocation, customUrl), UpdateFrequency.Weekly, DateTime.UtcNow));
}
/// <summary>
/// Write sitemap index file into the stream
/// </summary>
/// <param name="urlHelper">URL helper</param>
/// <param name="stream">Stream</param>
/// <param name="sitemapNumber">The number of sitemaps</param>
protected virtual void WriteSitemapIndex(UrlHelper urlHelper, Stream stream, int sitemapNumber)
{
using (var writer = new XmlTextWriter(stream, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("sitemapindex");
writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xsi:schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
//write URLs of all available sitemaps
for (var id = 1; id <= sitemapNumber; id++)
{
var url = urlHelper.RouteUrl("sitemap-indexed.xml", new { Id = id }, GetHttpProtocol());
var location = XmlHelper.XmlEncode(url);
writer.WriteStartElement("sitemap");
writer.WriteElementString("loc", location);
writer.WriteElementString("lastmod", DateTime.UtcNow.ToString(DateFormat));
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
/// <summary>
/// Write sitemap file into the stream
/// </summary>
/// <param name="urlHelper">URL helper</param>
/// <param name="stream">Stream</param>
/// <param name="sitemapUrls">List of sitemap URLs</param>
protected virtual void WriteSitemap(UrlHelper urlHelper, Stream stream, IList<SitemapUrl> sitemapUrls)
{
using (var writer = new XmlTextWriter(stream, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("urlset");
writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xsi:schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
//write URLs from list to the sitemap
foreach (var url in sitemapUrls)
{
writer.WriteStartElement("url");
var location = XmlHelper.XmlEncode(url.Location);
writer.WriteElementString("loc", location);
writer.WriteElementString("changefreq", url.UpdateFrequency.ToString().ToLowerInvariant());
writer.WriteElementString("lastmod", url.UpdatedOn.ToString(DateFormat));
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
#endregion
#region Methods
/// <summary>
/// This will build an xml sitemap for better index with search engines.
/// See http://en.wikipedia.org/wiki/Sitemaps for more information.
/// </summary>
/// <param name="urlHelper">URL helper</param>
/// <param name="id">Sitemap identifier</param>
/// <returns>Sitemap.xml as string</returns>
public virtual string Generate(UrlHelper urlHelper, int? id)
{
using (var stream = new MemoryStream())
{
Generate(urlHelper, stream, id);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
/// <summary>
/// This will build an xml sitemap for better index with search engines.
/// See http://en.wikipedia.org/wiki/Sitemaps for more information.
/// </summary>
/// <param name="urlHelper">URL helper</param>
/// <param name="id">Sitemap identifier</param>
/// <param name="stream">Stream of sitemap.</param>
public virtual void Generate(UrlHelper urlHelper, Stream stream, int? id)
{
//generate all URLs for the sitemap
var sitemapUrls = GenerateUrls(urlHelper);
//split URLs into separate lists based on the max size
var sitemaps = sitemapUrls.Select((url, index) => new { Index = index, Value = url })
.GroupBy(group => group.Index / maxSitemapUrlNumber).Select(group => group.Select(url => url.Value).ToList()).ToList();
if (!sitemaps.Any())
return;
if (id.HasValue)
{
//requested sitemap does not exist
if (id.Value == 0 || id.Value > sitemaps.Count)
return;
//otherwise write a certain numbered sitemap file into the stream
WriteSitemap(urlHelper, stream, sitemaps.ElementAt(id.Value - 1));
}
else
{
//URLs more than the maximum allowable, so generate a sitemap index file
if (sitemapUrls.Count >= maxSitemapUrlNumber)
{
//write a sitemap index file into the stream
WriteSitemapIndex(urlHelper, stream, sitemaps.Count);
}
else
{
//otherwise generate a standard sitemap
WriteSitemap(urlHelper, stream, sitemaps.First());
}
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TCPListener.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net.Sockets {
using System;
using System.Net;
using System.Security.Permissions;
using System.Threading.Tasks;
/// <devdoc>
/// <para>The <see cref='System.Net.Sockets.TcpListener'/> class provide TCP services at a higher level of abstraction than the <see cref='System.Net.Sockets.Socket'/>
/// class. <see cref='System.Net.Sockets.TcpListener'/> is used to create a host process that
/// listens for connections from TCP clients.</para>
/// </devdoc>
public class TcpListener {
IPEndPoint m_ServerSocketEP;
Socket m_ServerSocket;
bool m_Active;
bool m_ExclusiveAddressUse;
/// <devdoc>
/// <para>
/// Initializes a new instance of the TcpListener class with the specified local
/// end point.
/// </para>
/// </devdoc>
public TcpListener(IPEndPoint localEP) {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "TcpListener", localEP);
if (localEP == null) {
throw new ArgumentNullException("localEP");
}
m_ServerSocketEP = localEP;
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "TcpListener", null);
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the TcpListener class that listens to the
/// specified IP address and port.
/// </para>
/// </devdoc>
public TcpListener(IPAddress localaddr, int port) {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "TcpListener", localaddr);
if (localaddr == null) {
throw new ArgumentNullException("localaddr");
}
if (!ValidationHelper.ValidateTcpPort(port)) {
throw new ArgumentOutOfRangeException("port");
}
m_ServerSocketEP = new IPEndPoint(localaddr, port);
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "TcpListener", null);
}
// implementation picks an address for client
/// <devdoc>
/// <para>
/// Initiailizes a new instance of the TcpListener class
/// that listens on the specified
/// port.
/// </para>
/// </devdoc>
///
[Obsolete("This method has been deprecated. Please use TcpListener(IPAddress localaddr, int port) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public TcpListener(int port){
if (!ValidationHelper.ValidateTcpPort(port))
throw new ArgumentOutOfRangeException("port");
m_ServerSocketEP = new IPEndPoint(IPAddress.Any, port);
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
// This creates a TcpListener that listens on both IPv4 and IPv6 on the given port.
public static TcpListener Create(int port) {
if (Logging.On) Logging.Enter(Logging.Sockets, "TcpListener.Create", "Port: " + port);
if (!ValidationHelper.ValidateTcpPort(port)) {
throw new ArgumentOutOfRangeException("port");
}
TcpListener listener = new TcpListener(IPAddress.IPv6Any, port);
listener.Server.DualMode = true;
if (Logging.On) Logging.Exit(Logging.Sockets, "TcpListener.Create", "Port: " + port);
return listener;
}
/// <devdoc>
/// <para>
/// Used by the class to provide the underlying network socket.
/// </para>
/// </devdoc>
public Socket Server {
get {
return m_ServerSocket;
}
}
/// <devdoc>
/// <para>
/// Used
/// by the class to indicate that the listener's socket has been bound to a port
/// and started listening.
/// </para>
/// </devdoc>
protected bool Active {
get {
return m_Active;
}
}
/// <devdoc>
/// <para>
/// Gets the m_Active EndPoint for the local listener socket.
/// </para>
/// </devdoc>
public EndPoint LocalEndpoint {
get {
return m_Active ? m_ServerSocket.LocalEndPoint : m_ServerSocketEP;
}
}
public bool ExclusiveAddressUse {
get {
return m_ServerSocket.ExclusiveAddressUse;
}
set{
if (m_Active) {
throw new InvalidOperationException(SR.GetString(SR.net_tcplistener_mustbestopped));
}
m_ServerSocket.ExclusiveAddressUse = value;
m_ExclusiveAddressUse = value;
}
}
public void AllowNatTraversal(bool allowed) {
if (m_Active) {
throw new InvalidOperationException(SR.GetString(SR.net_tcplistener_mustbestopped));
}
if (allowed) {
m_ServerSocket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
}
else {
m_ServerSocket.SetIPProtectionLevel(IPProtectionLevel.EdgeRestricted);
}
}
// Start/stop the listener
/// <devdoc>
/// <para>
/// Starts listening to network requests.
/// </para>
/// </devdoc>
public void Start() {
Start((int)SocketOptionName.MaxConnections);
}
public void Start(int backlog) {
if (backlog > (int)SocketOptionName.MaxConnections || backlog < 0) {
throw new ArgumentOutOfRangeException("backlog");
}
if(Logging.On)Logging.Enter(Logging.Sockets, this, "Start", null);
GlobalLog.Print("TCPListener::Start()");
if (m_ServerSocket == null)
throw new InvalidOperationException(SR.GetString(SR.net_InvalidSocketHandle));
//already listening
if (m_Active) {
if(Logging.On)Logging.Exit(Logging.Sockets, this, "Start", null);
return;
}
m_ServerSocket.Bind(m_ServerSocketEP);
try {
m_ServerSocket.Listen(backlog);
}
// When there is an exception unwind previous actions (bind etc)
catch (SocketException) {
Stop();
throw;
}
m_Active = true;
if(Logging.On)Logging.Exit(Logging.Sockets, this, "Start", null);
}
/// <devdoc>
/// <para>
/// Closes the network connection.
/// </para>
/// </devdoc>
public void Stop() {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "Stop", null);
GlobalLog.Print("TCPListener::Stop()");
if (m_ServerSocket != null) {
m_ServerSocket.Close();
m_ServerSocket = null;
}
m_Active = false;
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (m_ExclusiveAddressUse) {
m_ServerSocket.ExclusiveAddressUse = true;
}
if(Logging.On)Logging.Exit(Logging.Sockets, this, "Stop", null);
}
// Determine if there are pending connections
/// <devdoc>
/// <para>
/// Determine if there are pending connection requests.
/// </para>
/// </devdoc>
public bool Pending() {
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
return m_ServerSocket.Poll(0, SelectMode.SelectRead);
}
// Accept the first pending connection
/// <devdoc>
/// <para>
/// Accepts a pending connection request.
/// </para>
/// </devdoc>
public Socket AcceptSocket() {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "AcceptSocket", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
Socket socket = m_ServerSocket.Accept();
if(Logging.On)Logging.Exit(Logging.Sockets, this, "AcceptSocket", socket);
return socket;
}
// UEUE
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public TcpClient AcceptTcpClient() {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "AcceptTcpClient", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
Socket acceptedSocket = m_ServerSocket.Accept();
TcpClient returnValue = new TcpClient(acceptedSocket);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "AcceptTcpClient", returnValue);
return returnValue;
}
//methods
[HostProtection(ExternalThreading=true)]
public IAsyncResult BeginAcceptSocket(AsyncCallback callback, object state)
{
if(Logging.On)Logging.Enter(Logging.Sockets, this, "BeginAcceptSocket", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
IAsyncResult result = m_ServerSocket.BeginAccept(callback,state);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "BeginAcceptSocket", null);
return result;
}
public Socket EndAcceptSocket(IAsyncResult asyncResult){
if(Logging.On)Logging.Enter(Logging.Sockets, this, "EndAcceptSocket", null);
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
}
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "EndAcceptSocket", socket);
return socket;
}
[HostProtection(ExternalThreading=true)]
public IAsyncResult BeginAcceptTcpClient(AsyncCallback callback, object state)
{
if(Logging.On)Logging.Enter(Logging.Sockets, this, "BeginAcceptTcpClient", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
IAsyncResult result = m_ServerSocket.BeginAccept(callback,state);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "BeginAcceptTcpClient", null);
return result;
}
public TcpClient EndAcceptTcpClient(IAsyncResult asyncResult){
if(Logging.On)Logging.Enter(Logging.Sockets, this, "EndAcceptTcpClient", null);
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
}
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "EndAcceptTcpClient", socket);
return new TcpClient(socket);
}
//************* Task-based async public methods *************************
[HostProtection(ExternalThreading = true)]
public Task<Socket> AcceptSocketAsync()
{
return Task<Socket>.Factory.FromAsync(BeginAcceptSocket, EndAcceptSocket, null);
}
[HostProtection(ExternalThreading = true)]
public Task<TcpClient> AcceptTcpClientAsync()
{
return Task<TcpClient>.Factory.FromAsync(BeginAcceptTcpClient, EndAcceptTcpClient, null);
}
}; // class TcpListener
} // namespace System.Net.Sockets
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Unicode;
namespace Microsoft.Framework.WebEncoders
{
// These implement ASP.NET interfaces. They will be removed once we transition ASP.NET
internal sealed class HtmlEncoder : IHtmlEncoder
{
System.Text.Encodings.Web.DefaultHtmlEncoder _encoder;
static HtmlEncoder s_default;
/// <summary>
/// A default instance of <see cref="HtmlEncoder"/>.
/// </summary>
/// <remarks>
/// This normally corresponds to <see cref="UnicodeRanges.BasicLatin"/>. However, this property is
/// settable so that a developer can change the default implementation application-wide.
/// </remarks>
public static HtmlEncoder Default
{
get
{
if (s_default == null)
{
s_default = new HtmlEncoder();
}
return s_default;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
s_default = value;
}
}
public HtmlEncoder()
{
_encoder = System.Text.Encodings.Web.DefaultHtmlEncoder.Singleton;
}
public HtmlEncoder(TextEncoderSettings filter)
{
_encoder = new System.Text.Encodings.Web.DefaultHtmlEncoder(filter);
}
public HtmlEncoder(UnicodeRange allowedRange) : this(new TextEncoderSettings(allowedRange))
{ }
public HtmlEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges))
{ }
public void HtmlEncode(char[] value, int startIndex, int characterCount, TextWriter output)
{
_encoder.Encode(output, value, startIndex, characterCount);
}
public string HtmlEncode(string value)
{
return _encoder.Encode(value);
}
public void HtmlEncode(string value, int startIndex, int characterCount, TextWriter output)
{
_encoder.Encode(output, value, startIndex, characterCount);
}
}
internal sealed class JavaScriptStringEncoder : IJavaScriptStringEncoder
{
System.Text.Encodings.Web.DefaultJavaScriptEncoder _encoder;
static JavaScriptStringEncoder s_default;
/// <summary>
/// A default instance of <see cref="JavaScriptEncoder"/>.
/// </summary>
/// <remarks>
/// This normally corresponds to <see cref="UnicodeRanges.BasicLatin"/>. However, this property is
/// settable so that a developer can change the default implementation application-wide.
/// </remarks>
public static JavaScriptStringEncoder Default
{
get
{
if (s_default == null)
{
s_default = new JavaScriptStringEncoder();
}
return s_default;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
s_default = value;
}
}
public JavaScriptStringEncoder()
{
_encoder = System.Text.Encodings.Web.DefaultJavaScriptEncoder.Singleton;
}
public JavaScriptStringEncoder(TextEncoderSettings filter)
{
_encoder = new System.Text.Encodings.Web.DefaultJavaScriptEncoder(filter);
}
public JavaScriptStringEncoder(UnicodeRange allowedRange) : this(new TextEncoderSettings(allowedRange))
{ }
public JavaScriptStringEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges))
{ }
public void JavaScriptStringEncode(char[] value, int startIndex, int characterCount, TextWriter output)
{
_encoder.Encode(output, value, startIndex, characterCount);
}
public string JavaScriptStringEncode(string value)
{
return _encoder.Encode(value);
}
public void JavaScriptStringEncode(string value, int startIndex, int characterCount, TextWriter output)
{
_encoder.Encode(output, value, startIndex, characterCount);
}
}
internal sealed class UrlEncoder : IUrlEncoder
{
System.Text.Encodings.Web.DefaultUrlEncoder _encoder;
static UrlEncoder s_default;
/// <summary>
/// A default instance of <see cref="UrlEncoder"/>.
/// </summary>
/// <remarks>
/// This normally corresponds to <see cref="UnicodeRanges.BasicLatin"/>. However, this property is
/// settable so that a developer can change the default implementation application-wide.
/// </remarks>
public static UrlEncoder Default
{
get
{
if (s_default == null)
{
s_default = new UrlEncoder();
}
return s_default;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
s_default = value;
}
}
public UrlEncoder()
{
_encoder = System.Text.Encodings.Web.DefaultUrlEncoder.Singleton;
}
public UrlEncoder(TextEncoderSettings filter)
{
_encoder = new System.Text.Encodings.Web.DefaultUrlEncoder(filter);
}
public UrlEncoder(UnicodeRange allowedRange) : this(new TextEncoderSettings(allowedRange))
{ }
public UrlEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges))
{ }
public void UrlEncode(char[] value, int startIndex, int characterCount, TextWriter output)
{
_encoder.Encode(output, value, startIndex, characterCount);
}
public string UrlEncode(string value)
{
return _encoder.Encode(value); ;
}
public void UrlEncode(string value, int startIndex, int characterCount, TextWriter output)
{
_encoder.Encode(output, value, startIndex, characterCount);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace Hydra.Framework.Geometric
{
public class PointObject : IMapviewObject, ICloneable, IPersist
{
#region Private Members of Point Object
public event GraphicEvents GraphicSelected;
private float x1;
private float y1;
private int size = 2;
private bool isselected = false;
private bool isfilled = false;
private bool visible = true;
private bool showtooptip = false;
private bool iscurrent = true;
private bool islocked = false;
private bool isdisabled = false;
private bool showhandle = false;
private int handlesize = 6;
private Color fillcolor = Color.Cyan;
private Color normalcolor = Color.Yellow;
private Color selectcolor = Color.Red;
private Color disabledcolor = Color.Gray;
private int linewidth = 2;
public PointF[] points;
private string xml = "";
#endregion
#region Properties of Point Object
public PointF[] Vertices
{
get { return points; }
set { points = value; }
}
[Category("Colors"), Description("The disabled graphic object will be drawn using this pen")]
public Color DisabledColor
{
get { return disabledcolor; }
set { disabledcolor = value; }
}
[Category("Colors"), Description("The selected graphic object willbe drawn using this pen")]
public Color SelectColor
{
get { return selectcolor; }
set { selectcolor = value; }
}
[Category("Colors"), Description("The graphic object willbe drawn using this pen")]
public Color NormalColor
{
get { return normalcolor; }
set { normalcolor = value; }
}
[DefaultValue(2), Category("AbstractStyle"), Description("The gives the Point thickness of the graphic object")]
public int LineWidth
{
get { return linewidth; }
set { linewidth = value; }
}
[Category("Appearance"), Description("The graphic object will be filled with a given color or pattern")]
public bool IsFilled
{
get { return isfilled; }
set { isfilled = value; }
}
[Category("Appearance"), Description("Determines whether the object is visible or hidden")]
public bool Visible
{
get { return visible; }
set { visible = value; }
}
[Category("Appearance"), Description("Determines whether the tooltip information to be shown or not")]
public bool ShowToopTip
{
get { return showtooptip; }
set { showtooptip = value; }
}
[Category("Appearance"), Description("Determines whether the object is in current selected legend or not")]
public bool IsCurrent
{
get { return iscurrent; }
set { iscurrent = value; }
}
[Category("Appearance"), Description("Determines whether the object is locked from the current user or not")]
public bool IsLocked
{
get { return islocked; }
set { islocked = value; }
}
[Category("Appearance"), Description("Determines whether the object is disabled from editing")]
public bool IsDisabled
{
get { return isdisabled; }
set { isdisabled = value; }
}
[Category("Appearance"), Description("Determines whether the object is in edit mode")]
public bool IsEdit
{
get { return showhandle; }
set { showhandle = value; }
}
#endregion
#region Constructors of Point Object
public PointObject(float x_1, float y_1)
{
x1 = x_1;
y1 = y_1;
}
public PointObject(PointObject po) { }
#endregion
#region Methods of ICloneable
/// <summary>
/// Deep-copy clone routine
/// </summary>
/// <returns>A new, independent copy of the Point Object</returns>
public object Clone()
{
return new PointObject(this);
}
#endregion
#region Methods of Point Object
public bool IsSelected()
{
return isselected;
}
public void Select(bool m)
{
isselected = m;
}
public bool IsObjectAt(PointF pnt, float dist)
{
double curr_dist = GeoUtil.SquareDistance(new PointF(x1, y1), pnt);
return Math.Sqrt(curr_dist) < dist;
}
public Rectangle BoundingBox()
{
return new Rectangle((int)x1 - 2, (int)y1 - 2, (int)x1 + 2, (int)y1 + 2);
}
public float X() { return x1; }
public float Y() { return y1; }
public void Move(PointF p)
{
float dx = p.X - x1;
float dy = p.Y - y1;
x1 += dx;
y1 += dy;
}
public void MoveBy(float xs, float ys)
{
x1 += xs;
y1 += ys;
}
public void Scale(int scale)
{
x1 *= scale;
y1 *= scale;
}
public void Rotate(float radians)
{
//
}
public void RotateAt(PointF pt)
{
//
}
public void RoateAt(Point pt)
{
//
}
public void Draw(Graphics graph, System.Drawing.Drawing2D.Matrix trans)
{
if (visible)
{
// create 0,0 and width,height points
PointF[] points = { new PointF(x1, y1) };
trans.TransformPoints(points);
if (isselected)
{
graph.DrawEllipse(new Pen(selectcolor, linewidth), (int)points[0].X - 1, (int)points[0].Y - 1, size, size);
}
else if (isdisabled || islocked)
{
graph.DrawEllipse(new Pen(disabledcolor, linewidth), (int)points[0].X - 2, (int)points[0].Y - 2, size, size);
}
else
{
graph.DrawEllipse(new Pen(normalcolor, linewidth), (int)points[0].X - 2, (int)points[0].Y - 2, size, size);
}
}
}
#endregion
#region IPersist Members
public string ToXML
{
get { return xml; }
set { xml = value; }
}
public string ToVML
{
get { return xml; }
set { xml = value; }
}
public string ToGML
{
get { return xml; }
set { xml = value; }
}
public string ToSVG
{
get { return xml; }
set { xml = value; }
}
#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.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.SharpZipLib.BZip2;
using QuantConnect.Data.Market;
using QuantConnect.Logging;
using QuantConnect.Util;
namespace QuantConnect.ToolBox.AlgoSeekOptionsConverter
{
using Processors = Dictionary<Symbol, List<AlgoSeekOptionsProcessor>>;
/// <summary>
/// Process a directory of algoseek option files into separate resolutions.
/// </summary>
public class AlgoSeekOptionsConverter
{
private string _source;
private string _remote;
private string _remoteMask;
private string _destination;
private Resolution _resolution;
private DateTime _referenceDate;
private readonly ParallelOptions parallelOptionsProcessing = new ParallelOptions {MaxDegreeOfParallelism = Environment.ProcessorCount};
private readonly ParallelOptions parallelOptionsZipping = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 5 };
/// <summary>
/// Create a new instance of the AlgoSeekOptions Converter. Parse a single input directory into an output.
/// </summary>
/// <param name="resolution">Convert this resolution</param>
/// <param name="referenceDate">Datetime to be added to the milliseconds since midnight. Algoseek data is stored in channel files (XX.bz2) and in a source directory</param>
/// <param name="source">Remote directory of the .bz algoseek files</param>
/// <param name="source">Source directory of the .csv algoseek files</param>
/// <param name="destination">Data directory of LEAN</param>
public AlgoSeekOptionsConverter(Resolution resolution, DateTime referenceDate, string remote, string remoteMask, string source, string destination)
{
_remote = remote;
_remoteMask = remoteMask;
_source = source;
_referenceDate = referenceDate;
_destination = destination;
_resolution = resolution;
}
/// <summary>
/// Give the reference date and source directory, convert the algoseek options data into n-resolutions LEAN format.
/// </summary>
/// <param name="symbolFilter">HashSet of symbols as string to process. *Only used for testing*</param>
public void Convert(HashSet<string> symbolFilter = null)
{
//Get the list of all the files, then for each file open a separate streamer.
var compressedRawDatafiles = Directory.EnumerateFiles(_remote, _remoteMask).Select(f => new FileInfo(f)).ToList();
var rawDatafiles = new List<FileInfo>();
Log.Trace("AlgoSeekOptionsConverter.Convert(): Loading {0} AlgoSeekOptionsReader for {1} ", compressedRawDatafiles.Count, _referenceDate);
//Initialize parameters
var totalLinesProcessed = 0L;
var totalFiles = compressedRawDatafiles.Count;
var totalFilesProcessed = 0;
var start = DateTime.MinValue;
foreach (var compressedRawDatafile in compressedRawDatafiles)
{
var counter = 1;
var timer = DateTime.UtcNow;
var rawDataFile = new FileInfo(Path.Combine(_source, compressedRawDatafile.Name.Replace(".bz2", "")));
var decompressSuccessful = false;
do
{
var attempt = counter == 1 ? string.Empty : $" attempt {counter} of 3";
Log.Trace($"AlgoSeekOptionsConverter.Convert(): Extracting {compressedRawDatafile.Name}{attempt}.");
decompressSuccessful = DecompressOpraFile(compressedRawDatafile, rawDataFile);
counter++;
} while (!decompressSuccessful && counter <= 3);
if (!decompressSuccessful)
{
Log.Error($"Error decompressing {compressedRawDatafile}. Process Stop.");
throw new NotImplementedException();
}
Log.Trace($"AlgoSeekOptionsConverter.Convert(): Extraction successful in {DateTime.UtcNow - timer:g}.");
rawDatafiles.Add(rawDataFile);
}
//Process each file massively in parallel.
Parallel.ForEach(rawDatafiles, parallelOptionsProcessing, rawDataFile =>
{
Log.Trace("Source File :" + rawDataFile.Name);
// setting up local processors and the flush event
var processors = new Processors();
var waitForFlush = new ManualResetEvent(true);
// symbol filters
// var symbolFilterNames = new string[] { "AAPL", "TWX", "NWSA", "FOXA", "AIG", "EGLE", "EGEC" };
// var symbolFilter = symbolFilterNames.SelectMany(name => new[] { name, name + "1", name + ".1" }).ToHashSet();
// var reader = new AlgoSeekOptionsReader(csvFile, _referenceDate, symbolFilter);
using (var reader = new AlgoSeekOptionsReader(rawDataFile.FullName, _referenceDate, symbolFilter))
{
if (start == DateTime.MinValue)
{
start = DateTime.Now;
}
var flushStep = TimeSpan.FromMinutes(10);
if (reader.Current != null) // reader contains the data
{
var previousFlush = reader.Current.Time.RoundDown(flushStep);
do
{
var tick = reader.Current as Tick;
//If the next minute has clocked over; flush the consolidators; serialize and store data to disk.
if (tick.Time.RoundDown(flushStep) > previousFlush)
{
previousFlush = WriteToDisk(processors, waitForFlush, tick.Time, flushStep);
processors = new Processors();
}
//Add or create the consolidator-flush mechanism for symbol:
List<AlgoSeekOptionsProcessor> symbolProcessors;
if (!processors.TryGetValue(tick.Symbol, out symbolProcessors))
{
symbolProcessors = new List<AlgoSeekOptionsProcessor>(3)
{
new AlgoSeekOptionsProcessor(tick.Symbol, _referenceDate, TickType.Trade, _resolution, _destination),
new AlgoSeekOptionsProcessor(tick.Symbol, _referenceDate, TickType.Quote, _resolution, _destination),
new AlgoSeekOptionsProcessor(tick.Symbol, _referenceDate, TickType.OpenInterest, _resolution, _destination)
};
processors[tick.Symbol] = symbolProcessors;
}
// Pass current tick into processor: enum 0 = trade; 1 = quote, , 2 = oi
symbolProcessors[(int)tick.TickType].Process(tick);
if (Interlocked.Increment(ref totalLinesProcessed) % 1000000m == 0)
{
Log.Trace(
"AlgoSeekOptionsConverter.Convert(): Processed {0,3}M ticks( {1}k / sec); Memory in use: {2} MB; Total progress: {3}%",
Math.Round(totalLinesProcessed / 1000000m, 2),
Math.Round(totalLinesProcessed / 1000L / (DateTime.Now - start).TotalSeconds),
Process.GetCurrentProcess().WorkingSet64 / (1024 * 1024),
100 * totalFilesProcessed / totalFiles);
}
} while (reader.MoveNext());
Log.Trace("AlgoSeekOptionsConverter.Convert(): Performing final flush to disk... ");
Flush(processors, DateTime.MaxValue, true);
WriteToDisk(processors, waitForFlush, DateTime.MaxValue, flushStep, true);
}
Log.Trace("AlgoSeekOptionsConverter.Convert(): Cleaning up extracted options file {0}", rawDataFile.FullName);
}
rawDataFile.Delete();
processors = null;
Log.Trace("AlgoSeekOptionsConverter.Convert(): Finished processing file: " + rawDataFile);
Interlocked.Increment(ref totalFilesProcessed);
});
}
/// <summary>
/// Write the processor queues to disk
/// </summary>
/// <param name="peekTickTime">Time of the next tick in the stream</param>
/// <param name="step">Period between flushes to disk</param>
/// <param name="final">Final push to disk</param>
/// <returns></returns>
private DateTime WriteToDisk(Processors processors, ManualResetEvent waitForFlush, DateTime peekTickTime, TimeSpan step, bool final = false)
{
waitForFlush.WaitOne();
waitForFlush.Reset();
Flush(processors, peekTickTime, final);
Task.Run(() =>
{
try
{
foreach (var type in Enum.GetValues(typeof(TickType)))
{
var tickType = type;
var groups = processors.Values.Select(x => x[(int)tickType]).Where(x => x.Queue.Count > 0).GroupBy(process => process.Symbol.Underlying.Value);
Parallel.ForEach(groups, group =>
{
string zip = string.Empty;
try
{
var symbol = group.Key;
zip = group.First().ZipPath.Replace(".zip", string.Empty);
foreach (var processor in group)
{
var tempFileName = Path.Combine(zip, processor.EntryPath);
Directory.CreateDirectory(zip);
File.AppendAllText(tempFileName, FileBuilder(processor));
}
}
catch (Exception err)
{
Log.Error("AlgoSeekOptionsConverter.WriteToDisk() returned error: " + err.Message + " zip name: " + zip);
}
});
}
}
catch (Exception err)
{
Log.Error("AlgoSeekOptionsConverter.WriteToDisk() returned error: " + err.Message);
}
waitForFlush.Set();
});
//Pause while writing the final flush.
if (final) waitForFlush.WaitOne();
return peekTickTime.RoundDown(step);
}
/// <summary>
/// Output a list of basedata objects into a string csv line.
/// </summary>
/// <param name="processor"></param>
/// <returns></returns>
private string FileBuilder(AlgoSeekOptionsProcessor processor)
{
var sb = new StringBuilder();
foreach (var data in processor.Queue)
{
sb.AppendLine(LeanData.GenerateLine(data, SecurityType.Option, processor.Resolution));
}
return sb.ToString();
}
private void Flush(Processors processors, DateTime time, bool final)
{
foreach (var symbol in processors.Keys)
{
processors[symbol].ForEach(x => x.FlushBuffer(time, final));
}
}
/// <summary>
/// Compress the queue buffers directly to a zip file. Lightening fast as streaming ram-> compressed zip.
/// </summary>
public void Package(DateTime date)
{
Log.Trace("AlgoSeekOptionsConverter.Package(): Zipping all files ...");
var destination = Path.Combine(_destination, "option");
var dateMask = date.ToString(DateFormat.EightCharacter);
var files =
Directory.EnumerateFiles(destination, dateMask + "*.csv", SearchOption.AllDirectories)
.GroupBy(x => Directory.GetParent(x).FullName);
//Zip each file massively in parallel.
Parallel.ForEach(files, file =>
{
try
{
var outputFileName = file.Key + ".zip";
// Create and open a new ZIP file
var filesToCompress = Directory.GetFiles(file.Key, "*.csv", SearchOption.AllDirectories);
using (var zip = ZipFile.Open(outputFileName, ZipArchiveMode.Create))
{
Log.Trace("AlgoSeekOptionsConverter.Package(): Zipping " + outputFileName);
foreach (var fileToCompress in filesToCompress)
{
// Add the entry for each file
zip.CreateEntryFromFile(fileToCompress, Path.GetFileName(fileToCompress), CompressionLevel.Optimal);
}
}
try
{
Directory.Delete(file.Key, true);
}
catch (Exception err)
{
Log.Error("AlgoSeekOptionsConverter.Package(): Directory.Delete returned error: " + err.Message);
}
}
catch (Exception err)
{
Log.Error("File: {0} Err: {1} Source {2} Stack {3}", file, err.Message, err.Source, err.StackTrace);
}
});
}
/// <summary>
/// Cleans zip archives and source data folders before run
/// </summary>
public void Clean(DateTime date)
{
Log.Trace("AlgoSeekOptionsConverter.Clean(): cleaning all zip and csv files for {0} before start...", date.ToShortDateString());
var extensions = new HashSet<string> { ".zip", ".csv" };
var destination = Path.Combine(_destination, "option");
Directory.CreateDirectory(destination);
var dateMask = date.ToString(DateFormat.EightCharacter);
var files =
Directory.EnumerateFiles(destination, dateMask + "_" + "*.*", SearchOption.AllDirectories)
.Where(x => extensions.Contains(Path.GetExtension(x)))
.ToList();
Log.Trace("AlgoSeekOptionsConverter.Clean(): found {0} files..", files.Count);
//Clean each file massively in parallel.
Parallel.ForEach(files, parallelOptionsZipping, file =>
{
try
{
File.Delete(file);
}
catch (Exception err)
{
Log.Error("AlgoSeekOptionsConverter.Clean(): File.Delete returned error: " + err.Message);
}
});
}
/// <summary>
/// Decompress huge AlgoSeek's opra bz2 files and returns the outcome status.
/// </summary>
/// <param name="compressedRawDatafile">Fileinfo of the compressed orpa file.</param>
/// <param name="rawDatafile">Fileinfo of the uncompressed output file.</param>
/// <returns>Boolean indicating if this the process was successful.</returns>
/// <remarks>Public static members of the SharpZipLib.BZip2 type are safe for multithreaded operations.
/// Source: https://documentation.help/SharpZip/ICSharpCode.SharpZipLib.BZip2.BZip2.html
/// </remarks>>
private static bool DecompressOpraFile(FileInfo compressedRawDatafile, FileInfo rawDatafile)
{
var outcome = false;
using (FileStream fileToDecompressAsStream = compressedRawDatafile.OpenRead())
using (FileStream decompressedStream = File.Create(rawDatafile.FullName))
{
try
{
BZip2.Decompress(fileToDecompressAsStream, decompressedStream);
outcome = true;
}
catch (Exception ex)
{
Log.Error($"AlgoSeekOptionsConverter.DecompressOpraFile({compressedRawDatafile.Name}, {rawDatafile.Name}): SharpzipLib.BZip2.Decompress returned error: " + ex);
}
}
return outcome;
}
}
}
| |
// $ANTLR 3.1.2 abevformula.g 2011-01-22 19:07:24
// The variable 'variable' is assigned but its value is never used.
#pragma warning disable 219
// Unreachable code detected.
#pragma warning disable 162
using System.Collections.Generic;
using Antlr.Runtime;
using Stack = System.Collections.Generic.Stack<object>;
using List = System.Collections.IList;
using ArrayList = System.Collections.Generic.List<object>;
public partial class abevformulaLexer : Lexer
{
public const int EOF=-1;
public const int T__8=8;
public const int T__9=9;
public const int T__10=10;
public const int FUNC=4;
public const int STRING=5;
public const int WORD=6;
public const int WS=7;
// delegates
// delegators
public abevformulaLexer() {}
public abevformulaLexer( ICharStream input )
: this( input, new RecognizerSharedState() )
{
}
public abevformulaLexer( ICharStream input, RecognizerSharedState state )
: base( input, state )
{
}
public override string GrammarFileName { get { return "abevformula.g"; } }
// $ANTLR start "T__8"
private void mT__8()
{
try
{
int _type = T__8;
int _channel = DefaultTokenChannel;
// abevformula.g:7:8: ( ',' )
// abevformula.g:7:8: ','
{
Match(',');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "T__8"
// $ANTLR start "T__9"
private void mT__9()
{
try
{
int _type = T__9;
int _channel = DefaultTokenChannel;
// abevformula.g:8:8: ( '[' )
// abevformula.g:8:8: '['
{
Match('[');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "T__9"
// $ANTLR start "T__10"
private void mT__10()
{
try
{
int _type = T__10;
int _channel = DefaultTokenChannel;
// abevformula.g:9:9: ( ']' )
// abevformula.g:9:9: ']'
{
Match(']');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "T__10"
// $ANTLR start "WS"
private void mWS()
{
try
{
int _type = WS;
int _channel = DefaultTokenChannel;
// abevformula.g:33:6: ( ( '\\t' | ' ' ) )
// abevformula.g:33:6: ( '\\t' | ' ' )
{
if ( input.LA(1)=='\t'||input.LA(1)==' ' )
{
input.Consume();
}
else
{
MismatchedSetException mse = new MismatchedSetException(null,input);
Recover(mse);
throw mse;}
Skip();
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "WS"
// $ANTLR start "WORD"
private void mWORD()
{
try
{
int _type = WORD;
int _channel = DefaultTokenChannel;
// abevformula.g:34:8: ( (~ ( ' ' | '\\t' | '[' | ']' | '\"' | ',' ) )+ )
// abevformula.g:34:8: (~ ( ' ' | '\\t' | '[' | ']' | '\"' | ',' ) )+
{
// abevformula.g:34:8: (~ ( ' ' | '\\t' | '[' | ']' | '\"' | ',' ) )+
int cnt1=0;
for ( ; ; )
{
int alt1=2;
int LA1_0 = input.LA(1);
if ( ((LA1_0>='\u0000' && LA1_0<='\b')||(LA1_0>='\n' && LA1_0<='\u001F')||LA1_0=='!'||(LA1_0>='#' && LA1_0<='+')||(LA1_0>='-' && LA1_0<='Z')||LA1_0=='\\'||(LA1_0>='^' && LA1_0<='\uFFFF')) )
{
alt1=1;
}
switch ( alt1 )
{
case 1:
// abevformula.g:
{
input.Consume();
}
break;
default:
if ( cnt1 >= 1 )
goto loop1;
EarlyExitException eee1 = new EarlyExitException( 1, input );
throw eee1;
}
cnt1++;
}
loop1:
;
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "WORD"
// $ANTLR start "STRING"
private void mSTRING()
{
try
{
int _type = STRING;
int _channel = DefaultTokenChannel;
// abevformula.g:35:10: ( '\"' (~ '\"' )* '\"' )
// abevformula.g:35:10: '\"' (~ '\"' )* '\"'
{
Match('\"');
// abevformula.g:35:14: (~ '\"' )*
for ( ; ; )
{
int alt2=2;
int LA2_0 = input.LA(1);
if ( ((LA2_0>='\u0000' && LA2_0<='!')||(LA2_0>='#' && LA2_0<='\uFFFF')) )
{
alt2=1;
}
switch ( alt2 )
{
case 1:
// abevformula.g:
{
input.Consume();
}
break;
default:
goto loop2;
}
}
loop2:
;
Match('\"');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "STRING"
public override void mTokens()
{
// abevformula.g:1:10: ( T__8 | T__9 | T__10 | WS | WORD | STRING )
int alt3=6;
int LA3_0 = input.LA(1);
if ( (LA3_0==',') )
{
alt3=1;
}
else if ( (LA3_0=='[') )
{
alt3=2;
}
else if ( (LA3_0==']') )
{
alt3=3;
}
else if ( (LA3_0=='\t'||LA3_0==' ') )
{
alt3=4;
}
else if ( ((LA3_0>='\u0000' && LA3_0<='\b')||(LA3_0>='\n' && LA3_0<='\u001F')||LA3_0=='!'||(LA3_0>='#' && LA3_0<='+')||(LA3_0>='-' && LA3_0<='Z')||LA3_0=='\\'||(LA3_0>='^' && LA3_0<='\uFFFF')) )
{
alt3=5;
}
else if ( (LA3_0=='\"') )
{
alt3=6;
}
else
{
NoViableAltException nvae = new NoViableAltException("", 3, 0, input);
throw nvae;
}
switch ( alt3 )
{
case 1:
// abevformula.g:1:10: T__8
{
mT__8();
}
break;
case 2:
// abevformula.g:1:15: T__9
{
mT__9();
}
break;
case 3:
// abevformula.g:1:20: T__10
{
mT__10();
}
break;
case 4:
// abevformula.g:1:26: WS
{
mWS();
}
break;
case 5:
// abevformula.g:1:29: WORD
{
mWORD();
}
break;
case 6:
// abevformula.g:1:34: STRING
{
mSTRING();
}
break;
}
}
#region DFA
protected override void InitDFAs()
{
base.InitDFAs();
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Serialization;
using VotingInfo.Database.Contracts;
using VotingInfo.Database.Contracts.Client;
//////////////////////////////////////////////////////////////
//Do not modify this file. Use a partial class to extend. //
//Override methods in the logic front class. //
//////////////////////////////////////////////////////////////
namespace VotingInfo.Database.Logic.Client
{
[Serializable]
public abstract partial class CandidatesLogicBase : LogicBase<CandidatesLogicBase>
{
//Put your code in a separate file. This is auto generated.
[XmlArray] public List<CandidatesContract> Results;
public CandidatesLogicBase()
{
Results = new List<CandidatesContract>();
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldCandidateId">Value for CandidateId</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldCandidateId
)
{
bool result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Client].[Candidates_Exists]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@CandidateId", fldCandidateId)
});
result = (bool)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldCandidateId">Value for CandidateId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldCandidateId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Client].[Candidates_Exists]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@CandidateId", fldCandidateId)
});
return (bool)cmd.ExecuteScalar();
}
}
/// <summary>
/// Run Candidates_Search, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldCandidateName">Value for CandidateName</param>
/// <param name="fldSourceUrl">Value for SourceUrl</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool Search(string fldCandidateName
, string fldSourceUrl
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Client].[Candidates_Search]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@CandidateName", fldCandidateName)
,
new SqlParameter("@SourceUrl", fldSourceUrl)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Candidates_Search, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldCandidateName">Value for CandidateName</param>
/// <param name="fldSourceUrl">Value for SourceUrl</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool Search(string fldCandidateName
, string fldSourceUrl
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Client].[Candidates_Search]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@CandidateName", fldCandidateName)
,
new SqlParameter("@SourceUrl", fldSourceUrl)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Candidates_SelectAll, and return results as a list of CandidatesRow.
/// </summary>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectAll()
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectAll]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Candidates_SelectAll, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectAll]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Candidates_SelectBy_CandidateId, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldCandidateId">Value for CandidateId</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectBy_CandidateId(int fldCandidateId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectBy_CandidateId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@CandidateId", fldCandidateId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Candidates_SelectBy_CandidateId, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldCandidateId">Value for CandidateId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectBy_CandidateId(int fldCandidateId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectBy_CandidateId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@CandidateId", fldCandidateId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Candidates_SelectBy_ContentInspectionId, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectBy_ContentInspectionId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Candidates_SelectBy_ContentInspectionId, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectBy_ContentInspectionId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Candidates_SelectBy_OrganizationId, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldOrganizationId">Value for OrganizationId</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectBy_OrganizationId(int fldOrganizationId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectBy_OrganizationId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@OrganizationId", fldOrganizationId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Candidates_SelectBy_OrganizationId, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldOrganizationId">Value for OrganizationId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectBy_OrganizationId(int fldOrganizationId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectBy_OrganizationId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@OrganizationId", fldOrganizationId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Candidates_SelectBy_ProposedByUserId, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldProposedByUserId">Value for ProposedByUserId</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectBy_ProposedByUserId(int fldProposedByUserId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectBy_ProposedByUserId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ProposedByUserId", fldProposedByUserId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Candidates_SelectBy_ProposedByUserId, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldProposedByUserId">Value for ProposedByUserId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectBy_ProposedByUserId(int fldProposedByUserId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectBy_ProposedByUserId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ProposedByUserId", fldProposedByUserId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Candidates_SelectBy_ConfirmedByUserId, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldConfirmedByUserId">Value for ConfirmedByUserId</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectBy_ConfirmedByUserId(int fldConfirmedByUserId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectBy_ConfirmedByUserId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ConfirmedByUserId", fldConfirmedByUserId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Candidates_SelectBy_ConfirmedByUserId, and return results as a list of CandidatesRow.
/// </summary>
/// <param name="fldConfirmedByUserId">Value for ConfirmedByUserId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of CandidatesRow.</returns>
public virtual bool SelectBy_ConfirmedByUserId(int fldConfirmedByUserId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Client].[Candidates_SelectBy_ConfirmedByUserId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ConfirmedByUserId", fldConfirmedByUserId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Read all items into this collection
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadAll(SqlDataReader reader)
{
var canRead = ReadOne(reader);
var result = canRead;
while (canRead) canRead = ReadOne(reader);
return result;
}
/// <summary>
/// Read one item into Results
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadOne(SqlDataReader reader)
{
if (reader.Read())
{
Results.Add(
new CandidatesContract
{
CandidateId = reader.GetInt32(0),
ContentInspectionId = reader.GetInt32(1),
CandidateName = reader.GetString(2),
OrganizationId = reader.GetInt32(3),
IsArchived = reader.GetBoolean(4),
IsBeingProposed = reader.GetBoolean(5),
ProposedByUserId = reader.GetInt32(6),
ConfirmedByUserId = reader.GetInt32(7),
FalseInfoCount = reader.GetInt32(8),
TrueInfoCount = reader.GetInt32(9),
AdminInpsected = reader.GetBoolean(10),
DateLastChecked = reader.GetDateTime(11),
SourceUrl = reader.GetString(12),
});
return true;
}
return false;
}
}
}
| |
//
// Reflect.cs: Creates Element classes from an instance
//
// Author:
// Miguel de Icaza (miguel@gnome.org)
//
// Copyright 2010, Novell, Inc.
//
// Code licensed under the MIT X11 license
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Drawing;
#if XAMCORE_2_0
using UIKit;
using Foundation;
using NSAction = global::System.Action;
#else
using MonoTouch.UIKit;
using MonoTouch.Foundation;
#endif
namespace MonoTouch.Dialog
{
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class EntryAttribute : Attribute {
public EntryAttribute () : this (null) { }
public EntryAttribute (string placeholder)
{
Placeholder = placeholder;
}
public string Placeholder;
public UIKeyboardType KeyboardType;
public UITextAutocorrectionType AutocorrectionType;
public UITextAutocapitalizationType AutocapitalizationType;
public UITextFieldViewMode ClearButtonMode;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class DateAttribute : Attribute { }
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class TimeAttribute : Attribute { }
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class CheckboxAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class MultilineAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class HtmlAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class SkipAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class PasswordAttribute : EntryAttribute {
public PasswordAttribute (string placeholder) : base (placeholder) {}
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class AlignmentAttribute : Attribute {
public AlignmentAttribute (UITextAlignment alignment) {
Alignment = alignment;
}
public UITextAlignment Alignment;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class RadioSelectionAttribute : Attribute {
public string Target;
public RadioSelectionAttribute (string target)
{
Target = target;
}
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class OnTapAttribute : Attribute {
public OnTapAttribute (string method)
{
Method = method;
}
public string Method;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class CaptionAttribute : Attribute {
public CaptionAttribute (string caption)
{
Caption = caption;
}
public string Caption;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class SectionAttribute : Attribute {
public SectionAttribute () {}
public SectionAttribute (string caption)
{
Caption = caption;
}
public SectionAttribute (string caption, string footer)
{
Caption = caption;
Footer = footer;
}
public string Caption, Footer;
}
public class RangeAttribute : Attribute {
public RangeAttribute (float low, float high)
{
Low = low;
High = high;
}
public float Low, High;
public bool ShowCaption;
}
public class BindingContext : IDisposable {
public RootElement Root;
Dictionary<Element,MemberAndInstance> mappings;
class MemberAndInstance {
public MemberAndInstance (MemberInfo mi, object o)
{
Member = mi;
Obj = o;
}
public MemberInfo Member;
public object Obj;
}
static object GetValue (MemberInfo mi, object o)
{
var fi = mi as FieldInfo;
if (fi != null)
return fi.GetValue (o);
var pi = mi as PropertyInfo;
var getMethod = pi.GetGetMethod ();
return getMethod.Invoke (o, new object [0]);
}
static void SetValue (MemberInfo mi, object o, object val)
{
var fi = mi as FieldInfo;
if (fi != null){
fi.SetValue (o, val);
return;
}
var pi = mi as PropertyInfo;
var setMethod = pi.GetSetMethod ();
setMethod.Invoke (o, new object [] { val });
}
static string MakeCaption (string name)
{
var sb = new StringBuilder (name.Length);
bool nextUp = true;
foreach (char c in name){
if (nextUp){
sb.Append (Char.ToUpper (c));
nextUp = false;
} else {
if (c == '_'){
sb.Append (' ');
continue;
}
if (Char.IsUpper (c))
sb.Append (' ');
sb.Append (c);
}
}
return sb.ToString ();
}
// Returns the type for fields and properties and null for everything else
static Type GetTypeForMember (MemberInfo mi)
{
if (mi is FieldInfo)
return ((FieldInfo) mi).FieldType;
else if (mi is PropertyInfo)
return ((PropertyInfo) mi).PropertyType;
return null;
}
public BindingContext (object callbacks, object o, string title)
{
if (o == null)
throw new ArgumentNullException ("o");
mappings = new Dictionary<Element,MemberAndInstance> ();
Root = new RootElement (title);
Populate (callbacks, o, Root);
}
void Populate (object callbacks, object o, RootElement root)
{
MemberInfo last_radio_index = null;
var members = o.GetType ().GetMembers (BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance);
Section section = null;
foreach (var mi in members){
Type mType = GetTypeForMember (mi);
if (mType == null)
continue;
string caption = null;
object [] attrs = mi.GetCustomAttributes (false);
bool skip = false;
foreach (var attr in attrs){
if (attr is SkipAttribute || attr is System.Runtime.CompilerServices.CompilerGeneratedAttribute)
skip = true;
else if (attr is CaptionAttribute)
caption = ((CaptionAttribute) attr).Caption;
else if (attr is SectionAttribute){
if (section != null)
root.Add (section);
var sa = attr as SectionAttribute;
section = new Section (sa.Caption, sa.Footer);
}
}
if (skip)
continue;
if (caption == null)
caption = MakeCaption (mi.Name);
if (section == null)
section = new Section ();
Element element = null;
if (mType == typeof (string)){
PasswordAttribute pa = null;
AlignmentAttribute align = null;
EntryAttribute ea = null;
object html = null;
NSAction invoke = null;
bool multi = false;
foreach (object attr in attrs){
if (attr is PasswordAttribute)
pa = attr as PasswordAttribute;
else if (attr is EntryAttribute)
ea = attr as EntryAttribute;
else if (attr is MultilineAttribute)
multi = true;
else if (attr is HtmlAttribute)
html = attr;
else if (attr is AlignmentAttribute)
align = attr as AlignmentAttribute;
if (attr is OnTapAttribute){
string mname = ((OnTapAttribute) attr).Method;
if (callbacks == null){
throw new Exception ("Your class contains [OnTap] attributes, but you passed a null object for `context' in the constructor");
}
var method = callbacks.GetType ().GetMethod (mname);
if (method == null)
throw new Exception ("Did not find method " + mname);
invoke = delegate {
method.Invoke (method.IsStatic ? null : callbacks, new object [0]);
};
}
}
string value = (string) GetValue (mi, o);
if (pa != null)
element = new EntryElement (caption, pa.Placeholder, value, true);
else if (ea != null)
element = new EntryElement (caption, ea.Placeholder, value) { KeyboardType = ea.KeyboardType, AutocapitalizationType = ea.AutocapitalizationType, AutocorrectionType = ea.AutocorrectionType, ClearButtonMode = ea.ClearButtonMode };
else if (multi)
element = new MultilineElement (caption, value);
else if (html != null)
element = new HtmlElement (caption, value);
else {
var selement = new StringElement (caption, value);
element = selement;
if (align != null)
selement.Alignment = align.Alignment;
}
if (invoke != null)
((StringElement) element).Tapped += invoke;
} else if (mType == typeof (float)){
var floatElement = new FloatElement (null, null, (float) GetValue (mi, o));
floatElement.Caption = caption;
element = floatElement;
foreach (object attr in attrs){
if (attr is RangeAttribute){
var ra = attr as RangeAttribute;
floatElement.MinValue = ra.Low;
floatElement.MaxValue = ra.High;
floatElement.ShowCaption = ra.ShowCaption;
}
}
} else if (mType == typeof (bool)){
bool checkbox = false;
foreach (object attr in attrs){
if (attr is CheckboxAttribute)
checkbox = true;
}
if (checkbox)
element = new CheckboxElement (caption, (bool) GetValue (mi, o));
else
element = new BooleanElement (caption, (bool) GetValue (mi, o));
} else if (mType == typeof (DateTime)){
var dateTime = (DateTime) GetValue (mi, o);
bool asDate = false, asTime = false;
foreach (object attr in attrs){
if (attr is DateAttribute)
asDate = true;
else if (attr is TimeAttribute)
asTime = true;
}
if (asDate)
element = new DateElement (caption, dateTime);
else if (asTime)
element = new TimeElement (caption, dateTime);
else
element = new DateTimeElement (caption, dateTime);
} else if (mType.IsEnum){
var csection = new Section ();
ulong evalue = Convert.ToUInt64 (GetValue (mi, o), null);
int idx = 0;
int selected = 0;
foreach (var fi in mType.GetFields (BindingFlags.Public | BindingFlags.Static)){
ulong v = Convert.ToUInt64 (GetValue (fi, null));
if (v == evalue)
selected = idx;
CaptionAttribute ca = Attribute.GetCustomAttribute(fi, typeof(CaptionAttribute)) as CaptionAttribute;
csection.Add (new RadioElement (ca != null ? ca.Caption : MakeCaption (fi.Name)));
idx++;
}
element = new RootElement (caption, new RadioGroup (null, selected)) { csection };
} else if (mType == typeof (UIImage)){
element = new ImageElement ((UIImage) GetValue (mi, o));
} else if (typeof (System.Collections.IEnumerable).IsAssignableFrom (mType)){
var csection = new Section ();
int count = 0;
if (last_radio_index == null)
throw new Exception ("IEnumerable found, but no previous int found");
foreach (var e in (IEnumerable) GetValue (mi, o)){
csection.Add (new RadioElement (e.ToString ()));
count++;
}
int selected = (int) GetValue (last_radio_index, o);
if (selected >= count || selected < 0)
selected = 0;
element = new RootElement (caption, new MemberRadioGroup (null, selected, last_radio_index)) { csection };
last_radio_index = null;
} else if (typeof (int) == mType){
foreach (object attr in attrs){
if (attr is RadioSelectionAttribute){
last_radio_index = mi;
break;
}
}
} else {
var nested = GetValue (mi, o);
if (nested != null){
var newRoot = new RootElement (caption);
Populate (callbacks, nested, newRoot);
element = newRoot;
}
}
if (element == null)
continue;
section.Add (element);
mappings [element] = new MemberAndInstance (mi, o);
}
root.Add (section);
}
class MemberRadioGroup : RadioGroup {
public MemberInfo mi;
public MemberRadioGroup (string key, int selected, MemberInfo mi) : base (key, selected)
{
this.mi = mi;
}
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing){
foreach (var element in mappings.Keys){
element.Dispose ();
}
mappings = null;
}
}
public void Fetch ()
{
foreach (var dk in mappings){
Element element = dk.Key;
MemberInfo mi = dk.Value.Member;
object obj = dk.Value.Obj;
if (element is DateTimeElement)
SetValue (mi, obj, ((DateTimeElement) element).DateValue);
else if (element is FloatElement)
SetValue (mi, obj, ((FloatElement) element).Value);
else if (element is BooleanElement)
SetValue (mi, obj, ((BooleanElement) element).Value);
else if (element is CheckboxElement)
SetValue (mi, obj, ((CheckboxElement) element).Value);
else if (element is EntryElement){
var entry = (EntryElement) element;
entry.FetchValue ();
SetValue (mi, obj, entry.Value);
} else if (element is ImageElement)
SetValue (mi, obj, ((ImageElement) element).Value);
else if (element is RootElement){
var re = element as RootElement;
if (re.group as MemberRadioGroup != null){
var group = re.group as MemberRadioGroup;
SetValue (group.mi, obj, re.RadioSelected);
} else if (re.group as RadioGroup != null){
var mType = GetTypeForMember (mi);
var fi = mType.GetFields (BindingFlags.Public | BindingFlags.Static) [re.RadioSelected];
SetValue (mi, obj, fi.GetValue (null));
}
}
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using FuelSDKIntegration.Structures;
//-----------------------------------------------------------------
/*
IGNITE EVENTS
*/
//-----------------------------------------------------------------
public partial class FuelIgnite : MonoBehaviour
{
void onFuelSDKIgniteSampleEvents(Dictionary<string, object> data)
{
object eventsObject;
bool keyExists = data.TryGetValue("events", out eventsObject);
if (eventsObject == null || keyExists == false) {
FuelSDKCommon.Log (FuelSDKCommon.LogLevel.ERROR, "missing expected event list");
return;
}
List<object> sampleEventList = null;
try{
sampleEventList = eventsObject as List<object>;
if (sampleEventList == null) {
FuelSDKCommon.Log (FuelSDKCommon.LogLevel.ERROR, "invalid event list data type: " + eventsObject.GetType ().Name);
return;
}
}catch(Exception e){
FuelSDKCommon.Log (FuelSDKCommon.LogLevel.ERROR, "invalid event list data type: " + eventsObject.GetType ().Name + " error message : " + e.Message);
return;
}
foreach (object eventObj in sampleEventList) {
IgniteEvent igniteSampleEvent = new IgniteEvent ();
igniteSampleEvent.Create (eventObj as Dictionary<string,object>);
mIgniteSampleEventList.Add (igniteSampleEvent);
}
mIgniteSampleEventsRecieved = true;
}
void onFuelSDKIgniteEvents(Dictionary<string, object> data)
{
FuelSDKCommon.Log (FuelSDKCommon.LogLevel.DEBUG, "FuelIgnite : onFuelSDKIgniteEvents");
mIgniteEventsDictionary = new Dictionary<string, IgniteEvent> ();
object eventsObject;
bool keyExists = data.TryGetValue("events", out eventsObject);
if (eventsObject == null || keyExists == false) {
FuelSDKCommon.Log (FuelSDKCommon.LogLevel.ERROR, "missing expected event list");
return;
}
List<object> eventList = null;
try{
eventList = eventsObject as List<object>;
if (eventList == null) {
FuelSDKCommon.Log (FuelSDKCommon.LogLevel.ERROR, "invalid event list data type: " + eventsObject.GetType ().Name);
return;
}
}catch(Exception e){
FuelSDKCommon.Log (FuelSDKCommon.LogLevel.ERROR, "invalid event list data type: " + eventsObject.GetType ().Name + " error message : " + e.Message);
return;
}
foreach (object eventObj in eventList) {
IgniteEvent igniteEvent = new IgniteEvent ();
igniteEvent.Create (eventObj as Dictionary<string,object>);
mIgniteEventsDictionary [igniteEvent.Id] = igniteEvent;
}
mIgniteEventsRecieved = true;
}
Dictionary<string,object> progressDictionary = new Dictionary<string, object>();
public void ResetProgressDictionary()
{
progressDictionary = new Dictionary<string, object>();
}
public void SetRingsCollectedProgress(int rings)
{
Dictionary<string,int> ringsCollectedDict = new Dictionary<string,int>();
ringsCollectedDict ["value"] = rings;
progressDictionary["RingsCollected"] = ringsCollectedDict;
}
public void SetRedRingsCollectedProgress(int redRings)
{
Dictionary<string,int> redRingsCollectedDict = new Dictionary<string,int>();
redRingsCollectedDict ["value"] = redRings;
progressDictionary["RedRingsCollected"] = redRingsCollectedDict;
}
public void SendProgress()
{
ResetProgressDictionary ();
//Rings Collected
SetRingsCollectedProgress (100);
//Red Rings Collected
SetRedRingsCollectedProgress (100);
//Distance Run
Dictionary<string,int> distanceRunDict = new Dictionary<string,int>();
distanceRunDict ["value"] = 500;
progressDictionary["DistanceRunDict"] = distanceRunDict;
//Score
Dictionary<string,int> scoreDict = new Dictionary<string,int>();
scoreDict ["value"] = 500;
progressDictionary["ScoreDict"] = scoreDict;
//Destroy Enemies
Dictionary<string,int> destroyEnemiesDict = new Dictionary<string,int>();
destroyEnemiesDict ["value"] = 500;
progressDictionary["DestroyEnemiesDict"] = destroyEnemiesDict;
//Destroy Crabs
Dictionary<string,int> destroyCrabsDict = new Dictionary<string,int>();
destroyCrabsDict ["value"] = 25;
progressDictionary["DestroyCrabsDict"] = destroyCrabsDict;
//Destroy Motor Bugs
Dictionary<string,int> destroyMotorbugsDict = new Dictionary<string,int>();
destroyMotorbugsDict ["value"] = 25;
progressDictionary["DestroyMotorbugsDict"] = destroyMotorbugsDict;
//Lane Changes
Dictionary<string,int> laneChangesDict = new Dictionary<string,int>();
laneChangesDict ["value"] = 25;
progressDictionary["LaneChangesDict"] = laneChangesDict;
//Dashes Used
Dictionary<string,int> dashesUsedDict = new Dictionary<string,int>();
dashesUsedDict ["value"] = 9;
progressDictionary["DashesUsedDict"] = dashesUsedDict;
//Jump Obstacle
Dictionary<string,int> jumpObstacleDict = new Dictionary<string,int>();
jumpObstacleDict ["value"] = 9;
progressDictionary["JumpObstacleDict"] = jumpObstacleDict;
//Jump Enemy
Dictionary<string,int> jumpEnemyDict = new Dictionary<string,int>();
jumpEnemyDict ["value"] = 9;
progressDictionary["JumpEnemyDict"] = jumpEnemyDict;
//Roll Under
Dictionary<string,int> rollUnderDict = new Dictionary<string,int>();
rollUnderDict ["value"] = 9;
progressDictionary["RollUnderDict"] = rollUnderDict;
//Roll Distance
Dictionary<string,int> rollDistanceDict = new Dictionary<string,int>();
rollDistanceDict ["value"] = 9;
progressDictionary["RollDistanceDict"] = rollDistanceDict;
List<object> ruleFilterTags = new List<object>();
FuelSDK.SendProgress( progressDictionary, ruleFilterTags );
}
private List<object> GetEventFilterTags () {
List<object> eventFilterTags = new List<object>();
//add character unlocks
#if REDUX_TESTBED
//test filter A
string characterCohort = "unlocked_character_sonic";
eventFilterTags.Add (characterCohort);
characterCohort = "unlocked_character_tails";
eventFilterTags.Add (characterCohort);
characterCohort = "locked_character_knuckles";
eventFilterTags.Add (characterCohort);
characterCohort = "locked_character_amy";
eventFilterTags.Add (characterCohort);
characterCohort = "locked_character_shadow";
eventFilterTags.Add (characterCohort);
characterCohort = "locked_character_blaze";
eventFilterTags.Add (characterCohort);
#else
int characterTypeLength = Utils.GetEnumCount<Characters.Type>();
for (int c = 0; c < characterTypeLength; c++) {
if (Characters.CharacterUnlocked ((Characters.Type)c)) {
string characterUnlockCohort = "unlocked_" + Characters.IDStrings [c];
eventFilterTags.Add (characterUnlockCohort);
} else {
string characterLockCohort = "locked_" + Characters.IDStrings [c];
eventFilterTags.Add (characterLockCohort);
}
}
#endif
return eventFilterTags;
}
private List<object> GetSampleEventFilterTags () {
List<object> eventFilterTags = new List<object>();
//example: for any sequence 1-unlocked 2-locked add another sequence 2-unlocked 3-locked (if 3 is locked)
//this will query for the next locked event
#if REDUX_TESTBED
//test filter A
string characterCohort = "unlocked_character_sonic";
eventFilterTags.Add (characterCohort);
characterCohort = "unlocked_character_tails";
eventFilterTags.Add (characterCohort);
characterCohort = "locked_character_knuckles";
eventFilterTags.Add (characterCohort);
characterCohort = "locked_character_amy";
eventFilterTags.Add (characterCohort);
characterCohort = "locked_character_shadow";
eventFilterTags.Add (characterCohort);
characterCohort = "locked_character_blaze";
eventFilterTags.Add (characterCohort);
characterCohort = "unlocked_character_knuckles";
eventFilterTags.Add (characterCohort);
#else
int characterCount = Utils.GetEnumCount<Characters.Type>();
bool[] character_unlockState = new bool[characterCount];
for (int c = 0; c < characterCount; c++) {
if (Characters.CharacterUnlocked ((Characters.Type)c)) {
character_unlockState [c] = true;
} else {
character_unlockState [c] = false;
}
}
//add initial character unlocks
for (int c = 0; c < characterCount; c++) {
if (character_unlockState[c] == true) {
string characterUnlockCohort = "unlocked_" + Characters.IDStrings [c];
eventFilterTags.Add (characterUnlockCohort);
} else {
string characterLockCohort = "locked_" + Characters.IDStrings [c];
eventFilterTags.Add (characterLockCohort);
}
}
//add additional character locks
for (int c = 0; c < characterCount - 3; c++) {
if (character_unlockState[c] == true && character_unlockState[c+1] == false) {
for (int k = c; k < characterCount - 3; k++) {
if (character_unlockState [c + 2] == false) {
//item is locked see if there is a
} else {
}
}
//string characterUnlockCohort = "unlocked_" + Characters.IDStrings [c+1];
//eventFilterTags.Add (characterUnlockCohort);
}
}
#endif
return eventFilterTags;
}
private void FactorInSampleEvents()
{
Debug.Log ("REDUX LOG - FactorInSampleEvents");
for (int e = 0; e < mIgniteSampleEventList.Count; e++) {
IgniteEvent igniteEvent = mIgniteEventsDictionary[mIgniteSampleEventList[e].Id];
if (igniteEvent == null) {
//sample event is not in list so add it
IgniteEvent igniteSampleEvent = mIgniteSampleEventList[e];
Debug.Log ("REDUX LOG - igniteSampleEvent.EventLocked = true");
igniteSampleEvent.EventLocked = true;
mIgniteEventsDictionary.Add (igniteSampleEvent.Id, igniteSampleEvent);
break;//just add 1 sample event? yes for now
}
}
}
private void CreateSortedEventList()
{
//Find first Character event
mIgniteEventList = new List<IgniteEvent> ();
foreach(IgniteEvent e in mIgniteEventsDictionary.Values){
if(e.IsCharacterEvent == true) {
mIgniteEventList.Add( e );
}
}
foreach(IgniteEvent e in mIgniteEventsDictionary.Values){
if(e.IsCharacterEvent == false && e.Active == true) {
mIgniteEventList.Add( e );
}
}
foreach(IgniteEvent e in mIgniteEventsDictionary.Values){
if(e.IsCharacterEvent == false && e.Active == true) {
mIgniteEventList.Add( e );
}
}
foreach(IgniteEvent e in mIgniteEventsDictionary.Values){
if(e.IsCharacterEvent == false && e.Ended == true) {
mIgniteEventList.Add( e );
}
}
foreach(IgniteEvent e in mIgniteEventsDictionary.Values){
if(e.IsCharacterEvent == false && e.ComingSoon == true) {
mIgniteEventList.Add( e );
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DG.Tweening;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Proyecto26;
using RSG;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using Object = UnityEngine.Object;
public class LevelManager
{
public const string CoverThumbnailFilename = ".cover";
public readonly LevelInstallProgressEvent OnLevelInstallProgress = new LevelInstallProgressEvent();
public readonly LevelLoadProgressEvent OnLevelLoadProgress = new LevelLoadProgressEvent();
public readonly LevelEvent OnLevelMetaUpdated = new LevelEvent();
public readonly Dictionary<string, Level> LoadedLocalLevels = new Dictionary<string, Level>();
private readonly HashSet<string> loadedPaths = new HashSet<string>();
public async UniTask<List<string>> CopyBuiltInLevelsToDownloads(List<string> levelIds)
{
var packagePaths = new List<string>();
// Install all missing training levels that are built in
foreach (var uid in levelIds)
{
var packagePath = Application.streamingAssetsPath + "/Levels/" + uid + ".cytoidlevel";
if (Application.platform == RuntimePlatform.IPhonePlayer) packagePath = "file://" + packagePath;
// Copy the file from StreamingAssets to temp directory
using (var request = UnityWebRequest.Get(packagePath))
{
request.SetRequestHeader("User-Agent", $"CytoidClient/{Context.VersionName}");
await request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError(request.error);
Debug.LogError($"Failed to copy level {uid} from StreamingAssets");
continue;
}
var bytes = request.downloadHandler.data;
var targetDirectory = $"{Application.temporaryCachePath}/Downloads";
var targetFile = $"{targetDirectory}/{uid}.cytoidlevel";
try
{
Directory.CreateDirectory(targetDirectory);
File.WriteAllBytes(targetFile, bytes);
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Failed to copy level {uid} from StreamingAssets to {targetFile}");
continue;
}
packagePaths.Add(targetFile);
}
}
return packagePaths;
}
public async UniTask<List<Level>> LoadOrInstallBuiltInLevels()
{
var levels = new List<Level>();
foreach (var levelId in BuiltInData.BuiltInLevelIds)
{
levels.Add(await LoadOrInstallBuiltInLevel(levelId, LevelType.BuiltIn));
}
return levels;
}
public async UniTask<List<string>> InstallUserCommunityLevels()
{
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
var files = new List<string>();
var inboxPath = Context.UserDataPath + "/Inbox/";
if (Directory.Exists(inboxPath))
{
files.AddRange(Directory.GetFiles(inboxPath, "*.cytoidlevel"));
files.AddRange(Directory.GetFiles(inboxPath, "*.cytoidlevel.zip"));
}
if (Directory.Exists(Context.iOSTemporaryInboxPath))
{
files.AddRange(Directory.GetFiles(Context.iOSTemporaryInboxPath, "*.cytoidlevel"));
files.AddRange(Directory.GetFiles(Context.iOSTemporaryInboxPath, "*.cytoidlevel.zip"));
}
foreach (var file in files)
{
if (file == null) continue;
var toPath = Context.UserDataPath + "/" + Path.GetFileName(file);
try
{
if (File.Exists(toPath))
{
File.Delete(toPath);
}
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Failed to delete .cytoidlevel file at {toPath}");
continue;
}
try
{
File.Move(file, toPath);
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Failed to move .cytoidlevel file from {file} to {toPath}");
}
}
}
var levelFiles = new List<string>();
try
{
levelFiles.AddRange(Directory.GetFiles(Context.UserDataPath, "*.cytoidlevel"));
levelFiles.AddRange(Directory.GetFiles(Context.UserDataPath, "*.cytoidlevel.zip"));
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError("Cannot read from data path");
return new List<string>();
}
return await InstallLevels(levelFiles, LevelType.User);
}
public async UniTask<List<string>> InstallLevels(List<string> packagePaths, LevelType type)
{
var loadedLevelJsonFiles = new List<string>();
var index = 1;
foreach (var levelFile in packagePaths)
{
var fileName = Path.GetFileNameWithoutExtension(levelFile);
OnLevelInstallProgress.Invoke(fileName, index, packagePaths.Count);
var destFolder = $"{type.GetDataPath()}/{fileName}";
if (await UnpackLevelPackage(levelFile, destFolder))
{
loadedLevelJsonFiles.Add(destFolder + "/level.json");
Debug.Log($"Installed {index}/{packagePaths.Count}: {levelFile}");
}
else
{
Debug.LogWarning($"Could not install {index}/{packagePaths.Count}: {levelFile}");
}
try
{
File.Delete(levelFile);
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Could not delete level file at {levelFile}");
}
index++;
}
return loadedLevelJsonFiles;
}
public void DeleteLocalLevel(string id)
{
if (!LoadedLocalLevels.ContainsKey(id))
{
Debug.LogWarning($"Warning: Could not find level {id}");
return;
}
var level = LoadedLocalLevels[id];
level.Record.AddedDate = DateTimeOffset.MinValue;
level.SaveRecord();
Directory.Delete(Path.GetDirectoryName(level.Path) ?? throw new InvalidOperationException(), true);
LoadedLocalLevels.Remove(level.Id);
loadedPaths.Remove(level.Path);
}
public Promise<LevelMeta> FetchLevelMeta(string levelId, bool updateLocal = false)
{
return new Promise<LevelMeta>((resolve, reject) =>
{
RestClient.Get<OnlineLevel>(new RequestHelper
{
Uri = $"{Context.ApiUrl}/levels/{levelId}",
Headers = Context.OnlinePlayer.GetRequestHeaders()
}).Then(it =>
{
var remoteMeta = it.GenerateLevelMeta();
if (updateLocal && LoadedLocalLevels.ContainsKey(levelId))
{
var localLevel = LoadedLocalLevels[levelId];
localLevel.OnlineLevel = it;
if (UpdateLevelMeta(localLevel, remoteMeta))
{
Debug.Log($"Level meta updated for {localLevel.Id}");
OnLevelMetaUpdated.Invoke(localLevel);
}
}
resolve(remoteMeta);
}).CatchRequestError(error =>
{
if (!error.IsNetworkError && (error.StatusCode == 404 || error.StatusCode == 403))
{
if (error.StatusCode == 404)
{
Debug.Log($"Level {levelId} does not exist on the remote server");
}
else
{
Debug.Log($"Level {levelId} cannot be accessed on the remote server");
}
}
else
{
Debug.LogError(error);
}
reject(error);
});
});
}
public async UniTask<bool> UnpackLevelPackage(string packagePath, string destFolder)
{
const int bufferSize = 256 * 1024;
ZipStrings.CodePage = Encoding.UTF8.CodePage;
try
{
Directory.CreateDirectory(destFolder);
}
catch (Exception error)
{
Debug.LogError("Failed to create level folder.");
Debug.LogError(error);
return false;
}
string fileName;
try
{
fileName = Path.GetFileName(packagePath);
}
catch (Exception error)
{
Debug.LogError($"Failed to get filename for path {packagePath}.");
Debug.LogError(error);
return false;
}
byte[] zipFileData;
try
{
zipFileData = File.ReadAllBytes(packagePath);
}
catch (Exception error)
{
Debug.LogError($"Failed to read bytes from {packagePath}.");
Debug.LogError(error);
return false;
}
using (var fileStream = new MemoryStream())
{
ZipFile zipFile;
try
{
fileStream.Write(zipFileData, 0, zipFileData.Length);
fileStream.Flush();
fileStream.Seek(0, SeekOrigin.Begin);
zipFile = new ZipFile(fileStream);
foreach (ZipEntry entry in zipFile)
{
// Loop through all files to ensure the zip is valid
}
}
catch (Exception e)
{
Debug.LogError($"Cannot read {fileName}. Is it a valid .zip archive file?");
Debug.LogError(e.Message);
return false;
}
foreach (ZipEntry entry in zipFile)
{
var targetFile = Path.Combine(destFolder, entry.Name);
if (entry.Name.Contains("__MACOSX")) continue; // Fucking macOS...
Debug.Log("Extracting " + entry.Name + "...");
try
{
var outputFile = File.Create(targetFile);
using (outputFile)
{
if (entry.Size <= 0) continue;
var zippedStream = zipFile.GetInputStream(entry);
var dataBuffer = new byte[bufferSize];
int readBytes;
while ((readBytes = await zippedStream.ReadAsync(dataBuffer, 0, bufferSize)) > 0)
{
outputFile.Write(dataBuffer, 0, readBytes);
outputFile.Flush();
}
}
}
catch (Exception e)
{
Debug.LogError($"Cannot extract {entry.Name} from {fileName}. Is it a valid .zip archive file?");
Debug.LogError(e.Message);
return false;
}
}
var info = new FileInfo(destFolder);
var path = info.FullName + Path.DirectorySeparatorChar;
Debug.Log($"Removing {path}");
loadedPaths.Remove(path);
var coverPath = path + CoverThumbnailFilename;
Debug.Log($"Search {coverPath}");
if (File.Exists(coverPath))
{
try
{
File.Delete(coverPath);
File.Delete(coverPath + ".288.180");
File.Delete(coverPath + ".432.270");
File.Delete(coverPath + ".576.360"); // TODO: Unhardcode this (how?)
}
catch (Exception e)
{
Debug.LogError($"Failed to delete cover thumbnail: {coverPath}");
Debug.LogError(e);
}
}
}
return true;
}
public async UniTask<List<Level>> LoadLevelsOfType(LevelType type)
{
try
{
Directory.CreateDirectory(type.GetDataPath());
}
catch (Exception error)
{
Debug.LogError("Failed to create data folder.");
Debug.LogError(error);
return new List<Level>();
}
var jsonPaths = Directory.EnumerateDirectories(type.GetDataPath())
.SelectMany(it => Directory.EnumerateFiles(it, "level.json"))
.ToList();
Debug.Log($"Found {jsonPaths.Count} levels with type {type}");
return await LoadFromMetadataFiles(type, jsonPaths);
}
public void UnloadLevelsOfType(LevelType type)
{
var removals = LoadedLocalLevels.RemoveAll(level => level.Type == type);
var removedPaths = removals.Select(it => it.Item2.Path).ToHashSet();
loadedPaths.RemoveWhere(it => removedPaths.Contains(it));
}
public void UnloadAllLevels()
{
LoadedLocalLevels.Clear();
loadedPaths.Clear();
Context.AssetMemory.DisposeTaggedCacheAssets(AssetTag.LocalLevelCoverThumbnail);
}
public async UniTask<Level> LoadOrInstallBuiltInLevel(string id, LevelType loadType, bool forceInstall = false)
{
async UniTask<Level> GetLevel()
{
var levels = await LoadFromMetadataFiles(loadType, new List<string>
{
$"{loadType.GetDataPath()}/{id}/level.json"
});
if (levels.Count > 0) return levels.First();
return LoadedLocalLevels.ContainsKey(id) ? LoadedLocalLevels[id] : null;
}
var level = forceInstall ? null : await GetLevel();
if (level == null)
{
var paths = await Context.LevelManager.CopyBuiltInLevelsToDownloads(new List<string> {id});
await Context.LevelManager.InstallLevels(paths, loadType);
level = await GetLevel();
}
return level;
}
public async UniTask<List<Level>> LoadFromMetadataFiles(LevelType type, List<string> jsonPaths, bool forceReload = false)
{
var lowMemory = false;
Application.lowMemory += OnLowMemory;
void OnLowMemory()
{
lowMemory = true;
}
var loadedCount = 0;
var tasks = new List<UniTask>();
var results = new List<Level>();
int index;
for (index = 0; index < jsonPaths.Count; index++)
{
var loadIndex = index;
async UniTask LoadLevel()
{
var timer = new BenchmarkTimer($"Level loader ({loadIndex + 1} / {jsonPaths.Count})") {Enabled = false};
var jsonPath = jsonPaths[loadIndex];
try
{
FileInfo info;
try
{
info = new FileInfo(jsonPath);
if (info.Directory == null)
{
throw new FileNotFoundException(info.ToString());
}
}
catch (Exception e)
{
Debug.LogWarning(e);
Debug.LogWarning($"{jsonPath} could not be read");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
return;
}
var path = info.Directory.FullName + Path.DirectorySeparatorChar;
if (!forceReload && loadedPaths.Contains(path))
{
Debug.LogWarning($"Level from {path} is already loaded");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
Debug.Log($"Loading {loadIndex + 1}/{jsonPaths.Count} from {path}");
if (!File.Exists(jsonPath))
{
Debug.LogWarning($"level.json not found at {jsonPath}");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
await UniTask.SwitchToThreadPool();
var meta = JsonConvert.DeserializeObject<LevelMeta>(File.ReadAllText(jsonPath));
await UniTask.SwitchToMainThread();
timer.Time("Deserialization");
if (meta == null)
{
Debug.LogWarning($"Invalid level.json at {jsonPath}");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
if (type != LevelType.Temp && LoadedLocalLevels.ContainsKey(meta.id))
{
if (LoadedLocalLevels[meta.id].Type == LevelType.Tier && type == LevelType.User)
{
Debug.LogWarning($"Community level cannot override tier level");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
if (LoadedLocalLevels[meta.id].Meta.version > meta.version)
{
Debug.LogWarning($"Level to load has smaller version than loaded level");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
loadedPaths.Remove(LoadedLocalLevels[meta.id].Path);
}
// Sort charts
meta.SortCharts();
// Reject invalid level meta
if (!meta.Validate())
{
Debug.LogWarning($"Invalid metadata in level.json at {jsonPath}");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
timer.Time("Validate");
var db = Context.Database;
await UniTask.SwitchToThreadPool();
var level = Level.FromLocal(path, type, meta, db);
var record = level.Record;
if (record.AddedDate == DateTimeOffset.MinValue)
{
record.AddedDate = Context.Library.Levels.ContainsKey(level.Id)
? Context.Library.Levels[level.Id].Date
: info.LastWriteTimeUtc;
level.SaveRecord();
}
await UniTask.SwitchToMainThread();
timer.Time("LevelRecord");
if (type != LevelType.Temp)
{
LoadedLocalLevels[meta.id] = level;
loadedPaths.Add(path);
// Generate thumbnail
if (!File.Exists(level.Path + CoverThumbnailFilename))
{
var thumbnailPath = "file://" + level.Path + level.Meta.background.path;
if (lowMemory)
{
// Give up
Debug.LogWarning($"Low memory!");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
return;
}
using (var request = UnityWebRequest.Get(thumbnailPath))
{
request.SetRequestHeader("User-Agent", $"CytoidClient/{Context.VersionName}");
await request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.LogWarning(request.error);
Debug.LogWarning($"Cannot get background texture from {thumbnailPath}");
Debug.LogWarning(
$"Skipped generating thumbnail for {loadIndex + 1}/{jsonPaths.Count}: {meta.id} ({path})");
return;
}
var coverTexture = request.downloadHandler.data.ToTexture2D();
if (coverTexture == null)
{
Debug.LogWarning(request.error);
Debug.LogWarning($"Cannot get background texture from {thumbnailPath}");
Debug.LogWarning(
$"Skipped generating thumbnail for {loadIndex + 1}/{jsonPaths.Count}: {meta.id} ({path})");
return;
}
if (lowMemory)
{
// Give up
Object.Destroy(coverTexture);
Debug.LogWarning($"Low memory!");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
return;
}
var croppedTexture = TextureScaler.FitCrop(coverTexture, Context.LevelThumbnailWidth,
Context.LevelThumbnailHeight);
if (lowMemory)
{
// Give up
Object.Destroy(coverTexture);
Object.Destroy(croppedTexture);
Debug.LogWarning($"Low memory!");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
return;
}
var bytes = croppedTexture.EncodeToJPG();
Object.Destroy(coverTexture);
Object.Destroy(croppedTexture);
await UniTask.DelayFrame(0); // Reduce load to prevent crash
try
{
File.WriteAllBytes(level.Path + CoverThumbnailFilename, bytes);
Debug.Log(
$"Thumbnail generated {loadIndex + 1}/{jsonPaths.Count}: {level.Id} ({thumbnailPath})");
await UniTask.DelayFrame(0); // Reduce load to prevent crash
}
catch (Exception e)
{
Debug.LogWarning(e);
Debug.LogWarning($"Could not write to {level.Path + CoverThumbnailFilename}");
Debug.LogWarning(
$"Skipped generating thumbnail for {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
}
}
timer.Time("Generate thumbnail");
}
}
results.Add(level);
OnLevelLoadProgress.Invoke(meta.id, ++loadedCount, jsonPaths.Count);
Debug.Log($"Loaded {loadIndex + 1}/{jsonPaths.Count}: {meta.id} ");
timer.Time("OnLevelLoadProgressEvent");
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Unexpected error while loading from {jsonPath}");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
}
timer.Time();
}
tasks.Add(LoadLevel());
}
await UniTask.WhenAll(tasks);
Application.lowMemory -= OnLowMemory;
return results;
}
private bool UpdateLevelMeta(Level level, LevelMeta meta)
{
var local = level.Meta;
var remote = meta;
var updated = false;
if (local.version > remote.version)
{
Debug.Log($"Local version {local.version} > {remote.version}");
return false;
}
if (local.schema_version != remote.schema_version)
{
local.schema_version = remote.schema_version;
updated = true;
}
if (remote.title != null && local.title != remote.title)
{
local.title = remote.title;
updated = true;
}
if (remote.title_localized != null && local.title_localized != remote.title_localized)
{
local.title_localized = remote.title_localized;
updated = true;
}
if (remote.artist != null && local.artist != remote.artist)
{
local.artist = remote.artist;
updated = true;
}
if (remote.artist_localized != null && local.artist_localized != remote.artist_localized)
{
local.artist_localized = remote.artist_localized;
updated = true;
}
if (remote.artist_source != null && local.artist_source != remote.artist_source)
{
local.artist_source = remote.artist_source;
updated = true;
}
if (remote.illustrator != null && local.illustrator != remote.illustrator)
{
local.illustrator = remote.illustrator;
updated = true;
}
if (remote.illustrator_source != null && local.illustrator_source != remote.illustrator_source)
{
local.illustrator_source = remote.illustrator_source;
updated = true;
}
if (remote.charter != null && local.charter != remote.charter)
{
local.charter = remote.charter;
updated = true;
}
foreach (var type in new List<string> {LevelMeta.Easy, LevelMeta.Hard, LevelMeta.Extreme})
{
if (remote.GetChartSection(type) != null && local.GetChartSection(type) != null &&
local.GetChartSection(type).difficulty != remote.GetChartSection(type).difficulty)
{
local.GetChartSection(type).difficulty = remote.GetChartSection(type).difficulty;
updated = true;
}
}
if (updated)
{
File.WriteAllText($"{level.Path.Replace("file://", "")}/level.json", JsonConvert.SerializeObject(local));
}
return updated;
}
public void DownloadAndUnpackLevelDialog(
Level level,
bool allowAbort = true,
Action onDownloadSucceeded = default,
Action onDownloadAborted = default,
Action onDownloadFailed = default,
Action<Level> onUnpackSucceeded = default,
Action onUnpackFailed = default,
bool forceInternational = false,
bool batchDownloading = false,
int batchDownloadCurrent = default,
int batchDownloadTotal = default
)
{
if (!Context.OnlinePlayer.IsAuthenticated)
{
Toast.Next(Toast.Status.Failure, "TOAST_SIGN_IN_REQUIRED".Get());
return;
}
if (onDownloadSucceeded == default) onDownloadSucceeded = () => { };
if (onDownloadAborted == default) onDownloadAborted = () => { };
if (onDownloadFailed == default) onDownloadFailed = () => { };
if (onUnpackSucceeded == default) onUnpackSucceeded = _ => { };
if (onUnpackFailed == default) onUnpackFailed = () => { };
var dialog = Dialog.Instantiate();
dialog.Message = batchDownloading ? "DIALOG_BATCH_DOWNLOADING_P_Q".Get(batchDownloadCurrent, batchDownloadTotal) : "DIALOG_DOWNLOADING".Get();
dialog.UseProgress = true;
dialog.UsePositiveButton = false;
dialog.UseNegativeButton = allowAbort;
ulong downloadedSize;
var totalSize = 0UL;
var downloading = false;
var aborted = false;
var targetFile = $"{Application.temporaryCachePath}/Downloads/{level.Id}-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.cytoidlevel";
var destFolder = $"{level.Type.GetDataPath()}/{level.Id}";
try
{
Directory.CreateDirectory(destFolder);
}
catch (Exception error)
{
Debug.LogError("Failed to create level folder.");
Debug.LogError(error);
onDownloadFailed();
return;
}
if (level.IsLocal)
{
// Write to the local folder instead
destFolder = level.Path;
}
// Download detail first, then package
RequestHelper req;
var downloadHandler = new DownloadHandlerFile(targetFile)
{
removeFileOnAbort = true
};
RestClient.Get<OnlineLevel>(req = new RequestHelper
{
Uri = $"{(forceInternational ? CdnRegion.International.GetApiUrl() : Context.ApiUrl)}/levels/{level.Id}",
Headers = Context.OnlinePlayer.GetRequestHeaders(),
EnableDebug = true
}).Then(it =>
{
if (aborted)
{
throw new OperationCanceledException();
}
totalSize = (ulong) it.Size;
downloading = true;
var packagePath = (forceInternational ? CdnRegion.International : Context.CdnRegion).GetPackageUrl(level.Id);
Debug.Log($"Package path: {packagePath}");
// Get resources
return RestClient.Post<OnlineLevelResources>(req = new RequestHelper
{
Uri = packagePath,
Headers = Context.OnlinePlayer.GetRequestHeaders(),
BodyString = SecuredOperations.WithCaptcha(new { }).ToString(),
EnableDebug = true
});
}).Then(res =>
{
if (aborted)
{
throw new OperationCanceledException();
}
Debug.Log($"Asset path: {res.package}");
// Start download
// TODO: Change to HttpClient
return RestClient.Get(req = new RequestHelper
{
Uri = res.package,
DownloadHandler = downloadHandler,
WillParseBody = false
});
}).Then(async res =>
{
downloading = false;
try
{
onDownloadSucceeded();
}
catch (Exception e)
{
Debug.LogError(e);
}
dialog.OnNegativeButtonClicked = it => { };
dialog.UseNegativeButton = false;
dialog.Progress = 0;
dialog.Message = "DIALOG_UNPACKING".Get();
DOTween.To(() => dialog.Progress, value => dialog.Progress = value, 1f, 1f).SetEase(Ease.OutCubic);
var success = await Context.LevelManager.UnpackLevelPackage(targetFile, destFolder);
if (success)
{
try
{
level =
(await Context.LevelManager.LoadFromMetadataFiles(level.Type, new List<string> {destFolder + "/level.json"}, true))
.First();
onUnpackSucceeded(level);
}
catch (Exception e)
{
Debug.LogError(e);
onUnpackFailed();
}
}
else
{
try
{
onUnpackFailed();
}
catch (Exception e)
{
Debug.LogError(e);
}
}
dialog.Close();
File.Delete(targetFile);
}).Catch(error =>
{
if (aborted || error is OperationCanceledException || (req != null && req.IsAborted))
{
try
{
onDownloadAborted();
}
catch (Exception e)
{
Debug.LogError(e);
}
}
else
{
if (!forceInternational
&& error is RequestException requestException
&& requestException.StatusCode < 400 && requestException.StatusCode >= 500)
{
DownloadAndUnpackLevelDialog(
level,
allowAbort,
onDownloadSucceeded,
onDownloadAborted,
onDownloadFailed,
onUnpackSucceeded,
onUnpackFailed,
true
);
}
else
{
Debug.LogError(error);
try
{
onDownloadFailed();
}
catch (Exception e)
{
Debug.LogError(e);
}
}
}
dialog.Close();
});
dialog.onUpdate.AddListener(it =>
{
if (!downloading) return;
if (req.Request == null)
{
// Download was cancelled due to Unity
Debug.LogError("UWR download failed");
try
{
onDownloadFailed();
}
catch (Exception e)
{
Debug.LogError(e);
}
dialog.Close();
return;
}
if (totalSize > 0)
{
downloadedSize = req.DownloadedBytes;
it.Progress = downloadedSize * 1.0f / totalSize;
if (batchDownloading)
{
it.Message = "DIALOG_BATCH_DOWNLOADING_P_Q_R_S_T".Get(batchDownloadCurrent, batchDownloadTotal, level.Meta.title, downloadedSize.ToHumanReadableFileSize(),
totalSize.ToHumanReadableFileSize());
}
else
{
it.Message = "DIALOG_DOWNLOADING_X_Y".Get(downloadedSize.ToHumanReadableFileSize(),
totalSize.ToHumanReadableFileSize());
}
}
else
{
it.Message = batchDownloading ? "DIALOG_BATCH_DOWNLOADING_P_Q".Get(batchDownloadCurrent, batchDownloadTotal) : "DIALOG_DOWNLOADING".Get();
}
});
if (allowAbort)
{
dialog.OnNegativeButtonClicked = it =>
{
aborted = true;
req?.Abort();
dialog.Close();
};
}
dialog.Open();
}
}
public class LevelEvent : UnityEvent<Level>
{
}
public class LevelInstallProgressEvent : UnityEvent<string, int, int> // Filename, current, total
{
}
public class LevelLoadProgressEvent : UnityEvent<string, int, int> // Level ID, current, total. Note: may NOT be continuous!
{
}
| |
using J2N;
using YAF.Lucene.Net.Index;
using YAF.Lucene.Net.Support;
using YAF.Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JCG = J2N.Collections.Generic;
namespace YAF.Lucene.Net.Search
{
/*
* 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 Attribute = YAF.Lucene.Net.Util.Attribute;
using AttributeSource = YAF.Lucene.Net.Util.AttributeSource;
using Automaton = YAF.Lucene.Net.Util.Automaton.Automaton;
using BasicAutomata = YAF.Lucene.Net.Util.Automaton.BasicAutomata;
using BasicOperations = YAF.Lucene.Net.Util.Automaton.BasicOperations;
using IBits = YAF.Lucene.Net.Util.IBits;
using ByteRunAutomaton = YAF.Lucene.Net.Util.Automaton.ByteRunAutomaton;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using CompiledAutomaton = YAF.Lucene.Net.Util.Automaton.CompiledAutomaton;
using DocsAndPositionsEnum = YAF.Lucene.Net.Index.DocsAndPositionsEnum;
using DocsEnum = YAF.Lucene.Net.Index.DocsEnum;
using FilteredTermsEnum = YAF.Lucene.Net.Index.FilteredTermsEnum;
using LevenshteinAutomata = YAF.Lucene.Net.Util.Automaton.LevenshteinAutomata;
using Term = YAF.Lucene.Net.Index.Term;
using Terms = YAF.Lucene.Net.Index.Terms;
using TermsEnum = YAF.Lucene.Net.Index.TermsEnum;
using TermState = YAF.Lucene.Net.Index.TermState;
using UnicodeUtil = YAF.Lucene.Net.Util.UnicodeUtil;
/// <summary>
/// Subclass of <see cref="TermsEnum"/> for enumerating all terms that are similar
/// to the specified filter term.
///
/// <para>Term enumerations are always ordered by
/// <see cref="Comparer"/>. Each term in the enumeration is
/// greater than all that precede it.</para>
/// </summary>
public class FuzzyTermsEnum : TermsEnum
{
private void InitializeInstanceFields()
{
boostAtt = Attributes.AddAttribute<IBoostAttribute>();
}
private TermsEnum actualEnum;
private IBoostAttribute actualBoostAtt;
private IBoostAttribute boostAtt;
private readonly IMaxNonCompetitiveBoostAttribute maxBoostAtt;
private readonly ILevenshteinAutomataAttribute dfaAtt;
private float bottom;
private BytesRef bottomTerm;
// TODO: chicken-and-egg
private readonly IComparer<BytesRef> termComparer = BytesRef.UTF8SortedAsUnicodeComparer;
protected readonly float m_minSimilarity;
protected readonly float m_scaleFactor;
protected readonly int m_termLength;
protected int m_maxEdits;
protected readonly bool m_raw;
protected readonly Terms m_terms;
private readonly Term term;
protected readonly int[] m_termText;
protected readonly int m_realPrefixLength;
private readonly bool transpositions;
/// <summary>
/// Constructor for enumeration of all terms from specified <c>reader</c> which share a prefix of
/// length <paramref name="prefixLength"/> with <paramref name="term"/> and which have a fuzzy similarity >
/// <paramref name="minSimilarity"/>.
/// <para/>
/// After calling the constructor the enumeration is already pointing to the first
/// valid term if such a term exists.
/// </summary>
/// <param name="terms"> Delivers terms. </param>
/// <param name="atts"> <see cref="AttributeSource"/> created by the rewrite method of <see cref="MultiTermQuery"/>
/// thats contains information about competitive boosts during rewrite. It is also used
/// to cache DFAs between segment transitions. </param>
/// <param name="term"> Pattern term. </param>
/// <param name="minSimilarity"> Minimum required similarity for terms from the reader. Pass an integer value
/// representing edit distance. Passing a fraction is deprecated. </param>
/// <param name="prefixLength"> Length of required common prefix. Default value is 0. </param>
/// <param name="transpositions"> Transpositions </param>
/// <exception cref="System.IO.IOException"> if there is a low-level IO error </exception>
public FuzzyTermsEnum(Terms terms, AttributeSource atts, Term term, float minSimilarity, int prefixLength, bool transpositions)
{
InitializeInstanceFields();
if (minSimilarity >= 1.0f && minSimilarity != (int)minSimilarity)
{
throw new ArgumentException("fractional edit distances are not allowed");
}
if (minSimilarity < 0.0f)
{
throw new ArgumentException("minimumSimilarity cannot be less than 0");
}
if (prefixLength < 0)
{
throw new ArgumentException("prefixLength cannot be less than 0");
}
this.m_terms = terms;
this.term = term;
// convert the string into a utf32 int[] representation for fast comparisons
string utf16 = term.Text();
this.m_termText = new int[utf16.CodePointCount(0, utf16.Length)];
for (int cp, i = 0, j = 0; i < utf16.Length; i += Character.CharCount(cp))
{
m_termText[j++] = cp = utf16.CodePointAt(i);
}
this.m_termLength = m_termText.Length;
this.dfaAtt = atts.AddAttribute<ILevenshteinAutomataAttribute>();
//The prefix could be longer than the word.
//It's kind of silly though. It means we must match the entire word.
this.m_realPrefixLength = prefixLength > m_termLength ? m_termLength : prefixLength;
// if minSimilarity >= 1, we treat it as number of edits
if (minSimilarity >= 1f)
{
this.m_minSimilarity = 0; // just driven by number of edits
m_maxEdits = (int)minSimilarity;
m_raw = true;
}
else
{
this.m_minSimilarity = minSimilarity;
// calculate the maximum k edits for this similarity
m_maxEdits = InitialMaxDistance(this.m_minSimilarity, m_termLength);
m_raw = false;
}
if (transpositions && m_maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE)
{
throw new System.NotSupportedException("with transpositions enabled, distances > " + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE + " are not supported ");
}
this.transpositions = transpositions;
this.m_scaleFactor = 1.0f / (1.0f - this.m_minSimilarity);
this.maxBoostAtt = atts.AddAttribute<IMaxNonCompetitiveBoostAttribute>();
bottom = maxBoostAtt.MaxNonCompetitiveBoost;
bottomTerm = maxBoostAtt.CompetitiveTerm;
BottomChanged(null, true);
}
/// <summary>
/// Return an automata-based enum for matching up to <paramref name="editDistance"/> from
/// <paramref name="lastTerm"/>, if possible
/// </summary>
protected virtual TermsEnum GetAutomatonEnum(int editDistance, BytesRef lastTerm)
{
IList<CompiledAutomaton> runAutomata = InitAutomata(editDistance);
if (editDistance < runAutomata.Count)
{
//if (BlockTreeTermsWriter.DEBUG) System.out.println("FuzzyTE.getAEnum: ed=" + editDistance + " lastTerm=" + (lastTerm==null ? "null" : lastTerm.utf8ToString()));
CompiledAutomaton compiled = runAutomata[editDistance];
return new AutomatonFuzzyTermsEnum(this, m_terms.Intersect(compiled, lastTerm == null ? null : compiled.Floor(lastTerm, new BytesRef())), runAutomata.SubList(0, editDistance + 1).ToArray(/*new CompiledAutomaton[editDistance + 1]*/));
}
else
{
return null;
}
}
/// <summary>
/// Initialize levenshtein DFAs up to maxDistance, if possible </summary>
private IList<CompiledAutomaton> InitAutomata(int maxDistance)
{
IList<CompiledAutomaton> runAutomata = dfaAtt.Automata;
//System.out.println("cached automata size: " + runAutomata.size());
if (runAutomata.Count <= maxDistance && maxDistance <= LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE)
{
LevenshteinAutomata builder = new LevenshteinAutomata(UnicodeUtil.NewString(m_termText, m_realPrefixLength, m_termText.Length - m_realPrefixLength), transpositions);
for (int i = runAutomata.Count; i <= maxDistance; i++)
{
Automaton a = builder.ToAutomaton(i);
//System.out.println("compute automaton n=" + i);
// constant prefix
if (m_realPrefixLength > 0)
{
Automaton prefix = BasicAutomata.MakeString(UnicodeUtil.NewString(m_termText, 0, m_realPrefixLength));
a = BasicOperations.Concatenate(prefix, a);
}
runAutomata.Add(new CompiledAutomaton(a, true, false));
}
}
return runAutomata;
}
/// <summary>
/// Swap in a new actual enum to proxy to </summary>
protected virtual void SetEnum(TermsEnum actualEnum)
{
this.actualEnum = actualEnum;
this.actualBoostAtt = actualEnum.Attributes.AddAttribute<IBoostAttribute>();
}
/// <summary>
/// Fired when the max non-competitive boost has changed. This is the hook to
/// swap in a smarter actualEnum
/// </summary>
private void BottomChanged(BytesRef lastTerm, bool init)
{
int oldMaxEdits = m_maxEdits;
// true if the last term encountered is lexicographically equal or after the bottom term in the PQ
bool termAfter = bottomTerm == null || (lastTerm != null && termComparer.Compare(lastTerm, bottomTerm) >= 0);
// as long as the max non-competitive boost is >= the max boost
// for some edit distance, keep dropping the max edit distance.
while (m_maxEdits > 0 && (termAfter ? bottom >= CalculateMaxBoost(m_maxEdits) : bottom > CalculateMaxBoost(m_maxEdits)))
{
m_maxEdits--;
}
if (oldMaxEdits != m_maxEdits || init) // the maximum n has changed
{
MaxEditDistanceChanged(lastTerm, m_maxEdits, init);
}
}
protected virtual void MaxEditDistanceChanged(BytesRef lastTerm, int maxEdits, bool init)
{
TermsEnum newEnum = GetAutomatonEnum(maxEdits, lastTerm);
// instead of assert, we do a hard check in case someone uses our enum directly
// assert newEnum != null;
if (newEnum == null)
{
Debug.Assert(maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE);
throw new System.ArgumentException("maxEdits cannot be > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE");
}
SetEnum(newEnum);
}
// for some raw min similarity and input term length, the maximum # of edits
private int InitialMaxDistance(float minimumSimilarity, int termLen)
{
return (int)((1D - minimumSimilarity) * termLen);
}
// for some number of edits, the maximum possible scaled boost
private float CalculateMaxBoost(int nEdits)
{
float similarity = 1.0f - ((float)nEdits / (float)(m_termLength));
return (similarity - m_minSimilarity) * m_scaleFactor;
}
private BytesRef queuedBottom = null;
public override BytesRef Next()
{
if (queuedBottom != null)
{
BottomChanged(queuedBottom, false);
queuedBottom = null;
}
BytesRef term = actualEnum.Next();
boostAtt.Boost = actualBoostAtt.Boost;
float bottom = maxBoostAtt.MaxNonCompetitiveBoost;
BytesRef bottomTerm = maxBoostAtt.CompetitiveTerm;
if (term != null && (bottom != this.bottom || bottomTerm != this.bottomTerm))
{
this.bottom = bottom;
this.bottomTerm = bottomTerm;
// clone the term before potentially doing something with it
// this is a rare but wonderful occurrence anyway
queuedBottom = BytesRef.DeepCopyOf(term);
}
return term;
}
// proxy all other enum calls to the actual enum
public override int DocFreq
{
get { return actualEnum.DocFreq; }
}
public override long TotalTermFreq
{
get { return actualEnum.TotalTermFreq; }
}
public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
return actualEnum.Docs(liveDocs, reuse, flags);
}
public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags)
{
return actualEnum.DocsAndPositions(liveDocs, reuse, flags);
}
public override void SeekExact(BytesRef term, TermState state)
{
actualEnum.SeekExact(term, state);
}
public override TermState GetTermState()
{
return actualEnum.GetTermState();
}
public override IComparer<BytesRef> Comparer => actualEnum.Comparer;
public override long Ord => actualEnum.Ord;
public override bool SeekExact(BytesRef text)
{
return actualEnum.SeekExact(text);
}
public override SeekStatus SeekCeil(BytesRef text)
{
return actualEnum.SeekCeil(text);
}
public override void SeekExact(long ord)
{
actualEnum.SeekExact(ord);
}
public override BytesRef Term => actualEnum.Term;
/// <summary>
/// Implement fuzzy enumeration with <see cref="Terms.Intersect(CompiledAutomaton, BytesRef)"/>.
/// <para/>
/// This is the fastest method as opposed to LinearFuzzyTermsEnum:
/// as enumeration is logarithmic to the number of terms (instead of linear)
/// and comparison is linear to length of the term (rather than quadratic)
/// </summary>
private class AutomatonFuzzyTermsEnum : FilteredTermsEnum
{
internal virtual void InitializeInstanceFields()
{
boostAtt = Attributes.AddAttribute<IBoostAttribute>();
}
private readonly FuzzyTermsEnum outerInstance;
private readonly ByteRunAutomaton[] matchers;
private readonly BytesRef termRef;
private IBoostAttribute boostAtt;
public AutomatonFuzzyTermsEnum(FuzzyTermsEnum outerInstance, TermsEnum tenum, CompiledAutomaton[] compiled)
: base(tenum, false)
{
this.outerInstance = outerInstance;
InitializeInstanceFields();
this.matchers = new ByteRunAutomaton[compiled.Length];
for (int i = 0; i < compiled.Length; i++)
{
this.matchers[i] = compiled[i].RunAutomaton;
}
termRef = new BytesRef(outerInstance.term.Text());
}
/// <summary>
/// Finds the smallest Lev(n) DFA that accepts the term. </summary>
protected override AcceptStatus Accept(BytesRef term)
{
//System.out.println("AFTE.accept term=" + term);
int ed = matchers.Length - 1;
// we are wrapping either an intersect() TermsEnum or an AutomatonTermsENum,
// so we know the outer DFA always matches.
// now compute exact edit distance
while (ed > 0)
{
if (Matches(term, ed - 1))
{
ed--;
}
else
{
break;
}
}
//System.out.println("CHECK term=" + term.utf8ToString() + " ed=" + ed);
// scale to a boost and return (if similarity > minSimilarity)
if (ed == 0) // exact match
{
boostAtt.Boost = 1.0F;
//System.out.println(" yes");
return AcceptStatus.YES;
}
else
{
int codePointCount = UnicodeUtil.CodePointCount(term);
float similarity = 1.0f - ((float)ed / (float)(Math.Min(codePointCount, outerInstance.m_termLength)));
if (similarity > outerInstance.m_minSimilarity)
{
boostAtt.Boost = (similarity - outerInstance.m_minSimilarity) * outerInstance.m_scaleFactor;
//System.out.println(" yes");
return AcceptStatus.YES;
}
else
{
return AcceptStatus.NO;
}
}
}
/// <summary>
/// Returns <c>true</c> if <paramref name="term"/> is within <paramref name="k"/> edits of the query term </summary>
internal bool Matches(BytesRef term, int k)
{
return k == 0 ? term.Equals(termRef) : matchers[k].Run(term.Bytes, term.Offset, term.Length);
}
}
/// <summary>
/// @lucene.internal </summary>
public virtual float MinSimilarity => m_minSimilarity;
/// <summary>
/// @lucene.internal </summary>
public virtual float ScaleFactor => m_scaleFactor;
/// <summary>
/// Reuses compiled automata across different segments,
/// because they are independent of the index
/// <para/>
/// @lucene.internal
/// </summary>
public interface ILevenshteinAutomataAttribute : IAttribute
{
IList<CompiledAutomaton> Automata { get; }
}
/// <summary>
/// Stores compiled automata as a list (indexed by edit distance)
/// <para/>
/// @lucene.internal
/// </summary>
public sealed class LevenshteinAutomataAttribute : Attribute, ILevenshteinAutomataAttribute
{
// LUCENENET NOTE: Must use JCG.List for Equals and GetHashCode()
private readonly IList<CompiledAutomaton> automata = new JCG.List<CompiledAutomaton>();
public IList<CompiledAutomaton> Automata
{
get { return automata; }
}
public override void Clear()
{
automata.Clear();
}
public override int GetHashCode()
{
return automata.GetHashCode();
}
public override bool Equals(object other)
{
if (this == other)
{
return true;
}
if (!(other is LevenshteinAutomataAttribute))
{
return false;
}
return automata.Equals(((LevenshteinAutomataAttribute)other).automata);
}
public override void CopyTo(IAttribute target)
{
IList<CompiledAutomaton> targetAutomata = ((LevenshteinAutomataAttribute)target).Automata;
targetAutomata.Clear();
targetAutomata.AddRange(automata);
}
}
}
}
| |
// Project: Loading Screen for Daggerfall Unity
// Web Site: http://forums.dfworkshop.net/viewtopic.php?f=14&t=469
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/TheLacus/loadingscreen-du-mod
// Original Author: TheLacus (TheLacus@yandex.com)
// Contributors:
using System;
using System.IO;
using UnityEngine;
using DaggerfallWorkshop.Game;
using DaggerfallWorkshop.Game.Serialization;
using DaggerfallWorkshop.Utility.AssetInjection;
using DaggerfallWorkshop.Game.UserInterfaceWindows;
namespace LoadingScreen.Components
{
/// <summary>
/// Implements a component for the loading screen.
/// </summary>
public abstract class LoadingScreenComponent : ILoadingEventsHandler
{
#region Fields & Properties
protected bool enabled = true;
protected Rect rect;
protected GUIStyle style;
readonly Rect relRect;
readonly int referenceFontSize = -1;
/// <summary>
/// Show or hide the component.
/// </summary>
public bool Enabled
{
get { return enabled; }
set { enabled = value; }
}
public Rect Rect
{
get { return rect; }
}
public int Font
{
set { SetFont(value); }
}
public int FontSize
{
get { return style.fontSize; }
set { style.fontSize = value; }
}
public FontStyle FontStyle
{
get { return style.fontStyle; }
set { style.fontStyle = value; }
}
public Color FontColor
{
get { return style.normal.textColor; }
set { style.normal.textColor = value; }
}
public LoadingScreenPanel Parent { get; set; }
#endregion
#region Constructor
/// <summary>
/// Set component rect and style.
/// </summary>
/// <param name="virtualRect">Rect in a 100x100 resolution.</param>
protected LoadingScreenComponent(Rect virtualRect)
{
Rect relRect = new Rect(
virtualRect.position / 100f,
virtualRect.size / 100f);
var style = new GUIStyle();
style.alignment = GetTextAnchor(relRect);
if (relRect.x < 0)
relRect.x += 1 - relRect.width;
if (relRect.y < 0)
relRect.y += 1 - relRect.height;
relRect.x = Mathf.Clamp(relRect.x, 0, 1 - relRect.width);
relRect.y = Mathf.Clamp(relRect.y, 0, 1 - relRect.height);
this.relRect = relRect;
this.rect = new Rect(RelToScreen(relRect.position), RelToScreen(relRect.size));
this.style = style;
}
/// <summary>
/// Set component rect and style.
/// Font size will be automatically scaled on resolution and rect size.
/// </summary>
/// <param name="virtualRect">Rect in a 100x100 resolution.</param>
/// <param name="referenceFontSize">A font size that fits the rect.</param>
protected LoadingScreenComponent(Rect virtualRect, int referenceFontSize)
:this(virtualRect)
{
this.referenceFontSize = referenceFontSize;
this.style.fontSize = CalcFontSize(referenceFontSize);
}
#endregion
#region Public Methods
/// <summary>
/// Draws on OnGui().
/// </summary>
public abstract void Draw();
/// <summary>
/// Called when the user load a save.
/// </summary>
/// <param name="saveData">Save being loaded.</param>
public abstract void OnLoadingScreen(SaveData_v1 saveData);
/// <summary>
/// Called during a fast travel.
/// </summary>
/// <param name="sender">Travel popup..</param>
public abstract void OnLoadingScreen(DaggerfallTravelPopUp sender);
/// <summary>
/// Called during transition (entering/exiting building).
/// </summary>
/// <param name="args">Transition parameters.</param>
public abstract void OnLoadingScreen(PlayerEnterExit.TransitionEventArgs args);
/// <summary>
/// Called once per frame.
/// </summary>
public virtual void UpdateScreen()
{
}
/// <summary>
/// Called on press-any-key screen.
/// </summary>
public virtual void OnEndScreen()
{
}
/// <summary>
/// Hide components that don't support death screen.
/// Override to show and do something.
/// </summary>
public virtual void OnDeathScreen()
{
enabled = false;
}
public virtual void RefreshRect()
{
rect.position = RelToScreen(relRect.position);
rect.size = RelToScreen(relRect.size);
if (referenceFontSize != -1)
style.fontSize = CalcFontSize(referenceFontSize);
}
public static implicit operator bool(LoadingScreenComponent plugin)
{
return !object.ReferenceEquals(plugin, null);
}
#endregion
#region Protected Methods
/// <summary>
/// Gets font size scaled on resolution and rect size.
/// </summary>
/// <param name="referenceSize">A font size that fits the rect.</param>
/// <returns>Font size for the guistyle</returns>
protected int CalcFontSize(int referenceSize)
{
Vector2 scale = new Vector2(rect.width / 100, rect.height / 100);
return Mathf.RoundToInt(referenceSize * (scale.x + scale.y) / 2);
}
/// <summary>
/// Import a texture from resources. This texture can be overriden with loose files.
/// </summary>
protected Texture2D ImportTexture(string name)
{
Texture2D tex;
if (!TextureReplacement.TryImportTextureFromLooseFiles(Path.Combine(LoadingScreenPanel.ResourcesPath, name), false, false, true, out tex))
tex = LoadingScreen.Mod.GetAsset<Texture2D>(name);
return tex;
}
#endregion
#region Private Methods
private void SetFont(int fontID)
{
string name = GetFontName(fontID);
style.font = name != null ? Resources.Load<Font>(name) : null;
}
/// <summary>
/// Get text alignment for this relative rect.
/// </summary>
/// <remarks>
/// From 0 to 1 is left(up) alignment, from 0 to -1 is right(bottom) aligment.
/// Center and Middle are used according to center point.
/// </remarks>
private static TextAnchor GetTextAnchor(Rect relRect)
{
bool isCenter = Mathf.Approximately(Mathf.Abs(relRect.center.x), 0.5f);
bool isMiddle = Mathf.Approximately(Mathf.Abs(relRect.center.y), 0.5f);
// Center
if (isCenter)
{
if (isMiddle)
return TextAnchor.MiddleCenter;
if (relRect.y > 0)
return TextAnchor.UpperCenter;
return TextAnchor.LowerCenter;
}
// Left
if (relRect.x > 0)
{
if (isMiddle)
return TextAnchor.MiddleLeft;
if (relRect.y > 0)
return TextAnchor.UpperLeft;
return TextAnchor.LowerLeft;
}
// Right
if (isMiddle)
return TextAnchor.MiddleRight;
if (relRect.y > 0)
return TextAnchor.UpperRight;
return TextAnchor.LowerRight;
}
private static Vector2 RelToScreen(Vector2 rel)
{
return new Vector2(rel.x * Screen.width, rel.y * Screen.height);
}
/// <summary>
/// Convert font id to font path.
/// </summary>
private static string GetFontName(int fontID)
{
switch (fontID)
{
case 0: return null; // Arial or Liberation Sans
case 1: return "Fonts/OpenSans/OpenSans-ExtraBold";
case 2: return "Fonts/OpenSans/OpenSansBold";
case 3: return "Fonts/OpenSans/OpenSansSemibold";
case 4: return "Fonts/OpenSans/OpenSansRegular";
case 5: return "Fonts/OpenSans/OpenSansLight";
case 6: return "Fonts/TESFonts/Kingthings Exeter";
case 7: return "Fonts/TESFonts/Kingthings Petrock";
case 8: return "Fonts/TESFonts/Kingthings Petrock light";
case 9: return "Fonts/TESFonts/MorrisRomanBlack";
case 10: return "Fonts/TESFonts/oblivion-font";
case 11: return "Fonts/TESFonts/Planewalker";
}
throw new ArgumentException(string.Format("Undefined fontID: {0}", fontID));
}
#endregion
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.DynamicProxy.Generators.Emitters
{
using System;
using System.Reflection;
using System.Reflection.Emit;
internal abstract class OpCodeUtil
{
/// <summary>
/// Emits a load indirect opcode of the appropriate type for a value or object reference.
/// Pops a pointer off the evaluation stack, dereferences it and loads
/// a value of the specified type.
/// </summary>
/// <param name = "gen"></param>
/// <param name = "type"></param>
public static void EmitLoadIndirectOpCodeForType(ILGenerator gen, Type type)
{
if (type.IsEnum())
{
EmitLoadIndirectOpCodeForType(gen, GetUnderlyingTypeOfEnum(type));
return;
}
if (type.IsByRef)
{
throw new NotSupportedException("Cannot load ByRef values");
}
else if (type.IsPrimitive() && type != typeof(IntPtr))
{
var opCode = LdindOpCodesDictionary.Instance[type];
if (opCode == LdindOpCodesDictionary.EmptyOpCode)
{
throw new ArgumentException("Type " + type + " could not be converted to a OpCode");
}
gen.Emit(opCode);
}
else if (type.IsValueType())
{
gen.Emit(OpCodes.Ldobj, type);
}
else if (type.IsGenericParameter)
{
gen.Emit(OpCodes.Ldobj, type);
}
else
{
gen.Emit(OpCodes.Ldind_Ref);
}
}
/// <summary>
/// Emits a load opcode of the appropriate kind for a constant string or
/// primitive value.
/// </summary>
/// <param name = "gen"></param>
/// <param name = "value"></param>
public static void EmitLoadOpCodeForConstantValue(ILGenerator gen, object value)
{
if (value is String)
{
gen.Emit(OpCodes.Ldstr, value.ToString());
}
else if (value is Int32)
{
var code = LdcOpCodesDictionary.Instance[value.GetType()];
gen.Emit(code, (int)value);
}
else if (value is bool)
{
var code = LdcOpCodesDictionary.Instance[value.GetType()];
gen.Emit(code, Convert.ToInt32(value));
}
else
{
throw new NotSupportedException();
}
}
/// <summary>
/// Emits a load opcode of the appropriate kind for the constant default value of a
/// type, such as 0 for value types and null for reference types.
/// </summary>
public static void EmitLoadOpCodeForDefaultValueOfType(ILGenerator gen, Type type)
{
if (type.IsPrimitive())
{
var opCode = LdcOpCodesDictionary.Instance[type];
switch (opCode.StackBehaviourPush)
{
case StackBehaviour.Pushi:
gen.Emit(opCode, 0);
if (Is64BitTypeLoadedAsInt32(type))
{
// we load Int32, and have to convert it to 64bit type
gen.Emit(OpCodes.Conv_I8);
}
break;
case StackBehaviour.Pushr8:
gen.Emit(opCode, 0D);
break;
case StackBehaviour.Pushi8:
gen.Emit(opCode, 0L);
break;
case StackBehaviour.Pushr4:
gen.Emit(opCode, 0F);
break;
default:
throw new NotSupportedException();
}
}
else
{
gen.Emit(OpCodes.Ldnull);
}
}
/// <summary>
/// Emits a store indirectopcode of the appropriate type for a value or object reference.
/// Pops a value of the specified type and a pointer off the evaluation stack, and
/// stores the value.
/// </summary>
/// <param name = "gen"></param>
/// <param name = "type"></param>
public static void EmitStoreIndirectOpCodeForType(ILGenerator gen, Type type)
{
if (type.IsEnum())
{
EmitStoreIndirectOpCodeForType(gen, GetUnderlyingTypeOfEnum(type));
return;
}
if (type.IsByRef)
{
throw new NotSupportedException("Cannot store ByRef values");
}
else if (type.IsPrimitive() && type != typeof(IntPtr))
{
var opCode = StindOpCodesDictionary.Instance[type];
if (Equals(opCode, StindOpCodesDictionary.EmptyOpCode))
{
throw new ArgumentException("Type " + type + " could not be converted to a OpCode");
}
gen.Emit(opCode);
}
else if (type.IsValueType())
{
gen.Emit(OpCodes.Stobj, type);
}
else if (type.IsGenericParameter)
{
gen.Emit(OpCodes.Stobj, type);
}
else
{
gen.Emit(OpCodes.Stind_Ref);
}
}
private static Type GetUnderlyingTypeOfEnum(Type enumType)
{
var baseType = (Enum)Activator.CreateInstance(enumType);
var code = baseType.GetTypeCode();
switch (code)
{
case TypeCode.SByte:
return typeof(SByte);
case TypeCode.Byte:
return typeof(Byte);
case TypeCode.Int16:
return typeof(Int16);
case TypeCode.Int32:
return typeof(Int32);
case TypeCode.Int64:
return typeof(Int64);
case TypeCode.UInt16:
return typeof(UInt16);
case TypeCode.UInt32:
return typeof(UInt32);
case TypeCode.UInt64:
return typeof(UInt64);
default:
throw new NotSupportedException();
}
}
private static bool Is64BitTypeLoadedAsInt32(Type type)
{
return type == typeof(long) || type == typeof(ulong);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using System;
using System.Collections.Generic;
using osu.Game.Configuration;
using System.Linq;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModDifficultyAdjust : Mod, IApplicableToDifficulty
{
public override string Name => @"Difficulty Adjust";
public override string Description => @"Override a beatmap's difficulty settings.";
public override string Acronym => "DA";
public override ModType Type => ModType.Conversion;
public override IconUsage? Icon => FontAwesome.Solid.Hammer;
public override double ScoreMultiplier => 1.0;
public override bool RequiresConfiguration => true;
public override Type[] IncompatibleMods => new[] { typeof(ModEasy), typeof(ModHardRock) };
protected const int FIRST_SETTING_ORDER = 1;
protected const int LAST_SETTING_ORDER = 2;
[SettingSource("HP Drain", "Override a beatmap's set HP.", FIRST_SETTING_ORDER)]
public BindableNumber<float> DrainRate { get; } = new BindableFloatWithLimitExtension
{
Precision = 0.1f,
MinValue = 0,
MaxValue = 10,
Default = 5,
Value = 5,
};
[SettingSource("Accuracy", "Override a beatmap's set OD.", LAST_SETTING_ORDER)]
public BindableNumber<float> OverallDifficulty { get; } = new BindableFloatWithLimitExtension
{
Precision = 0.1f,
MinValue = 0,
MaxValue = 10,
Default = 5,
Value = 5,
};
[SettingSource("Extended Limits", "Adjust difficulty beyond sane limits.")]
public BindableBool ExtendedLimits { get; } = new BindableBool();
protected ModDifficultyAdjust()
{
ExtendedLimits.BindValueChanged(extend => ApplyLimits(extend.NewValue));
}
/// <summary>
/// Changes the difficulty adjustment limits. Occurs when the value of <see cref="ExtendedLimits"/> is changed.
/// </summary>
/// <param name="extended">Whether limits should extend beyond sane ranges.</param>
protected virtual void ApplyLimits(bool extended)
{
DrainRate.MaxValue = extended ? 11 : 10;
OverallDifficulty.MaxValue = extended ? 11 : 10;
}
public override string SettingDescription
{
get
{
string drainRate = DrainRate.IsDefault ? string.Empty : $"HP {DrainRate.Value:N1}";
string overallDifficulty = OverallDifficulty.IsDefault ? string.Empty : $"OD {OverallDifficulty.Value:N1}";
return string.Join(", ", new[]
{
drainRate,
overallDifficulty
}.Where(s => !string.IsNullOrEmpty(s)));
}
}
private BeatmapDifficulty difficulty;
public void ReadFromDifficulty(BeatmapDifficulty difficulty)
{
if (this.difficulty == null || this.difficulty.ID != difficulty.ID)
{
TransferSettings(difficulty);
this.difficulty = difficulty;
}
}
public void ApplyToDifficulty(BeatmapDifficulty difficulty) => ApplySettings(difficulty);
/// <summary>
/// Transfer initial settings from the beatmap to settings.
/// </summary>
/// <param name="difficulty">The beatmap's initial values.</param>
protected virtual void TransferSettings(BeatmapDifficulty difficulty)
{
TransferSetting(DrainRate, difficulty.DrainRate);
TransferSetting(OverallDifficulty, difficulty.OverallDifficulty);
}
private readonly Dictionary<IBindable, bool> userChangedSettings = new Dictionary<IBindable, bool>();
/// <summary>
/// Transfer a setting from <see cref="BeatmapDifficulty"/> to a configuration bindable.
/// Only performs the transfer if the user is not currently overriding.
/// </summary>
protected void TransferSetting<T>(BindableNumber<T> bindable, T beatmapDefault)
where T : struct, IComparable<T>, IConvertible, IEquatable<T>
{
bindable.UnbindEvents();
userChangedSettings.TryAdd(bindable, false);
bindable.Default = beatmapDefault;
// users generally choose a difficulty setting and want it to stick across multiple beatmap changes.
// we only want to value transfer if the user hasn't changed the value previously.
if (!userChangedSettings[bindable])
bindable.Value = beatmapDefault;
bindable.ValueChanged += _ => userChangedSettings[bindable] = !bindable.IsDefault;
}
internal override void CopyAdjustedSetting(IBindable target, object source)
{
// if the value is non-bindable, it's presumably coming from an external source (like the API) - therefore presume it is not default.
// if the value is bindable, defer to the source's IsDefault to be able to tell.
userChangedSettings[target] = !(source is IBindable bindableSource) || !bindableSource.IsDefault;
base.CopyAdjustedSetting(target, source);
}
/// <summary>
/// Applies a setting from a configuration bindable using <paramref name="applyFunc"/>, if it has been changed by the user.
/// </summary>
protected void ApplySetting<T>(BindableNumber<T> setting, Action<T> applyFunc)
where T : struct, IComparable<T>, IConvertible, IEquatable<T>
{
if (userChangedSettings.TryGetValue(setting, out bool userChangedSetting) && userChangedSetting)
applyFunc.Invoke(setting.Value);
}
/// <summary>
/// Apply all custom settings to the provided beatmap.
/// </summary>
/// <param name="difficulty">The beatmap to have settings applied.</param>
protected virtual void ApplySettings(BeatmapDifficulty difficulty)
{
ApplySetting(DrainRate, dr => difficulty.DrainRate = dr);
ApplySetting(OverallDifficulty, od => difficulty.OverallDifficulty = od);
}
public override void ResetSettingsToDefaults()
{
base.ResetSettingsToDefaults();
if (difficulty != null)
{
// base implementation potentially overwrite modified defaults that came from a beatmap selection.
TransferSettings(difficulty);
}
}
/// <summary>
/// A <see cref="BindableDouble"/> that extends its min/max values to support any assigned value.
/// </summary>
protected class BindableDoubleWithLimitExtension : BindableDouble
{
public override double Value
{
get => base.Value;
set
{
if (value < MinValue)
MinValue = value;
if (value > MaxValue)
MaxValue = value;
base.Value = value;
}
}
}
/// <summary>
/// A <see cref="BindableFloat"/> that extends its min/max values to support any assigned value.
/// </summary>
protected class BindableFloatWithLimitExtension : BindableFloat
{
public override float Value
{
get => base.Value;
set
{
if (value < MinValue)
MinValue = value;
if (value > MaxValue)
MaxValue = value;
base.Value = value;
}
}
}
/// <summary>
/// A <see cref="BindableInt"/> that extends its min/max values to support any assigned value.
/// </summary>
protected class BindableIntWithLimitExtension : BindableInt
{
public override int Value
{
get => base.Value;
set
{
if (value < MinValue)
MinValue = value;
if (value > MaxValue)
MaxValue = value;
base.Value = value;
}
}
}
}
}
| |
using System;
using Lucene.Net.Randomized.Generators;
using NUnit.Framework;
namespace Lucene.Net.Util.Fst
{
/*
* 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 Directory = Lucene.Net.Store.Directory;
using IOContext = Lucene.Net.Store.IOContext;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
[TestFixture]
public class TestBytesStore : LuceneTestCase
{
[Test]
public virtual void TestRandom()
{
int iters = AtLeast(10);
for (int iter = 0; iter < iters; iter++)
{
int numBytes = TestUtil.NextInt(Random(), 1, 200000);
sbyte[] expected = new sbyte[numBytes];
int blockBits = TestUtil.NextInt(Random(), 8, 15);
BytesStore bytes = new BytesStore(blockBits);
if (VERBOSE)
{
Console.WriteLine("TEST: iter=" + iter + " numBytes=" + numBytes + " blockBits=" + blockBits);
}
int pos = 0;
while (pos < numBytes)
{
int op = Random().Next(8);
if (VERBOSE)
{
Console.WriteLine(" cycle pos=" + pos);
}
switch (op)
{
case 0:
{
// write random byte
sbyte b = (sbyte)Random().Next(256);
if (VERBOSE)
{
Console.WriteLine(" writeByte b=" + b);
}
expected[pos++] = b;
bytes.WriteByte(b);
}
break;
case 1:
{
// write random byte[]
int len = Random().Next(Math.Min(numBytes - pos, 100));
sbyte[] temp = new sbyte[len];
Random().NextBytes(temp);
if (VERBOSE)
{
Console.WriteLine(" writeBytes len=" + len + " bytes=" + Arrays.ToString(temp));
}
Array.Copy(temp, 0, expected, pos, temp.Length);
bytes.WriteBytes(temp, 0, temp.Length);
pos += len;
}
break;
case 2:
{
// write int @ absolute pos
if (pos > 4)
{
int x = Random().Next();
int randomPos = Random().Next(pos - 4);
if (VERBOSE)
{
Console.WriteLine(" abs writeInt pos=" + randomPos + " x=" + x);
}
bytes.writeInt(randomPos, x);
expected[randomPos++] = (sbyte)(x >> 24);
expected[randomPos++] = (sbyte)(x >> 16);
expected[randomPos++] = (sbyte)(x >> 8);
expected[randomPos++] = (sbyte)x;
}
}
break;
case 3:
{
// reverse bytes
if (pos > 1)
{
int len = TestUtil.NextInt(Random(), 2, Math.Min(100, pos));
int start;
if (len == pos)
{
start = 0;
}
else
{
start = Random().Next(pos - len);
}
int end = start + len - 1;
if (VERBOSE)
{
Console.WriteLine(" reverse start=" + start + " end=" + end + " len=" + len + " pos=" + pos);
}
bytes.reverse(start, end);
while (start <= end)
{
sbyte b = expected[end];
expected[end] = expected[start];
expected[start] = b;
start++;
end--;
}
}
}
break;
case 4:
{
// abs write random byte[]
if (pos > 2)
{
int randomPos = Random().Next(pos - 1);
int len = TestUtil.NextInt(Random(), 1, Math.Min(pos - randomPos - 1, 100));
sbyte[] temp = new sbyte[len];
Random().NextBytes(temp);
if (VERBOSE)
{
Console.WriteLine(" abs writeBytes pos=" + randomPos + " len=" + len + " bytes=" + Arrays.ToString(temp));
}
Array.Copy(temp, 0, expected, randomPos, temp.Length);
bytes.WriteBytes(randomPos, temp, 0, temp.Length);
}
}
break;
case 5:
{
// copyBytes
if (pos > 1)
{
int src = Random().Next(pos - 1);
int dest = TestUtil.NextInt(Random(), src + 1, pos - 1);
int len = TestUtil.NextInt(Random(), 1, Math.Min(300, pos - dest));
if (VERBOSE)
{
Console.WriteLine(" copyBytes src=" + src + " dest=" + dest + " len=" + len);
}
Array.Copy(expected, src, expected, dest, len);
bytes.copyBytes(src, dest, len);
}
}
break;
case 6:
{
// skip
int len = Random().Next(Math.Min(100, numBytes - pos));
if (VERBOSE)
{
Console.WriteLine(" skip len=" + len);
}
pos += len;
bytes.skipBytes(len);
// NOTE: must fill in zeros in case truncate was
// used, else we get false fails:
if (len > 0)
{
sbyte[] zeros = new sbyte[len];
bytes.WriteBytes(pos - len, zeros, 0, len);
}
}
break;
case 7:
{
// absWriteByte
if (pos > 0)
{
int dest = Random().Next(pos);
sbyte b = (sbyte)Random().Next(256);
expected[dest] = b;
bytes.WriteByte(dest, b);
}
break;
}
}
Assert.AreEqual(pos, bytes.Position);
if (pos > 0 && Random().Next(50) == 17)
{
// truncate
int len = TestUtil.NextInt(Random(), 1, Math.Min(pos, 100));
bytes.truncate(pos - len);
pos -= len;
Arrays.fill(expected, pos, pos + len, (sbyte)0);
if (VERBOSE)
{
Console.WriteLine(" truncate len=" + len + " newPos=" + pos);
}
}
if ((pos > 0 && Random().Next(200) == 17))
{
Verify(bytes, expected, pos);
}
}
BytesStore bytesToVerify;
if (Random().NextBoolean())
{
if (VERBOSE)
{
Console.WriteLine("TEST: save/load final bytes");
}
Directory dir = NewDirectory();
IndexOutput @out = dir.CreateOutput("bytes", IOContext.DEFAULT);
bytes.writeTo(@out);
@out.Dispose();
IndexInput @in = dir.OpenInput("bytes", IOContext.DEFAULT);
bytesToVerify = new BytesStore(@in, numBytes, TestUtil.NextInt(Random(), 256, int.MaxValue));
@in.Dispose();
dir.Dispose();
}
else
{
bytesToVerify = bytes;
}
Verify(bytesToVerify, expected, numBytes);
}
}
private void Verify(BytesStore bytes, sbyte[] expected, int totalLength)
{
Assert.AreEqual(totalLength, bytes.Position);
if (totalLength == 0)
{
return;
}
if (VERBOSE)
{
Console.WriteLine(" verify...");
}
// First verify whole thing in one blast:
sbyte[] actual = new sbyte[totalLength];
if (Random().NextBoolean())
{
if (VERBOSE)
{
Console.WriteLine(" bulk: reversed");
}
// reversed
FST.BytesReader r = bytes.ReverseReader;
Assert.IsTrue(r.reversed());
r.Position = totalLength - 1;
r.ReadBytes(actual, 0, actual.Length);
int start = 0;
int end = totalLength - 1;
while (start < end)
{
sbyte b = actual[start];
actual[start] = actual[end];
actual[end] = b;
start++;
end--;
}
}
else
{
// forward
if (VERBOSE)
{
Console.WriteLine(" bulk: forward");
}
FST.BytesReader r = bytes.ForwardReader;
Assert.IsFalse(r.reversed());
r.ReadBytes(actual, 0, actual.Length);
}
for (int i = 0; i < totalLength; i++)
{
Assert.AreEqual("byte @ index=" + i, expected[i], actual[i]);
}
FST.BytesReader r;
// Then verify ops:
bool reversed = Random().NextBoolean();
if (reversed)
{
if (VERBOSE)
{
Console.WriteLine(" ops: reversed");
}
r = bytes.ReverseReader;
}
else
{
if (VERBOSE)
{
Console.WriteLine(" ops: forward");
}
r = bytes.ForwardReader;
}
if (totalLength > 1)
{
int numOps = TestUtil.NextInt(Random(), 100, 200);
for (int op = 0; op < numOps; op++)
{
int numBytes = Random().Next(Math.Min(1000, totalLength - 1));
int pos;
if (reversed)
{
pos = TestUtil.NextInt(Random(), numBytes, totalLength - 1);
}
else
{
pos = Random().Next(totalLength - numBytes);
}
if (VERBOSE)
{
Console.WriteLine(" op iter=" + op + " reversed=" + reversed + " numBytes=" + numBytes + " pos=" + pos);
}
sbyte[] temp = new sbyte[numBytes];
r.Position = pos;
Assert.AreEqual(pos, r.Position);
r.ReadBytes(temp, 0, temp.Length);
for (int i = 0; i < numBytes; i++)
{
sbyte expectedByte;
if (reversed)
{
expectedByte = expected[pos - i];
}
else
{
expectedByte = expected[pos + i];
}
Assert.AreEqual("byte @ index=" + i, expectedByte, temp[i]);
}
int left;
int expectedPos;
if (reversed)
{
expectedPos = pos - numBytes;
left = (int)r.Position;
}
else
{
expectedPos = pos + numBytes;
left = (int)(totalLength - r.Position);
}
Assert.AreEqual(expectedPos, r.Position);
if (left > 4)
{
int skipBytes = Random().Next(left - 4);
int expectedInt = 0;
if (reversed)
{
expectedPos -= skipBytes;
expectedInt |= (expected[expectedPos--] & 0xFF) << 24;
expectedInt |= (expected[expectedPos--] & 0xFF) << 16;
expectedInt |= (expected[expectedPos--] & 0xFF) << 8;
expectedInt |= (expected[expectedPos--] & 0xFF);
}
else
{
expectedPos += skipBytes;
expectedInt |= (expected[expectedPos++] & 0xFF) << 24;
expectedInt |= (expected[expectedPos++] & 0xFF) << 16;
expectedInt |= (expected[expectedPos++] & 0xFF) << 8;
expectedInt |= (expected[expectedPos++] & 0xFF);
}
if (VERBOSE)
{
Console.WriteLine(" skip numBytes=" + skipBytes);
Console.WriteLine(" readInt");
}
r.skipBytes(skipBytes);
Assert.AreEqual(expectedInt, r.readInt());
}
}
}
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2017 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
using System.IO;
#if NETFX_CORE
using System.Linq;
#endif
using System.Linq.Expressions;
#if NETFX_CORE
using System.Reflection;
#endif
#if !NETFX_CORE && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3
using System.Runtime.Serialization.Formatters.Binary;
#else
using System.Runtime.Serialization;
#endif // !NETFX_CORE && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3
using System.Security;
#if !NETFX_CORE && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3
using System.Security.Permissions;
using System.Security.Policy;
#endif // !NETFX_CORE && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3
#if !MSTEST
using NUnit.Framework;
#else
using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
using TimeoutAttribute = NUnit.Framework.TimeoutAttribute;
using Assert = NUnit.Framework.Assert;
using Is = NUnit.Framework.Is;
#endif
#if UNITY
using MsgPack.Serialization;
#endif // UNITY
namespace MsgPack
{
/// <summary>
/// Test suite for standard exception constructors, properties, and serialization.
/// </summary>
/// <typeparam name="T">Target exception type.</typeparam>
public sealed class GenericExceptionTester<T>
#if !NETFX_CORE && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3
: MarshalByRefObject
#endif // !NETFX_CORE && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3
where T : Exception
{
private static readonly Type[] _emptyTypes = new Type[ 0 ];
private static readonly Type[] _messageConstructorParameterTypes = new[] { typeof( string ) };
private static readonly Type[] _innerExceptionConstructorParameterTypes = new[] { typeof( string ), typeof( Exception ) };
private readonly Func<T> _defaultConstructor;
private readonly Func<string, T> _messageConstructor;
private readonly Func<string, Exception, T> _innerExceptionConstructor;
private readonly Exception _constructorException;
public T CreateTargetInstance( string message, Exception inner )
{
return this._innerExceptionConstructor( message, inner );
}
/// <summary>
/// Initializes a new instance of the <see cref="GenericExceptionTester<T>"/> class.
/// </summary>
public GenericExceptionTester()
{
try
{
#if UNITY
this._defaultConstructor = () => ReflectionExtensions.CreateInstancePreservingExceptionType<T>( typeof( T ) );
#elif !NETFX_CORE
this._defaultConstructor = Expression.Lambda<Func<T>>( Expression.New( typeof( T ).GetConstructor( _emptyTypes ) ) ).Compile();
#else
this._defaultConstructor = Expression.Lambda<Func<T>>( Expression.New( typeof( T ).GetTypeInfo().DeclaredConstructors.Single( c => c.GetParameters().Length == 0 ) ) ).Compile();
#endif // if UNITY elif !NETFX_CORE
var message = Expression.Parameter( typeof( string ), "message" );
var innerException = Expression.Parameter( typeof( Exception ), "innerException" );
#if !UNITY
this._messageConstructor =
Expression.Lambda<Func<string, T>>(
#if !NETFX_CORE
Expression.New( typeof( T ).GetConstructor( _messageConstructorParameterTypes ), message ),
#else
Expression.New( typeof( T ).GetTypeInfo().DeclaredConstructors.Single( c => c.GetParameters().Select( p => p.ParameterType ).SequenceEqual( _messageConstructorParameterTypes ) ), message ),
#endif // !NETFX_CORE
message
).Compile();
#else
this._messageConstructor = msg => ReflectionExtensions.CreateInstancePreservingExceptionType<T>( typeof( T ), msg );
#endif // !UNITY
#if !UNITY
this._innerExceptionConstructor =
Expression.Lambda<Func<string, Exception, T>>(
#if !NETFX_CORE
Expression.New( typeof( T ).GetConstructor( _innerExceptionConstructorParameterTypes ), message, innerException ),
#else
Expression.New( typeof( T ).GetTypeInfo().DeclaredConstructors.Single( c => c.GetParameters().Select( p => p.ParameterType ).SequenceEqual( _innerExceptionConstructorParameterTypes ) ), message, innerException ),
#endif // !NETFX_CORE
message,
innerException
).Compile();
#else
this._innerExceptionConstructor = ( msg, inner ) => ReflectionExtensions.CreateInstancePreservingExceptionType<T>( typeof( T ), msg, inner );
#endif // !UNITY
}
catch ( Exception ex )
{
this._constructorException = ex;
}
}
/// <summary>
/// Tests the exception.
/// </summary>
public void TestException()
{
if ( this._constructorException != null )
{
Assert.Fail( this._constructorException.ToString() );
}
this.TestDefaultConstructor();
this.TestMessageConstructor_WithMessage_SetToMessage();
this.TestMessageConstructor_WithNull_SetToDefaultMessage();
this.TestInnerExceptionConstructor_WithMessageAndInnerException_SetToMessageAndInnerException();
this.TestInnerExceptionConstructor_Null_SetToDefaultMessageAndNullInnerException();
#if !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3
this.TestSerialization();
#if !NETSTANDARD2_0
this.TestSerializationOnPartialTrust();
#endif // !NETSTANDARD2_0
#endif // !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3
}
private void TestDefaultConstructor()
{
var target = this._defaultConstructor();
Assert.That( target.Message, Is.Not.Null.And.Not.Empty, "Message should not be null nor empty." );
TestToString( target, typeof( T ).Name + "()" );
}
private void TestMessageConstructor_WithMessage_SetToMessage()
{
var message = Guid.NewGuid().ToString();
var target = this._messageConstructor( message );
Assert.That( target.Message, Is.Not.Null.And.Contains( message ), "Message should contain message argument." );
TestToString( target, typeof( T ).Name + "()" );
}
private void TestMessageConstructor_WithNull_SetToDefaultMessage()
{
var defaultInstance = this._defaultConstructor();
var target = this._messageConstructor( null );
Assert.That( target.Message, Is.Not.Null.And.Contains( defaultInstance.Message ), "Message should equal to default message." );
TestToString( target, typeof( T ).Name + "()" );
}
private void TestInnerExceptionConstructor_WithMessageAndInnerException_SetToMessageAndInnerException()
{
var message = Guid.NewGuid().ToString();
var innerException = new Exception();
var target = this._innerExceptionConstructor( message, innerException );
Assert.That( target.Message, Is.Not.Null.And.Contains( message ), "Message should contain message argument." );
Assert.That( target.InnerException, Is.SameAs( innerException ), "InnerException should contain innerException argument." );
TestToString( target, typeof( T ).Name + "()" );
}
private void TestInnerExceptionConstructor_Null_SetToDefaultMessageAndNullInnerException()
{
var defaultInstance = this._defaultConstructor();
var target = this._innerExceptionConstructor( null, null );
Assert.That( target.Message, Is.Not.Null.And.Contains( defaultInstance.Message ), "Message should equal to default message." );
Assert.That( target.InnerException, Is.Null, "InnerException should be null." );
TestToString( target, typeof( T ).Name + "()" );
}
private static void TestToString( T target, string ctor )
{
TestToStringCore( MakeStackTrace( target ), ctor );
}
private static T MakeStackTrace( T target )
{
try
{
throw target;
}
catch ( T ex )
{
return ex;
}
}
private static void TestToStringCore( T target, string ctor )
{
Assert.That( target.ToString(), Is.Not.Null.And.Not.Empty.And.Contains( target.Message ).And.Contains( target.GetType().FullName ).And.Contains( target.StackTrace ), "ToString() should contain Message, Type.FullName, and StackTrace ({0}).", ctor );
if ( target.InnerException != null )
{
Assert.That( target.ToString(), Is.Not.Null.And.Contains( target.InnerException.Message ), "ToString() should contain InnerException ({0}).", ctor );
}
}
#if !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3
private void TestSerialization()
{
#if !NETSTANDARD2_0
Assert.That( typeof( T ), Is.BinarySerializable );
#else // !NETSTANDARD2_0
Assert.That( typeof( T ).IsSerializable, Is.True );
#endif // !NETSTANDARD2_0
var innerMessage = Guid.NewGuid().ToString();
var message = Guid.NewGuid().ToString();
var target = this._innerExceptionConstructor( message, new Exception( innerMessage ) );
using ( var buffer = new MemoryStream() )
{
var serializer = new BinaryFormatter();
serializer.Serialize( buffer, target );
buffer.Position = 0;
var deserialized = serializer.Deserialize( buffer ) as T;
Assert.That( deserialized, Is.Not.Null );
Assert.That( deserialized.Message, Is.EqualTo( target.Message ) );
Assert.That( deserialized.InnerException, Is.Not.Null.And.TypeOf( typeof( Exception ) ) );
Assert.That( deserialized.InnerException.Message, Is.EqualTo( target.InnerException.Message ) );
}
}
#if !NETSTANDARD2_0
private void TestSerializationOnPartialTrust()
{
var appDomainSetUp = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase };
var evidence = new Evidence();
#if MONO || NET35
#pragma warning disable 0612
// TODO: patching
// currently, Mono does not declare AddHostEvidence
evidence.AddHost( new Zone( SecurityZone.Internet ) );
#pragma warning restore 0612
var permisions = GetDefaultInternetZoneSandbox();
#else
evidence.AddHostEvidence( new Zone( SecurityZone.Internet ) );
var permisions = SecurityManager.GetStandardSandbox( evidence );
#endif
AppDomain workerDomain = AppDomain.CreateDomain( "PartialTrust", evidence, appDomainSetUp, permisions, GetStrongName( this.GetType() ), GetStrongName( typeof( Assert ) ) );
try
{
var innerMessage = Guid.NewGuid().ToString();
var message = Guid.NewGuid().ToString();
workerDomain.SetData( "MsgPack.GenericExceptionTester.InnerMessage", innerMessage );
workerDomain.SetData( "MsgPack.GenericExceptionTester.Message", message );
workerDomain.SetData( "MsgPack.GenericExceptionTester.Proxy", this );
workerDomain.DoCallBack( TestSerializationOnPartialTrustCore );
var target = workerDomain.GetData( "MsgPack.GenericExceptionTester.Target" ) as T;
Assert.That( target, Is.Not.Null );
Assert.That( target.Message, Is.EqualTo( target.Message ) );
Assert.That( target.InnerException is Exception, target.InnerException == null ? "(null)" : target.InnerException.GetType().ToString() );
Assert.That( target.InnerException.Message, Is.EqualTo( target.InnerException.Message ) );
}
finally
{
AppDomain.Unload( workerDomain );
}
}
#if MONO || NET35
private static PermissionSet GetDefaultInternetZoneSandbox()
{
var permissions = new PermissionSet( PermissionState.None );
permissions.AddPermission(
new FileDialogPermission(
FileDialogPermissionAccess.Open
)
);
permissions.AddPermission(
new IsolatedStorageFilePermission( PermissionState.None )
{
UsageAllowed = IsolatedStorageContainment.ApplicationIsolationByUser,
UserQuota = 1024000
}
);
permissions.AddPermission(
new SecurityPermission(
SecurityPermissionFlag.Execution |
SecurityPermissionFlag.SkipVerification // for unsafe code
)
);
permissions.AddPermission(
new UIPermission(
UIPermissionWindow.SafeTopLevelWindows,
UIPermissionClipboard.OwnClipboard
)
);
return permissions;
}
#endif // if MONO || NET35
public static void TestSerializationOnPartialTrustCore()
{
var innerMessage = AppDomain.CurrentDomain.GetData( "MsgPack.GenericExceptionTester.InnerMessage" ) as string;
var message = AppDomain.CurrentDomain.GetData( "MsgPack.GenericExceptionTester.Message" ) as string;
var instance = AppDomain.CurrentDomain.GetData( "MsgPack.GenericExceptionTester.Proxy" ) as GenericExceptionTester<T>;
var target = instance.CreateTargetInstance( message, new Exception( innerMessage ) );
Assert.That( target, Is.Not.Null );
Assert.That( target.Message, Is.EqualTo( target.Message ) );
Assert.That( target.InnerException is Exception, target.InnerException == null ? "(null)" : target.InnerException.GetType().ToString() );
Assert.That( target.InnerException.Message, Is.EqualTo( target.InnerException.Message ) );
AppDomain.CurrentDomain.SetData( "MsgPack.GenericExceptionTester.Target", target );
}
private static StrongName GetStrongName( Type type )
{
var assemblyName = type.Assembly.GetName();
return new StrongName( new StrongNamePublicKeyBlob( assemblyName.GetPublicKey() ), assemblyName.Name, assemblyName.Version );
}
#endif // !NETSTANDARD2_0
#endif // !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3
}
}
| |
// <copyright file="IntegerTheoryTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Globalization;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.EuclidTests
{
/// <summary>
/// Integer theory tests.
/// </summary>
[TestFixture, Category("Functions")]
public class IntegerTheoryTest
{
[Test]
public void TestModulus()
{
Assert.That(Euclid.Modulus(0, 3), Is.EqualTo(0));
Assert.That(Euclid.Modulus(2, 3), Is.EqualTo(2));
Assert.That(Euclid.Modulus(3, 3), Is.EqualTo(0));
Assert.That(Euclid.Modulus(4, 3), Is.EqualTo(1));
Assert.That(Euclid.Modulus(6, 3), Is.EqualTo(0));
Assert.That(Euclid.Modulus(-1, 3), Is.EqualTo(2));
Assert.That(Euclid.Modulus(-2, 3), Is.EqualTo(1));
Assert.That(Euclid.Modulus(-3, 3), Is.EqualTo(0));
Assert.That(Euclid.Modulus(-4, 3), Is.EqualTo(2));
Assert.That(Euclid.Modulus(0, -3), Is.EqualTo(0));
Assert.That(Euclid.Modulus(2, -3), Is.EqualTo(-1));
Assert.That(Euclid.Modulus(3, -3), Is.EqualTo(0));
Assert.That(Euclid.Modulus(4, -3), Is.EqualTo(-2));
Assert.That(Euclid.Modulus(6, -3), Is.EqualTo(0));
Assert.That(Euclid.Modulus(-1, -3), Is.EqualTo(-1));
Assert.That(Euclid.Modulus(-2, -3), Is.EqualTo(-2));
Assert.That(Euclid.Modulus(-3, -3), Is.EqualTo(0));
Assert.That(Euclid.Modulus(-4, -3), Is.EqualTo(-1));
}
[Test]
public void TestModulusFloatingPoint()
{
Assert.That(Euclid.Modulus(0.2, 3), Is.EqualTo(0.2).Within(1e-12));
Assert.That(Euclid.Modulus(2.2, 3), Is.EqualTo(2.2).Within(1e-12));
Assert.That(Euclid.Modulus(3.2, 3), Is.EqualTo(0.2).Within(1e-12));
Assert.That(Euclid.Modulus(4.2, 3), Is.EqualTo(1.2).Within(1e-12));
Assert.That(Euclid.Modulus(6.2, 3), Is.EqualTo(0.2).Within(1e-12));
Assert.That(Euclid.Modulus(-1.2, 3), Is.EqualTo(1.8).Within(1e-12));
Assert.That(Euclid.Modulus(-2.2, 3), Is.EqualTo(0.8).Within(1e-12));
Assert.That(Euclid.Modulus(-3.2, 3), Is.EqualTo(2.8).Within(1e-12));
Assert.That(Euclid.Modulus(-4.2, 3), Is.EqualTo(1.8).Within(1e-12));
Assert.That(Euclid.Modulus(0.2, -3), Is.EqualTo(-2.8).Within(1e-12));
Assert.That(Euclid.Modulus(2.2, -3), Is.EqualTo(-0.8).Within(1e-12));
Assert.That(Euclid.Modulus(3.2, -3), Is.EqualTo(-2.8).Within(1e-12));
Assert.That(Euclid.Modulus(4.2, -3), Is.EqualTo(-1.8).Within(1e-12));
Assert.That(Euclid.Modulus(6.2, -3), Is.EqualTo(-2.8).Within(1e-12));
Assert.That(Euclid.Modulus(-1.2, -3), Is.EqualTo(-1.2).Within(1e-12));
Assert.That(Euclid.Modulus(-2.2, -3), Is.EqualTo(-2.2).Within(1e-12));
Assert.That(Euclid.Modulus(-3.2, -3), Is.EqualTo(-0.2).Within(1e-12));
Assert.That(Euclid.Modulus(-4.2, -3), Is.EqualTo(-1.2).Within(1e-12));
}
[Test]
public void TestRemainder()
{
Assert.That(Euclid.Remainder(0, 3), Is.EqualTo(0));
Assert.That(Euclid.Remainder(2, 3), Is.EqualTo(2));
Assert.That(Euclid.Remainder(3, 3), Is.EqualTo(0));
Assert.That(Euclid.Remainder(4, 3), Is.EqualTo(1));
Assert.That(Euclid.Remainder(6, 3), Is.EqualTo(0));
Assert.That(Euclid.Remainder(-1, 3), Is.EqualTo(-1));
Assert.That(Euclid.Remainder(-2, 3), Is.EqualTo(-2));
Assert.That(Euclid.Remainder(-3, 3), Is.EqualTo(0));
Assert.That(Euclid.Remainder(-4, 3), Is.EqualTo(-1));
Assert.That(Euclid.Remainder(0, -3), Is.EqualTo(0));
Assert.That(Euclid.Remainder(2, -3), Is.EqualTo(2));
Assert.That(Euclid.Remainder(3, -3), Is.EqualTo(0));
Assert.That(Euclid.Remainder(4, -3), Is.EqualTo(1));
Assert.That(Euclid.Remainder(6, -3), Is.EqualTo(0));
Assert.That(Euclid.Remainder(-1, -3), Is.EqualTo(-1));
Assert.That(Euclid.Remainder(-2, -3), Is.EqualTo(-2));
Assert.That(Euclid.Remainder(-3, -3), Is.EqualTo(0));
Assert.That(Euclid.Remainder(-4, -3), Is.EqualTo(-1));
}
[Test]
public void TestRemainderFloatingPoint()
{
Assert.That(Euclid.Remainder(0.2, 3), Is.EqualTo(0.2).Within(1e-12));
Assert.That(Euclid.Remainder(2.2, 3), Is.EqualTo(2.2).Within(1e-12));
Assert.That(Euclid.Remainder(3.2, 3), Is.EqualTo(0.2).Within(1e-12));
Assert.That(Euclid.Remainder(4.2, 3), Is.EqualTo(1.2).Within(1e-12));
Assert.That(Euclid.Remainder(6.2, 3), Is.EqualTo(0.2).Within(1e-12));
Assert.That(Euclid.Remainder(-1.2, 3), Is.EqualTo(-1.2).Within(1e-12));
Assert.That(Euclid.Remainder(-2.2, 3), Is.EqualTo(-2.2).Within(1e-12));
Assert.That(Euclid.Remainder(-3.2, 3), Is.EqualTo(-0.2).Within(1e-12));
Assert.That(Euclid.Remainder(-4.2, 3), Is.EqualTo(-1.2).Within(1e-12));
Assert.That(Euclid.Remainder(0.2, -3), Is.EqualTo(0.2).Within(1e-12));
Assert.That(Euclid.Remainder(2.2, -3), Is.EqualTo(2.2).Within(1e-12));
Assert.That(Euclid.Remainder(3.2, -3), Is.EqualTo(0.2).Within(1e-12));
Assert.That(Euclid.Remainder(4.2, -3), Is.EqualTo(1.2).Within(1e-12));
Assert.That(Euclid.Remainder(6.2, -3), Is.EqualTo(0.2).Within(1e-12));
Assert.That(Euclid.Remainder(-1.2, -3), Is.EqualTo(-1.2).Within(1e-12));
Assert.That(Euclid.Remainder(-2.2, -3), Is.EqualTo(-2.2).Within(1e-12));
Assert.That(Euclid.Remainder(-3.2, -3), Is.EqualTo(-0.2).Within(1e-12));
Assert.That(Euclid.Remainder(-4.2, -3), Is.EqualTo(-1.2).Within(1e-12));
}
/// <summary>
/// Test even/odd int32.
/// </summary>
[Test]
public void TestEvenOdd32()
{
Assert.IsTrue(0.IsEven(), "0 is even");
Assert.IsFalse(0.IsOdd(), "0 is not odd");
Assert.IsFalse(1.IsEven(), "1 is not even");
Assert.IsTrue(1.IsOdd(), "1 is odd");
Assert.IsFalse((-1).IsEven(), "-1 is not even");
Assert.IsTrue((-1).IsOdd(), "-1 is odd");
Assert.IsFalse(Int32.MaxValue.IsEven(), "Int32.Max is not even");
Assert.IsTrue(Int32.MaxValue.IsOdd(), "Int32.Max is odd");
Assert.IsTrue(Int32.MinValue.IsEven(), "Int32.Min is even");
Assert.IsFalse(Int32.MinValue.IsOdd(), "Int32.Min is not odd");
}
/// <summary>
/// Test even/odd int64.
/// </summary>
[Test]
public void TestEvenOdd64()
{
Assert.IsTrue(((long)0).IsEven(), "0 is even");
Assert.IsFalse(((long)0).IsOdd(), "0 is not odd");
Assert.IsFalse(((long)1).IsEven(), "1 is not even");
Assert.IsTrue(((long)1).IsOdd(), "1 is odd");
Assert.IsFalse(((long)-1).IsEven(), "-1 is not even");
Assert.IsTrue(((long)-1).IsOdd(), "-1 is odd");
Assert.IsFalse(Int64.MaxValue.IsEven(), "Int64.Max is not even");
Assert.IsTrue(Int64.MaxValue.IsOdd(), "Int64.Max is odd");
Assert.IsTrue(Int64.MinValue.IsEven(), "Int64.Min is even");
Assert.IsFalse(Int64.MinValue.IsOdd(), "Int64.Min is not odd");
}
/// <summary>
/// Test if int32 is power of 2.
/// </summary>
[Test]
public void TestIsPowerOfTwo32()
{
for (var i = 2; i < 31; i++)
{
var x = 1 << i;
Assert.IsTrue(x.IsPowerOfTwo(), x + " (+)");
Assert.IsFalse((x - 1).IsPowerOfTwo(), x + "-1 (-)");
Assert.IsFalse((x + 1).IsPowerOfTwo(), x + "+1 (-)");
Assert.IsFalse((-x).IsPowerOfTwo(), "-" + x + " (-)");
Assert.IsFalse((-x + 1).IsPowerOfTwo(), "-" + x + "+1 (-)");
Assert.IsFalse((-x - 1).IsPowerOfTwo(), "-" + x + "-1 (-)");
}
Assert.IsTrue(4.IsPowerOfTwo(), "4 (+)");
Assert.IsFalse(3.IsPowerOfTwo(), "3 (-)");
Assert.IsTrue(2.IsPowerOfTwo(), "2 (+)");
Assert.IsTrue(1.IsPowerOfTwo(), "1 (+)");
Assert.IsFalse(0.IsPowerOfTwo(), "0 (-)");
Assert.IsFalse((-1).IsPowerOfTwo(), "-1 (-)");
Assert.IsFalse((-2).IsPowerOfTwo(), "-2 (-)");
Assert.IsFalse((-3).IsPowerOfTwo(), "-3 (-)");
Assert.IsFalse((-4).IsPowerOfTwo(), "-4 (-)");
Assert.IsFalse(Int32.MinValue.IsPowerOfTwo(), "Int32.MinValue (-)");
Assert.IsFalse((Int32.MinValue + 1).IsPowerOfTwo(), "Int32.MinValue+1 (-)");
Assert.IsFalse(Int32.MaxValue.IsPowerOfTwo(), "Int32.MaxValue (-)");
Assert.IsFalse((Int32.MaxValue - 1).IsPowerOfTwo(), "Int32.MaxValue-1 (-)");
}
/// <summary>
/// Test if int64 is power of 2.
/// </summary>
[Test]
public void TestIsPowerOfTwo64()
{
for (var i = 2; i < 63; i++)
{
var x = ((long)1) << i;
Assert.IsTrue(x.IsPowerOfTwo(), x + " (+)");
Assert.IsFalse((x - 1).IsPowerOfTwo(), x + "-1 (-)");
Assert.IsFalse((x + 1).IsPowerOfTwo(), x + "+1 (-)");
Assert.IsFalse((-x).IsPowerOfTwo(), "-" + x + " (-)");
Assert.IsFalse((-x + 1).IsPowerOfTwo(), "-" + x + "+1 (-)");
Assert.IsFalse((-x - 1).IsPowerOfTwo(), "-" + x + "-1 (-)");
}
Assert.IsTrue(((long)4).IsPowerOfTwo(), "4 (+)");
Assert.IsFalse(((long)3).IsPowerOfTwo(), "3 (-)");
Assert.IsTrue(((long)2).IsPowerOfTwo(), "2 (+)");
Assert.IsTrue(((long)1).IsPowerOfTwo(), "1 (+)");
Assert.IsFalse(((long)0).IsPowerOfTwo(), "0 (-)");
Assert.IsFalse(((long)-1).IsPowerOfTwo(), "-1 (-)");
Assert.IsFalse(((long)-2).IsPowerOfTwo(), "-2 (-)");
Assert.IsFalse(((long)-3).IsPowerOfTwo(), "-3 (-)");
Assert.IsFalse(((long)-4).IsPowerOfTwo(), "-4 (-)");
Assert.IsFalse(Int64.MinValue.IsPowerOfTwo(), "Int32.MinValue (-)");
Assert.IsFalse((Int64.MinValue + 1).IsPowerOfTwo(), "Int32.MinValue+1 (-)");
Assert.IsFalse(Int64.MaxValue.IsPowerOfTwo(), "Int32.MaxValue (-)");
Assert.IsFalse((Int64.MaxValue - 1).IsPowerOfTwo(), "Int32.MaxValue-1 (-)");
}
/// <summary>
/// Ceiling to power of two handles positive int32 correctly.
/// </summary>
[Test]
public void CeilingToPowerOfHandlesPositiveIntegersCorrectly32()
{
Assert.AreEqual(0, 0.CeilingToPowerOfTwo(), "0");
Assert.AreEqual(1, 1.CeilingToPowerOfTwo(), "1");
Assert.AreEqual(2, 2.CeilingToPowerOfTwo(), "2");
Assert.AreEqual(4, 3.CeilingToPowerOfTwo(), "3");
Assert.AreEqual(4, 4.CeilingToPowerOfTwo(), "4");
for (var i = 2; i < 31; i++)
{
var x = 1 << i;
Assert.AreEqual(x, x.CeilingToPowerOfTwo(), x.ToString(CultureInfo.InvariantCulture));
Assert.AreEqual(x, (x - 1).CeilingToPowerOfTwo(), x + "-1");
Assert.AreEqual(x, ((x >> 1) + 1).CeilingToPowerOfTwo(), x + "/2+1");
Assert.AreEqual(0, (-x).CeilingToPowerOfTwo(), "-" + x);
}
const int MaxPowerOfTwo = 0x40000000;
Assert.AreEqual(MaxPowerOfTwo, MaxPowerOfTwo.CeilingToPowerOfTwo(), "max");
Assert.AreEqual(MaxPowerOfTwo, (MaxPowerOfTwo - 1).CeilingToPowerOfTwo(), "max");
}
/// <summary>
/// Ceiling to power of two handles positive int64 correctly.
/// </summary>
[Test]
public void CeilingToPowerOfHandlesPositiveIntegersCorrectly64()
{
Assert.AreEqual(0, ((long)0).CeilingToPowerOfTwo(), "0");
Assert.AreEqual(1, ((long)1).CeilingToPowerOfTwo(), "1");
Assert.AreEqual(2, ((long)2).CeilingToPowerOfTwo(), "2");
Assert.AreEqual(4, ((long)3).CeilingToPowerOfTwo(), "3");
Assert.AreEqual(4, ((long)4).CeilingToPowerOfTwo(), "4");
for (var i = 2; i < 63; i++)
{
var x = ((long)1) << i;
Assert.AreEqual(x, x.CeilingToPowerOfTwo(), x.ToString(CultureInfo.InvariantCulture));
Assert.AreEqual(x, (x - 1).CeilingToPowerOfTwo(), x + "-1");
Assert.AreEqual(x, ((x >> 1) + 1).CeilingToPowerOfTwo(), x + "/2+1");
Assert.AreEqual(0, (-x).CeilingToPowerOfTwo(), "-" + x);
}
const long MaxPowerOfTwo = 0x4000000000000000;
Assert.AreEqual(MaxPowerOfTwo, MaxPowerOfTwo.CeilingToPowerOfTwo(), "max");
Assert.AreEqual(MaxPowerOfTwo, (MaxPowerOfTwo - 1).CeilingToPowerOfTwo(), "max");
}
/// <summary>
/// Ceiling to power of two returns zero for negative int32.
/// </summary>
[Test]
public void CeilingToPowerOfTwoReturnsZeroForNegativeNumbers32()
{
Assert.AreEqual(0, (-1).CeilingToPowerOfTwo(), "-1");
Assert.AreEqual(0, (-2).CeilingToPowerOfTwo(), "-2");
Assert.AreEqual(0, (-3).CeilingToPowerOfTwo(), "-3");
Assert.AreEqual(0, (-4).CeilingToPowerOfTwo(), "-4");
Assert.AreEqual(0, Int32.MinValue.CeilingToPowerOfTwo(), "Int32.MinValue");
Assert.AreEqual(0, (Int32.MinValue + 1).CeilingToPowerOfTwo(), "Int32.MinValue+1");
}
/// <summary>
/// Ceiling to power of two returns zero for negative int64.
/// </summary>
[Test]
public void CeilingToPowerOfTwoReturnsZeroForNegativeNumbers64()
{
Assert.AreEqual(0, ((long)-1).CeilingToPowerOfTwo(), "-1");
Assert.AreEqual(0, ((long)-2).CeilingToPowerOfTwo(), "-2");
Assert.AreEqual(0, ((long)-3).CeilingToPowerOfTwo(), "-3");
Assert.AreEqual(0, ((long)-4).CeilingToPowerOfTwo(), "-4");
Assert.AreEqual(0, Int64.MinValue.CeilingToPowerOfTwo(), "Int64.MinValue");
Assert.AreEqual(0, (Int64.MinValue + 1).CeilingToPowerOfTwo(), "Int64.MinValue+1");
}
/// <summary>
/// Ceiling to power of two throws <c>ArgumentOutOfRangeException</c> when result would overflow int32.
/// </summary>
[Test]
public void CeilingToPowerOfTwoThrowsWhenResultWouldOverflow32()
{
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => Int32.MaxValue.CeilingToPowerOfTwo());
const int MaxPowerOfTwo = 0x40000000;
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => (MaxPowerOfTwo + 1).CeilingToPowerOfTwo());
Assert.DoesNotThrow(
() => (MaxPowerOfTwo - 1).CeilingToPowerOfTwo());
}
/// <summary>
/// Ceiling to power of two throws <c>ArgumentOutOfRangeException</c> when result would overflow int64.
/// </summary>
[Test]
public void CeilingToPowerOfTwoThrowsWhenResultWouldOverflow64()
{
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => Int64.MaxValue.CeilingToPowerOfTwo());
const long MaxPowerOfTwo = 0x4000000000000000;
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => (MaxPowerOfTwo + 1).CeilingToPowerOfTwo());
Assert.DoesNotThrow(
() => (MaxPowerOfTwo - 1).CeilingToPowerOfTwo());
}
/// <summary>
/// Power of two matches floating point power int32.
/// </summary>
[Test]
public void PowerOfTwoMatchesFloatingPointPower32()
{
for (var i = 0; i < 31; i++)
{
Assert.AreEqual(Math.Round(Math.Pow(2, i)), i.PowerOfTwo());
}
}
/// <summary>
/// Power of two matches floating point power int64.
/// </summary>
[Test]
public void PowerOfTwoMatchesFloatingPointPower64()
{
for (var i = 0; i < 63; i++)
{
Assert.AreEqual(Math.Round(Math.Pow(2, i)), ((long)i).PowerOfTwo());
}
}
/// <summary>
/// Power of two throws <c>ArgumentOutOfRangeException</c> when int32 is out of range.
/// </summary>
[Test]
public void PowerOfTwoThrowsWhenOutOfRange32()
{
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => (-1).PowerOfTwo());
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => 31.PowerOfTwo());
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => Int32.MinValue.PowerOfTwo());
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => Int32.MaxValue.PowerOfTwo());
Assert.DoesNotThrow(
() => 30.PowerOfTwo());
Assert.DoesNotThrow(
() => 0.PowerOfTwo());
}
/// <summary>
/// Power of two throws <c>ArgumentOutOfRangeException</c> when int64 is out of range.
/// </summary>
[Test]
public void PowerOfTwoThrowsWhenOutOfRange64()
{
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => ((long)-1).PowerOfTwo());
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => ((long)63).PowerOfTwo());
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => Int64.MinValue.PowerOfTwo());
Assert.Throws(
typeof(ArgumentOutOfRangeException),
() => Int64.MaxValue.PowerOfTwo());
Assert.DoesNotThrow(
() => ((long)62).PowerOfTwo());
Assert.DoesNotThrow(
() => ((long)0).PowerOfTwo());
}
/// <summary>
/// Log2 matches floating point for int32.
/// </summary>
[Test]
public void Log2MatchesFloatingPoint32()
{
for (var i = 0; i < 31; i++)
{
int number = i.PowerOfTwo();
Assert.AreEqual((int)Math.Log(number, 2), number.Log2());
Assert.AreEqual((int)Math.Log(number + 1, 2), (number + 1).Log2());
if (number > 1)
{
Assert.AreEqual((int)Math.Log(number - 1, 2), (number - 1).Log2());
}
}
}
/// <summary>
/// Test if int32 is perfect square.
/// </summary>
[Test]
public void TestIsPerfectSquare32()
{
// Test all known suares
var lastRadix = (int)Math.Floor(Math.Sqrt(Int32.MaxValue));
for (var i = 0; i <= lastRadix; i++)
{
Assert.IsTrue((i * i).IsPerfectSquare(), i + "^2 (+)");
}
// Test 1-offset from all known squares
for (var i = 2; i <= lastRadix; i++)
{
Assert.IsFalse(((i * i) - 1).IsPerfectSquare(), i + "^2-1 (-)");
Assert.IsFalse(((i * i) + 1).IsPerfectSquare(), i + "^2+1 (-)");
}
// Selected Cases
Assert.IsTrue(100000000.IsPerfectSquare(), "100000000 (+)");
Assert.IsFalse(100000001.IsPerfectSquare(), "100000001 (-)");
Assert.IsFalse(99999999.IsPerfectSquare(), "99999999 (-)");
Assert.IsFalse((-4).IsPerfectSquare(), "-4 (-)");
Assert.IsFalse(Int32.MinValue.IsPerfectSquare(), "Int32.MinValue (-)");
Assert.IsFalse(Int32.MaxValue.IsPerfectSquare(), "Int32.MaxValue (-)");
Assert.IsTrue(1.IsPerfectSquare(), "1 (+)");
Assert.IsTrue(0.IsPerfectSquare(), "0 (+)");
Assert.IsFalse((-1).IsPerfectSquare(), "-1 (-)");
}
/// <summary>
/// Test if int64 is perfect square.
/// </summary>
[Test]
public void TestIsPerfectSquare64()
{
// Test all known suares
for (var i = 0; i < 32; i++)
{
var t = ((long)1) << i;
Assert.IsTrue((t * t).IsPerfectSquare(), t + "^2 (+)");
}
// Test 1-offset from all known squares
for (var i = 1; i < 32; i++)
{
var t = ((long)1) << i;
Assert.IsFalse(((t * t) - 1).IsPerfectSquare(), t + "^2-1 (-)");
Assert.IsFalse(((t * t) + 1).IsPerfectSquare(), t + "^2+1 (-)");
}
// Selected Cases
Assert.IsTrue(1000000000000000000.IsPerfectSquare(), "1000000000000000000 (+)");
Assert.IsFalse(1000000000000000001.IsPerfectSquare(), "1000000000000000001 (-)");
Assert.IsFalse(999999999999999999.IsPerfectSquare(), "999999999999999999 (-)");
Assert.IsFalse(999999999999999993.IsPerfectSquare(), "999999999999999993 (-)");
Assert.IsFalse(((long)-4).IsPerfectSquare(), "-4 (-)");
Assert.IsFalse(Int64.MinValue.IsPerfectSquare(), "Int32.MinValue (-)");
Assert.IsFalse(Int64.MaxValue.IsPerfectSquare(), "Int32.MaxValue (-)");
Assert.IsTrue(((long)1).IsPerfectSquare(), "1 (+)");
Assert.IsTrue(((long)0).IsPerfectSquare(), "0 (+)");
Assert.IsFalse(((long)-1).IsPerfectSquare(), "-1 (-)");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Persistence.Caching;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.cache;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.language;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.web;
using umbraco.cms.helpers;
using umbraco.DataLayer;
using umbraco.interfaces;
namespace umbraco.cms.businesslogic.propertytype
{
/// <summary>
/// Summary description for propertytype.
/// </summary>
[Obsolete("Use the ContentTypeService instead")]
public class PropertyType
{
#region Declarations
private readonly int _contenttypeid;
private readonly int _id;
private int _DataTypeId;
private string _alias;
private string _description = "";
private bool _mandatory;
private string _name;
private int _sortOrder;
private int _tabId;
private int _propertyTypeGroup;
private string _validationRegExp = "";
#endregion
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
#region Constructors
public PropertyType(int id)
{
using (IRecordsReader dr = SqlHelper.ExecuteReader(
"Select mandatory, DataTypeId, propertyTypeGroupId, ContentTypeId, sortOrder, alias, name, validationRegExp, description from cmsPropertyType where id=@id",
SqlHelper.CreateParameter("@id", id)))
{
if (!dr.Read())
throw new ArgumentException("Propertytype with id: " + id + " doesnt exist!");
_mandatory = dr.GetBoolean("mandatory");
_id = id;
if (!dr.IsNull("propertyTypeGroupId"))
{
_propertyTypeGroup = dr.GetInt("propertyTypeGroupId");
//TODO: Remove after refactoring!
_tabId = _propertyTypeGroup;
}
_sortOrder = dr.GetInt("sortOrder");
_alias = dr.GetString("alias");
_name = dr.GetString("Name");
_validationRegExp = dr.GetString("validationRegExp");
_DataTypeId = dr.GetInt("DataTypeId");
_contenttypeid = dr.GetInt("contentTypeId");
_description = dr.GetString("description");
}
}
#endregion
#region Properties
public DataTypeDefinition DataTypeDefinition
{
get { return DataTypeDefinition.GetDataTypeDefinition(_DataTypeId); }
set
{
_DataTypeId = value.Id;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set DataTypeId = " + value.Id + " where id=" + Id);
}
}
public int Id
{
get { return _id; }
}
/// <summary>
/// Setting the tab id is not meant to be used directly in code. Use the ContentType SetTabOnPropertyType method instead
/// as that will handle all of the caching properly, this will not.
/// </summary>
/// <remarks>
/// Setting the tab id to a negative value will actually set the value to NULL in the database
/// </remarks>
[Obsolete("Use the new PropertyTypeGroup parameter", false)]
public int TabId
{
get { return _tabId; }
set
{
_tabId = value;
PropertyTypeGroup = value;
InvalidateCache();
}
}
public int PropertyTypeGroup
{
get { return _propertyTypeGroup; }
set
{
_propertyTypeGroup = value;
object dbPropertyTypeGroup = value;
if (value < 1)
{
dbPropertyTypeGroup = DBNull.Value;
}
SqlHelper.ExecuteNonQuery("Update cmsPropertyType set propertyTypeGroupId = @propertyTypeGroupId where id = @id",
SqlHelper.CreateParameter("@propertyTypeGroupId", dbPropertyTypeGroup),
SqlHelper.CreateParameter("@id", Id));
}
}
public bool Mandatory
{
get { return _mandatory; }
set
{
_mandatory = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set mandatory = @mandatory where id = @id",
SqlHelper.CreateParameter("@mandatory", value),
SqlHelper.CreateParameter("@id", Id));
}
}
public string ValidationRegExp
{
get { return _validationRegExp; }
set
{
_validationRegExp = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set validationRegExp = @validationRegExp where id = @id",
SqlHelper.CreateParameter("@validationRegExp", value), SqlHelper.CreateParameter("@id", Id));
}
}
public string Description
{
get
{
if (_description != null)
{
if (!_description.StartsWith("#"))
return _description;
else
{
Language lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name);
if (lang != null)
{
if (Dictionary.DictionaryItem.hasKey(_description.Substring(1, _description.Length - 1)))
{
var di =
new Dictionary.DictionaryItem(_description.Substring(1, _description.Length - 1));
return di.Value(lang.id);
}
}
}
return "[" + _description + "]";
}
return _description;
}
set
{
_description = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set description = @description where id = @id",
SqlHelper.CreateParameter("@description", value),
SqlHelper.CreateParameter("@id", Id));
}
}
public int SortOrder
{
get { return _sortOrder; }
set
{
_sortOrder = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"Update cmsPropertyType set sortOrder = @sortOrder where id = @id",
SqlHelper.CreateParameter("@sortOrder", value),
SqlHelper.CreateParameter("@id", Id));
}
}
public string Alias
{
get { return _alias; }
set
{
_alias = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery("Update cmsPropertyType set alias = @alias where id= @id",
SqlHelper.CreateParameter("@alias", Casing.SafeAliasWithForcingCheck(_alias)),
SqlHelper.CreateParameter("@id", Id));
}
}
public int ContentTypeId
{
get { return _contenttypeid; }
}
public string Name
{
get
{
if (!_name.StartsWith("#"))
return _name;
else
{
Language lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name);
if (lang != null)
{
if (Dictionary.DictionaryItem.hasKey(_name.Substring(1, _name.Length - 1)))
{
var di = new Dictionary.DictionaryItem(_name.Substring(1, _name.Length - 1));
return di.Value(lang.id);
}
}
return "[" + _name + "]";
}
}
set
{
_name = value;
InvalidateCache();
SqlHelper.ExecuteNonQuery(
"UPDATE cmsPropertyType SET name=@name WHERE id=@id",
SqlHelper.CreateParameter("@name", _name),
SqlHelper.CreateParameter("@id", Id));
}
}
#endregion
#region Methods
public string GetRawName()
{
return _name;
}
public string GetRawDescription()
{
return _description;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static PropertyType MakeNew(DataTypeDefinition dt, ContentType ct, string name, string alias)
{
//make sure that the alias starts with a letter
if (string.IsNullOrEmpty(alias))
throw new ArgumentNullException("alias");
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (!Char.IsLetter(alias[0]))
throw new ArgumentException("alias must start with a letter", "alias");
PropertyType pt;
try
{
// The method is synchronized, but we'll still look it up with an additional parameter (alias)
SqlHelper.ExecuteNonQuery(
"INSERT INTO cmsPropertyType (DataTypeId, ContentTypeId, alias, name) VALUES (@DataTypeId, @ContentTypeId, @alias, @name)",
SqlHelper.CreateParameter("@DataTypeId", dt.Id),
SqlHelper.CreateParameter("@ContentTypeId", ct.Id),
SqlHelper.CreateParameter("@alias", alias),
SqlHelper.CreateParameter("@name", name));
pt =
new PropertyType(
SqlHelper.ExecuteScalar<int>("SELECT MAX(id) FROM cmsPropertyType WHERE alias=@alias",
SqlHelper.CreateParameter("@alias", alias)));
}
finally
{
// Clear cached items
ApplicationContext.Current.ApplicationCache.ClearCacheByKeySearch(CacheKeys.PropertyTypeCacheKey);
}
return pt;
}
public static PropertyType[] GetAll()
{
var result = GetPropertyTypes();
return result.ToArray();
}
public static IEnumerable<PropertyType> GetPropertyTypes()
{
var result = new List<PropertyType>();
using (IRecordsReader dr =
SqlHelper.ExecuteReader("select id from cmsPropertyType order by Name"))
{
while (dr.Read())
{
PropertyType pt = GetPropertyType(dr.GetInt("id"));
if (pt != null)
result.Add(pt);
}
}
return result;
}
public static IEnumerable<PropertyType> GetPropertyTypesByGroup(int groupId, List<int> contentTypeIds)
{
return GetPropertyTypesByGroup(groupId).Where(x => contentTypeIds.Contains(x.ContentTypeId));
}
public static IEnumerable<PropertyType> GetPropertyTypesByGroup(int groupId)
{
var result = new List<PropertyType>();
using (IRecordsReader dr =
SqlHelper.ExecuteReader("SELECT id FROM cmsPropertyType WHERE propertyTypeGroupId = @groupId order by SortOrder",
SqlHelper.CreateParameter("@groupId", groupId)))
{
while (dr.Read())
{
PropertyType pt = GetPropertyType(dr.GetInt("id"));
if (pt != null)
result.Add(pt);
}
}
return result;
}
/// <summary>
/// Returns all property types based on the data type definition
/// </summary>
/// <param name="dataTypeDefId"></param>
/// <returns></returns>
public static IEnumerable<PropertyType> GetByDataTypeDefinition(int dataTypeDefId)
{
var result = new List<PropertyType>();
using (IRecordsReader dr =
SqlHelper.ExecuteReader(
"select id, Name from cmsPropertyType where dataTypeId=@dataTypeId order by Name",
SqlHelper.CreateParameter("@dataTypeId", dataTypeDefId)))
{
while (dr.Read())
{
PropertyType pt = GetPropertyType(dr.GetInt("id"));
if (pt != null)
result.Add(pt);
}
}
return result.ToList();
}
public void delete()
{
// flush cache
FlushCache();
// Delete all properties of propertytype
CleanPropertiesOnDeletion(_contenttypeid);
//delete tag refs
SqlHelper.ExecuteNonQuery("Delete from cmsTagRelationship where propertyTypeId = " + Id);
// Delete PropertyType ..
SqlHelper.ExecuteNonQuery("Delete from cmsPropertyType where id = " + Id);
// delete cache from either master (via tabid) or current contentype
FlushCacheBasedOnTab();
InvalidateCache();
}
public void FlushCacheBasedOnTab()
{
if (TabId != 0)
{
ContentType.FlushFromCache(ContentType.Tab.GetTab(TabId).ContentType);
}
else
{
ContentType.FlushFromCache(ContentTypeId);
}
}
private void CleanPropertiesOnDeletion(int contentTypeId)
{
// first delete from all master document types
//TODO: Verify no endless loops with mixins
DocumentType.GetAllAsList().FindAll(dt => dt.MasterContentTypes.Contains(contentTypeId)).ForEach(
dt => CleanPropertiesOnDeletion(dt.Id));
//Initially Content.getContentOfContentType() was called, but because this doesn't include members we resort to sql lookups and deletes
var tmp = new List<int>();
IRecordsReader dr = SqlHelper.ExecuteReader("SELECT nodeId FROM cmsContent INNER JOIN umbracoNode ON cmsContent.nodeId = umbracoNode.id WHERE ContentType = " + contentTypeId + " ORDER BY umbracoNode.text ");
while (dr.Read()) tmp.Add(dr.GetInt("nodeId"));
dr.Close();
foreach (var contentId in tmp)
{
SqlHelper.ExecuteNonQuery("DELETE FROM cmsPropertyData WHERE PropertyTypeId =" + this.Id + " AND contentNodeId = " + contentId);
}
// invalidate content type cache
ContentType.FlushFromCache(contentTypeId);
}
public IDataType GetEditControl(object value, bool isPostBack)
{
IDataType dt = DataTypeDefinition.DataType;
dt.DataEditor.Editor.ID = Alias;
IData df = DataTypeDefinition.DataType.Data;
(dt.DataEditor.Editor).ID = Alias;
if (!isPostBack)
{
if (value != null)
dt.Data.Value = value;
else
dt.Data.Value = "";
}
return dt;
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public virtual void Save()
{
FlushCache();
}
protected virtual void FlushCache()
{
// clear local cache
ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id));
// clear cache in contentype
ApplicationContext.Current.ApplicationCache.ClearCacheItem(CacheKeys.ContentTypePropertiesCacheKey + _contenttypeid);
//Ensure that DocumentTypes are reloaded from db by clearing cache - this similar to the Save method on DocumentType.
//NOTE Would be nice if we could clear cache by type instead of emptying the entire cache.
InMemoryCacheProvider.Current.Clear();
RuntimeCacheProvider.Current.Clear();
}
public static PropertyType GetPropertyType(int id)
{
return ApplicationContext.Current.ApplicationCache.GetCacheItem(
GetCacheKey(id),
TimeSpan.FromMinutes(30),
delegate
{
try
{
return new PropertyType(id);
}
catch
{
return null;
}
});
}
private void InvalidateCache()
{
ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id));
}
private static string GetCacheKey(int id)
{
return CacheKeys.PropertyTypeCacheKey + id;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Collections;
//create for delegate combine(delegate a,delagate b) testing
namespace DelegateTest
{
delegate bool booldelegate();
delegate void voiddelegate();
delegate void delegatecombine(booldelegate delgate1, booldelegate delgate2);
public class DelegateCombine1
{
const string c_StartWrok = "Stark";
const string c_Working = "Working";
enum identify_null
{
c_Start_null_true,
c_Start_null_false,
c_Working_null_true,
c_Working_null_false
}
booldelegate starkWork;
booldelegate working;
voiddelegate completeWork;
public static int Main()
{
DelegateCombine1 delegateCombine1 = new DelegateCombine1();
TestLibrary.TestFramework.BeginTestCase("DelegateCombine1");
if (delegateCombine1.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: combine two delegates which are not null");
try
{
if (GetInvocationListFlag(identify_null.c_Start_null_false, identify_null.c_Working_null_false ) != c_StartWrok + c_Working)
{
TestLibrary.TestFramework.LogError("001", "delegate combine is not successful ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: combine two delegate ,first is null,second is not null");
try
{
if (GetInvocationListFlag(identify_null.c_Start_null_true, identify_null.c_Working_null_false ) != c_Working)
{
TestLibrary.TestFramework.LogError("003", "delegate combine is not successful ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: combine two delegate ,first is not null,second is null");
try
{
if (GetInvocationListFlag( identify_null.c_Start_null_false, identify_null.c_Working_null_true ) != c_StartWrok)
{
TestLibrary.TestFramework.LogError("005", "delegate combine is not successful ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: combine two delegate ,first is null and second is null");
try
{
if (GetInvocationListFlag( identify_null.c_Start_null_true , identify_null.c_Working_null_true) != string.Empty )
{
TestLibrary.TestFramework.LogError("007", "delegate combine is not successful ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:Both a and b are not a null reference , and a and b are not instances of the same delegate type.");
try
{
DelegateCombine1 delctor = new DelegateCombine1();
TestClass testinstance = new TestClass();
delctor.starkWork = new booldelegate(testinstance.StartWork_Bool);
delctor.completeWork = new voiddelegate(testinstance.CompleteWork_Void);
object obj = Delegate.Combine(delctor.starkWork, delctor.completeWork);
TestLibrary.TestFramework.LogError("009", "a ArgumentException should be throw ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
private string GetInvocationListFlag(identify_null start,identify_null working)
{
DelegateCombine1 delctor = new DelegateCombine1();
TestClass testinstance = new TestClass();
string sFlag = string.Empty;
if (start == identify_null.c_Start_null_false)
{
delctor.starkWork = new booldelegate(testinstance.StartWork_Bool);
}
else
{
delctor.starkWork = null;
}
if (working == identify_null.c_Working_null_false)
{
delctor.working = new booldelegate(testinstance.Working_Bool );
}
else
{
delctor.working = null;
}
booldelegate combine = (booldelegate)Delegate.Combine(delctor.starkWork, delctor.working);
if (combine == null)
{
return string.Empty;
}
for (IEnumerator itr = combine.GetInvocationList().GetEnumerator(); itr.MoveNext(); )
{
booldelegate bd = (booldelegate)itr.Current;
if (bd.Equals(delctor.starkWork))
{
sFlag += c_StartWrok;
}
if (bd.Equals(delctor.working))
{
sFlag += c_Working;
}
}
combine();
return sFlag;
}
}
//create testclass for provding test method and test target.
class TestClass
{
public bool StartWork_Bool()
{
TestLibrary.TestFramework.LogInformation("StartWork_Bool method is running .");
return true;
}
public bool Working_Bool()
{
TestLibrary.TestFramework.LogInformation("Working_Bool method is running .");
return true;
}
public void CompleteWork_Void()
{
TestLibrary.TestFramework.LogInformation("CompleteWork_Void method is running .");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;
using System.Threading;
using System.Text;
namespace NativeWifi
{
/// <summary>
/// Represents a client to the Zeroconf (Native Wifi) service.
/// </summary>
/// <remarks>
/// This class is the entrypoint to Native Wifi management. To manage WiFi settings, create an instance
/// of this class.
/// </remarks>
public class WlanClient
{
/// <summary>
/// Represents a Wifi network interface.
/// </summary>
public class WlanInterface
{
private WlanClient client;
private Wlan.WlanInterfaceInfo info;
#region Events
/// <summary>
/// Represents a method that will handle <see cref="WlanNotification"/> events.
/// </summary>
/// <param name="notifyData">The notification data.</param>
public delegate void WlanNotificationEventHandler(Wlan.WlanNotificationData notifyData);
/// <summary>
/// Represents a method that will handle <see cref="WlanConnectionNotification"/> events.
/// </summary>
/// <param name="notifyData">The notification data.</param>
/// <param name="connNotifyData">The notification data.</param>
public delegate void WlanConnectionNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData);
/// <summary>
/// Represents a method that will handle <see cref="WlanReasonNotification"/> events.
/// </summary>
/// <param name="notifyData">The notification data.</param>
/// <param name="reasonCode">The reason code.</param>
public delegate void WlanReasonNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode);
/// <summary>
/// Occurs when an event of any kind occurs on a WLAN interface.
/// </summary>
public event WlanNotificationEventHandler WlanNotification;
/// <summary>
/// Occurs when a WLAN interface changes connection state.
/// </summary>
public event WlanConnectionNotificationEventHandler WlanConnectionNotification;
/// <summary>
/// Occurs when a WLAN operation fails due to some reason.
/// </summary>
public event WlanReasonNotificationEventHandler WlanReasonNotification;
#endregion
#region Event queue
private bool queueEvents;
private AutoResetEvent eventQueueFilled = new AutoResetEvent(false);
private Queue<object> eventQueue = new Queue<object>();
private struct WlanConnectionNotificationEventData
{
public Wlan.WlanNotificationData notifyData;
public Wlan.WlanConnectionNotificationData connNotifyData;
}
private struct WlanReasonNotificationData
{
public Wlan.WlanNotificationData notifyData;
public Wlan.WlanReasonCode reasonCode;
}
#endregion
internal WlanInterface(WlanClient client, Wlan.WlanInterfaceInfo info)
{
this.client = client;
this.info = info;
}
/// <summary>
/// Sets a parameter of the interface whose data type is <see cref="int"/>.
/// </summary>
/// <param name="opCode">The opcode of the parameter.</param>
/// <param name="value">The value to set.</param>
private void SetInterfaceInt(Wlan.WlanIntfOpcode opCode, int value)
{
IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(valuePtr, value);
try
{
Wlan.ThrowIfError(
Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero));
}
finally
{
Marshal.FreeHGlobal(valuePtr);
}
}
/// <summary>
/// Gets a parameter of the interface whose data type is <see cref="int"/>.
/// </summary>
/// <param name="opCode">The opcode of the parameter.</param>
/// <returns>The integer value.</returns>
private int GetInterfaceInt(Wlan.WlanIntfOpcode opCode)
{
IntPtr valuePtr;
int valueSize;
Wlan.WlanOpcodeValueType opcodeValueType;
Wlan.ThrowIfError(
Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
try
{
return Marshal.ReadInt32(valuePtr);
}
finally
{
Wlan.WlanFreeMemory(valuePtr);
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="WlanInterface"/> is automatically configured.
/// </summary>
/// <value><c>true</c> if "autoconf" is enabled; otherwise, <c>false</c>.</value>
public bool Autoconf
{
get
{
return GetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled) != 0;
}
set
{
SetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled, value ? 1 : 0);
}
}
/// <summary>
/// Gets or sets the BSS type for the indicated interface.
/// </summary>
/// <value>The type of the BSS.</value>
public Wlan.Dot11BssType BssType
{
get
{
return (Wlan.Dot11BssType) GetInterfaceInt(Wlan.WlanIntfOpcode.BssType);
}
set
{
SetInterfaceInt(Wlan.WlanIntfOpcode.BssType, (int)value);
}
}
/// <summary>
/// Gets the state of the interface.
/// </summary>
/// <value>The state of the interface.</value>
public Wlan.WlanInterfaceState InterfaceState
{
get
{
return (Wlan.WlanInterfaceState)GetInterfaceInt(Wlan.WlanIntfOpcode.InterfaceState);
}
}
/// <summary>
/// Gets the channel.
/// </summary>
/// <value>The channel.</value>
/// <remarks>Not supported on Windows XP SP2.</remarks>
public int Channel
{
get
{
return GetInterfaceInt(Wlan.WlanIntfOpcode.ChannelNumber);
}
}
/// <summary>
/// Gets the RSSI.
/// </summary>
/// <value>The RSSI.</value>
/// <remarks>Not supported on Windows XP SP2.</remarks>
public int RSSI
{
get
{
return GetInterfaceInt(Wlan.WlanIntfOpcode.RSSI);
}
}
/// <summary>
/// Gets the current operation mode.
/// </summary>
/// <value>The current operation mode.</value>
/// <remarks>Not supported on Windows XP SP2.</remarks>
public Wlan.Dot11OperationMode CurrentOperationMode
{
get
{
return (Wlan.Dot11OperationMode) GetInterfaceInt(Wlan.WlanIntfOpcode.CurrentOperationMode);
}
}
/// <summary>
/// Gets the attributes of the current connection.
/// </summary>
/// <value>The current connection attributes.</value>
/// <exception cref="Win32Exception">An exception with code 0x0000139F (The group or resource is not in the correct state to perform the requested operation.) will be thrown if the interface is not connected to a network.</exception>
public Wlan.WlanConnectionAttributes CurrentConnection
{
get
{
int valueSize;
IntPtr valuePtr;
Wlan.WlanOpcodeValueType opcodeValueType;
Wlan.ThrowIfError(
Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.CurrentConnection, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
try
{
return (Wlan.WlanConnectionAttributes)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanConnectionAttributes));
}
finally
{
Wlan.WlanFreeMemory(valuePtr);
}
}
}
/// <summary>
/// Requests a scan for available networks.
/// </summary>
/// <remarks>
/// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
/// </remarks>
public void Scan()
{
Wlan.ThrowIfError(
Wlan.WlanScan(client.clientHandle, info.interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
}
/// <summary>
/// Disconnects from a network
/// </summary>
public void Disconnect()
{
Wlan.ThrowIfError(Wlan.WlanDisconnect(client.clientHandle, info.interfaceGuid, IntPtr.Zero));
}
/// <summary>
/// Converts a pointer to a available networks list (header + entries) to an array of available network entries.
/// </summary>
/// <param name="bssListPtr">A pointer to an available networks list's header.</param>
/// <returns>An array of available network entries.</returns>
private Wlan.WlanAvailableNetwork[] ConvertAvailableNetworkListPtr(IntPtr availNetListPtr)
{
Wlan.WlanAvailableNetworkListHeader availNetListHeader = (Wlan.WlanAvailableNetworkListHeader)Marshal.PtrToStructure(availNetListPtr, typeof(Wlan.WlanAvailableNetworkListHeader));
long availNetListIt = availNetListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanAvailableNetworkListHeader));
Wlan.WlanAvailableNetwork[] availNets = new Wlan.WlanAvailableNetwork[availNetListHeader.numberOfItems];
for (int i = 0; i < availNetListHeader.numberOfItems; ++i)
{
availNets[i] = (Wlan.WlanAvailableNetwork)Marshal.PtrToStructure(new IntPtr(availNetListIt), typeof(Wlan.WlanAvailableNetwork));
availNetListIt += Marshal.SizeOf(typeof(Wlan.WlanAvailableNetwork));
}
return availNets;
}
/// <summary>
/// Retrieves the list of available networks.
/// </summary>
/// <param name="flags">Controls the type of networks returned.</param>
/// <returns>A list of the available networks.</returns>
public Wlan.WlanAvailableNetwork[] GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags flags)
{
IntPtr availNetListPtr;
Wlan.ThrowIfError(
Wlan.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr));
try
{
return ConvertAvailableNetworkListPtr(availNetListPtr);
}
finally
{
Wlan.WlanFreeMemory(availNetListPtr);
}
}
/// <summary>
/// Converts a pointer to a BSS list (header + entries) to an array of BSS entries.
/// </summary>
/// <param name="bssListPtr">A pointer to a BSS list's header.</param>
/// <returns>An array of BSS entries.</returns>
private Wlan.WlanBssEntry[] ConvertBssListPtr(IntPtr bssListPtr)
{
Wlan.WlanBssListHeader bssListHeader = (Wlan.WlanBssListHeader)Marshal.PtrToStructure(bssListPtr, typeof(Wlan.WlanBssListHeader));
long bssListIt = bssListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanBssListHeader));
Wlan.WlanBssEntry[] bssEntries = new Wlan.WlanBssEntry[bssListHeader.numberOfItems];
for (int i=0; i<bssListHeader.numberOfItems; ++i)
{
bssEntries[i] = (Wlan.WlanBssEntry)Marshal.PtrToStructure(new IntPtr(bssListIt), typeof(Wlan.WlanBssEntry));
bssListIt += Marshal.SizeOf(typeof(Wlan.WlanBssEntry));
}
return bssEntries;
}
/// <summary>
/// Retrieves the basic service sets (BSS) list of all available networks.
/// </summary>
public Wlan.WlanBssEntry[] GetNetworkBssList()
{
IntPtr bssListPtr;
Wlan.ThrowIfError(
Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Wlan.Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr));
try
{
return ConvertBssListPtr(bssListPtr);
}
finally
{
Wlan.WlanFreeMemory(bssListPtr);
}
}
/// <summary>
/// Retrieves the basic service sets (BSS) list of the specified network.
/// </summary>
/// <param name="ssid">Specifies the SSID of the network from which the BSS list is requested.</param>
/// <param name="bssType">Indicates the BSS type of the network.</param>
/// <param name="securityEnabled">Indicates whether security is enabled on the network.</param>
public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled)
{
IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
Marshal.StructureToPtr(ssid, ssidPtr, false);
try
{
IntPtr bssListPtr;
Wlan.ThrowIfError(
Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr));
try
{
return ConvertBssListPtr(bssListPtr);
}
finally
{
Wlan.WlanFreeMemory(bssListPtr);
}
}
finally
{
Marshal.FreeHGlobal(ssidPtr);
}
}
/// <summary>
/// Connects to a network defined by a connection parameters structure.
/// </summary>
/// <param name="connectionParams">The connection paramters.</param>
protected void Connect(Wlan.WlanConnectionParameters connectionParams)
{
Wlan.ThrowIfError(
Wlan.WlanConnect(client.clientHandle, info.interfaceGuid, ref connectionParams, IntPtr.Zero));
}
/// <summary>
/// Connects to a network using profile and preferred list of APs
/// </summary>
/// <param name="connectionMode"></param>
/// <param name="bssType">Should match the type in the profile</param>
/// <param name="bssMacs">The MACs of APs to attempt to connect to</param>
/// <param name="profile">profile for the relevant SSID</param>
/// mostly taken from https://social.msdn.microsoft.com/Forums/de-DE/d11150ae-9bb7-4e44-9c57-6a411b9772d7/cant-connect-to-a-specific-ap-using-wlanconnect?forum=vistawirelesssdk
public void ConnectBSS(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, byte[][] bssMacs, string profile)
{
Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
connectionParams.wlanConnectionMode = connectionMode;
connectionParams.profile = profile;
connectionParams.dot11BssType = bssType;
connectionParams.flags = 0;
Wlan.NDIS_OBJECT_HEADER ndoh;// = new Wlan.NDIS_OBJECT_HEADER();
ndoh.Type = Wlan.NDIS_OBJECT_TYPE_DEFAULT;
ndoh.Revision = Wlan.DOT11_BSSID_LIST_REVISION_1;
ndoh.Size = (ushort)System.Runtime.InteropServices.Marshal.SizeOf(typeof(Wlan.DOT11_BSSID_LIST));
Wlan.DOT11_BSSID_LIST desBssidList = new Wlan.DOT11_BSSID_LIST();
desBssidList.Header = ndoh;
desBssidList.uNumOfEntries = (uint)bssMacs.Length;
desBssidList.uTotalNumOfEntries = (uint)bssMacs.Length;
desBssidList.BSSIDs = new Wlan.DOT11_MAC_ADDRESS[bssMacs.Length];
int i = 0;
foreach (byte[] bssMac in bssMacs)
{
Wlan.DOT11_MAC_ADDRESS bssid = new Wlan.DOT11_MAC_ADDRESS();
bssid.Dot11MacAddress = bssMac;
desBssidList.BSSIDs[i++] = bssid;
}
IntPtr desBssidListPtr = Marshal.AllocHGlobal(Marshal.SizeOf(desBssidList));
Marshal.StructureToPtr(desBssidList, desBssidListPtr, false);
connectionParams.desiredBssidListPtr = desBssidListPtr;
Connect(connectionParams);
}
/// <summary>
/// Requests a connection (association) to the specified wireless network.
/// </summary>
/// <remarks>
/// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
/// </remarks>
public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile)
{
Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
connectionParams.wlanConnectionMode = connectionMode;
connectionParams.profile = profile;
connectionParams.dot11BssType = bssType;
connectionParams.flags = 0;
Connect(connectionParams);
}
/// <summary>
/// Connects (associates) to the specified wireless network, returning either on a success to connect
/// or a failure.
/// </summary>
/// <param name="connectionMode"></param>
/// <param name="bssType"></param>
/// <param name="profile"></param>
/// <param name="connectTimeout"></param>
/// <returns></returns>
public bool ConnectSynchronously(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, int connectTimeout)
{
queueEvents = true;
try
{
Connect(connectionMode, bssType, profile);
while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true))
{
lock (eventQueue)
{
while (eventQueue.Count != 0)
{
object e = eventQueue.Dequeue();
if (e is WlanConnectionNotificationEventData)
{
WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e;
// Check if the conditions are good to indicate either success or failure.
if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM)
{
switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode)
{
case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
if (wlanConnectionData.connNotifyData.profileName == profile)
return true;
break;
}
}
break;
}
}
}
}
}
finally
{
queueEvents = false;
eventQueue.Clear();
}
return false; // timeout expired and no "connection complete"
}
/// <summary>
/// Connects (associates) to the specified wireless network, returning either on a success to connect
/// or a failure.
/// </summary>
/// <param name="connectionMode"></param>
/// <param name="bssType"></param>
/// <param name="profile"></param>
/// <param name="connectTimeout"></param>
/// <returns></returns>
public bool ConnectSynchronouslyBSS(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, byte[][] bssMacs, string profile, int connectTimeout)
{
queueEvents = true;
try
{
ConnectBSS(connectionMode, bssType, bssMacs, profile);
while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true))
{
lock (eventQueue)
{
while (eventQueue.Count != 0)
{
object e = eventQueue.Dequeue();
if (e is WlanConnectionNotificationEventData)
{
WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e;
// Check if the conditions are good to indicate either success or failure.
if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM)
{
switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode)
{
case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
if (wlanConnectionData.connNotifyData.profileName == profile)
return true;
break;
}
}
break;
}
}
}
}
}
finally
{
queueEvents = false;
eventQueue.Clear();
}
return false; // timeout expired and no "connection complete"
}
/// <summary>
/// Connects to the specified wireless network.
/// </summary>
/// <remarks>
/// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
/// </remarks>
public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, Wlan.Dot11Ssid ssid, Wlan.WlanConnectionFlags flags)
{
Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
connectionParams.wlanConnectionMode = connectionMode;
connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false);
connectionParams.dot11BssType = bssType;
connectionParams.flags = flags;
Connect(connectionParams);
Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType());
Marshal.FreeHGlobal(connectionParams.dot11SsidPtr);
}
/// <summary>
/// Deletes a profile.
/// </summary>
/// <param name="profileName">
/// The name of the profile to be deleted. Profile names are case-sensitive.
/// On Windows XP SP2, the supplied name must match the profile name derived automatically from the SSID of the network. For an infrastructure network profile, the SSID must be supplied for the profile name. For an ad hoc network profile, the supplied name must be the SSID of the ad hoc network followed by <c>-adhoc</c>.
/// </param>
public void DeleteProfile(string profileName)
{
Wlan.ThrowIfError(
Wlan.WlanDeleteProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero));
}
/// <summary>
/// Sets the profile.
/// </summary>
/// <param name="flags">The flags to set on the profile.</param>
/// <param name="profileXml">The XML representation of the profile. On Windows XP SP 2, special care should be taken to adhere to its limitations.</param>
/// <param name="overwrite">If a profile by the given name already exists, then specifies whether to overwrite it (if <c>true</c>) or return an error (if <c>false</c>).</param>
/// <returns>The resulting code indicating a success or the reason why the profile wasn't valid.</returns>
public Wlan.WlanReasonCode SetProfile(Wlan.WlanProfileFlags flags, string profileXml, bool overwrite)
{
Wlan.WlanReasonCode reasonCode;
Wlan.ThrowIfError(
Wlan.WlanSetProfile(client.clientHandle, info.interfaceGuid, flags, profileXml, null, overwrite, IntPtr.Zero, out reasonCode));
return reasonCode;
}
/// <summary>
/// Gets the profile's XML specification.
/// </summary>
/// <param name="profileName">The name of the profile.</param>
/// <returns>The XML document.</returns>
public string GetProfileXml(string profileName)
{
IntPtr profileXmlPtr;
Wlan.WlanProfileFlags flags;
Wlan.WlanAccess access;
Wlan.ThrowIfError(
Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, out flags,
out access));
try
{
return Marshal.PtrToStringUni(profileXmlPtr);
}
finally
{
Wlan.WlanFreeMemory(profileXmlPtr);
}
}
/// <summary>
/// Gets the information of all profiles on this interface.
/// </summary>
/// <returns>The profiles information.</returns>
public Wlan.WlanProfileInfo[] GetProfiles()
{
IntPtr profileListPtr;
Wlan.ThrowIfError(
Wlan.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr));
try
{
Wlan.WlanProfileInfoListHeader header = (Wlan.WlanProfileInfoListHeader) Marshal.PtrToStructure(profileListPtr, typeof(Wlan.WlanProfileInfoListHeader));
Wlan.WlanProfileInfo[] profileInfos = new Wlan.WlanProfileInfo[header.numberOfItems];
long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header);
for (int i=0; i<header.numberOfItems; ++i)
{
Wlan.WlanProfileInfo profileInfo = (Wlan.WlanProfileInfo) Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(Wlan.WlanProfileInfo));
profileInfos[i] = profileInfo;
profileListIterator += Marshal.SizeOf(profileInfo);
}
return profileInfos;
}
finally
{
Wlan.WlanFreeMemory(profileListPtr);
}
}
internal void OnWlanConnection(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData)
{
if (WlanConnectionNotification != null)
WlanConnectionNotification(notifyData, connNotifyData);
if (queueEvents)
{
WlanConnectionNotificationEventData queuedEvent = new WlanConnectionNotificationEventData();
queuedEvent.notifyData = notifyData;
queuedEvent.connNotifyData = connNotifyData;
EnqueueEvent(queuedEvent);
}
}
internal void OnWlanReason(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode)
{
if (WlanReasonNotification != null)
WlanReasonNotification(notifyData, reasonCode);
if (queueEvents)
{
WlanReasonNotificationData queuedEvent = new WlanReasonNotificationData();
queuedEvent.notifyData = notifyData;
queuedEvent.reasonCode = reasonCode;
EnqueueEvent(queuedEvent);
}
}
internal void OnWlanNotification(Wlan.WlanNotificationData notifyData)
{
if (WlanNotification != null)
WlanNotification(notifyData);
}
/// <summary>
/// Enqueues a notification event to be processed serially.
/// </summary>
private void EnqueueEvent(object queuedEvent)
{
lock (eventQueue)
eventQueue.Enqueue(queuedEvent);
eventQueueFilled.Set();
}
/// <summary>
/// Gets the network interface of this wireless interface.
/// </summary>
/// <remarks>
/// The network interface allows querying of generic network properties such as the interface's IP address.
/// </remarks>
public NetworkInterface NetworkInterface
{
get
{
// Do not cache the NetworkInterface; We need it fresh
// each time cause otherwise it caches the IP information.
foreach (NetworkInterface netIface in NetworkInterface.GetAllNetworkInterfaces())
{
Guid netIfaceGuid = new Guid(netIface.Id);
if (netIfaceGuid.Equals(info.interfaceGuid))
{
return netIface;
}
}
return null;
}
}
/// <summary>
/// The GUID of the interface (same content as the <see cref="System.Net.NetworkInformation.NetworkInterface.Id"/> value).
/// </summary>
public Guid InterfaceGuid
{
get { return info.interfaceGuid; }
}
/// <summary>
/// The description of the interface.
/// This is a user-immutable string containing the vendor and model name of the adapter.
/// </summary>
public string InterfaceDescription
{
get { return info.interfaceDescription; }
}
/// <summary>
/// The friendly name given to the interface by the user (e.g. "Local Area Network Connection").
/// </summary>
public string InterfaceName
{
get { return NetworkInterface.Name; }
}
}
private IntPtr clientHandle;
private uint negotiatedVersion;
private Wlan.WlanNotificationCallbackDelegate wlanNotificationCallback;
private Dictionary<Guid,WlanInterface> ifaces = new Dictionary<Guid,WlanInterface>();
/// <summary>
/// Creates a new instance of a Native Wifi service client.
/// </summary>
public WlanClient()
{
Wlan.ThrowIfError(
Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle));
try
{
Wlan.WlanNotificationSource prevSrc;
wlanNotificationCallback = new Wlan.WlanNotificationCallbackDelegate(OnWlanNotification);
Wlan.ThrowIfError(
Wlan.WlanRegisterNotification(clientHandle, Wlan.WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc));
}
catch
{
Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
throw;
}
}
~WlanClient()
{
Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
}
private Wlan.WlanConnectionNotificationData? ParseWlanConnectionNotification(ref Wlan.WlanNotificationData notifyData)
{
int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanConnectionNotificationData));
if (notifyData.dataSize < expectedSize)
return null;
Wlan.WlanConnectionNotificationData connNotifyData =
(Wlan.WlanConnectionNotificationData)
Marshal.PtrToStructure(notifyData.dataPtr, typeof(Wlan.WlanConnectionNotificationData));
if (connNotifyData.wlanReasonCode == Wlan.WlanReasonCode.Success)
{
IntPtr profileXmlPtr = new IntPtr(
notifyData.dataPtr.ToInt64() +
Marshal.OffsetOf(typeof(Wlan.WlanConnectionNotificationData), "profileXml").ToInt64());
connNotifyData.profileXml = Marshal.PtrToStringUni(profileXmlPtr);
}
return connNotifyData;
}
private void OnWlanNotification(ref Wlan.WlanNotificationData notifyData, IntPtr context)
{
WlanInterface wlanIface = ifaces.ContainsKey(notifyData.interfaceGuid) ? ifaces[notifyData.interfaceGuid] : null;
switch(notifyData.notificationSource)
{
case Wlan.WlanNotificationSource.ACM:
switch((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode)
{
case Wlan.WlanNotificationCodeAcm.ConnectionStart:
case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail:
case Wlan.WlanNotificationCodeAcm.Disconnecting:
case Wlan.WlanNotificationCodeAcm.Disconnected:
Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
if (connNotifyData.HasValue)
if (wlanIface != null)
wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
break;
case Wlan.WlanNotificationCodeAcm.ScanFail:
{
int expectedSize = Marshal.SizeOf(typeof (Wlan.WlanReasonCode));
if (notifyData.dataSize >= expectedSize)
{
Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode) Marshal.ReadInt32(notifyData.dataPtr);
if (wlanIface != null)
wlanIface.OnWlanReason(notifyData, reasonCode);
}
}
break;
}
break;
case Wlan.WlanNotificationSource.MSM:
switch((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode)
{
case Wlan.WlanNotificationCodeMsm.Associating:
case Wlan.WlanNotificationCodeMsm.Associated:
case Wlan.WlanNotificationCodeMsm.Authenticating:
case Wlan.WlanNotificationCodeMsm.Connected:
case Wlan.WlanNotificationCodeMsm.RoamingStart:
case Wlan.WlanNotificationCodeMsm.RoamingEnd:
case Wlan.WlanNotificationCodeMsm.Disassociating:
case Wlan.WlanNotificationCodeMsm.Disconnected:
case Wlan.WlanNotificationCodeMsm.PeerJoin:
case Wlan.WlanNotificationCodeMsm.PeerLeave:
case Wlan.WlanNotificationCodeMsm.AdapterRemoval:
Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
if (connNotifyData.HasValue)
if (wlanIface != null)
wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
break;
}
break;
}
if (wlanIface != null)
wlanIface.OnWlanNotification(notifyData);
}
/// <summary>
/// Gets the WLAN interfaces.
/// </summary>
/// <value>The WLAN interfaces.</value>
public WlanInterface[] Interfaces
{
get
{
IntPtr ifaceList;
Wlan.ThrowIfError(
Wlan.WlanEnumInterfaces(clientHandle, IntPtr.Zero, out ifaceList));
try
{
Wlan.WlanInterfaceInfoListHeader header =
(Wlan.WlanInterfaceInfoListHeader) Marshal.PtrToStructure(ifaceList, typeof (Wlan.WlanInterfaceInfoListHeader));
Int64 listIterator = ifaceList.ToInt64() + Marshal.SizeOf(header);
WlanInterface[] interfaces = new WlanInterface[header.numberOfItems];
List<Guid> currentIfaceGuids = new List<Guid>();
for (int i = 0; i < header.numberOfItems; ++i)
{
Wlan.WlanInterfaceInfo info =
(Wlan.WlanInterfaceInfo) Marshal.PtrToStructure(new IntPtr(listIterator), typeof (Wlan.WlanInterfaceInfo));
listIterator += Marshal.SizeOf(info);
WlanInterface wlanIface;
currentIfaceGuids.Add(info.interfaceGuid);
if (ifaces.ContainsKey(info.interfaceGuid))
wlanIface = ifaces[info.interfaceGuid];
else
wlanIface = new WlanInterface(this, info);
interfaces[i] = wlanIface;
ifaces[info.interfaceGuid] = wlanIface;
}
// Remove stale interfaces
Queue<Guid> deadIfacesGuids = new Queue<Guid>();
foreach (Guid ifaceGuid in ifaces.Keys)
{
if (!currentIfaceGuids.Contains(ifaceGuid))
deadIfacesGuids.Enqueue(ifaceGuid);
}
while(deadIfacesGuids.Count != 0)
{
Guid deadIfaceGuid = deadIfacesGuids.Dequeue();
ifaces.Remove(deadIfaceGuid);
}
return interfaces;
}
finally
{
Wlan.WlanFreeMemory(ifaceList);
}
}
}
/// <summary>
/// Gets a string that describes a specified reason code.
/// </summary>
/// <param name="reasonCode">The reason code.</param>
/// <returns>The string.</returns>
public string GetStringForReasonCode(Wlan.WlanReasonCode reasonCode)
{
StringBuilder sb = new StringBuilder(1024); // the 1024 size here is arbitrary; the WlanReasonCodeToString docs fail to specify a recommended size
Wlan.ThrowIfError(
Wlan.WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero));
return sb.ToString();
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.Common
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using Microsoft.Protocols.TestTools;
/// <summary>
/// This class is partial class ActiveSyncClient, mainly aims to verify the response XML whether consistent with the schemas.
/// </summary>
public partial class ActiveSyncClient
{
#region Private Fields
/// <summary>
/// Schema list field
/// </summary>
private string[] xmlSchemaList = null;
/// <summary>
/// The error results of XML Schema validation
/// </summary>
private Collection<ValidationEventArgs> xmlValidationErrors;
/// <summary>
/// The warning results of XML Schema validation
/// </summary>
private Collection<ValidationEventArgs> xmlValidationWarnings;
/// <summary>
/// The last XML soap message string
/// </summary>
private string lastRawString;
/// <summary>
/// The schema validation result, True/False
/// </summary>
private bool validationResult;
#endregion
#region Public Properties
/// <summary>
/// Gets a value indicating whether the last server response if success or not
/// </summary>
public bool ValidationResult
{
get
{
return this.validationResult;
}
}
/// <summary>
/// Gets the error events generated during XML validation.
/// </summary>
public Collection<ValidationEventArgs> XmlValidationErrors
{
get
{
return this.xmlValidationErrors;
}
}
/// <summary>
/// Gets the warning events generated during XML validation.
/// </summary>
public Collection<ValidationEventArgs> XmlValidationWarnings
{
get
{
return this.xmlValidationWarnings;
}
}
/// <summary>
/// Gets the used schema list
/// </summary>
public string[] XmlSchemaList
{
get
{
if (this.xmlSchemaList == null)
{
List<string> list = new List<string>
{
ReadXsdFile("AirSync.xsd"),
ReadXsdFile("AirSyncBase.xsd"),
ReadXsdFile("AutodiscoverMobileSync.xsd"),
ReadXsdFile("AutodiscoverResponse.xsd"),
ReadXsdFile("Calendar.xsd"),
ReadXsdFile("ComposeMail.xsd"),
ReadXsdFile("Contacts.xsd"),
ReadXsdFile("Contacts2.xsd"),
ReadXsdFile("DocumentLibrary.xsd"),
ReadXsdFile("Email.xsd"),
ReadXsdFile("Email2.xsd"),
ReadXsdFile("FolderCreateResponse.xsd"),
ReadXsdFile("FolderDeleteResponse.xsd"),
ReadXsdFile("FolderHierarchy.xsd"),
ReadXsdFile("FolderSyncResponse.xsd"),
ReadXsdFile("FolderUpdateResponse.xsd"),
ReadXsdFile("GAL.xsd"),
ReadXsdFile("GetHierarchyResponse.xsd"),
ReadXsdFile("GetItemEstimateResponse.xsd"),
ReadXsdFile("ItemOperations.xsd"),
ReadXsdFile("ItemOperationsResponse.xsd"),
ReadXsdFile("MeetingResponseResponse.xsd"),
ReadXsdFile("MoveItemsResponse.xsd"),
ReadXsdFile("Notes.xsd"),
ReadXsdFile("PingResponse.xsd"),
ReadXsdFile("Provision.xsd"),
ReadXsdFile("ProvisionResponse.xsd"),
ReadXsdFile("ResolveRecipientsResponse.xsd"),
ReadXsdFile("RightsManagement.xsd"),
ReadXsdFile("Search.xsd"),
ReadXsdFile("SearchResponse.xsd"),
ReadXsdFile("SendMailResponse.xsd"),
ReadXsdFile("Settings.xsd"),
ReadXsdFile("SettingsResponse.xsd"),
ReadXsdFile("SmartForwardResponse.xsd"),
ReadXsdFile("SmartReplyResponse.xsd"),
ReadXsdFile("SyncResponse.xsd"),
ReadXsdFile("Tasks.xsd"),
ReadXsdFile("ValidateCertResponse.xsd")
};
this.xmlSchemaList = list.ToArray();
}
return this.xmlSchemaList;
}
}
#endregion
#region Schema Validation method
/// <summary>
/// The schema validation for the XML string.
/// </summary>
/// <param name="decodeXMLstring">The XML string which is decoded from WBXML format</param>
/// <param name="testSite">An instance of interface ITestSite which provides logging, assertions, and adapters for test code onto its execution context.</param>
public void ValidateResponseSchema(string decodeXMLstring, ITestSite testSite)
{
if (string.IsNullOrEmpty(decodeXMLstring))
{
this.validationResult = true;
return;
}
this.lastRawString = decodeXMLstring;
// Initialize Validation Result Recorder
this.validationResult = false;
this.xmlValidationWarnings = new Collection<ValidationEventArgs>();
this.xmlValidationErrors = new Collection<ValidationEventArgs>();
// Prepare settings of XML reader
XmlReaderSettings settings = new XmlReaderSettings();
foreach (string xmlSchema in this.XmlSchemaList)
{
using (StringReader stringReader = new StringReader(xmlSchema))
{
settings.Schemas.Add(GetTargetNamespace(xmlSchema), XmlReader.Create(stringReader));
}
}
settings.ValidationType = ValidationType.Schema;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallBack);
// Load into the memory stream
using (MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.UTF8.GetBytes(this.lastRawString)))
{
// Create XML reader for SOAP client message
XmlReader xmlReader = XmlReader.Create(ms, settings);
while (xmlReader.Read())
{
}
}
this.validationResult = this.xmlValidationErrors.Count == 0 && this.xmlValidationWarnings.Count == 0;
if (!this.validationResult)
{
string errorInformation = null;
string warningInformation = null;
if (this.xmlValidationErrors.Count > 0)
{
if (this.xmlValidationErrors.Count == 1)
{
errorInformation = string.Format("There is a schema validation error:\r\n");
}
else
{
errorInformation = string.Format("There are {0} schema validation errors:\r\n", this.xmlValidationErrors.Count);
}
for (int i = 0; i < this.xmlValidationErrors.Count; i++)
{
errorInformation = errorInformation + string.Format("Error: {0}\r\n", this.xmlValidationErrors[i].Message);
}
}
if (this.xmlValidationWarnings.Count > 0)
{
if (this.xmlValidationWarnings.Count == 1)
{
warningInformation = string.Format("There is a schema validation warning:\r\n");
}
else
{
warningInformation = string.Format("There are {0} schema validation warnings:\r\n", this.xmlValidationWarnings.Count);
}
for (int i = 0; i < this.xmlValidationWarnings.Count; i++)
{
warningInformation = warningInformation + string.Format("Warning: {0}\r\n", this.xmlValidationWarnings[i].Message);
}
}
testSite.Assert.Fail(errorInformation + warningInformation);
}
}
#endregion
#region Private Methods
/// <summary>
/// Read the xsd file content
/// </summary>
/// <param name="fileName">Specific the XSD file path</param>
/// <returns>The content string of the specified file name</returns>
private static string ReadXsdFile(string fileName)
{
FileStream fs = null;
try
{
fs = File.OpenRead(fileName);
using (StreamReader sr = new StreamReader(fs))
{
return sr.ReadToEnd();
}
}
finally
{
if (fs != null)
{
fs.Dispose();
}
}
}
/// <summary>
/// Get the target namespace of the schema
/// </summary>
/// <param name="schema">The schema string</param>
/// <returns>The target name of the give schema</returns>
private static string GetTargetNamespace(string schema)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml(schema);
if (xd.ChildNodes.Count <= 1)
{
throw new XmlException("Can't find schema element in " + xd.Name);
}
if (xd.ChildNodes[1].Attributes != null)
{
XmlAttributeCollection attributeList = xd.ChildNodes[1].Attributes;
return attributeList["targetNamespace"] == null ? string.Empty : attributeList["targetNamespace"].Value;
}
return null;
}
/// <summary>
/// The callback method that will handle XML schema validation events.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="args"> A ValidationEventArgs containing the event data.</param>
private void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Error)
{
this.xmlValidationErrors.Add(args);
}
else
{
this.xmlValidationWarnings.Add(args);
}
}
#endregion
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Xml.Serialization;
using OpenMetaverse;
namespace OpenSim.Framework
{
[Serializable]
public class AssetBase
{
private byte[] m_data;
[NonSerialized]
private AssetMetadata m_metadata;
public AssetBase()
{
m_metadata = new AssetMetadata();
}
public AssetBase(UUID assetId, string name)
{
m_metadata = new AssetMetadata();
m_metadata.FullID = assetId;
m_metadata.Name = name;
}
public AssetBase(UUID assetID, string name, sbyte assetType, string creatorID)
{
m_metadata = new AssetMetadata();
m_metadata.FullID = assetID;
m_metadata.Name = name;
m_metadata.Type = assetType;
}
public bool ContainsReferences
{
get
{
return
IsTextualAsset && (
Type != (sbyte)AssetType.Notecard
&& Type != (sbyte)AssetType.CallingCard
&& Type != (sbyte)AssetType.LSLText
&& Type != (sbyte)AssetType.Landmark);
}
}
public bool IsTextualAsset
{
get
{
return !IsBinaryAsset;
}
}
public bool IsBinaryAsset
{
get
{
return
(Type == (sbyte) AssetType.Animation ||
Type == (sbyte)AssetType.Gesture ||
Type == (sbyte)AssetType.Simstate ||
Type == (sbyte)AssetType.Unknown ||
Type == (sbyte)AssetType.Object ||
Type == (sbyte)AssetType.Sound ||
Type == (sbyte)AssetType.SoundWAV ||
Type == (sbyte)AssetType.Texture ||
Type == (sbyte)AssetType.TextureTGA ||
Type == (sbyte)AssetType.Folder ||
Type == (sbyte)FolderType.Root ||
Type == (sbyte)FolderType.LostAndFound ||
Type == (sbyte)FolderType.Snapshot ||
Type == (sbyte)FolderType.Trash ||
Type == (sbyte)AssetType.ImageJPEG ||
Type == (sbyte) AssetType.ImageTGA ||
Type == (sbyte) AssetType.LSLBytecode);
}
}
public bool IsImageAsset
{
get
{
return (
Type == (sbyte)AssetType.Texture ||
Type == (sbyte)AssetType.TextureTGA ||
Type == (sbyte)AssetType.ImageJPEG ||
Type == (sbyte)AssetType.ImageTGA
);
}
}
public virtual byte[] Data
{
get { return m_data; }
set { m_data = value; }
}
public UUID FullID
{
get { return m_metadata.FullID; }
set { m_metadata.FullID = value; }
}
public string ID
{
get { return m_metadata.ID; }
set { m_metadata.ID = value; }
}
public string Name
{
get { return m_metadata.Name; }
set { m_metadata.Name = value; }
}
public string Description
{
get { return m_metadata.Description; }
set { m_metadata.Description = value; }
}
public sbyte Type
{
get { return m_metadata.Type; }
set { m_metadata.Type = value; }
}
public bool Local
{
get { return m_metadata.Local; }
set { m_metadata.Local = value; }
}
public bool Temporary
{
get { return m_metadata.Temporary; }
set { m_metadata.Temporary = value; }
}
[XmlIgnore]
public AssetMetadata Metadata
{
get { return m_metadata; }
set { m_metadata = value; }
}
}
public class AssetMetadata
{
private UUID m_fullid;
private string m_name = String.Empty;
private string m_description = String.Empty;
private DateTime m_creation_date;
private sbyte m_type;
private string m_content_type;
private byte[] m_sha1;
private bool m_local = false;
private bool m_temporary = false;
//private Dictionary<string, Uri> m_methods = new Dictionary<string, Uri>();
//private OSDMap m_extra_data;
public UUID FullID
{
get { return m_fullid; }
set { m_fullid = value; }
}
public string ID
{
get { return m_fullid.ToString(); }
set { m_fullid = new UUID(value); }
}
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public string Description
{
get { return m_description; }
set { m_description = value; }
}
public DateTime CreationDate
{
get { return m_creation_date; }
set { m_creation_date = value; }
}
public sbyte Type
{
get { return m_type; }
set { m_type = value; }
}
public string ContentType
{
get { return m_content_type; }
set { m_content_type = value; }
}
public byte[] SHA1
{
get { return m_sha1; }
set { m_sha1 = value; }
}
public bool Local
{
get { return m_local; }
set { m_local = value; }
}
public bool Temporary
{
get { return m_temporary; }
set { m_temporary = value; }
}
//public Dictionary<string, Uri> Methods
//{
// get { return m_methods; }
// set { m_methods = value; }
//}
//public OSDMap ExtraData
//{
// get { return m_extra_data; }
// set { m_extra_data = value; }
//}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace HackathonBackend.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);
}
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004 - 2008
Matthew Holmes (matthew@wildfiregames.com),
Dan Moorehead (dan05a@gmail.com),
C.J. Adams-Collier (cjac@colliertech.org),
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Nodes;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Targets
{
/// <summary>
///
/// </summary>
[Target("nant")]
public class NAntTarget : ITarget
{
#region Fields
private Kernel m_Kernel;
#endregion
#region Private Methods
private static string PrependPath(string path)
{
string tmpPath = Helper.NormalizePath(path, '/');
Regex regex = new Regex(@"(\w):/(\w+)");
Match match = regex.Match(tmpPath);
//if(match.Success || tmpPath[0] == '.' || tmpPath[0] == '/')
//{
tmpPath = Helper.NormalizePath(tmpPath);
//}
// else
// {
// tmpPath = Helper.NormalizePath("./" + tmpPath);
// }
return tmpPath;
}
private static string BuildReference(SolutionNode solution, ProjectNode currentProject, ReferenceNode refr)
{
if (!String.IsNullOrEmpty(refr.Path))
{
return refr.Path;
}
if (solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode projectRef = (ProjectNode) solution.ProjectsTable[refr.Name];
string finalPath =
Helper.NormalizePath(refr.Name + GetProjectExtension(projectRef), '/');
return finalPath;
}
ProjectNode project = (ProjectNode) refr.Parent;
// Do we have an explicit file reference?
string fileRef = FindFileReference(refr.Name, project);
if (fileRef != null)
{
return fileRef;
}
// Is there an explicit path in the project ref?
if (refr.Path != null)
{
return Helper.NormalizePath(refr.Path + "/" + refr.Name + GetProjectExtension(project), '/');
}
// No, it's an extensionless GAC ref, but nant needs the .dll extension anyway
return refr.Name + ".dll";
}
public static string GetRefFileName(string refName)
{
if (ExtensionSpecified(refName))
{
return refName;
}
else
{
return refName + ".dll";
}
}
private static bool ExtensionSpecified(string refName)
{
return refName.EndsWith(".dll") || refName.EndsWith(".exe");
}
private static string GetProjectExtension(ProjectNode project)
{
string extension = ".dll";
if (project.Type == ProjectType.Exe || project.Type == ProjectType.WinExe)
{
extension = ".exe";
}
return extension;
}
private static string FindFileReference(string refName, ProjectNode project)
{
foreach (ReferencePathNode refPath in project.ReferencePaths)
{
string fullPath = Helper.MakeFilePath(refPath.Path, refName);
if (File.Exists(fullPath))
{
return fullPath;
}
fullPath = Helper.MakeFilePath(refPath.Path, refName, "dll");
if (File.Exists(fullPath))
{
return fullPath;
}
fullPath = Helper.MakeFilePath(refPath.Path, refName, "exe");
if (File.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
/// <summary>
/// Gets the XML doc file.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="conf">The conf.</param>
/// <returns></returns>
public static string GetXmlDocFile(ProjectNode project, ConfigurationNode conf)
{
if (conf == null)
{
throw new ArgumentNullException("conf");
}
if (project == null)
{
throw new ArgumentNullException("project");
}
string docFile = (string)conf.Options["XmlDocFile"];
// if(docFile != null && docFile.Length == 0)//default to assembly name if not specified
// {
// return Path.GetFileNameWithoutExtension(project.AssemblyName) + ".xml";
// }
return docFile;
}
private void WriteProject(SolutionNode solution, ProjectNode project)
{
string projFile = Helper.MakeFilePath(project.FullPath, project.Name + GetProjectExtension(project), "build");
StreamWriter ss = new StreamWriter(projFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projFile));
bool hasDoc = false;
using (ss)
{
ss.WriteLine("<?xml version=\"1.0\" ?>");
ss.WriteLine("<project name=\"{0}\" default=\"build\">", project.Name);
ss.WriteLine(" <target name=\"{0}\">", "build");
ss.WriteLine(" <echo message=\"Build Directory is ${project::get-base-directory()}/${build.dir}\" />");
ss.WriteLine(" <mkdir dir=\"${project::get-base-directory()}/${build.dir}\" />");
ss.Write(" <csc ");
ss.Write(" target=\"{0}\"", project.Type.ToString().ToLower());
ss.Write(" debug=\"{0}\"", "${build.debug}");
ss.Write(" platform=\"${build.platform}\"");
foreach (ConfigurationNode conf in project.Configurations)
{
if (conf.Options.KeyFile != "")
{
ss.Write(" keyfile=\"{0}\"", conf.Options.KeyFile);
break;
}
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" unsafe=\"{0}\"", conf.Options.AllowUnsafe);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" warnaserror=\"{0}\"", conf.Options.WarningsAsErrors);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" define=\"{0}\"", conf.Options.CompilerDefines);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" nostdlib=\"{0}\"", conf.Options["NoStdLib"]);
break;
}
ss.Write(" main=\"{0}\"", project.StartupObject);
foreach (ConfigurationNode conf in project.Configurations)
{
if (GetXmlDocFile(project, conf) != "")
{
ss.Write(" doc=\"{0}\"", "${project::get-base-directory()}/${build.dir}/" + GetXmlDocFile(project, conf));
hasDoc = true;
}
break;
}
ss.Write(" output=\"{0}", "${project::get-base-directory()}/${build.dir}/${project::get-name()}");
if (project.Type == ProjectType.Library)
{
ss.Write(".dll\"");
}
else
{
ss.Write(".exe\"");
}
if (project.AppIcon != null && project.AppIcon.Length != 0)
{
ss.Write(" win32icon=\"{0}\"", Helper.NormalizePath(project.AppIcon, '/'));
}
// This disables a very different behavior between VS and NAnt. With Nant,
// If you have using System.Xml; it will ensure System.Xml.dll is referenced,
// but not in VS. This will force the behaviors to match, so when it works
// in nant, it will work in VS.
ss.Write(" noconfig=\"true\"");
ss.WriteLine(">");
ss.WriteLine(" <resources prefix=\"{0}\" dynamicprefix=\"true\" >", project.RootNamespace);
foreach (string file in project.Files)
{
switch (project.Files.GetBuildAction(file))
{
case BuildAction.EmbeddedResource:
ss.WriteLine(" {0}", "<include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
break;
default:
if (project.Files.GetSubType(file) != SubType.Code && project.Files.GetSubType(file) != SubType.Settings)
{
ss.WriteLine(" <include name=\"{0}\" />", file.Substring(0, file.LastIndexOf('.')) + ".resx");
}
break;
}
}
//if (project.Files.GetSubType(file).ToString() != "Code")
//{
// ps.WriteLine(" <EmbeddedResource Include=\"{0}\">", file.Substring(0, file.LastIndexOf('.')) + ".resx");
ss.WriteLine(" </resources>");
ss.WriteLine(" <sources failonempty=\"true\">");
foreach (string file in project.Files)
{
switch (project.Files.GetBuildAction(file))
{
case BuildAction.Compile:
ss.WriteLine(" <include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
break;
default:
break;
}
}
ss.WriteLine(" </sources>");
ss.WriteLine(" <references basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <lib>");
ss.WriteLine(" <include name=\"${project::get-base-directory()}\" />");
foreach(ReferencePathNode refPath in project.ReferencePaths)
{
ss.WriteLine(" <include name=\"${project::get-base-directory()}/" + refPath.Path.TrimEnd('/', '\\') + "\" />");
}
ss.WriteLine(" </lib>");
foreach (ReferenceNode refr in project.References)
{
string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReference(solution, project, refr)), '/');
if (refr.Path != null) {
if (ExtensionSpecified(refr.Name))
{
ss.WriteLine (" <include name=\"" + path + refr.Name + "\"/>");
}
else
{
ss.WriteLine (" <include name=\"" + path + refr.Name + ".dll\"/>");
}
}
else
{
ss.WriteLine (" <include name=\"" + path + "\" />");
}
}
ss.WriteLine(" </references>");
ss.WriteLine(" </csc>");
foreach (ConfigurationNode conf in project.Configurations)
{
if (!String.IsNullOrEmpty(conf.Options.OutputPath))
{
string targetDir = Helper.NormalizePath(conf.Options.OutputPath, '/');
ss.WriteLine(" <echo message=\"Copying from [${project::get-base-directory()}/${build.dir}/] to [${project::get-base-directory()}/" + targetDir + "\" />");
ss.WriteLine(" <mkdir dir=\"${project::get-base-directory()}/" + targetDir + "\"/>");
ss.WriteLine(" <copy todir=\"${project::get-base-directory()}/" + targetDir + "\">");
ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}/${build.dir}/\" >");
ss.WriteLine(" <include name=\"*.dll\"/>");
ss.WriteLine(" <include name=\"*.exe\"/>");
ss.WriteLine(" <include name=\"*.mdb\" if='${build.debug}'/>");
ss.WriteLine(" <include name=\"*.pdb\" if='${build.debug}'/>");
ss.WriteLine(" </fileset>");
ss.WriteLine(" </copy>");
break;
}
}
ss.WriteLine(" </target>");
ss.WriteLine(" <target name=\"clean\">");
ss.WriteLine(" <delete dir=\"${bin.dir}\" failonerror=\"false\" />");
ss.WriteLine(" <delete dir=\"${obj.dir}\" failonerror=\"false\" />");
ss.WriteLine(" </target>");
ss.WriteLine(" <target name=\"doc\" description=\"Creates documentation.\">");
if (hasDoc)
{
ss.WriteLine(" <property name=\"doc.target\" value=\"\" />");
ss.WriteLine(" <if test=\"${platform::is-unix()}\">");
ss.WriteLine(" <property name=\"doc.target\" value=\"Web\" />");
ss.WriteLine(" </if>");
ss.WriteLine(" <ndoc failonerror=\"false\" verbose=\"true\">");
ss.WriteLine(" <assemblies basedir=\"${project::get-base-directory()}\">");
ss.Write(" <include name=\"${build.dir}/${project::get-name()}");
if (project.Type == ProjectType.Library)
{
ss.WriteLine(".dll\" />");
}
else
{
ss.WriteLine(".exe\" />");
}
ss.WriteLine(" </assemblies>");
ss.WriteLine(" <summaries basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"${build.dir}/${project::get-name()}.xml\"/>");
ss.WriteLine(" </summaries>");
ss.WriteLine(" <referencepaths basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"${build.dir}\" />");
// foreach(ReferenceNode refr in project.References)
// {
// string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReferencePath(solution, refr)), '/');
// if (path != "")
// {
// ss.WriteLine(" <include name=\"{0}\" />", path);
// }
// }
ss.WriteLine(" </referencepaths>");
ss.WriteLine(" <documenters>");
ss.WriteLine(" <documenter name=\"MSDN\">");
ss.WriteLine(" <property name=\"OutputDirectory\" value=\"${project::get-base-directory()}/${build.dir}/doc/${project::get-name()}\" />");
ss.WriteLine(" <property name=\"OutputTarget\" value=\"${doc.target}\" />");
ss.WriteLine(" <property name=\"HtmlHelpName\" value=\"${project::get-name()}\" />");
ss.WriteLine(" <property name=\"IncludeFavorites\" value=\"False\" />");
ss.WriteLine(" <property name=\"Title\" value=\"${project::get-name()} SDK Documentation\" />");
ss.WriteLine(" <property name=\"SplitTOCs\" value=\"False\" />");
ss.WriteLine(" <property name=\"DefaulTOC\" value=\"\" />");
ss.WriteLine(" <property name=\"ShowVisualBasic\" value=\"True\" />");
ss.WriteLine(" <property name=\"AutoDocumentConstructors\" value=\"True\" />");
ss.WriteLine(" <property name=\"ShowMissingSummaries\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingRemarks\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingParams\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingReturns\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingValues\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"DocumentInternals\" value=\"False\" />");
ss.WriteLine(" <property name=\"DocumentPrivates\" value=\"False\" />");
ss.WriteLine(" <property name=\"DocumentProtected\" value=\"True\" />");
ss.WriteLine(" <property name=\"DocumentEmptyNamespaces\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"IncludeAssemblyVersion\" value=\"True\" />");
ss.WriteLine(" </documenter>");
ss.WriteLine(" </documenters>");
ss.WriteLine(" </ndoc>");
}
ss.WriteLine(" </target>");
ss.WriteLine("</project>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void WriteCombine(SolutionNode solution)
{
m_Kernel.Log.Write("Creating NAnt build files");
foreach (ProjectNode project in solution.Projects)
{
if (m_Kernel.AllowProject(project.FilterGroups))
{
m_Kernel.Log.Write("...Creating project: {0}", project.Name);
WriteProject(solution, project);
}
}
m_Kernel.Log.Write("");
string combFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "build");
StreamWriter ss = new StreamWriter(combFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(combFile));
using (ss)
{
ss.WriteLine("<?xml version=\"1.0\" ?>");
ss.WriteLine("<project name=\"{0}\" default=\"build\">", solution.Name);
ss.WriteLine(" <echo message=\"Using '${nant.settings.currentframework}' Framework\"/>");
ss.WriteLine();
//ss.WriteLine(" <property name=\"dist.dir\" value=\"dist\" />");
//ss.WriteLine(" <property name=\"source.dir\" value=\"source\" />");
ss.WriteLine(" <property name=\"bin.dir\" value=\"bin\" />");
ss.WriteLine(" <property name=\"obj.dir\" value=\"obj\" />");
ss.WriteLine(" <property name=\"doc.dir\" value=\"doc\" />");
ss.WriteLine(" <property name=\"project.main.dir\" value=\"${project::get-base-directory()}\" />");
// Use the active configuration, which is the first configuration name in the prebuild file.
Dictionary<string,string> emittedConfigurations = new Dictionary<string, string>();
ss.WriteLine(" <property name=\"project.config\" value=\"{0}\" />", solution.ActiveConfig);
ss.WriteLine();
foreach (ConfigurationNode conf in solution.Configurations)
{
// If the name isn't in the emitted configurations, we give a high level target to the
// platform specific on. This lets "Debug" point to "Debug-AnyCPU".
if (!emittedConfigurations.ContainsKey(conf.Name))
{
// Add it to the dictionary so we only emit one.
emittedConfigurations.Add(conf.Name, conf.Platform);
// Write out the target block.
ss.WriteLine(" <target name=\"{0}\" description=\"{0}|{1}\" depends=\"{0}-{1}\">", conf.Name, conf.Platform);
ss.WriteLine(" </target>");
ss.WriteLine();
}
// Write out the target for the configuration.
ss.WriteLine(" <target name=\"{0}-{1}\" description=\"{0}|{1}\">", conf.Name, conf.Platform);
ss.WriteLine(" <property name=\"project.config\" value=\"{0}\" />", conf.Name);
ss.WriteLine(" <property name=\"build.debug\" value=\"{0}\" />", conf.Options["DebugInformation"].ToString().ToLower());
ss.WriteLine("\t\t <property name=\"build.platform\" value=\"{0}\" />", conf.Platform);
ss.WriteLine(" </target>");
ss.WriteLine();
}
ss.WriteLine(" <target name=\"net-1.1\" description=\"Sets framework to .NET 1.1\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-1.1\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"net-2.0\" description=\"Sets framework to .NET 2.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-2.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"net-3.5\" description=\"Sets framework to .NET 3.5\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-3.5\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-1.0\" description=\"Sets framework to mono 1.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-1.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-2.0\" description=\"Sets framework to mono 2.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-2.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-3.5\" description=\"Sets framework to mono 3.5\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-3.5\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"init\" description=\"\">");
ss.WriteLine(" <call target=\"${project.config}\" />");
ss.WriteLine(" <property name=\"sys.os.platform\"");
ss.WriteLine(" value=\"${platform::get-name()}\"");
ss.WriteLine(" />");
ss.WriteLine(" <echo message=\"Platform ${sys.os.platform}\" />");
ss.WriteLine(" <property name=\"build.dir\" value=\"${bin.dir}/${project.config}\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
// sdague - ok, this is an ugly hack, but what it lets
// us do is native include of files into the nant
// created files from all .nant/*include files. This
// lets us keep using prebuild, but allows for
// extended nant targets to do build and the like.
try
{
Regex re = new Regex(".include$");
DirectoryInfo nantdir = new DirectoryInfo(".nant");
foreach (FileSystemInfo item in nantdir.GetFileSystemInfos())
{
if (item is DirectoryInfo) { }
else if (item is FileInfo)
{
if (re.Match(item.FullName) !=
System.Text.RegularExpressions.Match.Empty)
{
Console.WriteLine("Including file: " + item.FullName);
using (FileStream fs = new FileStream(item.FullName,
FileMode.Open,
FileAccess.Read,
FileShare.None))
{
using (StreamReader sr = new StreamReader(fs))
{
ss.WriteLine("<!-- included from {0} -->", (item).FullName);
while (sr.Peek() != -1)
{
ss.WriteLine(sr.ReadLine());
}
ss.WriteLine();
}
}
}
}
}
}
catch { }
// ss.WriteLine(" <include buildfile=\".nant/local.include\" />");
// ss.WriteLine(" <target name=\"zip\" description=\"\">");
// ss.WriteLine(" <zip zipfile=\"{0}-{1}.zip\">", solution.Name, solution.Version);
// ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">");
// ss.WriteLine(" <include name=\"${project::get-base-directory()}/**/*.cs\" />");
// // ss.WriteLine(" <include name=\"${project.main.dir}/**/*\" />");
// ss.WriteLine(" </fileset>");
// ss.WriteLine(" </zip>");
// ss.WriteLine(" <echo message=\"Building zip target\" />");
// ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"clean\" description=\"\">");
ss.WriteLine(" <echo message=\"Deleting all builds from all configurations\" />");
//ss.WriteLine(" <delete dir=\"${dist.dir}\" failonerror=\"false\" />");
// justincc: FIXME FIXME FIXME - A temporary OpenSim hack to clean up files when "nant clean" is executed.
// Should be replaced with extreme prejudice once anybody finds out if the CleanFiles stuff works or there is
// another working mechanism for specifying this stuff
ss.WriteLine(" <delete failonerror=\"false\">");
ss.WriteLine(" <fileset basedir=\"${bin.dir}\">");
ss.WriteLine(" <include name=\"OpenSim*.dll\"/>");
ss.WriteLine(" <include name=\"OpenSim*.dll.mdb\"/>");
ss.WriteLine(" <include name=\"OpenSim*.exe\"/>");
ss.WriteLine(" <include name=\"OpenSim*.exe.mdb\"/>");
ss.WriteLine(" <include name=\"ScriptEngines/*\"/>");
ss.WriteLine(" <include name=\"Physics/*.dll\"/>");
ss.WriteLine(" <include name=\"Physics/*.dll.mdb\"/>");
ss.WriteLine(" <exclude name=\"OpenSim.32BitLaunch.exe\"/>");
ss.WriteLine(" <exclude name=\"ScriptEngines/Default.lsl\"/>");
ss.WriteLine(" </fileset>");
ss.WriteLine(" </delete>");
if (solution.Cleanup != null && solution.Cleanup.CleanFiles.Count > 0)
{
foreach (CleanFilesNode cleanFile in solution.Cleanup.CleanFiles)
{
ss.WriteLine(" <delete failonerror=\"false\">");
ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"{0}/*\"/>", cleanFile.Pattern);
ss.WriteLine(" <include name=\"{0}\"/>", cleanFile.Pattern);
ss.WriteLine(" </fileset>");
ss.WriteLine(" </delete>");
}
}
ss.WriteLine(" <delete dir=\"${obj.dir}\" failonerror=\"false\" />");
foreach (ProjectNode project in solution.Projects)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
ss.WriteLine(" target=\"clean\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"build\" depends=\"init\" description=\"\">");
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
ss.WriteLine(" target=\"build\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"build-release\" depends=\"Release, init, build\" description=\"Builds in Release mode\" />");
ss.WriteLine();
ss.WriteLine(" <target name=\"build-debug\" depends=\"Debug, init, build\" description=\"Builds in Debug mode\" />");
ss.WriteLine();
//ss.WriteLine(" <target name=\"package\" depends=\"clean, doc, copyfiles, zip\" description=\"Builds in Release mode\" />");
ss.WriteLine(" <target name=\"package\" depends=\"clean, doc\" description=\"Builds all\" />");
ss.WriteLine();
ss.WriteLine(" <target name=\"doc\" depends=\"build-release\">");
ss.WriteLine(" <echo message=\"Generating all documentation from all builds\" />");
foreach (ProjectNode project in solution.Projects)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
ss.WriteLine(" target=\"doc\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine("</project>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void CleanProject(ProjectNode project)
{
m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name + GetProjectExtension(project), "build");
Helper.DeleteIfExists(projectFile);
}
private void CleanSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Cleaning NAnt build files for", solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "build");
Helper.DeleteIfExists(slnFile);
foreach (ProjectNode project in solution.Projects)
{
CleanProject(project);
}
m_Kernel.Log.Write("");
}
#endregion
#region ITarget Members
/// <summary>
/// Writes the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public void Write(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach (SolutionNode solution in kern.Solutions)
{
WriteCombine(solution);
}
m_Kernel = null;
}
/// <summary>
/// Cleans the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Clean(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach (SolutionNode sol in kern.Solutions)
{
CleanSolution(sol);
}
m_Kernel = null;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return "nant";
}
}
#endregion
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace ASC.Mail.Net.SIP.Stack
{
#region usings
using System;
using System.Net;
using System.Timers;
using Message;
#endregion
/// <summary>
/// This class represent SIP UA registration.
/// </summary>
public class SIP_UA_Registration
{
#region Events
/// <summary>
/// This event is raised when registration has disposed.
/// </summary>
public event EventHandler Disposed = null;
/// <summary>
/// This event is raised when REGISTER/un-REGISTER has failed.
/// </summary>
public event EventHandler<SIP_ResponseReceivedEventArgs> Error = null;
/// <summary>
/// This event is raised when REGISTER has completed successfully.
/// </summary>
public event EventHandler Registered = null;
/// <summary>
/// This event is raised when registration state has changed.
/// </summary>
public event EventHandler StateChanged = null;
/// <summary>
/// This event is raised when un-REGISTER has completed successfully.
/// </summary>
public event EventHandler Unregistered = null;
#endregion
#region Members
private readonly string m_AOR = "";
private readonly AbsoluteUri m_pContact;
private readonly SIP_Uri m_pServer;
private readonly int m_RefreshInterval = 300;
private bool m_AutoDispose;
private bool m_AutoRefresh = true;
private bool m_IsDisposed;
private SIP_Flow m_pFlow;
private SIP_RequestSender m_pRegisterSender;
private SIP_Stack m_pStack;
private TimerEx m_pTimer;
private SIP_RequestSender m_pUnregisterSender;
private SIP_UA_RegistrationState m_State = SIP_UA_RegistrationState.Unregistered;
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="stack">Owner SIP stack.</param>
/// <param name="server">Registrar server URI. For example: sip:domain.com.</param>
/// <param name="aor">Address of record. For example: user@domain.com.</param>
/// <param name="contact">Contact URI.</param>
/// <param name="expires">Gets after how many seconds reigisration expires.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>ua</b>,<b>server</b>,<b>transport</b>,<b>aor</b> or <b>contact</b> is null reference.</exception>
/// <exception cref="ArgumentException">Is raised when any of the arguments contains invalid value.</exception>
internal SIP_UA_Registration(SIP_Stack stack,
SIP_Uri server,
string aor,
AbsoluteUri contact,
int expires)
{
if (stack == null)
{
throw new ArgumentNullException("stack");
}
if (server == null)
{
throw new ArgumentNullException("server");
}
if (aor == null)
{
throw new ArgumentNullException("aor");
}
if (aor == string.Empty)
{
throw new ArgumentException("Argument 'aor' value must be specified.");
}
if (contact == null)
{
throw new ArgumentNullException("contact");
}
m_pStack = stack;
m_pServer = server;
m_AOR = aor;
m_pContact = contact;
m_RefreshInterval = expires;
m_pTimer = new TimerEx((m_RefreshInterval - 15)*1000);
m_pTimer.AutoReset = false;
m_pTimer.Elapsed += m_pTimer_Elapsed;
m_pTimer.Enabled = false;
}
#endregion
#region Properties
/// <summary>
/// Gets registration address of record.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception>
public string AOR
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_AOR;
}
}
/// <summary>
/// If true and contact is different than received or rport, received and rport is used as contact.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception>
public bool AutoFixContact
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
// TODO:
return false;
}
}
/// <summary>
/// Gets registration contact URI.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception>
public AbsoluteUri Contact
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pContact;
}
}
/// <summary>
/// Gets after how many seconds contact expires.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception>
public int Expires
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return 3600;
}
}
/// <summary>
/// Gets if this object is disposed.
/// </summary>
public bool IsDisposed
{
get { return m_IsDisposed; }
}
/// <summary>
/// Gets registration state.
/// </summary>
public SIP_UA_RegistrationState State
{
get { return m_State; }
}
#endregion
#region Methods
/// <summary>
/// Cleans up any resources being used.
/// </summary>
public void Dispose()
{
if (m_IsDisposed)
{
return;
}
m_IsDisposed = true;
m_pStack = null;
m_pTimer.Dispose();
m_pTimer = null;
SetState(SIP_UA_RegistrationState.Disposed);
OnDisposed();
Registered = null;
Unregistered = null;
Error = null;
Disposed = null;
}
/// <summary>
/// Starts registering.
/// </summary>
/// <param name="autoRefresh">If true, registration takes care of refreshing itself to registrar server.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception>
public void BeginRegister(bool autoRefresh)
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
// Fix ME: Stack not running, try register on next step.
// In ideal solution we need to start registering when stack starts.
if (!m_pStack.IsRunning)
{
m_pTimer.Enabled = true;
return;
}
m_AutoRefresh = autoRefresh;
SetState(SIP_UA_RegistrationState.Registering);
/* RFC 3261 10.1 Constructing the REGISTER Request.
Request-URI: The Request-URI names the domain of the location service for which the registration is meant (for example,
"sip:chicago.com"). The "userinfo" and "@" components of the SIP URI MUST NOT be present.
*/
SIP_Request register = m_pStack.CreateRequest(SIP_Methods.REGISTER,
new SIP_t_NameAddress(m_pServer.Scheme + ":" + m_AOR),
new SIP_t_NameAddress(m_pServer.Scheme + ":" + m_AOR));
register.RequestLine.Uri =
SIP_Uri.Parse(m_pServer.Scheme + ":" + m_AOR.Substring(m_AOR.IndexOf('@') + 1));
register.Route.Add(m_pServer.ToString());
register.Contact.Add("<" + Contact + ">;expires=" + m_RefreshInterval);
m_pRegisterSender = m_pStack.CreateRequestSender(register, m_pFlow);
m_pRegisterSender.ResponseReceived += m_pRegisterSender_ResponseReceived;
m_pRegisterSender.Start();
}
/// <summary>
/// Starts unregistering.
/// </summary>
/// <param name="dispose">If true, registration will be disposed after unregister.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception>
public void BeginUnregister(bool dispose)
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
m_AutoDispose = dispose;
// Stop register timer, otherwise we may get register and unregister race condition.
m_pTimer.Enabled = false;
if (m_State == SIP_UA_RegistrationState.Registered)
{
/* RFC 3261 10.1 Constructing the REGISTER Request.
Request-URI: The Request-URI names the domain of the location service for which the registration is meant (for example,
"sip:chicago.com"). The "userinfo" and "@" components of the SIP URI MUST NOT be present.
*/
SIP_Request unregister = m_pStack.CreateRequest(SIP_Methods.REGISTER,
new SIP_t_NameAddress(m_pServer.Scheme + ":" +
m_AOR),
new SIP_t_NameAddress(m_pServer.Scheme + ":" +
m_AOR));
unregister.RequestLine.Uri =
SIP_Uri.Parse(m_pServer.Scheme + ":" + m_AOR.Substring(m_AOR.IndexOf('@') + 1));
unregister.Route.Add(m_pServer.ToString());
unregister.Contact.Add("<" + Contact + ">;expires=0");
m_pUnregisterSender = m_pStack.CreateRequestSender(unregister, m_pFlow);
m_pUnregisterSender.ResponseReceived += m_pUnregisterSender_ResponseReceived;
m_pUnregisterSender.Start();
}
else
{
SetState(SIP_UA_RegistrationState.Unregistered);
OnUnregistered();
if (m_AutoDispose)
{
Dispose();
}
m_pUnregisterSender = null;
}
}
#endregion
#region Utility methods
/// <summary>
/// This method is raised when registration needs to refresh server registration.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (m_pStack.IsRunning)
{
BeginRegister(m_AutoRefresh);
}
}
/// <summary>
/// This method is called when REGISTER has finished.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pRegisterSender_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e)
{
m_pFlow = e.ClientTransaction.Flow;
if (e.Response.StatusCodeType == SIP_StatusCodeType.Success)
{
SetState(SIP_UA_RegistrationState.Registered);
OnRegistered();
m_pFlow.SendKeepAlives = true;
}
else
{
SetState(SIP_UA_RegistrationState.Error);
OnError(e);
}
// REMOVE ME:
if (AutoFixContact && (m_pContact is SIP_Uri))
{
// If Via: received or rport paramter won't match to our sent-by, use received and rport to construct new contact value.
SIP_Uri cContact = ((SIP_Uri) m_pContact);
IPAddress cContactIP = Net_Utils.IsIPAddress(cContact.Host)
? IPAddress.Parse(cContact.Host)
: null;
SIP_t_ViaParm via = e.Response.Via.GetTopMostValue();
if (via != null && cContactIP != null)
{
IPEndPoint ep = new IPEndPoint(via.Received != null ? via.Received : cContactIP,
via.RPort > 0 ? via.RPort : cContact.Port);
if (!cContactIP.Equals(ep.Address) || cContact.Port != via.RPort)
{
// Unregister old contact.
BeginUnregister(false);
// Fix contact.
cContact.Host = ep.Address.ToString();
cContact.Port = ep.Port;
m_pRegisterSender.Dispose();
m_pRegisterSender = null;
BeginRegister(m_AutoRefresh);
return;
}
}
}
if (m_AutoRefresh)
{
// Set registration refresh timer.
m_pTimer.Enabled = true;
}
m_pRegisterSender.Dispose();
m_pRegisterSender = null;
}
/// <summary>
/// This method is called when un-REGISTER has finished.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pUnregisterSender_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e)
{
SetState(SIP_UA_RegistrationState.Unregistered);
OnUnregistered();
if (m_AutoDispose)
{
Dispose();
}
m_pUnregisterSender = null;
}
/// <summary>
/// Changes current registration state.
/// </summary>
/// <param name="newState">New registration state.</param>
private void SetState(SIP_UA_RegistrationState newState)
{
m_State = newState;
OnStateChanged();
}
/// <summary>
/// Raises event <b>StateChanged</b>.
/// </summary>
private void OnStateChanged()
{
if (StateChanged != null)
{
StateChanged(this, new EventArgs());
}
}
/// <summary>
/// Raises event <b>Registered</b>.
/// </summary>
private void OnRegistered()
{
if (Registered != null)
{
Registered(this, new EventArgs());
}
}
/// <summary>
/// Raises event <b>Unregistered</b>.
/// </summary>
private void OnUnregistered()
{
if (Unregistered != null)
{
Unregistered(this, new EventArgs());
}
}
/// <summary>
/// Raises event <b>Error</b>.
/// </summary>
/// <param name="e">Event data.</param>
private void OnError(SIP_ResponseReceivedEventArgs e)
{
if (Error != null)
{
Error(this, e);
}
}
/// <summary>
/// Raises event <b>Disposed</b>.
/// </summary>
private void OnDisposed()
{
if (Disposed != null)
{
Disposed(this, new EventArgs());
}
}
#endregion
}
}
| |
// /*
// * Copyright (c) 2016, Alachisoft. All Rights Reserved.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Alachisoft.NosDB.Common.Protobuf {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class AuthenticationCommand {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationCommand__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.AuthenticationCommand, global::Alachisoft.NosDB.Common.Protobuf.AuthenticationCommand.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationCommand__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static AuthenticationCommand() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChtBdXRoZW50aWNhdGlvbkNvbW1hbmQucHJvdG8SIEFsYWNoaXNvZnQuTm9z",
"REIuQ29tbW9uLlByb3RvYnVmGhlBdXRoZW50aWNhdGlvblRva2VuLnByb3Rv",
"IpgBChVBdXRoZW50aWNhdGlvbkNvbW1hbmQSUgoTYXV0aGVudGljYXRpb25U",
"b2tlbhgBIAEoCzI1LkFsYWNoaXNvZnQuTm9zREIuQ29tbW9uLlByb3RvYnVm",
"LkF1dGhlbnRpY2F0aW9uVG9rZW4SGAoQY29ubmVjdGlvblN0cmluZxgCIAEo",
"CRIRCglwcm9jZXNzSUQYAyABKAlCRQokY29tLmFsYWNoaXNvZnQubm9zZGIu",
"Y29tbW9uLnByb3RvYnVmQh1BdXRoZW50aWNhdGlvbkNvbW1hbmRQcm90b2Nv",
"bA=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationCommand__Descriptor = Descriptor.MessageTypes[0];
internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationCommand__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.AuthenticationCommand, global::Alachisoft.NosDB.Common.Protobuf.AuthenticationCommand.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationCommand__Descriptor,
new string[] { "AuthenticationToken", "ConnectionString", "ProcessID", });
return null;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Alachisoft.NosDB.Common.Protobuf.Proto.AuthenticationToken.Descriptor,
}, assigner);
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class AuthenticationCommand : pb::GeneratedMessage<AuthenticationCommand, AuthenticationCommand.Builder> {
private AuthenticationCommand() { }
private static readonly AuthenticationCommand defaultInstance = new AuthenticationCommand().MakeReadOnly();
private static readonly string[] _authenticationCommandFieldNames = new string[] { "authenticationToken", "connectionString", "processID" };
private static readonly uint[] _authenticationCommandFieldTags = new uint[] { 10, 18, 26 };
public static AuthenticationCommand DefaultInstance {
get { return defaultInstance; }
}
public override AuthenticationCommand DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override AuthenticationCommand ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.AuthenticationCommand.internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationCommand__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<AuthenticationCommand, AuthenticationCommand.Builder> InternalFieldAccessors {
get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.AuthenticationCommand.internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationCommand__FieldAccessorTable; }
}
public const int AuthenticationTokenFieldNumber = 1;
private bool hasAuthenticationToken;
private global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken authenticationToken_;
public bool HasAuthenticationToken {
get { return hasAuthenticationToken; }
}
public global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken AuthenticationToken {
get { return authenticationToken_ ?? global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken.DefaultInstance; }
}
public const int ConnectionStringFieldNumber = 2;
private bool hasConnectionString;
private string connectionString_ = "";
public bool HasConnectionString {
get { return hasConnectionString; }
}
public string ConnectionString {
get { return connectionString_; }
}
public const int ProcessIDFieldNumber = 3;
private bool hasProcessID;
private string processID_ = "";
public bool HasProcessID {
get { return hasProcessID; }
}
public string ProcessID {
get { return processID_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _authenticationCommandFieldNames;
if (hasAuthenticationToken) {
output.WriteMessage(1, field_names[0], AuthenticationToken);
}
if (hasConnectionString) {
output.WriteString(2, field_names[1], ConnectionString);
}
if (hasProcessID) {
output.WriteString(3, field_names[2], ProcessID);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasAuthenticationToken) {
size += pb::CodedOutputStream.ComputeMessageSize(1, AuthenticationToken);
}
if (hasConnectionString) {
size += pb::CodedOutputStream.ComputeStringSize(2, ConnectionString);
}
if (hasProcessID) {
size += pb::CodedOutputStream.ComputeStringSize(3, ProcessID);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static AuthenticationCommand ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static AuthenticationCommand ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static AuthenticationCommand ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static AuthenticationCommand ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static AuthenticationCommand ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static AuthenticationCommand ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static AuthenticationCommand ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static AuthenticationCommand ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static AuthenticationCommand ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static AuthenticationCommand ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private AuthenticationCommand MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(AuthenticationCommand prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<AuthenticationCommand, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(AuthenticationCommand cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private AuthenticationCommand result;
private AuthenticationCommand PrepareBuilder() {
if (resultIsReadOnly) {
AuthenticationCommand original = result;
result = new AuthenticationCommand();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override AuthenticationCommand MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Alachisoft.NosDB.Common.Protobuf.AuthenticationCommand.Descriptor; }
}
public override AuthenticationCommand DefaultInstanceForType {
get { return global::Alachisoft.NosDB.Common.Protobuf.AuthenticationCommand.DefaultInstance; }
}
public override AuthenticationCommand BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is AuthenticationCommand) {
return MergeFrom((AuthenticationCommand) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(AuthenticationCommand other) {
if (other == global::Alachisoft.NosDB.Common.Protobuf.AuthenticationCommand.DefaultInstance) return this;
PrepareBuilder();
if (other.HasAuthenticationToken) {
MergeAuthenticationToken(other.AuthenticationToken);
}
if (other.HasConnectionString) {
ConnectionString = other.ConnectionString;
}
if (other.HasProcessID) {
ProcessID = other.ProcessID;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_authenticationCommandFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _authenticationCommandFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken.CreateBuilder();
if (result.hasAuthenticationToken) {
subBuilder.MergeFrom(AuthenticationToken);
}
input.ReadMessage(subBuilder, extensionRegistry);
AuthenticationToken = subBuilder.BuildPartial();
break;
}
case 18: {
result.hasConnectionString = input.ReadString(ref result.connectionString_);
break;
}
case 26: {
result.hasProcessID = input.ReadString(ref result.processID_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasAuthenticationToken {
get { return result.hasAuthenticationToken; }
}
public global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken AuthenticationToken {
get { return result.AuthenticationToken; }
set { SetAuthenticationToken(value); }
}
public Builder SetAuthenticationToken(global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasAuthenticationToken = true;
result.authenticationToken_ = value;
return this;
}
public Builder SetAuthenticationToken(global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasAuthenticationToken = true;
result.authenticationToken_ = builderForValue.Build();
return this;
}
public Builder MergeAuthenticationToken(global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasAuthenticationToken &&
result.authenticationToken_ != global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken.DefaultInstance) {
result.authenticationToken_ = global::Alachisoft.NosDB.Common.Protobuf.AuthenticationToken.CreateBuilder(result.authenticationToken_).MergeFrom(value).BuildPartial();
} else {
result.authenticationToken_ = value;
}
result.hasAuthenticationToken = true;
return this;
}
public Builder ClearAuthenticationToken() {
PrepareBuilder();
result.hasAuthenticationToken = false;
result.authenticationToken_ = null;
return this;
}
public bool HasConnectionString {
get { return result.hasConnectionString; }
}
public string ConnectionString {
get { return result.ConnectionString; }
set { SetConnectionString(value); }
}
public Builder SetConnectionString(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasConnectionString = true;
result.connectionString_ = value;
return this;
}
public Builder ClearConnectionString() {
PrepareBuilder();
result.hasConnectionString = false;
result.connectionString_ = "";
return this;
}
public bool HasProcessID {
get { return result.hasProcessID; }
}
public string ProcessID {
get { return result.ProcessID; }
set { SetProcessID(value); }
}
public Builder SetProcessID(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasProcessID = true;
result.processID_ = value;
return this;
}
public Builder ClearProcessID() {
PrepareBuilder();
result.hasProcessID = false;
result.processID_ = "";
return this;
}
}
static AuthenticationCommand() {
object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.AuthenticationCommand.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// This is where we group together all the internal calls.
//
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Internal.Runtime;
namespace System.Runtime
{
internal enum DispatchCellType
{
InterfaceAndSlot = 0x0,
MetadataToken = 0x1,
VTableOffset = 0x2,
}
internal struct DispatchCellInfo
{
public DispatchCellType CellType;
public EETypePtr InterfaceType;
public ushort InterfaceSlot;
public byte HasCache;
public uint MetadataToken;
public uint VTableOffset;
}
// Constants used with RhpGetClasslibFunction, to indicate which classlib function
// we are interested in.
// Note: make sure you change the def in ICodeManager.h if you change this!
internal enum ClassLibFunctionId
{
GetRuntimeException = 0,
FailFast = 1,
// UnhandledExceptionHandler = 2, // unused
AppendExceptionStackFrame = 3,
CheckStaticClassConstruction = 4,
GetSystemArrayEEType = 5,
OnFirstChance = 6,
DebugFuncEvalHelper = 7,
DebugFuncEvalAbortHelper = 8,
}
internal static class InternalCalls
{
//
// internalcalls for System.GC.
//
// Force a garbage collection.
[RuntimeExport("RhCollect")]
internal static void RhCollect(int generation, InternalGCCollectionMode mode)
{
RhpCollect(generation, mode);
}
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
private static extern void RhpCollect(int generation, InternalGCCollectionMode mode);
[RuntimeExport("RhGetGcTotalMemory")]
internal static long RhGetGcTotalMemory()
{
return RhpGetGcTotalMemory();
}
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
private static extern long RhpGetGcTotalMemory();
[RuntimeExport("RhStartNoGCRegion")]
internal static Int32 RhStartNoGCRegion(Int64 totalSize, bool hasLohSize, Int64 lohSize, bool disallowFullBlockingGC)
{
return RhpStartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC);
}
[RuntimeExport("RhEndNoGCRegion")]
internal static Int32 RhEndNoGCRegion()
{
return RhpEndNoGCRegion();
}
//
// internalcalls for System.Runtime.__Finalizer.
//
// Fetch next object which needs finalization or return null if we've reached the end of the list.
[RuntimeImport(Redhawk.BaseName, "RhpGetNextFinalizableObject")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern Object RhpGetNextFinalizableObject();
//
// internalcalls for System.Runtime.InteropServices.GCHandle.
//
// Allocate handle.
[RuntimeImport(Redhawk.BaseName, "RhpHandleAlloc")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern IntPtr RhpHandleAlloc(Object value, GCHandleType type);
// Allocate dependent handle.
[RuntimeImport(Redhawk.BaseName, "RhpHandleAllocDependent")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern IntPtr RhpHandleAllocDependent(Object primary, Object secondary);
// Allocate variable handle.
[RuntimeImport(Redhawk.BaseName, "RhpHandleAllocVariable")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern IntPtr RhpHandleAllocVariable(Object value, uint type);
[RuntimeImport(Redhawk.BaseName, "RhHandleGet")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern Object RhHandleGet(IntPtr handle);
[RuntimeImport(Redhawk.BaseName, "RhHandleSet")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern IntPtr RhHandleSet(IntPtr handle, Object value);
//
// internal calls for allocation
//
[RuntimeImport(Redhawk.BaseName, "RhpNewFast")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewFast(EEType* pEEType); // BEWARE: not for finalizable objects!
[RuntimeImport(Redhawk.BaseName, "RhpNewFinalizable")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewFinalizable(EEType* pEEType);
[RuntimeImport(Redhawk.BaseName, "RhpNewArray")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewArray(EEType* pEEType, int length);
#if FEATURE_64BIT_ALIGNMENT
[RuntimeImport(Redhawk.BaseName, "RhpNewFastAlign8")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewFastAlign8(EEType * pEEType); // BEWARE: not for finalizable objects!
[RuntimeImport(Redhawk.BaseName, "RhpNewFinalizableAlign8")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewFinalizableAlign8(EEType* pEEType);
[RuntimeImport(Redhawk.BaseName, "RhpNewArrayAlign8")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewArrayAlign8(EEType* pEEType, int length);
[RuntimeImport(Redhawk.BaseName, "RhpNewFastMisalign")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewFastMisalign(EEType * pEEType);
#endif // FEATURE_64BIT_ALIGNMENT
[RuntimeImport(Redhawk.BaseName, "RhpBox")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe void RhpBox(object obj, ref byte data);
[RuntimeImport(Redhawk.BaseName, "RhUnbox")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe void RhUnbox(object obj, ref byte data, EEType* pUnboxToEEType);
[RuntimeImport(Redhawk.BaseName, "RhpCopyObjectContents")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpCopyObjectContents(object objDest, object objSrc);
[RuntimeImport(Redhawk.BaseName, "RhpCompareObjectContents")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static bool RhpCompareObjectContentsAndPadding(object obj1, object obj2);
[RuntimeImport(Redhawk.BaseName, "RhpAssignRef")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpAssignRef(ref Object address, object obj);
#if FEATURE_GC_STRESS
//
// internal calls for GC stress
//
[RuntimeImport(Redhawk.BaseName, "RhpInitializeGcStress")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpInitializeGcStress();
#endif // FEATURE_GC_STRESS
[RuntimeImport(Redhawk.BaseName, "RhpEHEnumInitFromStackFrameIterator")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe bool RhpEHEnumInitFromStackFrameIterator(ref StackFrameIterator pFrameIter, byte** pMethodStartAddress, void* pEHEnum);
[RuntimeImport(Redhawk.BaseName, "RhpEHEnumNext")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe bool RhpEHEnumNext(void* pEHEnum, void* pEHClause);
[RuntimeImport(Redhawk.BaseName, "RhpGetArrayBaseType")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe EEType* RhpGetArrayBaseType(EEType* pEEType);
[RuntimeImport(Redhawk.BaseName, "RhpHasDispatchMap")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe bool RhpHasDispatchMap(EEType* pEETypen);
[RuntimeImport(Redhawk.BaseName, "RhpGetDispatchMap")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe DispatchResolve.DispatchMap* RhpGetDispatchMap(EEType* pEEType);
[RuntimeImport(Redhawk.BaseName, "RhpGetSealedVirtualSlot")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpGetSealedVirtualSlot(EEType* pEEType, ushort slot);
[RuntimeImport(Redhawk.BaseName, "RhpGetDispatchCellInfo")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpGetDispatchCellInfo(IntPtr pCell, out DispatchCellInfo newCellInfo);
[RuntimeImport(Redhawk.BaseName, "RhpSearchDispatchCellCache")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpSearchDispatchCellCache(IntPtr pCell, EEType* pInstanceType);
[RuntimeImport(Redhawk.BaseName, "RhpUpdateDispatchCellCache")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpUpdateDispatchCellCache(IntPtr pCell, IntPtr pTargetCode, EEType* pInstanceType, ref DispatchCellInfo newCellInfo);
[RuntimeImport(Redhawk.BaseName, "RhpGetClasslibFunctionFromCodeAddress")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void* RhpGetClasslibFunctionFromCodeAddress(IntPtr address, ClassLibFunctionId id);
[RuntimeImport(Redhawk.BaseName, "RhpGetClasslibFunctionFromEEType")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void* RhpGetClasslibFunctionFromEEType(IntPtr pEEType, ClassLibFunctionId id);
//
// StackFrameIterator
//
[RuntimeImport(Redhawk.BaseName, "RhpSfiInit")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern unsafe bool RhpSfiInit(ref StackFrameIterator pThis, void* pStackwalkCtx, bool instructionFault);
[RuntimeImport(Redhawk.BaseName, "RhpSfiNext")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern bool RhpSfiNext(ref StackFrameIterator pThis, out uint uExCollideClauseIdx, out bool fUnwoundReversePInvoke);
//
// DebugEventSource
//
[RuntimeImport(Redhawk.BaseName, "RhpGetRequestedExceptionEvents")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern ExceptionEventKind RhpGetRequestedExceptionEvents();
[DllImport(Redhawk.BaseName)]
internal static extern unsafe void RhpSendExceptionEventToDebugger(ExceptionEventKind eventKind, byte* ip, UIntPtr sp);
//
// Miscellaneous helpers.
//
// Get the rarely used (optional) flags of an EEType. If they're not present 0 will be returned.
[RuntimeImport(Redhawk.BaseName, "RhpGetEETypeRareFlags")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe UInt32 RhpGetEETypeRareFlags(EEType* pEEType);
// Retrieve the offset of the value embedded in a Nullable<T>.
[RuntimeImport(Redhawk.BaseName, "RhpGetNullableEETypeValueOffset")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe byte RhpGetNullableEETypeValueOffset(EEType* pEEType);
// Retrieve the target type T in a Nullable<T>.
[RuntimeImport(Redhawk.BaseName, "RhpGetNullableEEType")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe EEType* RhpGetNullableEEType(EEType* pEEType);
// For an ICastable type return a pointer to code that implements ICastable.IsInstanceOfInterface.
[RuntimeImport(Redhawk.BaseName, "RhpGetICastableIsInstanceOfInterfaceMethod")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpGetICastableIsInstanceOfInterfaceMethod(EEType* pEEType);
// For an ICastable type return a pointer to code that implements ICastable.GetImplType.
[RuntimeImport(Redhawk.BaseName, "RhpGetICastableGetImplTypeMethod")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpGetICastableGetImplTypeMethod(EEType* pEEType);
[RuntimeImport(Redhawk.BaseName, "RhpGetNextFinalizerInitCallback")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpGetNextFinalizerInitCallback();
[RuntimeImport(Redhawk.BaseName, "RhpCallCatchFunclet")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpCallCatchFunclet(
object exceptionObj, byte* pHandlerIP, void* pvRegDisplay, ref EH.ExInfo exInfo);
[RuntimeImport(Redhawk.BaseName, "RhpCallFinallyFunclet")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpCallFinallyFunclet(byte* pHandlerIP, void* pvRegDisplay);
[RuntimeImport(Redhawk.BaseName, "RhpCallFilterFunclet")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe bool RhpCallFilterFunclet(
object exceptionObj, byte* pFilterIP, void* pvRegDisplay);
[RuntimeImport(Redhawk.BaseName, "RhpFallbackFailFast")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpFallbackFailFast();
[RuntimeImport(Redhawk.BaseName, "RhpSetThreadDoNotTriggerGC")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static void RhpSetThreadDoNotTriggerGC();
[System.Diagnostics.Conditional("DEBUG")]
[RuntimeImport(Redhawk.BaseName, "RhpValidateExInfoStack")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static void RhpValidateExInfoStack();
[RuntimeImport(Redhawk.BaseName, "RhpCopyContextFromExInfo")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpCopyContextFromExInfo(void* pOSContext, int cbOSContext, EH.PAL_LIMITED_CONTEXT* pPalContext);
[RuntimeImport(Redhawk.BaseName, "RhpGetCastableObjectDispatchHelper")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetCastableObjectDispatchHelper();
[RuntimeImport(Redhawk.BaseName, "RhpGetCastableObjectDispatchHelper_TailCalled")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetCastableObjectDispatchHelper_TailCalled();
[RuntimeImport(Redhawk.BaseName, "RhpGetCastableObjectDispatch_CommonStub")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetCastableObjectDispatch_CommonStub();
[RuntimeImport(Redhawk.BaseName, "RhpGetTailCallTLSDispatchCell")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetTailCallTLSDispatchCell();
[RuntimeImport(Redhawk.BaseName, "RhpSetTLSDispatchCell")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpSetTLSDispatchCell(IntPtr pCell);
[RuntimeImport(Redhawk.BaseName, "RhpGetNumThunkBlocksPerMapping")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static int RhpGetNumThunkBlocksPerMapping();
[RuntimeImport(Redhawk.BaseName, "RhpGetNumThunksPerBlock")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static int RhpGetNumThunksPerBlock();
[RuntimeImport(Redhawk.BaseName, "RhpGetThunkSize")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static int RhpGetThunkSize();
[RuntimeImport(Redhawk.BaseName, "RhpGetThunkDataBlockAddress")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetThunkDataBlockAddress(IntPtr thunkStubAddress);
[RuntimeImport(Redhawk.BaseName, "RhpGetThunkStubsBlockAddress")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetThunkStubsBlockAddress(IntPtr thunkDataAddress);
[RuntimeImport(Redhawk.BaseName, "RhpGetThunkBlockSize")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static int RhpGetThunkBlockSize();
[RuntimeImport(Redhawk.BaseName, "RhpGetThreadAbortException")]
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static Exception RhpGetThreadAbortException();
//------------------------------------------------------------------------------------------------------------
// PInvoke-based internal calls
//
// These either do not need to be called in cooperative mode or, in some cases, MUST be called in preemptive
// mode. Note that they must use the Cdecl calling convention due to a limitation in our .obj file linking
// support.
//------------------------------------------------------------------------------------------------------------
// Block the current thread until at least one object needs to be finalized (returns true) or
// memory is low (returns false and the finalizer thread should initiate a garbage collection).
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern UInt32 RhpWaitForFinalizerRequest();
// Indicate that the current round of finalizations is complete.
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RhpSignalFinalizationComplete();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RhpAcquireCastCacheLock();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RhpReleaseCastCacheLock();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal extern static long PalGetTickCount64();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RhpAcquireThunkPoolLock();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RhpReleaseThunkPoolLock();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr RhAllocateThunksMapping();
// Enters a no GC region, possibly doing a blocking GC if there is not enough
// memory available to satisfy the caller's request.
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern Int32 RhpStartNoGCRegion(Int64 totalSize, bool hasLohSize, Int64 lohSize, bool disallowFullBlockingGC);
// Exits a no GC region, possibly doing a GC to clean up the garbage that
// the caller allocated.
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern Int32 RhpEndNoGCRegion();
}
}
| |
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
namespace Jovian.Tools.Support
{
/// <summary>
/// Summary description for rtfFormatting.
/// </summary>
public class rtfFormatting : System.Windows.Forms.UserControl
{
private System.Windows.Forms.Button btnXML;
private System.Windows.Forms.Button btnTabBraces;
private System.Windows.Forms.Button btnExplode;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnCollapse;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Button btnTabXML;
private System.Windows.Forms.Button btnStyXML;
private System.Windows.Forms.Button btnStyJS;
private System.Windows.Forms.Button btnExtraNewLines;
private System.Windows.Forms.Button btnStySQL;
private System.Windows.Forms.Button btnCollapseExtraSpaces;
private System.Windows.Forms.Button btnSqlSmash;
private System.Windows.Forms.Button btnTrim;
private System.Windows.Forms.Button btnStyCSS;
private Button btnGrillScript;
private Button validJS;
private Button validCSS;
private JovianEdit _Owner;
public rtfFormatting(JovianEdit O)
{
_Owner = O;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitializeComponent call
SyncCmds();
}
public void Colorize(Button B)
{
if(B.Enabled)
{
B.BackColor = Color.Yellow;
}
else
{
B.BackColor = Color.DarkGray;
}
}
public void SyncCmds()
{
btnCollapse.Enabled = _Owner.Engine is Jovian.Tools.Styles.JavaScript || _Owner.Engine is Jovian.Tools.Styles.CSS|| _Owner.Engine is Jovian.Tools.Styles.GrillScript;
btnExplode.Enabled = _Owner.Engine is Jovian.Tools.Styles.JavaScript || _Owner.Engine is Jovian.Tools.Styles.CSS|| _Owner.Engine is Jovian.Tools.Styles.GrillScript;
btnTabBraces.Enabled = _Owner.Engine is Jovian.Tools.Styles.JavaScript || _Owner.Engine is Jovian.Tools.Styles.CSS|| _Owner.Engine is Jovian.Tools.Styles.GrillScript;
btnXML.Enabled = (_Owner.Engine is Jovian.Tools.Styles.XML);
btnSqlSmash.Enabled = _Owner.Engine is Jovian.Tools.Styles.SQL;
btnTrim.Enabled = _Owner.Engine is Jovian.Tools.Styles.XML;
btnTabXML.Enabled = _Owner.Engine is Jovian.Tools.Styles.XML;
validJS.Enabled = _Owner.Engine is Jovian.Tools.Styles.JavaScript;
validCSS.Enabled = _Owner.Engine is Jovian.Tools.Styles.CSS;
//btnGrillScript.Enabled = _Owner.Engine is JovianTools.Styles.GrillScript;
Colorize(btnCollapse);
Colorize(btnExplode);
Colorize(btnTabBraces);
Colorize(btnXML);
Colorize(btnTabXML);
Colorize(btnSqlSmash);
Colorize(btnTrim);
}
/// <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 Component 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.btnXML = new System.Windows.Forms.Button();
this.btnTabBraces = new System.Windows.Forms.Button();
this.btnExplode = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnGrillScript = new System.Windows.Forms.Button();
this.btnStyCSS = new System.Windows.Forms.Button();
this.btnTrim = new System.Windows.Forms.Button();
this.btnSqlSmash = new System.Windows.Forms.Button();
this.btnCollapseExtraSpaces = new System.Windows.Forms.Button();
this.btnStySQL = new System.Windows.Forms.Button();
this.btnExtraNewLines = new System.Windows.Forms.Button();
this.btnStyJS = new System.Windows.Forms.Button();
this.btnStyXML = new System.Windows.Forms.Button();
this.btnTabXML = new System.Windows.Forms.Button();
this.btnCollapse = new System.Windows.Forms.Button();
this.validJS = new System.Windows.Forms.Button();
this.validCSS = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// btnXML
//
this.btnXML.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.btnXML.Location = new System.Drawing.Point(8, 46);
this.btnXML.Name = "btnXML";
this.btnXML.Size = new System.Drawing.Size(53, 24);
this.btnXML.TabIndex = 0;
this.btnXML.Text = "Explode";
this.btnXML.UseVisualStyleBackColor = false;
this.btnXML.Click += new System.EventHandler(this.btnXML_Click);
//
// btnTabBraces
//
this.btnTabBraces.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.btnTabBraces.Location = new System.Drawing.Point(8, 16);
this.btnTabBraces.Name = "btnTabBraces";
this.btnTabBraces.Size = new System.Drawing.Size(78, 24);
this.btnTabBraces.TabIndex = 1;
this.btnTabBraces.Text = "Tab Braces";
this.btnTabBraces.UseVisualStyleBackColor = false;
this.btnTabBraces.Click += new System.EventHandler(this.btnTabBraces_Click);
//
// btnExplode
//
this.btnExplode.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.btnExplode.Location = new System.Drawing.Point(92, 16);
this.btnExplode.Name = "btnExplode";
this.btnExplode.Size = new System.Drawing.Size(66, 24);
this.btnExplode.TabIndex = 2;
this.btnExplode.Text = "Explode {}";
this.btnExplode.UseVisualStyleBackColor = false;
this.btnExplode.Click += new System.EventHandler(this.btnExplode_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.validCSS);
this.groupBox1.Controls.Add(this.validJS);
this.groupBox1.Controls.Add(this.btnGrillScript);
this.groupBox1.Controls.Add(this.btnStyCSS);
this.groupBox1.Controls.Add(this.btnTrim);
this.groupBox1.Controls.Add(this.btnSqlSmash);
this.groupBox1.Controls.Add(this.btnCollapseExtraSpaces);
this.groupBox1.Controls.Add(this.btnStySQL);
this.groupBox1.Controls.Add(this.btnExtraNewLines);
this.groupBox1.Controls.Add(this.btnStyJS);
this.groupBox1.Controls.Add(this.btnStyXML);
this.groupBox1.Controls.Add(this.btnTabXML);
this.groupBox1.Controls.Add(this.btnCollapse);
this.groupBox1.Controls.Add(this.btnExplode);
this.groupBox1.Controls.Add(this.btnTabBraces);
this.groupBox1.Controls.Add(this.btnXML);
this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(236, 140);
this.groupBox1.TabIndex = 3;
this.groupBox1.TabStop = false;
this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter);
//
// btnGrillScript
//
this.btnGrillScript.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192)))));
this.btnGrillScript.Location = new System.Drawing.Point(94, 76);
this.btnGrillScript.Name = "btnGrillScript";
this.btnGrillScript.Size = new System.Drawing.Size(38, 24);
this.btnGrillScript.TabIndex = 13;
this.btnGrillScript.Text = "fGS";
this.btnGrillScript.UseVisualStyleBackColor = false;
this.btnGrillScript.Click += new System.EventHandler(this.btnGrillScript_Click);
//
// btnStyCSS
//
this.btnStyCSS.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192)))));
this.btnStyCSS.Location = new System.Drawing.Point(184, 76);
this.btnStyCSS.Name = "btnStyCSS";
this.btnStyCSS.Size = new System.Drawing.Size(40, 24);
this.btnStyCSS.TabIndex = 12;
this.btnStyCSS.Text = "fCSS";
this.btnStyCSS.UseVisualStyleBackColor = false;
this.btnStyCSS.Click += new System.EventHandler(this.btnStyCSS_Click);
//
// btnTrim
//
this.btnTrim.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.btnTrim.Location = new System.Drawing.Point(111, 46);
this.btnTrim.Name = "btnTrim";
this.btnTrim.Size = new System.Drawing.Size(40, 24);
this.btnTrim.TabIndex = 11;
this.btnTrim.Text = "Trim";
this.btnTrim.UseVisualStyleBackColor = false;
this.btnTrim.Click += new System.EventHandler(this.btnTrim_Click);
//
// btnSqlSmash
//
this.btnSqlSmash.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.btnSqlSmash.Location = new System.Drawing.Point(157, 46);
this.btnSqlSmash.Name = "btnSqlSmash";
this.btnSqlSmash.Size = new System.Drawing.Size(74, 24);
this.btnSqlSmash.TabIndex = 10;
this.btnSqlSmash.Text = "SQL Smash";
this.btnSqlSmash.UseVisualStyleBackColor = false;
this.btnSqlSmash.Click += new System.EventHandler(this.btnSqlSmash_Click);
//
// btnCollapseExtraSpaces
//
this.btnCollapseExtraSpaces.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.btnCollapseExtraSpaces.Location = new System.Drawing.Point(54, 106);
this.btnCollapseExtraSpaces.Name = "btnCollapseExtraSpaces";
this.btnCollapseExtraSpaces.Size = new System.Drawing.Size(40, 24);
this.btnCollapseExtraSpaces.TabIndex = 9;
this.btnCollapseExtraSpaces.Text = "\" \"";
this.btnCollapseExtraSpaces.UseVisualStyleBackColor = false;
this.btnCollapseExtraSpaces.Click += new System.EventHandler(this.btnCollapseExtraSpaces_Click);
//
// btnStySQL
//
this.btnStySQL.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192)))));
this.btnStySQL.Location = new System.Drawing.Point(138, 76);
this.btnStySQL.Name = "btnStySQL";
this.btnStySQL.Size = new System.Drawing.Size(40, 24);
this.btnStySQL.TabIndex = 8;
this.btnStySQL.Text = "fSQL";
this.btnStySQL.UseVisualStyleBackColor = false;
this.btnStySQL.Click += new System.EventHandler(this.btnStySQL_Click);
//
// btnExtraNewLines
//
this.btnExtraNewLines.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.btnExtraNewLines.Location = new System.Drawing.Point(8, 106);
this.btnExtraNewLines.Name = "btnExtraNewLines";
this.btnExtraNewLines.Size = new System.Drawing.Size(40, 24);
this.btnExtraNewLines.TabIndex = 7;
this.btnExtraNewLines.Text = "\\n\\n";
this.btnExtraNewLines.UseVisualStyleBackColor = false;
this.btnExtraNewLines.Click += new System.EventHandler(this.btnExtraNewLines_Click);
//
// btnStyJS
//
this.btnStyJS.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192)))));
this.btnStyJS.Location = new System.Drawing.Point(54, 76);
this.btnStyJS.Name = "btnStyJS";
this.btnStyJS.Size = new System.Drawing.Size(32, 24);
this.btnStyJS.TabIndex = 6;
this.btnStyJS.Text = "fJS";
this.btnStyJS.UseVisualStyleBackColor = false;
this.btnStyJS.Click += new System.EventHandler(this.btnStyJS_Click);
//
// btnStyXML
//
this.btnStyXML.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192)))));
this.btnStyXML.Location = new System.Drawing.Point(8, 76);
this.btnStyXML.Name = "btnStyXML";
this.btnStyXML.Size = new System.Drawing.Size(40, 24);
this.btnStyXML.TabIndex = 5;
this.btnStyXML.Text = "fXML";
this.btnStyXML.UseVisualStyleBackColor = false;
this.btnStyXML.Click += new System.EventHandler(this.btnStyXML_Click);
//
// btnTabXML
//
this.btnTabXML.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.btnTabXML.Location = new System.Drawing.Point(67, 46);
this.btnTabXML.Name = "btnTabXML";
this.btnTabXML.Size = new System.Drawing.Size(38, 24);
this.btnTabXML.TabIndex = 4;
this.btnTabXML.Text = "Tab";
this.btnTabXML.UseVisualStyleBackColor = false;
this.btnTabXML.Click += new System.EventHandler(this.btnTabXML_Click);
//
// btnCollapse
//
this.btnCollapse.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.btnCollapse.Location = new System.Drawing.Point(164, 16);
this.btnCollapse.Name = "btnCollapse";
this.btnCollapse.Size = new System.Drawing.Size(67, 24);
this.btnCollapse.TabIndex = 3;
this.btnCollapse.Text = "Collapse {}";
this.btnCollapse.UseVisualStyleBackColor = false;
this.btnCollapse.Click += new System.EventHandler(this.btnCollapse_Click);
//
// validJS
//
this.validJS.BackColor = System.Drawing.Color.LightSteelBlue;
this.validJS.Location = new System.Drawing.Point(101, 106);
this.validJS.Name = "validJS";
this.validJS.Size = new System.Drawing.Size(50, 23);
this.validJS.TabIndex = 14;
this.validJS.Text = "vJS";
this.validJS.UseVisualStyleBackColor = false;
this.validJS.Click += new System.EventHandler(this.validJS_Click);
//
// validCSS
//
this.validCSS.BackColor = System.Drawing.Color.LightSteelBlue;
this.validCSS.Location = new System.Drawing.Point(157, 106);
this.validCSS.Name = "validCSS";
this.validCSS.Size = new System.Drawing.Size(50, 23);
this.validCSS.TabIndex = 15;
this.validCSS.Text = "vCSS";
this.validCSS.UseVisualStyleBackColor = false;
this.validCSS.Click += new System.EventHandler(this.validCSS_Click);
//
// rtfFormatting
//
this.BackColor = System.Drawing.Color.White;
this.Controls.Add(this.groupBox1);
this.Cursor = System.Windows.Forms.Cursors.Arrow;
this.Name = "rtfFormatting";
this.Size = new System.Drawing.Size(240, 143);
this.Load += new System.EventHandler(this.rtfFormatting_Load);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void btnCollapse_Click(object sender, System.EventArgs e)
{
_Owner.ApplyFormatter(new Jovian.Tools.Formating.CollapseBraces());
}
private void btnTabBraces_Click(object sender, System.EventArgs e)
{
_Owner.ApplyFormatter(new Jovian.Tools.Formating.TabBraces());
}
private void btnXML_Click(object sender, System.EventArgs e)
{
_Owner.ApplyFormatter(new Jovian.Tools.Formating.XMLSmash());
}
private void btnExplode_Click(object sender, System.EventArgs e)
{
_Owner.ApplyFormatter(new Jovian.Tools.Formating.ExplodeBraces());
}
private void btnTabXML_Click(object sender, System.EventArgs e)
{
_Owner.ApplyFormatter(new Jovian.Tools.Formating.TabXML());
}
private void btnStyXML_Click(object sender, System.EventArgs e)
{
_Owner.Engine = new Jovian.Tools.Styles.XML();
SyncCmds();
}
private void btnStyJS_Click(object sender, System.EventArgs e)
{
_Owner.Engine = new Jovian.Tools.Styles.JavaScript();
SyncCmds();
}
private void btnExtraNewLines_Click(object sender, System.EventArgs e)
{
_Owner.ApplyFormatter(new Jovian.Tools.Formating.CollapseExtraNewlines());
}
private void btnCollapseExtraSpaces_Click(object sender, System.EventArgs e)
{
_Owner.ApplyFormatter(new Jovian.Tools.Formating.CollapseExtraSpaces());
}
private void btnStySQL_Click(object sender, System.EventArgs e)
{
_Owner.Engine = new Jovian.Tools.Styles.SQL();
SyncCmds();
}
private void btnSqlSmash_Click(object sender, System.EventArgs e)
{
_Owner.ApplyFormatter(new Jovian.Tools.Formating.BlueSmash());
}
private void groupBox1_Enter(object sender, System.EventArgs e)
{
}
private void btnTrim_Click(object sender, System.EventArgs e)
{
_Owner.ApplyFormatter(new Jovian.Tools.Formating.XMLPack());
}
private void rtfFormatting_Load(object sender, System.EventArgs e)
{
}
private void btnStyCSS_Click(object sender, System.EventArgs e)
{
_Owner.Engine = new Jovian.Tools.Styles.CSS();
SyncCmds();
}
private void btnGrillScript_Click(object sender, EventArgs e)
{
_Owner.Engine = new Jovian.Tools.Styles.GrillScript();
SyncCmds();
}
private void btnClipEmptyLines_Click(object sender, EventArgs e)
{
}
private void validJS_Click(object sender, EventArgs e)
{
MessageBox.Show(JavaScriptPro.Just.Check(_Owner.Text));
}
private void validCSS_Click(object sender, EventArgs e)
{
MessageBox.Show(CascadePro.Just.Check(_Owner.Text));
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="QueryExpr.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Common.EntitySql.AST
{
using System;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Represents select kind (value,row).
/// </summary>
internal enum SelectKind
{
Value,
Row
}
/// <summary>
/// Represents join kind (cross,inner,leftouter,rightouter).
/// </summary>
internal enum JoinKind
{
Cross,
Inner,
LeftOuter,
FullOuter,
RightOuter
}
/// <summary>
/// Represents order kind (none=asc,asc,desc).
/// </summary>
internal enum OrderKind
{
None,
Asc,
Desc
}
/// <summary>
/// Represents distinct kind (none=all,all,distinct).
/// </summary>
internal enum DistinctKind
{
None,
All,
Distinct
}
/// <summary>
/// Represents apply kind (cross,outer).
/// </summary>
internal enum ApplyKind
{
Cross,
Outer
}
/// <summary>
/// Represents a query expression ast node.
/// </summary>
internal sealed class QueryExpr : Node
{
private readonly SelectClause _selectClause;
private readonly FromClause _fromClause;
private readonly Node _whereClause;
private readonly GroupByClause _groupByClause;
private readonly HavingClause _havingClause;
private readonly OrderByClause _orderByClause;
/// <summary>
/// Initializes a query expression ast node.
/// </summary>
/// <param name="selectClause">select clause</param>
/// <param name="fromClause">from clasuse</param>
/// <param name="whereClause">optional where clause</param>
/// <param name="groupByClause">optional group by clause</param>
/// <param name="havingClause">optional having clause</param>
/// <param name="orderByClause">optional order by clause</param>
internal QueryExpr(SelectClause selectClause,
FromClause fromClause,
Node whereClause,
GroupByClause groupByClause,
HavingClause havingClause,
OrderByClause orderByClause)
{
_selectClause = selectClause;
_fromClause = fromClause;
_whereClause = whereClause;
_groupByClause = groupByClause;
_havingClause = havingClause;
_orderByClause = orderByClause;
}
/// <summary>
/// Returns select clause.
/// </summary>
internal SelectClause SelectClause
{
get { return _selectClause; }
}
/// <summary>
/// Returns from clause.
/// </summary>
internal FromClause FromClause
{
get { return _fromClause; }
}
/// <summary>
/// Returns optional where clause (expr).
/// </summary>
internal Node WhereClause
{
get { return _whereClause; }
}
/// <summary>
/// Returns optional group by clause.
/// </summary>
internal GroupByClause GroupByClause
{
get { return _groupByClause; }
}
/// <summary>
/// Returns optional having clause (expr).
/// </summary>
internal HavingClause HavingClause
{
get { return _havingClause; }
}
/// <summary>
/// Returns optional order by clause.
/// </summary>
internal OrderByClause OrderByClause
{
get { return _orderByClause; }
}
/// <summary>
/// Returns true if method calls are present.
/// </summary>
internal bool HasMethodCall
{
get
{
return _selectClause.HasMethodCall ||
(null != _havingClause && _havingClause.HasMethodCall) ||
(null != _orderByClause && _orderByClause.HasMethodCall);
}
}
}
/// <summary>
/// Represents select clause.
/// </summary>
internal sealed class SelectClause : Node
{
private readonly NodeList<AliasedExpr> _selectClauseItems;
private readonly SelectKind _selectKind;
private readonly DistinctKind _distinctKind;
private readonly Node _topExpr;
private readonly uint _methodCallCount;
/// <summary>
/// Initialize SelectKind.SelectRow clause.
/// </summary>
internal SelectClause(NodeList<AliasedExpr> items, SelectKind selectKind, DistinctKind distinctKind, Node topExpr, uint methodCallCount)
{
_selectKind = selectKind;
_selectClauseItems = items;
_distinctKind = distinctKind;
_topExpr = topExpr;
_methodCallCount = methodCallCount;
}
/// <summary>
/// Projection list.
/// </summary>
internal NodeList<AliasedExpr> Items
{
get { return _selectClauseItems; }
}
/// <summary>
/// Select kind (row or value).
/// </summary>
internal SelectKind SelectKind
{
get { return _selectKind; }
}
/// <summary>
/// Distinct kind (none,all,distinct).
/// </summary>
internal DistinctKind DistinctKind
{
get { return _distinctKind; }
}
/// <summary>
/// Optional top expression.
/// </summary>
internal Node TopExpr
{
get { return _topExpr; }
}
/// <summary>
/// True if select list has method calls.
/// </summary>
internal bool HasMethodCall
{
get { return (_methodCallCount > 0); }
}
}
/// <summary>
/// Represents from clause.
/// </summary>
internal sealed class FromClause : Node
{
private readonly NodeList<FromClauseItem> _fromClauseItems;
/// <summary>
/// Initializes from clause.
/// </summary>
internal FromClause(NodeList<FromClauseItem> fromClauseItems)
{
_fromClauseItems = fromClauseItems;
}
/// <summary>
/// List of from clause items.
/// </summary>
internal NodeList<FromClauseItem> FromClauseItems
{
get { return _fromClauseItems; }
}
}
/// <summary>
/// From clause item kind.
/// </summary>
internal enum FromClauseItemKind
{
AliasedFromClause,
JoinFromClause,
ApplyFromClause
}
/// <summary>
/// Represents single from clause item.
/// </summary>
internal sealed class FromClauseItem : Node
{
private readonly Node _fromClauseItemExpr;
private readonly FromClauseItemKind _fromClauseItemKind;
/// <summary>
/// Initializes as 'simple' aliased expression.
/// </summary>
internal FromClauseItem(AliasedExpr aliasExpr)
{
_fromClauseItemExpr = aliasExpr;
_fromClauseItemKind = FromClauseItemKind.AliasedFromClause;
}
/// <summary>
/// Initializes as join clause item.
/// </summary>
internal FromClauseItem(JoinClauseItem joinClauseItem)
{
_fromClauseItemExpr = joinClauseItem;
_fromClauseItemKind = FromClauseItemKind.JoinFromClause;
}
/// <summary>
/// Initializes as apply clause item.
/// </summary>
internal FromClauseItem(ApplyClauseItem applyClauseItem)
{
_fromClauseItemExpr = applyClauseItem;
_fromClauseItemKind = FromClauseItemKind.ApplyFromClause;
}
/// <summary>
/// From clause item expression.
/// </summary>
internal Node FromExpr
{
get { return _fromClauseItemExpr; }
}
/// <summary>
/// From clause item kind (alias,join,apply).
/// </summary>
internal FromClauseItemKind FromClauseItemKind
{
get { return _fromClauseItemKind; }
}
}
/// <summary>
/// Represents group by clause.
/// </summary>
internal sealed class GroupByClause : Node
{
private readonly NodeList<AliasedExpr> _groupItems;
/// <summary>
/// Initializes GROUP BY clause
/// </summary>
internal GroupByClause(NodeList<AliasedExpr> groupItems)
{
_groupItems = groupItems;
}
/// <summary>
/// Group items.
/// </summary>
internal NodeList<AliasedExpr> GroupItems
{
get { return _groupItems; }
}
}
/// <summary>
/// Represents having clause.
/// </summary>
internal sealed class HavingClause : Node
{
private readonly Node _havingExpr;
private readonly uint _methodCallCount;
/// <summary>
/// Initializes having clause.
/// </summary>
internal HavingClause(Node havingExpr, uint methodCallCounter)
{
_havingExpr = havingExpr;
_methodCallCount = methodCallCounter;
}
/// <summary>
/// Returns having inner expression.
/// </summary>
internal Node HavingPredicate
{
get { return _havingExpr; }
}
/// <summary>
/// True if predicate has method calls.
/// </summary>
internal bool HasMethodCall
{
get { return (_methodCallCount > 0); }
}
}
/// <summary>
/// Represents order by clause.
/// </summary>
internal sealed class OrderByClause : Node
{
private readonly NodeList<OrderByClauseItem> _orderByClauseItem;
private readonly Node _skipExpr;
private readonly Node _limitExpr;
private readonly uint _methodCallCount;
/// <summary>
/// Initializes order by clause.
/// </summary>
internal OrderByClause(NodeList<OrderByClauseItem> orderByClauseItem, Node skipExpr, Node limitExpr, uint methodCallCount)
{
_orderByClauseItem = orderByClauseItem;
_skipExpr = skipExpr;
_limitExpr = limitExpr;
_methodCallCount = methodCallCount;
}
/// <summary>
/// Returns order by clause items.
/// </summary>
internal NodeList<OrderByClauseItem> OrderByClauseItem
{
get { return _orderByClauseItem; }
}
/// <summary>
/// Returns skip sub clause ast node.
/// </summary>
internal Node SkipSubClause
{
get { return _skipExpr; }
}
/// <summary>
/// Returns limit sub-clause ast node.
/// </summary>
internal Node LimitSubClause
{
get { return _limitExpr; }
}
/// <summary>
/// True if order by has method calls.
/// </summary>
internal bool HasMethodCall
{
get { return (_methodCallCount > 0); }
}
}
/// <summary>
/// Represents a order by clause item.
/// </summary>
internal sealed class OrderByClauseItem : Node
{
private readonly Node _orderExpr;
private readonly OrderKind _orderKind;
private readonly Identifier _optCollationIdentifier;
/// <summary>
/// Initializes non-collated order by clause item.
/// </summary>
internal OrderByClauseItem(Node orderExpr, OrderKind orderKind)
: this(orderExpr, orderKind, null)
{
}
/// <summary>
/// Initializes collated order by clause item.
/// </summary>
/// <param name="optCollationIdentifier">optional Collation identifier</param>
internal OrderByClauseItem(Node orderExpr, OrderKind orderKind, Identifier optCollationIdentifier)
{
_orderExpr = orderExpr;
_orderKind = orderKind;
_optCollationIdentifier = optCollationIdentifier;
}
/// <summary>
/// Oeturns order expression.
/// </summary>
internal Node OrderExpr
{
get { return _orderExpr; }
}
/// <summary>
/// Returns order kind (none,asc,desc).
/// </summary>
internal OrderKind OrderKind
{
get { return _orderKind; }
}
/// <summary>
/// Returns collattion identifier if one exists.
/// </summary>
internal Identifier Collation
{
get { return _optCollationIdentifier; }
}
}
/// <summary>
/// Represents join clause item.
/// </summary>
internal sealed class JoinClauseItem : Node
{
private readonly FromClauseItem _joinLeft;
private readonly FromClauseItem _joinRight;
private JoinKind _joinKind;
private readonly Node _onExpr;
/// <summary>
/// Initializes join clause item without ON expression.
/// </summary>
internal JoinClauseItem(FromClauseItem joinLeft, FromClauseItem joinRight, JoinKind joinKind)
: this(joinLeft, joinRight, joinKind, null)
{
}
/// <summary>
/// Initializes join clause item with ON expression.
/// </summary>
internal JoinClauseItem(FromClauseItem joinLeft, FromClauseItem joinRight, JoinKind joinKind, Node onExpr)
{
_joinLeft = joinLeft;
_joinRight = joinRight;
_joinKind = joinKind;
_onExpr = onExpr;
}
/// <summary>
/// Returns join left expression.
/// </summary>
internal FromClauseItem LeftExpr
{
get { return _joinLeft; }
}
/// <summary>
/// Returns join right expression.
/// </summary>
internal FromClauseItem RightExpr
{
get { return _joinRight; }
}
/// <summary>
/// Join kind (cross, inner, full, left outer,right outer).
/// </summary>
internal JoinKind JoinKind
{
get { return _joinKind; }
set { _joinKind = value; }
}
/// <summary>
/// Returns join on expression.
/// </summary>
internal Node OnExpr
{
get { return _onExpr; }
}
}
/// <summary>
/// Represents apply expression.
/// </summary>
internal sealed class ApplyClauseItem : Node
{
private readonly FromClauseItem _applyLeft;
private readonly FromClauseItem _applyRight;
private readonly ApplyKind _applyKind;
/// <summary>
/// Initializes apply clause item.
/// </summary>
internal ApplyClauseItem(FromClauseItem applyLeft, FromClauseItem applyRight, ApplyKind applyKind)
{
_applyLeft = applyLeft;
_applyRight = applyRight;
_applyKind = applyKind;
}
/// <summary>
/// Returns apply left expression.
/// </summary>
internal FromClauseItem LeftExpr
{
get { return _applyLeft; }
}
/// <summary>
/// Returns apply right expression.
/// </summary>
internal FromClauseItem RightExpr
{
get { return _applyRight; }
}
/// <summary>
/// Returns apply kind (cross,outer).
/// </summary>
internal ApplyKind ApplyKind
{
get { return _applyKind; }
}
}
}
| |
/*
Copyright (c) 2005-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Runtime.Remoting.Messaging;
using PHP.Core.Reflection;
using PHP.Core.Emit;
using System.Collections.Generic;
namespace PHP.Core
{
/// <summary>
/// Represents a set of data associated with the current web request targeting PHP scripts.
/// </summary>
public sealed partial class RequestContext : IDisposable, ILogicalThreadAffinative
{
#region Initialization etc.
static RequestContext()
{
if (HttpContext.Current != null)
DebugUtils.WebInitialize();
}
/// <summary>
/// The request context associated with the current thread executing the request.
/// Set by <see cref="Initialize"/> method when the request starts.
/// Contains a <B>null</B> reference when the current thread is not executing any web request
/// (or prior to the call to <see cref="Initialize"/> method).
/// </summary>
[DebuggerNonUserCode]
public static RequestContext CurrentContext
{
get
{
RequestContext info;
ThreadStatic.Properties.TryGetProperty<RequestContext>(out info);
return info;
}
set
{
ThreadStatic.Properties.SetProperty<RequestContext>(value);
}
}
private RequestContext(HttpContext/*!*/ httpContext)
{
this.httpContext = httpContext;
this.connectionAborted = false;
this.responseFilter = null;
// Initialized on the first use (work item 13528)
// (because the HttpRequest object is not available until
// the module is actually processing an event in the Request pipeline.)
this.requestFile = null;
}
/// <summary>
/// Source file targeted by the request.
/// </summary>
public PhpSourceFile/*!*/ RequestFile
{
get
{
// called by PHP.Core.RequestHandler.ProcessRequest
if (requestFile == null)
{
requestFile = new PhpSourceFile(
new FullPath(HttpRuntime.AppDomainAppPath, false),
new FullPath(httpContext.Request.PhysicalPath, false)
);
}
return requestFile;
}
}
private PhpSourceFile/*!*/ requestFile;
/// <summary>
/// Current HTTP context.
/// </summary>
public HttpContext/*!*/ HttpContext { get { return httpContext; } }
private HttpContext/*!*/ httpContext;
#endregion
#region Request Processing
/// <summary>
/// Initializes the context.
/// </summary>
private void Initialize(ApplicationContext/*!*/ appContext)
{
Debug.Assert(appContext != null);
defaultResponseEncoding = httpContext.Response.ContentEncoding;
scriptContext = ScriptContext.InitWebRequest(appContext, httpContext);
TrackClientDisconnection = !scriptContext.Config.RequestControl.IgnoreUserAbort;
// Session is ended after destructing objects since PHP 5.0.5, use two-phase finalization:
scriptContext.TryDispose += () =>
{
this.TryDisposeBeforeFinalization(); // ends session
// finalize objects created during session closing and output finalization:
this.scriptContext.GuardedCall<object, object>(this.scriptContext.FinalizePhpObjects, null, false);
// Platforms-specific dispose
this.TryDisposeAfterFinalization(); // flushes headers
};
// Platforms-specific finally dispose
scriptContext.FinallyDispose += FinallyDispose;
//
if (RequestBegin != null) RequestBegin();
}
/// <summary>
/// Creates and initializes request and script contexts associated with the current thread.
/// </summary>
/// <param name="appContext">Application context.</param>
/// <param name="context">Current HTTP context.</param>
/// <returns>The initialized request context.</returns>
/// <remarks>
/// <para>
/// Request context provides PHP with the web server environment.
/// It should be initialized before any PHP code is invoked within web server and finalized (disposed)
/// at the end of the request. This method can be called for multiple times, however it creates and
/// initializes a new request context only once per HTTP request.
/// </para>
/// <para>
/// The following steps take place during the initialization (in this order):
/// <list type="number">
/// <term>Configuration is loaded (if not loaded yet).</term>
/// <term>A new instance of <see cref="RequestContext"/> is created and bound to the current thread.</term>
/// <term>A new instance of <see cref="ScriptContext"/> is created and initialized.</term>
/// <term>Event <see cref="RequestBegin"/> is fired.</term>
/// <term>Session is started if session auto-start confgiuration option is switched on.</term>
/// </list>
/// </para>
/// <para>
/// The request context can be accessed via the returned instance or via <see cref="CurrentContext"/>
/// thread static field anytime between the initialization and disposal.
/// </para>
/// </remarks>
public static RequestContext/*!*/ Initialize(ApplicationContext/*!*/ appContext, HttpContext/*!*/ context)
{
if (appContext == null)
throw new ArgumentNullException("appContext");
if (context == null)
throw new ArgumentNullException("context");
RequestContext req_context = CurrentContext;
// already initialized within the current request:
if (req_context != null && req_context.httpContext.Timestamp == context.Timestamp)
return req_context;
Debug.WriteLine("REQUEST", "-- started ----------------------");
req_context = new RequestContext(context);
CurrentContext = req_context;
req_context.Initialize(appContext);
return req_context;
}
/// <summary>
/// Invokes <see cref="RequestBegin"/>.
/// </summary>
internal static void InvokeRequestBegin()
{
var callback = RequestContext.RequestBegin;
if (callback != null)
callback();
}
/// <summary>
/// Invokes <see cref="RequestEnd"/>.
/// </summary>
internal static void InvokeRequestEnd()
{
var callback = RequestContext.RequestEnd;
if (callback != null)
callback();
}
/// <summary>
/// Finalizes (disposes) the current request context, if there is any.
/// </summary>
public static void FinalizeContext()
{
RequestContext req_context = CurrentContext;
if (req_context != null) req_context.Dispose();
}
#endregion
#region Temporary Per-Request Files
/// <summary>
/// A list of temporary files which was created during the request and should be deleted at its end.
/// </summary>
private List<string>/*!*/TemporaryFiles
{
get
{
if (this._temporaryFiles == null)
this._temporaryFiles = new List<string>();
return this._temporaryFiles;
}
}
private List<string> _temporaryFiles;
/// <summary>
/// Silently deletes all temporary files.
/// </summary>
private void DeleteTemporaryFiles()
{
if (this._temporaryFiles != null)
{
for (int i = 0; i < this._temporaryFiles.Count; i++)
{
try
{
File.Delete(this._temporaryFiles[i]);
}
catch { }
}
this._temporaryFiles = null;
}
}
/// <summary>
/// Adds temporary file to current handler's temp files list.
/// </summary>
/// <param name="path">A path to the file.</param>
internal void AddTemporaryFile(string path)
{
Debug.Assert(path != null);
this.TemporaryFiles.Add(path);
}
/// <summary>
/// Checks whether the given filename is a path to a temporary file
/// (for example created using the filet upload mechanism).
/// </summary>
/// <remarks>
/// The stored paths are checked case-insensitively.
/// </remarks>
/// <exception cref="ArgumentNullException">Argument is a <B>null</B> reference.</exception>
public bool IsTemporaryFile(string path)
{
if (path == null) throw new ArgumentNullException("path");
return this._temporaryFiles != null && this._temporaryFiles.IndexOf(path, FullPath.StringComparer) >= 0;
}
/// <summary>
/// Removes a file from a list of temporary files.
/// </summary>
/// <param name="path">A full path to the file.</param>
/// <exception cref="ArgumentNullException">Argument is a <B>null</B> reference.</exception>
public bool RemoveTemporaryFile(string path)
{
if (path == null) throw new ArgumentNullException("path");
if (this._temporaryFiles == null)
return false;
var index = this._temporaryFiles.IndexOf(path, FullPath.StringComparer);
if (index >= 0)
{
this._temporaryFiles.RemoveAt(index);
return true;
}
else
{
return false;
}
}
#endregion
#region Connection
#region Nested Class: Response Filter
/// <summary>
/// A filter installed on the response. All data sent to the client go through this filter.
/// The filter checks whether the client is connected or not while flushing the data.
/// If the state changes from connected to disconnected then a callback specified in the ctor is invoked.
/// </summary>
private class ResponseFilter : Stream
{
private Action clientDisconnected;
private HttpResponse response;
public Stream Sink { get { return sink; } }
private Stream sink;
public ResponseFilter(HttpResponse response, Action clientDisconnected)
{
this.sink = response.Filter;
this.response = response;
this.clientDisconnected = clientDisconnected;
}
public override void Flush()
{
if (clientDisconnected != null && !response.IsClientConnected)
{
// throws ScriptDiedException:
clientDisconnected();
}
sink.Flush();
}
#region Pass thru
public override bool CanRead { get { return sink.CanRead; } }
public override bool CanSeek { get { return sink.CanSeek; } }
public override bool CanWrite { get { return sink.CanWrite; } }
public override void Write(byte[] buffer, int offset, int count)
{
sink.Write(buffer, offset, count);
}
public override long Length
{
get
{
return sink.Length;
}
}
public override long Position
{
get
{
return sink.Position;
}
set
{
sink.Position = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return sink.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return sink.Seek(offset, origin);
}
public override void SetLength(long value)
{
sink.SetLength(value);
}
#endregion
}
#endregion
/// <summary>
/// Gets whether the connection has been aborted due to client disconnection.
/// It doesn't check, however, whether the client is connected right now.
/// </summary>
public bool ConnectionAborted { get { return connectionAborted; } }
bool connectionAborted;
/// <summary>
/// Enables tracking for client disconnecion.
/// </summary>
public bool TrackClientDisconnection
{
get
{
return responseFilter != null && httpContext.Response.Filter == responseFilter;
}
set
{
// ignores the value if connection has been aborted or filtering is not supported:
if (value && !connectionAborted && httpContext.Response.Filter != null)
{
if (responseFilter == null)
responseFilter = new ResponseFilter(httpContext.Response, new Action(ClientDisconnected));
httpContext.Response.Filter = responseFilter;
}
else
{
if (responseFilter != null)
httpContext.Response.Filter = responseFilter.Sink;
}
}
}
private ResponseFilter responseFilter;
private void ClientDisconnected()
{
if (httpContext == null)
return; //already disposed
// switch off tracking;
// if connection has been aborted then we needn't to track it any more:
TrackClientDisconnection = false;
connectionAborted = true;
throw new ScriptDiedException();
}
#endregion
#region Session
/// <summary>
/// Whether a session has been started (i.e. session variables has been loaded).
/// </summary>
public SessionStates SessionState { get { return sessionState; } }
private SessionStates sessionState = SessionStates.Closed;
/// <summary>
/// Gets whether a session exists (i.e. has been started or is being closed).
/// </summary>
public bool SessionExists
{
get { return sessionState == SessionStates.Started || sessionState == SessionStates.Closing; }
}
/// <summary>
/// Ensures that Session ID is set, so calls to Flush() don't cause issues
/// (if flush() is called, session ID can't be set because cookie can't be created).
/// </summary>
private void EnsureSessionId()
{
Debug.Assert(httpContext != null);
if (httpContext.Session != null && httpContext.Session.IsNewSession && httpContext.Session.Count == 0)
{
// Ensure the internal method SessionStateModule.DelayedGetSessionId() is called now,
// not after the request is processed if no one uses SessionId during the request.
// Otherwise it causes an attempt to save the Session ID when the response stream was already flushed.
var ensureId = httpContext.Session.SessionID;
System.Diagnostics.Debug.WriteLine("SessionId: " + ensureId);
}
}
/// <summary>
/// Adds/update a SID global PHP constant.
/// </summary>
/// <remarks>The constant is non-empty only for cookie-less sessions.</remarks>
public void UpdateSID()
{
Debug.Assert(httpContext.Session != null);
scriptContext.Constants["SID", false] = (httpContext.Session.IsCookieless) ? String.Concat(AspNetSessionHandler.AspNetSessionName, "=", httpContext.Session.SessionID) : String.Empty;
}
/// <summary>
/// Starts session if not already started. Loads session variables from <c>HttpContext.Session</c>.
/// </summary>
/// <para>
/// Session state (<c>HttpContext.Session</c>) has to be available at the time of the call.
/// Otherwise, an exception occurs.
/// </para>
/// <para>
/// Starting the session inheres in importing session variables from the session data store.
/// The store is specific to the current PHP session handler
/// defined by configuration option <see cref="LocalConfiguration.SessionSection.Handler"/>.
/// In the case the ASP.NET handler is active, values from <c>HttpContext.Session</c> are imported to
/// <c>$_SESSION</c> PHP auto-global variable. Hence, items added to the <c>HttpContext.Session</c> by
/// non-PHP code after the start of the session will not be visible to PHP code. The <c>$_SESSION</c> variable
/// has to be updated directly (see <c>ScriptContext.AutoGlobals</c>) to make these items visible to PHP.
/// </para>
/// <exception cref="SessionException">Session state not available.</exception>
public void StartSession()
{
// checks and changes session state:
if (disposed || sessionState != SessionStates.Closed) return;
sessionState = SessionStates.Starting;
if (httpContext.Session == null)
throw new SessionException(CoreResources.GetString("session_state_unavailable"));
EnsureSessionId();
GlobalConfiguration global = Configuration.Global;
PhpArray variables = null;
// removes dummy item keeping the session alive:
if (httpContext.Session[AspNetSessionHandler.PhpNetSessionVars] as string == AspNetSessionHandler.DummySessionItem)
httpContext.Session.Remove(AspNetSessionHandler.PhpNetSessionVars);
// loads an array of session variables using the current session handler:
variables = scriptContext.Config.Session.Handler.Load(scriptContext, httpContext);
// variables cannot be null:
if (variables == null)
variables = new PhpArray();
// sets the auto-global variable (the previous content of $_SESSION array is discarded):
PhpReference.SetValue(ref scriptContext.AutoGlobals.Session, variables);
// copies session variables to $GLOBALS array if necessary:
if (global.GlobalVariables.RegisterGlobals)
scriptContext.RegisterSessionGlobals();
// adds a SID constant:
UpdateSID();
sessionState = SessionStates.Started;
}
/// <summary>
/// Ends session, i.e. stores content of the $_SESSION array to the <c>HttpContext.Session</c> collection.
/// </summary>
/// <param name="abandon">Whether to abandon the session without persisting variables.</param>
/// <exception cref="SessionException">Session state not available.</exception>
public void EndSession(bool abandon)
{
// checks and changes session state:
if (disposed || sessionState != SessionStates.Started) return;
sessionState = SessionStates.Closing;
if (httpContext.Session == null)
throw new SessionException(CoreResources.GetString("session_state_unavailable"));
GlobalConfiguration global = Configuration.Global;
PhpArray variables = PhpReference.AsPhpArray(scriptContext.AutoGlobals.Session);
if (variables == null) variables = new PhpArray();
try
{
if (!abandon)
scriptContext.Config.Session.Handler.Persist(variables, scriptContext, httpContext);
else
scriptContext.Config.Session.Handler.Abandoning(scriptContext, httpContext);
}
finally
{
if (!abandon)
{
// if ASP.NET session state is empty then adds a dump item to preserve the session:
if (httpContext.Session.Count == 0)
httpContext.Session.Add(AspNetSessionHandler.PhpNetSessionVars, AspNetSessionHandler.DummySessionItem);
}
else
{
// abandons ASP.NET session:
httpContext.Session.Abandon();
}
sessionState = SessionStates.Closed;
}
}
/// <summary>
/// Gets or sets a lifetime of the session cookie.
/// Cookie expiration is updated after the request using this value.
/// Non-positive value means infinite.
/// </summary>
public int SessionCookieLifetime
{
get
{
HttpCookie cookie = AspNetSessionHandler.GetCookie(httpContext);
if (cookie != null && cookie.Expires != DateTime.MinValue)
{
// expiration time has been set when the request has been processed by ASP.NET server;
// that shouldn't take more than half a minute so the precision is enought:
TimeSpan span = cookie.Expires - httpContext.Timestamp;
return (span.Minutes < 0) ? 0 : span.Minutes;
}
else
{
return 0;
}
}
set
{
sessionCookieLifetime = value;
sessionCookieLifetimeSet = true;
}
}
private int sessionCookieLifetime;
private bool sessionCookieLifetimeSet = false;
/// <summary>
/// Updates the session cookie expiration time using <see cref="SessionCookieLifetime"/> field.
/// Called at the end of the request.
/// </summary>
private void UpdateSessionCookieExpiration()
{
if (sessionCookieLifetimeSet)
{
HttpCookie cookie = AspNetSessionHandler.GetCookie(httpContext);
if (cookie != null)
{
cookie.Expires = (sessionCookieLifetime <= 0) ? DateTime.MinValue : DateTime.Now.AddMinutes(sessionCookieLifetime);
}
}
}
#endregion
#region Cleanup
void TryDisposeBeforeFinalization()
{
scriptContext.GuardedCall<object,object>((_) => { EndSession(false); return null; }, null, false);
}
void TryDisposeAfterFinalization()
{
// flushes headers (if it wasn't done earlier)
scriptContext.Headers.Flush(HttpContext);
}
void FinallyDispose()
{
DeleteTemporaryFiles();
// updates session cookie expiration stamp:
UpdateSessionCookieExpiration();
this.httpContext = null;
CurrentContext = null;
}
#endregion
#region Compilation
internal MultiScriptAssembly[]/*!!*/GetPrecompiledAssemblies()
{
return scriptContext.ApplicationContext.RuntimeCompilerManager.GetPrecompiledAssemblies();
}
/// <summary>
/// Get the precompiled script from several locations - script library database, precompiled SSA, precompiled MSA (WebPages.dll).
/// </summary>
/// <param name="sourceFile">The source file of the script to retrieve.</param>
/// <returns>The <see cref="ScriptInfo"/> of required script or null if such script cannot be obtained.</returns>
internal ScriptInfo GetCompiledScript(PhpSourceFile/*!*/ sourceFile)
{
return scriptContext.ApplicationContext.RuntimeCompilerManager.GetCompiledScript(sourceFile, this);
}
#endregion
}
}
| |
// $ANTLR 2.7.6 (20061021): "iCal.g" -> "iCalLexer.cs"$
using System.Text;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using DDay.iCal.Serialization;
using DDay.iCal.Serialization.iCalendar;
namespace DDay.iCal
{
// Generate header specific to lexer CSharp file
using System;
using Stream = System.IO.Stream;
using TextReader = System.IO.TextReader;
using Hashtable = System.Collections.Hashtable;
using Comparer = System.Collections.Comparer;
using TokenStreamException = antlr.TokenStreamException;
using TokenStreamIOException = antlr.TokenStreamIOException;
using TokenStreamRecognitionException = antlr.TokenStreamRecognitionException;
using CharStreamException = antlr.CharStreamException;
using CharStreamIOException = antlr.CharStreamIOException;
using ANTLRException = antlr.ANTLRException;
using CharScanner = antlr.CharScanner;
using InputBuffer = antlr.InputBuffer;
using ByteBuffer = antlr.ByteBuffer;
using CharBuffer = antlr.CharBuffer;
using Token = antlr.Token;
using IToken = antlr.IToken;
using CommonToken = antlr.CommonToken;
using SemanticException = antlr.SemanticException;
using RecognitionException = antlr.RecognitionException;
using NoViableAltForCharException = antlr.NoViableAltForCharException;
using MismatchedCharException = antlr.MismatchedCharException;
using TokenStream = antlr.TokenStream;
using LexerSharedInputState = antlr.LexerSharedInputState;
using BitSet = antlr.collections.impl.BitSet;
public class iCalLexer : antlr.CharScanner , TokenStream
{
public const int EOF = 1;
public const int NULL_TREE_LOOKAHEAD = 3;
public const int CRLF = 4;
public const int BEGIN = 5;
public const int COLON = 6;
public const int VCALENDAR = 7;
public const int END = 8;
public const int IANA_TOKEN = 9;
public const int X_NAME = 10;
public const int SEMICOLON = 11;
public const int EQUAL = 12;
public const int COMMA = 13;
public const int DQUOTE = 14;
public const int CTL = 15;
public const int BACKSLASH = 16;
public const int NUMBER = 17;
public const int DOT = 18;
public const int CR = 19;
public const int LF = 20;
public const int ALPHA = 21;
public const int DIGIT = 22;
public const int DASH = 23;
public const int UNDERSCORE = 24;
public const int UNICODE = 25;
public const int SPECIAL = 26;
public const int SPACE = 27;
public const int HTAB = 28;
public const int SLASH = 29;
public const int ESCAPED_CHAR = 30;
public const int LINEFOLDER = 31;
public iCalLexer(Stream ins) : this(new ByteBuffer(ins))
{
}
public iCalLexer(TextReader r) : this(new CharBuffer(r))
{
}
public iCalLexer(InputBuffer ib) : this(new LexerSharedInputState(ib))
{
}
public iCalLexer(LexerSharedInputState state) : base(state)
{
initialize();
}
private void initialize()
{
caseSensitiveLiterals = true;
setCaseSensitive(true);
literals = new Hashtable(100, (float) 0.4, null, Comparer.Default);
}
override public IToken nextToken() //throws TokenStreamException
{
IToken theRetToken = null;
tryAgain:
for (;;)
{
IToken _token = null;
int _ttype = Token.INVALID_TYPE;
resetText();
try // for char stream error handling
{
try // for lexical error handling
{
switch ( cached_LA1 )
{
case '\n':
{
mLF(true);
theRetToken = returnToken_;
break;
}
case ' ':
{
mSPACE(true);
theRetToken = returnToken_;
break;
}
case '\t':
{
mHTAB(true);
theRetToken = returnToken_;
break;
}
case ':':
{
mCOLON(true);
theRetToken = returnToken_;
break;
}
case ';':
{
mSEMICOLON(true);
theRetToken = returnToken_;
break;
}
case ',':
{
mCOMMA(true);
theRetToken = returnToken_;
break;
}
case '.':
{
mDOT(true);
theRetToken = returnToken_;
break;
}
case '=':
{
mEQUAL(true);
theRetToken = returnToken_;
break;
}
case '/':
{
mSLASH(true);
theRetToken = returnToken_;
break;
}
case '"':
{
mDQUOTE(true);
theRetToken = returnToken_;
break;
}
default:
if ((cached_LA1=='\r') && (cached_LA2=='\n') && (LA(3)=='\t'||LA(3)==' '))
{
mLINEFOLDER(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='\r') && (cached_LA2=='\n') && (true)) {
mCRLF(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='\\') && (tokenSet_0_.member(cached_LA2))) {
mESCAPED_CHAR(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='\\') && (true)) {
mBACKSLASH(true);
theRetToken = returnToken_;
}
else if ((tokenSet_1_.member(cached_LA1)) && (true)) {
mCTL(true);
theRetToken = returnToken_;
}
else if ((tokenSet_2_.member(cached_LA1))) {
mIANA_TOKEN(true);
theRetToken = returnToken_;
}
else
{
if (cached_LA1==EOF_CHAR) { uponEOF(); returnToken_ = makeToken(Token.EOF_TYPE); }
else {throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());}
}
break; }
if ( null==returnToken_ ) goto tryAgain; // found SKIP token
_ttype = returnToken_.Type;
_ttype = testLiteralsTable(_ttype);
returnToken_.Type = _ttype;
return returnToken_;
}
catch (RecognitionException e) {
throw new TokenStreamRecognitionException(e);
}
}
catch (CharStreamException cse) {
if ( cse is CharStreamIOException ) {
throw new TokenStreamIOException(((CharStreamIOException)cse).io);
}
else {
throw new TokenStreamException(cse.Message);
}
}
}
}
protected void mCR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = CR;
match('\u000d');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLF(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LF;
match('\u000a');
_ttype = Token.SKIP;
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mALPHA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ALPHA;
switch ( cached_LA1 )
{
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z':
{
matchRange('\u0041','\u005a');
break;
}
case 'a': case 'b': case 'c': case 'd':
case 'e': case 'f': case 'g': case 'h':
case 'i': case 'j': case 'k': case 'l':
case 'm': case 'n': case 'o': case 'p':
case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x':
case 'y': case 'z':
{
matchRange('\u0061','\u007a');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mDIGIT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DIGIT;
matchRange('\u0030','\u0039');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mDASH(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DASH;
match('\u002d');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mUNDERSCORE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = UNDERSCORE;
match('\u005F');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mUNICODE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = UNICODE;
matchRange('\u0100','\uFFFE');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mSPECIAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SPECIAL;
switch ( cached_LA1 )
{
case '!':
{
match('\u0021');
break;
}
case '#': case '$': case '%': case '&':
case '\'': case '(': case ')': case '*':
case '+':
{
matchRange('\u0023','\u002b');
break;
}
case '<':
{
match('\u003c');
break;
}
case '>': case '?': case '@':
{
matchRange('\u003e','\u0040');
break;
}
case '[':
{
match('\u005b');
break;
}
case ']': case '^':
{
matchRange('\u005d','\u005e');
break;
}
case '`':
{
match('\u0060');
break;
}
case '{': case '|': case '}': case '~':
{
matchRange('\u007b','\u007e');
break;
}
default:
if (((cached_LA1 >= '\u0080' && cached_LA1 <= '\u00ff')))
{
matchRange('\u0080','\u00ff');
}
else
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
break; }
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSPACE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SPACE;
match('\u0020');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mHTAB(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = HTAB;
match('\u0009');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = COLON;
match('\u003a');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSEMICOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SEMICOLON;
match('\u003b');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCOMMA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = COMMA;
match('\u002c');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mDOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DOT;
match('\u002e');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mEQUAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = EQUAL;
match('\u003d');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mBACKSLASH(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = BACKSLASH;
match('\u005c');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSLASH(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SLASH;
match('\u002f');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mDQUOTE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DQUOTE;
match('\u0022');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCRLF(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = CRLF;
mCR(false);
mLF(false);
newline();
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCTL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = CTL;
switch ( cached_LA1 )
{
case '\u0000': case '\u0001': case '\u0002': case '\u0003':
case '\u0004': case '\u0005': case '\u0006': case '\u0007':
case '\u0008':
{
matchRange('\u0000','\u0008');
break;
}
case '\u000b': case '\u000c': case '\r': case '\u000e':
case '\u000f': case '\u0010': case '\u0011': case '\u0012':
case '\u0013': case '\u0014': case '\u0015': case '\u0016':
case '\u0017': case '\u0018': case '\u0019': case '\u001a':
case '\u001b': case '\u001c': case '\u001d': case '\u001e':
case '\u001f':
{
matchRange('\u000b','\u001F');
break;
}
case '\u007f':
{
match('\u007F');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mESCAPED_CHAR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ESCAPED_CHAR;
mBACKSLASH(false);
{
switch ( cached_LA1 )
{
case '\\':
{
mBACKSLASH(false);
break;
}
case '"':
{
mDQUOTE(false);
break;
}
case ';':
{
mSEMICOLON(false);
break;
}
case ',':
{
mCOMMA(false);
break;
}
case 'N':
{
match("N");
break;
}
case 'n':
{
match("n");
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mIANA_TOKEN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = IANA_TOKEN;
{ // ( ... )+
int _cnt82=0;
for (;;)
{
switch ( cached_LA1 )
{
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z': case 'a': case 'b':
case 'c': case 'd': case 'e': case 'f':
case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r':
case 's': case 't': case 'u': case 'v':
case 'w': case 'x': case 'y': case 'z':
{
mALPHA(false);
break;
}
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
{
mDIGIT(false);
break;
}
case '-':
{
mDASH(false);
break;
}
case '_':
{
mUNDERSCORE(false);
break;
}
default:
if ((tokenSet_3_.member(cached_LA1)))
{
mSPECIAL(false);
}
else if (((cached_LA1 >= '\u0100' && cached_LA1 <= '\ufffe'))) {
mUNICODE(false);
}
else
{
if (_cnt82 >= 1) { goto _loop82_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; }
}
break; }
_cnt82++;
}
_loop82_breakloop: ;
} // ( ... )+
string s = text.ToString(_begin, text.Length-_begin);
int val;
if (int.TryParse(s, out val))
_ttype = NUMBER;
else
{
switch(s.ToUpper())
{
case "BEGIN": _ttype = BEGIN; break;
case "END": _ttype = END; break;
case "VCALENDAR": _ttype = VCALENDAR; break;
default:
if (s.Length > 2 && s.Substring(0,2).Equals("X-"))
_ttype = X_NAME;
break;
}
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLINEFOLDER(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LINEFOLDER;
mCRLF(false);
{
switch ( cached_LA1 )
{
case ' ':
{
mSPACE(false);
break;
}
case '\t':
{
mHTAB(false);
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
_ttype = Token.SKIP;
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
private static long[] mk_tokenSet_0_()
{
long[] data = new long[1025];
data[0]=576478361669337088L;
data[1]=70369012629504L;
for (int i = 2; i<=1024; i++) { data[i]=0L; }
return data;
}
public static readonly BitSet tokenSet_0_ = new BitSet(mk_tokenSet_0_());
private static long[] mk_tokenSet_1_()
{
long[] data = new long[1025];
data[0]=4294965759L;
data[1]=-9223372036854775808L;
for (int i = 2; i<=1024; i++) { data[i]=0L; }
return data;
}
public static readonly BitSet tokenSet_1_ = new BitSet(mk_tokenSet_1_());
private static long[] mk_tokenSet_2_()
{
long[] data = new long[2560];
data[0]=-3170762861857210368L;
data[1]=9223372036586340351L;
for (int i = 2; i<=1022; i++) { data[i]=-1L; }
data[1023]=9223372036854775807L;
for (int i = 1024; i<=2559; i++) { data[i]=0L; }
return data;
}
public static readonly BitSet tokenSet_2_ = new BitSet(mk_tokenSet_2_());
private static long[] mk_tokenSet_3_()
{
long[] data = new long[1025];
data[0]=-3458746947404300288L;
data[1]=8646911290591150081L;
for (int i = 2; i<=3; i++) { data[i]=-1L; }
for (int i = 4; i<=1024; i++) { data[i]=0L; }
return data;
}
public static readonly BitSet tokenSet_3_ = new BitSet(mk_tokenSet_3_());
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Dynamic;
namespace Python.Runtime
{
public class PyScopeException : Exception
{
public PyScopeException(string message)
: base(message)
{
}
}
/// <summary>
/// Classes/methods have this attribute must be used with GIL obtained.
/// </summary>
public class PyGILAttribute : Attribute
{
}
[PyGIL]
public class PyScope : DynamicObject, IDisposable
{
public readonly string Name;
/// <summary>
/// the python Module object the scope associated with.
/// </summary>
readonly PyObject obj;
internal BorrowedReference Reference => obj.Reference;
/// <summary>
/// the variable dict of the scope. Borrowed.
/// </summary>
internal readonly IntPtr variables;
internal BorrowedReference VarsRef => new BorrowedReference(variables);
/// <summary>
/// The Manager this scope associated with.
/// It provides scopes this scope can import.
/// </summary>
internal readonly PyScopeManager Manager;
/// <summary>
/// event which will be triggered after the scope disposed.
/// </summary>
public event Action<PyScope> OnDispose;
/// <summary>
/// Constructor
/// </summary>
/// <remarks>
/// Create a scope based on a Python Module.
/// </remarks>
internal PyScope(ref NewReference ptr, PyScopeManager manager)
{
if (!Runtime.PyType_IsSubtype(Runtime.PyObject_TYPE(ptr), Runtime.PyModuleType))
{
throw new PyScopeException("object is not a module");
}
Manager = manager ?? PyScopeManager.Global;
obj = ptr.MoveToPyObject();
//Refcount of the variables not increase
variables = Runtime.PyModule_GetDict(Reference).DangerousGetAddress();
PythonException.ThrowIfIsNull(variables);
int res = Runtime.PyDict_SetItem(
VarsRef, PyIdentifier.__builtins__,
Runtime.PyEval_GetBuiltins()
);
PythonException.ThrowIfIsNotZero(res);
this.Name = this.Get<string>("__name__");
}
/// <summary>
/// return the variable dict of the scope.
/// </summary>
public PyDict Variables()
{
Runtime.XIncref(variables);
return new PyDict(variables);
}
/// <summary>
/// Create a scope, and import all from this scope
/// </summary>
/// <returns></returns>
public PyScope NewScope()
{
var scope = Manager.Create();
scope.ImportAll(this);
return scope;
}
/// <summary>
/// Import method
/// </summary>
/// <remarks>
/// Import a scope or a module of given name,
/// scope will be looked up first.
/// </remarks>
public dynamic Import(string name, string asname = null)
{
Check();
if (String.IsNullOrEmpty(asname))
{
asname = name;
}
PyScope scope;
Manager.TryGet(name, out scope);
if (scope != null)
{
Import(scope, asname);
return scope;
}
else
{
PyObject module = PythonEngine.ImportModule(name);
Import(module, asname);
return module;
}
}
/// <summary>
/// Import method
/// </summary>
/// <remarks>
/// Import a scope as a variable of given name.
/// </remarks>
public void Import(PyScope scope, string asname)
{
this.SetPyValue(asname, scope.obj.Handle);
}
/// <summary>
/// Import Method
/// </summary>
/// <remarks>
/// The 'import .. as ..' statement in Python.
/// Import a module as a variable into the scope.
/// </remarks>
public void Import(PyObject module, string asname = null)
{
if (String.IsNullOrEmpty(asname))
{
asname = module.GetAttr("__name__").As<string>();
}
Set(asname, module);
}
/// <summary>
/// ImportAll Method
/// </summary>
/// <remarks>
/// The 'import * from ..' statement in Python.
/// Import all content of a scope/module of given name into the scope, scope will be looked up first.
/// </remarks>
public void ImportAll(string name)
{
PyScope scope;
Manager.TryGet(name, out scope);
if (scope != null)
{
ImportAll(scope);
return;
}
else
{
PyObject module = PythonEngine.ImportModule(name);
ImportAll(module);
}
}
/// <summary>
/// ImportAll Method
/// </summary>
/// <remarks>
/// Import all variables of the scope into this scope.
/// </remarks>
public void ImportAll(PyScope scope)
{
int result = Runtime.PyDict_Update(VarsRef, scope.VarsRef);
if (result < 0)
{
throw new PythonException();
}
}
/// <summary>
/// ImportAll Method
/// </summary>
/// <remarks>
/// Import all variables of the module into this scope.
/// </remarks>
public void ImportAll(PyObject module)
{
if (Runtime.PyObject_Type(module.obj) != Runtime.PyModuleType)
{
throw new PyScopeException("object is not a module");
}
var module_dict = Runtime.PyModule_GetDict(module.Reference);
int result = Runtime.PyDict_Update(VarsRef, module_dict);
if (result < 0)
{
throw new PythonException();
}
}
/// <summary>
/// ImportAll Method
/// </summary>
/// <remarks>
/// Import all variables in the dictionary into this scope.
/// </remarks>
public void ImportAll(PyDict dict)
{
int result = Runtime.PyDict_Update(VarsRef, dict.Reference);
if (result < 0)
{
throw new PythonException();
}
}
/// <summary>
/// Execute method
/// </summary>
/// <remarks>
/// Execute a Python ast and return the result as a PyObject.
/// The ast can be either an expression or stmts.
/// </remarks>
public PyObject Execute(PyObject script, PyDict locals = null)
{
Check();
IntPtr _locals = locals == null ? variables : locals.obj;
IntPtr ptr = Runtime.PyEval_EvalCode(script.Handle, variables, _locals);
PythonException.ThrowIfIsNull(ptr);
if (ptr == Runtime.PyNone)
{
Runtime.XDecref(ptr);
return null;
}
return new PyObject(ptr);
}
/// <summary>
/// Execute method
/// </summary>
/// <remarks>
/// Execute a Python ast and return the result as a PyObject,
/// and convert the result to a Managed Object of given type.
/// The ast can be either an expression or stmts.
/// </remarks>
public T Execute<T>(PyObject script, PyDict locals = null)
{
Check();
PyObject pyObj = Execute(script, locals);
if (pyObj == null)
{
return default(T);
}
var obj = pyObj.As<T>();
return obj;
}
/// <summary>
/// Eval method
/// </summary>
/// <remarks>
/// Evaluate a Python expression and return the result as a PyObject
/// or null if an exception is raised.
/// </remarks>
public PyObject Eval(string code, PyDict locals = null)
{
Check();
BorrowedReference _locals = locals == null ? VarsRef : locals.Reference;
NewReference reference = Runtime.PyRun_String(
code, RunFlagType.Eval, VarsRef, _locals
);
PythonException.ThrowIfIsNull(reference);
return reference.MoveToPyObject();
}
/// <summary>
/// Evaluate a Python expression
/// </summary>
/// <remarks>
/// Evaluate a Python expression
/// and convert the result to a Managed Object of given type.
/// </remarks>
public T Eval<T>(string code, PyDict locals = null)
{
Check();
PyObject pyObj = Eval(code, locals);
var obj = pyObj.As<T>();
return obj;
}
/// <summary>
/// Exec Method
/// </summary>
/// <remarks>
/// Exec a Python script and save its local variables in the current local variable dict.
/// </remarks>
public void Exec(string code, PyDict locals = null)
{
Check();
BorrowedReference _locals = locals == null ? VarsRef : locals.Reference;
Exec(code, VarsRef, _locals);
}
private void Exec(string code, BorrowedReference _globals, BorrowedReference _locals)
{
NewReference reference = Runtime.PyRun_String(
code, RunFlagType.File, _globals, _locals
);
PythonException.ThrowIfIsNull(reference);
reference.Dispose();
}
/// <summary>
/// Set Variable Method
/// </summary>
/// <remarks>
/// Add a new variable to the variables dict if it not exist
/// or update its value if the variable exists.
/// </remarks>
public void Set(string name, object value)
{
IntPtr _value = Converter.ToPython(value, value?.GetType());
SetPyValue(name, _value);
Runtime.XDecref(_value);
}
private void SetPyValue(string name, IntPtr value)
{
Check();
using (var pyKey = new PyString(name))
{
int r = Runtime.PyObject_SetItem(variables, pyKey.obj, value);
if (r < 0)
{
throw new PythonException();
}
}
}
/// <summary>
/// Remove Method
/// </summary>
/// <remarks>
/// Remove a variable from the variables dict.
/// </remarks>
public void Remove(string name)
{
Check();
using (var pyKey = new PyString(name))
{
int r = Runtime.PyObject_DelItem(variables, pyKey.obj);
if (r < 0)
{
throw new PythonException();
}
}
}
/// <summary>
/// Contains Method
/// </summary>
/// <remarks>
/// Returns true if the variable exists in the scope.
/// </remarks>
public bool Contains(string name)
{
Check();
using (var pyKey = new PyString(name))
{
return Runtime.PyMapping_HasKey(variables, pyKey.obj) != 0;
}
}
/// <summary>
/// Get Method
/// </summary>
/// <remarks>
/// Returns the value of the variable of given name.
/// If the variable does not exist, throw an Exception.
/// </remarks>
public PyObject Get(string name)
{
PyObject scope;
var state = TryGet(name, out scope);
if (!state)
{
throw new PyScopeException($"The scope of name '{Name}' has no attribute '{name}'");
}
return scope;
}
/// <summary>
/// TryGet Method
/// </summary>
/// <remarks>
/// Returns the value of the variable, local variable first.
/// If the variable does not exist, return null.
/// </remarks>
public bool TryGet(string name, out PyObject value)
{
Check();
using (var pyKey = new PyString(name))
{
if (Runtime.PyMapping_HasKey(variables, pyKey.obj) != 0)
{
IntPtr op = Runtime.PyObject_GetItem(variables, pyKey.obj);
if (op == IntPtr.Zero)
{
throw new PythonException();
}
if (op == Runtime.PyNone)
{
Runtime.XDecref(op);
value = null;
return true;
}
value = new PyObject(op);
return true;
}
else
{
value = null;
return false;
}
}
}
/// <summary>
/// Get Method
/// </summary>
/// <remarks>
/// Obtain the value of the variable of given name,
/// and convert the result to a Managed Object of given type.
/// If the variable does not exist, throw an Exception.
/// </remarks>
public T Get<T>(string name)
{
Check();
PyObject pyObj = Get(name);
if (pyObj == null)
{
return default(T);
}
return pyObj.As<T>();
}
/// <summary>
/// TryGet Method
/// </summary>
/// <remarks>
/// Obtain the value of the variable of given name,
/// and convert the result to a Managed Object of given type.
/// If the variable does not exist, return false.
/// </remarks>
public bool TryGet<T>(string name, out T value)
{
Check();
PyObject pyObj;
var result = TryGet(name, out pyObj);
if (!result)
{
value = default(T);
return false;
}
if (pyObj == null)
{
if (typeof(T).IsValueType)
{
throw new PyScopeException($"The value of the attribute '{name}' is None which cannot be convert to '{typeof(T).ToString()}'");
}
else
{
value = default(T);
return true;
}
}
value = pyObj.As<T>();
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this.Get(binder.Name);
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
this.Set(binder.Name, value);
return true;
}
private void Check()
{
if (this.obj.IsDisposed)
{
throw new PyScopeException($"The scope of name '{Name}' object has been disposed");
}
}
public void Dispose()
{
this.OnDispose?.Invoke(this);
this.obj.Dispose();
}
}
public class PyScopeManager
{
public static PyScopeManager Global;
private Dictionary<string, PyScope> NamedScopes = new Dictionary<string, PyScope>();
internal static void Reset()
{
Global = new PyScopeManager();
}
internal PyScope NewScope(string name)
{
if (name == null)
{
name = "";
}
var module = Runtime.PyModule_New(name);
if (module.IsNull())
{
throw new PythonException();
}
return new PyScope(ref module, this);
}
/// <summary>
/// Create Method
/// </summary>
/// <remarks>
/// Create an anonymous scope.
/// </remarks>
[PyGIL]
public PyScope Create()
{
var scope = this.NewScope(null);
return scope;
}
/// <summary>
/// Create Method
/// </summary>
/// <remarks>
/// Create an named scope of given name.
/// </remarks>
[PyGIL]
public PyScope Create(string name)
{
if (String.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
if (name != null && Contains(name))
{
throw new PyScopeException($"A scope of name '{name}' does already exist");
}
var scope = this.NewScope(name);
scope.OnDispose += Remove;
NamedScopes[name] = scope;
return scope;
}
/// <summary>
/// Contains Method
/// </summary>
/// <remarks>
/// return true if the scope exists in this manager.
/// </remarks>
public bool Contains(string name)
{
return NamedScopes.ContainsKey(name);
}
/// <summary>
/// Get Method
/// </summary>
/// <remarks>
/// Find the scope in this manager.
/// If the scope not exist, an Exception will be thrown.
/// </remarks>
public PyScope Get(string name)
{
if (String.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
if (NamedScopes.ContainsKey(name))
{
return NamedScopes[name];
}
throw new PyScopeException($"There is no scope named '{name}' registered in this manager");
}
/// <summary>
/// Get Method
/// </summary>
/// <remarks>
/// Try to find the scope in this manager.
/// </remarks>
public bool TryGet(string name, out PyScope scope)
{
return NamedScopes.TryGetValue(name, out scope);
}
/// <summary>
/// Remove Method
/// </summary>
/// <remarks>
/// remove the scope from this manager.
/// </remarks>
public void Remove(PyScope scope)
{
NamedScopes.Remove(scope.Name);
}
[PyGIL]
public void Clear()
{
var scopes = NamedScopes.Values.ToList();
foreach (var scope in scopes)
{
scope.Dispose();
}
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2017 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 Google.Protobuf.Reflection;
using Google.Protobuf.WellKnownTypes;
using NUnit.Framework;
using System;
using System.IO;
using System.Linq;
using UnitTest.Issues.TestProtos;
using static Google.Protobuf.WireFormat;
using static UnitTest.Issues.TestProtos.ComplexOptionType2.Types;
using static UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Extensions;
using static UnitTest.Issues.TestProtos.DummyMessageContainingEnum.Types;
using Google.Protobuf.TestProtos;
#pragma warning disable CS0618
namespace Google.Protobuf.Test.Reflection
{
/// <summary>
/// The majority of the testing here is done via parsed descriptors. That's simpler to
/// achieve (and more important) than constructing a CodedInputStream manually.
/// </summary>
public class CustomOptionsTest
{
delegate bool OptionFetcher<T>(int field, out T value);
OptionFetcher<E> EnumFetcher<E>(CustomOptions options)
{
return (int i, out E v) => {
if (options.TryGetInt32(i, out int value))
{
v = (E)(object)value;
return true;
}
else
{
v = default(E);
return false;
}
};
}
[Test]
public void BuiltinOptionsCanBeRetrieved()
{
// non-custom options (that are not extensions but regular fields) can only be accessed via descriptor.Options
var fileOptions = UnittestProto3Reflection.Descriptor.GetOptions();
Assert.AreEqual("Google.Protobuf.TestProtos", fileOptions.CsharpNamespace);
}
[Test]
public void OptionPresenceCanBeDetected()
{
// case 1: the descriptor has no options at all so the options message is not present
Assert.IsNull(TestAllTypes.Descriptor.GetOptions());
// case 2: the descriptor has some options, but not the one we're looking for
// HasExtension will be false and GetExtension returns extension's default value
Assert.IsFalse(UnittestProto3Reflection.Descriptor.GetOptions().HasExtension(FileOpt1));
Assert.AreEqual(0, UnittestProto3Reflection.Descriptor.GetOptions().GetExtension(FileOpt1));
// case 3: option is present
Assert.IsTrue(UnittestCustomOptionsProto3Reflection.Descriptor.GetOptions().HasExtension(FileOpt1));
Assert.AreEqual(9876543210UL, UnittestCustomOptionsProto3Reflection.Descriptor.GetOptions().GetExtension(FileOpt1));
}
[Test]
public void ScalarOptions()
{
var d = CustomOptionOtherValues.Descriptor;
var customOptions = d.CustomOptions;
AssertOption(-100, customOptions.TryGetInt32, Int32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(12.3456789f, customOptions.TryGetFloat, FloatOpt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(1.234567890123456789d, customOptions.TryGetDouble, DoubleOpt, d.GetOption, d.GetOptions().GetExtension);
AssertOption("Hello, \"World\"", customOptions.TryGetString, StringOpt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(ByteString.CopyFromUtf8("Hello\0World"), customOptions.TryGetBytes, BytesOpt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(TestEnumType.TestOptionEnumType2, EnumFetcher<TestEnumType>(customOptions), EnumOpt, d.GetOption, d.GetOptions().GetExtension);
}
[Test]
public void MessageOptions()
{
var d = VariousComplexOptions.Descriptor;
var customOptions = d.CustomOptions;
AssertOption(new ComplexOptionType1 { Foo = 42, Foo4 = { 99, 88 } }, customOptions.TryGetMessage, ComplexOpt1, d.GetOption, d.GetOptions().GetExtension);
AssertOption(new ComplexOptionType2
{
Baz = 987,
Bar = new ComplexOptionType1 { Foo = 743 },
Fred = new ComplexOptionType4 { Waldo = 321 },
Barney = { new ComplexOptionType4 { Waldo = 101 }, new ComplexOptionType4 { Waldo = 212 } }
},
customOptions.TryGetMessage, ComplexOpt2, d.GetOption, d.GetOptions().GetExtension);
AssertOption(new ComplexOptionType3 { Qux = 9 }, customOptions.TryGetMessage, ComplexOpt3, d.GetOption, d.GetOptions().GetExtension);
}
[Test]
public void OptionLocations()
{
var fileDescriptor = UnittestCustomOptionsProto3Reflection.Descriptor;
AssertOption(9876543210UL, fileDescriptor.CustomOptions.TryGetUInt64, FileOpt1, fileDescriptor.GetOption, fileDescriptor.GetOptions().GetExtension);
var messageDescriptor = TestMessageWithCustomOptions.Descriptor;
AssertOption(-56, messageDescriptor.CustomOptions.TryGetInt32, MessageOpt1, messageDescriptor.GetOption, messageDescriptor.GetOptions().GetExtension);
var fieldDescriptor = TestMessageWithCustomOptions.Descriptor.Fields["field1"];
AssertOption(8765432109UL, fieldDescriptor.CustomOptions.TryGetFixed64, FieldOpt1, fieldDescriptor.GetOption, fieldDescriptor.GetOptions().GetExtension);
var oneofDescriptor = TestMessageWithCustomOptions.Descriptor.Oneofs[0];
AssertOption(-99, oneofDescriptor.CustomOptions.TryGetInt32, OneofOpt1, oneofDescriptor.GetOption, oneofDescriptor.GetOptions().GetExtension);
var enumDescriptor = TestMessageWithCustomOptions.Descriptor.EnumTypes[0];
AssertOption(-789, enumDescriptor.CustomOptions.TryGetSFixed32, EnumOpt1, enumDescriptor.GetOption, enumDescriptor.GetOptions().GetExtension);
var enumValueDescriptor = TestMessageWithCustomOptions.Descriptor.EnumTypes[0].FindValueByNumber(2);
AssertOption(123, enumValueDescriptor.CustomOptions.TryGetInt32, EnumValueOpt1, enumValueDescriptor.GetOption, enumValueDescriptor.GetOptions().GetExtension);
var serviceDescriptor = UnittestCustomOptionsProto3Reflection.Descriptor.Services
.Single(s => s.Name == "TestServiceWithCustomOptions");
AssertOption(-9876543210, serviceDescriptor.CustomOptions.TryGetSInt64, ServiceOpt1, serviceDescriptor.GetOption, serviceDescriptor.GetOptions().GetExtension);
var methodDescriptor = serviceDescriptor.Methods[0];
AssertOption(UnitTest.Issues.TestProtos.MethodOpt1.Val2, EnumFetcher<UnitTest.Issues.TestProtos.MethodOpt1>(methodDescriptor.CustomOptions), UnittestCustomOptionsProto3Extensions.MethodOpt1, methodDescriptor.GetOption, methodDescriptor.GetOptions().GetExtension);
}
[Test]
public void MinValues()
{
var d = CustomOptionMinIntegerValues.Descriptor;
var customOptions = d.CustomOptions;
AssertOption(false, customOptions.TryGetBool, BoolOpt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(int.MinValue, customOptions.TryGetInt32, Int32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(long.MinValue, customOptions.TryGetInt64, Int64Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(uint.MinValue, customOptions.TryGetUInt32, Uint32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(ulong.MinValue, customOptions.TryGetUInt64, Uint64Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(int.MinValue, customOptions.TryGetSInt32, Sint32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(long.MinValue, customOptions.TryGetSInt64, Sint64Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(uint.MinValue, customOptions.TryGetUInt32, Fixed32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(ulong.MinValue, customOptions.TryGetUInt64, Fixed64Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(int.MinValue, customOptions.TryGetInt32, Sfixed32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(long.MinValue, customOptions.TryGetInt64, Sfixed64Opt, d.GetOption, d.GetOptions().GetExtension);
}
[Test]
public void MaxValues()
{
var d = CustomOptionMaxIntegerValues.Descriptor;
var customOptions = d.CustomOptions;
AssertOption(true, customOptions.TryGetBool, BoolOpt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(int.MaxValue, customOptions.TryGetInt32, Int32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(long.MaxValue, customOptions.TryGetInt64, Int64Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(uint.MaxValue, customOptions.TryGetUInt32, Uint32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(ulong.MaxValue, customOptions.TryGetUInt64, Uint64Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(int.MaxValue, customOptions.TryGetSInt32, Sint32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(long.MaxValue, customOptions.TryGetSInt64, Sint64Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(uint.MaxValue, customOptions.TryGetFixed32, Fixed32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(ulong.MaxValue, customOptions.TryGetFixed64, Fixed64Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(int.MaxValue, customOptions.TryGetSFixed32, Sfixed32Opt, d.GetOption, d.GetOptions().GetExtension);
AssertOption(long.MaxValue, customOptions.TryGetSFixed64, Sfixed64Opt, d.GetOption, d.GetOptions().GetExtension);
}
[Test]
public void AggregateOptions()
{
// Just two examples
var messageDescriptor = AggregateMessage.Descriptor;
AssertOption(new Aggregate { I = 101, S = "MessageAnnotation" }, messageDescriptor.CustomOptions.TryGetMessage, Msgopt, messageDescriptor.GetOption, messageDescriptor.GetOptions().GetExtension);
var fieldDescriptor = messageDescriptor.Fields["fieldname"];
AssertOption(new Aggregate { S = "FieldAnnotation" }, fieldDescriptor.CustomOptions.TryGetMessage, Fieldopt, fieldDescriptor.GetOption, fieldDescriptor.GetOptions().GetExtension);
}
[Test]
public void NoOptions()
{
var fileDescriptor = UnittestProto3Reflection.Descriptor;
var messageDescriptor = TestAllTypes.Descriptor;
Assert.NotNull(fileDescriptor.CustomOptions);
Assert.NotNull(messageDescriptor.CustomOptions);
Assert.NotNull(messageDescriptor.Fields[1].CustomOptions);
Assert.NotNull(fileDescriptor.Services[0].CustomOptions);
Assert.NotNull(fileDescriptor.Services[0].Methods[0].CustomOptions);
Assert.NotNull(fileDescriptor.EnumTypes[0].CustomOptions);
Assert.NotNull(fileDescriptor.EnumTypes[0].Values[0].CustomOptions);
Assert.NotNull(TestAllTypes.Descriptor.Oneofs[0].CustomOptions);
}
[Test]
public void MultipleImportOfSameFileWithExtension()
{
var descriptor = UnittestIssue6936CReflection.Descriptor;
var foo = Foo.Descriptor;
var bar = Bar.Descriptor;
AssertOption("foo", foo.CustomOptions.TryGetString, UnittestIssue6936AExtensions.Opt, foo.GetOption, foo.GetOptions().GetExtension);
AssertOption("bar", bar.CustomOptions.TryGetString, UnittestIssue6936AExtensions.Opt, bar.GetOption, bar.GetOptions().GetExtension);
}
[Test]
public void SelfReferentialOptions()
{
// Custom field option used in definition of the custom option's message.
var fooField = UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions.Descriptor.FindFieldByName("foo");
var fooFieldFooExtensionValue = fooField.GetOptions().GetExtension(UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsExtensions.FooOptions);
Assert.AreEqual(1234, fooFieldFooExtensionValue.Foo);
// Custom field option used on the definition of that field option.
var fileDescriptor = UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsReflection.Descriptor;
var barOptionsField = fileDescriptor.Extensions.UnorderedExtensions.Single(field => field.Name == "bar_options");
var barExtensionValue = barOptionsField.GetOptions().GetExtension(UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsExtensions.BarOptions);
Assert.AreEqual(1234, barExtensionValue);
// Custom field option used in definition of the extension message.
var intOptField = UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions.Descriptor.FindFieldByName("int_opt");
var intOptFieldFooExtensionValue = intOptField.GetOptions().GetExtension(UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsExtensions.FooOptions);
Assert.AreEqual(1, intOptFieldFooExtensionValue.IntOpt);
Assert.AreEqual(2, intOptFieldFooExtensionValue.GetExtension(UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsExtensions.FooIntOpt));
Assert.AreEqual(3, intOptFieldFooExtensionValue.GetExtension(UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsExtensions.FooFooOpt).IntOpt);
}
private void AssertOption<T, D>(T expected, OptionFetcher<T> customOptionFetcher, Extension<D, T> extension, Func<Extension<D, T>, T> getOptionFetcher, Func<Extension<D, T>, T> extensionFetcher) where D : IExtendableMessage<D>
{
Assert.IsTrue(customOptionFetcher(extension.FieldNumber, out T customOptionsValue));
Assert.AreEqual(expected, customOptionsValue);
T getOptionValue = getOptionFetcher(extension);
Assert.AreEqual(expected, getOptionValue);
T extensionValue = extensionFetcher(extension);
Assert.AreEqual(expected, extensionValue);
}
}
}
| |
using Lucene.Net.Support;
using NUnit.Framework;
using System;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Util.Fst
{
/*
* 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 Directory = Lucene.Net.Store.Directory;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOContext = Lucene.Net.Store.IOContext;
using MMapDirectory = Lucene.Net.Store.MMapDirectory;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
//ORIGINAL LINE: @TimeoutSuite(millis = 100 * TimeUnits.HOUR) public class Test2BFST extends Lucene.Net.Util.LuceneTestCase
[Ignore("Requires tons of heap to run (420G works)")]
[TestFixture]
public class Test2BFST : LuceneTestCase
{
private const long LIMIT = 3L * 1024 * 1024 * 1024;
[Test]
public virtual void Test()
{
int[] ints = new int[7];
Int32sRef input = new Int32sRef(ints, 0, ints.Length);
int seed = Random.Next();
Directory dir = new MMapDirectory(CreateTempDir("2BFST"));
for (int doPackIter = 0; doPackIter < 2; doPackIter++)
{
bool doPack = doPackIter == 1;
// Build FST w/ NoOutputs and stop when nodeCount > 2.2B
if (!doPack)
{
Console.WriteLine("\nTEST: 3B nodes; doPack=false output=NO_OUTPUTS");
Outputs<object> outputs = NoOutputs.Singleton;
object NO_OUTPUT = outputs.NoOutput;
Builder<object> b = new Builder<object>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, int.MaxValue, outputs, null, doPack, PackedInt32s.COMPACT, true, 15);
int count = 0;
Random r = new Random(seed);
int[] ints2 = new int[200];
Int32sRef input2 = new Int32sRef(ints2, 0, ints2.Length);
while (true)
{
//System.out.println("add: " + input + " -> " + output);
for (int i = 10; i < ints2.Length; i++)
{
ints2[i] = r.Next(256);
}
b.Add(input2, NO_OUTPUT);
count++;
if (count % 100000 == 0)
{
Console.WriteLine(count + ": " + b.GetFstSizeInBytes() + " bytes; " + b.TotStateCount + " nodes");
}
if (b.TotStateCount > int.MaxValue + 100L * 1024 * 1024)
{
break;
}
NextInput(r, ints2);
}
FST<object> fst = b.Finish();
for (int verify = 0; verify < 2; verify++)
{
Console.WriteLine("\nTEST: now verify [fst size=" + fst.GetSizeInBytes() + "; nodeCount=" + fst.NodeCount + "; arcCount=" + fst.ArcCount + "]");
Arrays.Fill(ints2, 0);
r = new Random(seed);
for (int i = 0; i < count; i++)
{
if (i % 1000000 == 0)
{
Console.WriteLine(i + "...: ");
}
for (int j = 10; j < ints2.Length; j++)
{
ints2[j] = r.Next(256);
}
Assert.AreEqual(NO_OUTPUT, Util.Get(fst, input2));
NextInput(r, ints2);
}
Console.WriteLine("\nTEST: enum all input/outputs");
Int32sRefFSTEnum<object> fstEnum = new Int32sRefFSTEnum<object>(fst);
Arrays.Fill(ints2, 0);
r = new Random(seed);
int upto = 0;
while (true)
{
Int32sRefFSTEnum.InputOutput<object> pair = fstEnum.Next();
if (pair == null)
{
break;
}
for (int j = 10; j < ints2.Length; j++)
{
ints2[j] = r.Next(256);
}
Assert.AreEqual(input2, pair.Input);
Assert.AreEqual(NO_OUTPUT, pair.Output);
upto++;
NextInput(r, ints2);
}
Assert.AreEqual(count, upto);
if (verify == 0)
{
Console.WriteLine("\nTEST: save/load FST and re-verify");
IndexOutput @out = dir.CreateOutput("fst", IOContext.DEFAULT);
fst.Save(@out);
@out.Dispose();
IndexInput @in = dir.OpenInput("fst", IOContext.DEFAULT);
fst = new FST<object>(@in, outputs);
@in.Dispose();
}
else
{
dir.DeleteFile("fst");
}
}
}
// Build FST w/ ByteSequenceOutputs and stop when FST
// size = 3GB
{
Console.WriteLine("\nTEST: 3 GB size; doPack=" + doPack + " outputs=bytes");
Outputs<BytesRef> outputs = ByteSequenceOutputs.Singleton;
Builder<BytesRef> b = new Builder<BytesRef>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, int.MaxValue, outputs, null, doPack, PackedInt32s.COMPACT, true, 15);
var outputBytes = new byte[20];
BytesRef output = new BytesRef(outputBytes);
Arrays.Fill(ints, 0);
int count = 0;
Random r = new Random(seed);
while (true)
{
r.NextBytes(outputBytes);
//System.out.println("add: " + input + " -> " + output);
b.Add(input, BytesRef.DeepCopyOf(output));
count++;
if (count % 1000000 == 0)
{
Console.WriteLine(count + "...: " + b.GetFstSizeInBytes() + " bytes");
}
if (b.GetFstSizeInBytes() > LIMIT)
{
break;
}
NextInput(r, ints);
}
FST<BytesRef> fst = b.Finish();
for (int verify = 0; verify < 2; verify++)
{
Console.WriteLine("\nTEST: now verify [fst size=" + fst.GetSizeInBytes() + "; nodeCount=" + fst.NodeCount + "; arcCount=" + fst.ArcCount + "]");
r = new Random(seed);
Arrays.Fill(ints, 0);
for (int i = 0; i < count; i++)
{
if (i % 1000000 == 0)
{
Console.WriteLine(i + "...: ");
}
r.NextBytes(outputBytes);
Assert.AreEqual(output, Util.Get(fst, input));
NextInput(r, ints);
}
Console.WriteLine("\nTEST: enum all input/outputs");
Int32sRefFSTEnum<BytesRef> fstEnum = new Int32sRefFSTEnum<BytesRef>(fst);
Arrays.Fill(ints, 0);
r = new Random(seed);
int upto = 0;
while (true)
{
Int32sRefFSTEnum.InputOutput<BytesRef> pair = fstEnum.Next();
if (pair == null)
{
break;
}
Assert.AreEqual(input, pair.Input);
r.NextBytes(outputBytes);
Assert.AreEqual(output, pair.Output);
upto++;
NextInput(r, ints);
}
Assert.AreEqual(count, upto);
if (verify == 0)
{
Console.WriteLine("\nTEST: save/load FST and re-verify");
IndexOutput @out = dir.CreateOutput("fst", IOContext.DEFAULT);
fst.Save(@out);
@out.Dispose();
IndexInput @in = dir.OpenInput("fst", IOContext.DEFAULT);
fst = new FST<BytesRef>(@in, outputs);
@in.Dispose();
}
else
{
dir.DeleteFile("fst");
}
}
}
// Build FST w/ PositiveIntOutputs and stop when FST
// size = 3GB
{
Console.WriteLine("\nTEST: 3 GB size; doPack=" + doPack + " outputs=long");
Outputs<long?> outputs = PositiveInt32Outputs.Singleton;
Builder<long?> b = new Builder<long?>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, int.MaxValue, outputs, null, doPack, PackedInt32s.COMPACT, true, 15);
long output = 1;
Arrays.Fill(ints, 0);
int count = 0;
Random r = new Random(seed);
while (true)
{
//System.out.println("add: " + input + " -> " + output);
b.Add(input, output);
output += 1 + r.Next(10);
count++;
if (count % 1000000 == 0)
{
Console.WriteLine(count + "...: " + b.GetFstSizeInBytes() + " bytes");
}
if (b.GetFstSizeInBytes() > LIMIT)
{
break;
}
NextInput(r, ints);
}
FST<long?> fst = b.Finish();
for (int verify = 0; verify < 2; verify++)
{
Console.WriteLine("\nTEST: now verify [fst size=" + fst.GetSizeInBytes() + "; nodeCount=" + fst.NodeCount + "; arcCount=" + fst.ArcCount + "]");
Arrays.Fill(ints, 0);
output = 1;
r = new Random(seed);
for (int i = 0; i < count; i++)
{
if (i % 1000000 == 0)
{
Console.WriteLine(i + "...: ");
}
// forward lookup:
Assert.AreEqual(output, (long)Util.Get(fst, input));
// reverse lookup:
Assert.AreEqual(input, Util.GetByOutput(fst, output));
output += 1 + r.Next(10);
NextInput(r, ints);
}
Console.WriteLine("\nTEST: enum all input/outputs");
Int32sRefFSTEnum<long?> fstEnum = new Int32sRefFSTEnum<long?>(fst);
Arrays.Fill(ints, 0);
r = new Random(seed);
int upto = 0;
output = 1;
while (true)
{
Int32sRefFSTEnum.InputOutput<long?> pair = fstEnum.Next();
if (pair == null)
{
break;
}
Assert.AreEqual(input, pair.Input);
Assert.AreEqual(output, pair.Output.Value);
output += 1 + r.Next(10);
upto++;
NextInput(r, ints);
}
Assert.AreEqual(count, upto);
if (verify == 0)
{
Console.WriteLine("\nTEST: save/load FST and re-verify");
IndexOutput @out = dir.CreateOutput("fst", IOContext.DEFAULT);
fst.Save(@out);
@out.Dispose();
IndexInput @in = dir.OpenInput("fst", IOContext.DEFAULT);
fst = new FST<long?>(@in, outputs);
@in.Dispose();
}
else
{
dir.DeleteFile("fst");
}
}
}
}
dir.Dispose();
}
private void NextInput(Random r, int[] ints)
{
int downTo = 6;
while (downTo >= 0)
{
// Must add random amounts (and not just 1) because
// otherwise FST outsmarts us and remains tiny:
ints[downTo] += 1 + r.Next(10);
if (ints[downTo] < 256)
{
break;
}
else
{
ints[downTo] = 0;
downTo--;
}
}
}
}
}
| |
/*
* Board.cs
*
* Balazs Pete
* 09771417
*
*/
using System;
using System.Linq;
using System.Data.Linq;
using System.Collections;
using System.Collections.Generic;
namespace Yavalath
{
public class Cell
{
public int Border {get; private set;}
public bool Playable {get; private set;}
public int Player {get; set;}
public string Position {get; private set;}
public int Index {get; private set;}
/// <summary>
/// Initializes a new instance of the <see cref="Yavalath.Board+Cell"/> class.
/// </summary>
/// <param name='border'>
/// Integer input determining the type of cell
/// </param>
/// <param name='playable'>
/// Integer indicating if cell is playable or not
/// </param>
/// <param name='player'>
/// Indicates which player takes up the cell
/// </param>
public Cell (int border, bool playable = false,
int index = -1, string position = "", int player = 0)
{
Border = border;
Playable = playable;
Player = player;
Position = position;
Index = index;
}
/// <summary>
/// Gets the symbol representation of the piece corresponding to the player
/// </summary>
/// <returns>
/// The player's symbol character or ' '.
/// </returns>
public char PieceSymbol ()
{
if (Player == 0) return ' ';
else if (Player == -1) return 'X';
return 'O';
}
}
public class Board
{
private const int DIMENSION = 11;
private const int SIZE = 121;
public struct CellIndex
{
public Cell Cell;
public int Index;
public double Score;
}
private Cell[] Cells = new Cell[SIZE];
private static int[] Borders = new int[] {
0, 0, 0, 0, 0, 1, 3, 3, 3, 3, 2,
0, 0, 0, 0, 5, 7, 7, 7, 7, 7, 2,
0, 0, 0, 5, 7, 7, 7, 7, 7, 7, 2,
0, 0, 5, 7, 7, 7, 7, 7, 7, 7, 2,
0, 5, 7, 7, 7, 7, 7, 7, 7, 7, 2,
4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0,
4, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0,
4, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0,
4, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0,
4, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
private static int[] PlayableCells = new int[] {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0,
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0,
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/// <summary>
/// Gets the last modified cell with its index.
/// </summary>
/// <value>
/// The latest modified cell.
/// </value>
public CellIndex Latest {get; private set;}
/// <summary>
/// Initializes a new instance of the <see cref="Yavalath.Board"/> class.
/// </summary>
public Board ()
{
var count = 0;
for(var i = 0; i < Cells.Length; i++) {
var playable = PlayableCells[i] == 1;
if(i % DIMENSION == 0) count = 1;
if(playable) count++;
Cells[i] = new Cell(Borders[i],
playable: playable,
index: i,
position: playable ?
String.Format("{0}{1}", (char)('A'-1+(i/DIMENSION)), count-1) : ""
);
}
}
/// <summary>
/// Output the current state of the Board
/// </summary>
public void Print()
{
Func<int, int> indent = delegate(int x)
{
while (x-- > 0)
Console.Write(" ");
return 0;
};
var indentation = 0;
var row = 0;
while(row < DIMENSION)
{
indent(indentation);
Console.Write(" ");
var cellsInRow = Cells.Skip(row * DIMENSION).Take(DIMENSION);
foreach (var cell in cellsInRow)
{
var symbol = cell.PieceSymbol();
Console.Write(symbol);
Console.Write(' ');
Console.Write(new int[]{ 4, 5, 6, 7 }.Contains(cell.Border) ? "|" : " ");
Console.Write(' ');
}
Console.WriteLine();
indent(indentation);
Console.Write(" ");
foreach (var cell in cellsInRow)
{
Console.Write(new int[]{ 2, 3, 6, 7 }.Contains(cell.Border) ? '\\' : ' ');
Console.Write(' ');
Console.Write(new int[]{ 1, 3, 5, 7 }.Contains(cell.Border) ? '/' : ' ');
Console.Write(' ');
}
Console.WriteLine();
indentation += 2;
row++;
}
}
/// <summary>
/// Gets the <see cref="Yavalath.Board"/> at the specified index.
/// </summary>
/// <param name='index'>
/// Index.
/// </param>
public Cell this [int index]
{
get
{
if(index < 0 || index >= SIZE) return null;
return Cells[index];
}
}
public Cell this [int row, int column]
{
get
{
return this [row * DIMENSION + column];
}
}
public Cell[] EmptyCells ()
{
return Cells.Where(c => c.Playable && c.Player == 0).ToArray();
}
public List<Cell> UpDiagonal(Cell cell)
{
return UpDiagonal(cell.Index);
}
public List<Cell> UpDiagonal (int cellIndex)
{
return line (cellIndex, 10);
}
public List<Cell> DownDiagonal (Cell cell)
{
return UpDiagonal(cell.Index);
}
public List<Cell> DownDiagonal (int cellIndex)
{
return line (cellIndex, -11);
}
public List<Cell> Row (Cell cell)
{
return Row(cell.Index);
}
public List<Cell> Row (int cellIndex)
{
return Cells.Skip((cellIndex/DIMENSION) * DIMENSION).Take(DIMENSION).ToList ();
}
private List<Cell> line (int index, int offset)
{
var column = index % DIMENSION;
var row = index / DIMENSION;
offset = Math.Abs (offset);
var columnOffset = offset == 10 ? 1 : 0;
var list = new List<Cell>();
while (0 < row && column < DIMENSION) {
row--;
column += columnOffset;
}
while (row < DIMENSION && column >= 0) {
list.Add (this[row, column]);
row++;
column -= columnOffset;
}
return list;
}
/// <summary>
/// Takes the cell.
/// </summary>
/// <returns>
/// <c>true</c>, if cell was taken, <c>false</c> otherwise.
/// </returns>
/// <param name='cellCoords'>
/// Cell coords.
/// </param>
/// <param name='player'>
/// Player.
/// </param>
public bool TakeCell(string cellCoords, int player = 0, bool takeOver = false)
{
if (cellCoords.Length < 2 || cellCoords.Length > 3)
return false;
try {
var row = cellCoords.Substring (0, 1).ToUpper ().ElementAt (0) - 'A' + 1;
var col = Convert.ToInt32 (cellCoords.Substring (1)) -1;
var cells = Cells.Skip(row * DIMENSION).Take(DIMENSION);
var playableCells = cells.Where(c => c.Playable).ToArray();
Cell cell = playableCells.ElementAt(col);
if(cell.Player != 0 && !takeOver) return false;
cell.Player = player;
Latest = new CellIndex {
Cell = cell,
Index = row*11 + (10 - playableCells.Length + col),
Score = Algorithms.Evaluation(this, cell, player, null)
};
return true;
} catch (Exception) {
Console.WriteLine("Error... YAY");
return false;
}
}
}
}
| |
/***************************************************************************
* Track.cs
*
* Copyright (C) 2006-2007 Alan McGovern
* Authors:
* Alan McGovern (alan.mcgovern@gmail.com)
****************************************************************************/
/* 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;
using System.Runtime.InteropServices;
namespace Mtp
{
public class Track
{
internal TrackStruct trackStruct;
private MtpDevice device;
public uint FileId {
get { return trackStruct.item_id; }
}
public string Album {
get { return trackStruct.album; }
set { trackStruct.album = value;}
}
public string Artist {
get { return trackStruct.artist; }
set { trackStruct.artist = value; }
}
public uint Bitrate {
get { return trackStruct.bitrate; }
}
public ushort BitrateType {
get { return trackStruct.bitratetype; }
}
public string ReleaseDate {
get { return trackStruct.date; }
set { trackStruct.date = value; }
}
public int Year {
get { return ReleaseDate == null || ReleaseDate.Length < 4 ? 0 : Int32.Parse (ReleaseDate.Substring(0, 4)); }
set { ReleaseDate = String.Format ("{0:0000}0101T0000.00", value); }
}
public uint Duration {
get { return trackStruct.duration; }
set { trackStruct.duration = value; }
}
public string FileName {
get { return trackStruct.filename; }
set { trackStruct.filename = value; }
}
public ulong FileSize {
get { return trackStruct.filesize; }
set { trackStruct.filesize = value; }
}
public FileType FileType {
get { return trackStruct.filetype; }
set { trackStruct.filetype = value; }
}
public string Genre {
get { return trackStruct.genre; }
set { trackStruct.genre = value; }
}
public ushort NoChannels {
get { return trackStruct.nochannels; }
set { trackStruct.nochannels = value; }
}
// 0 to 100
public ushort Rating {
get { return trackStruct.rating; }
set {
if (value < 0 || value > 100)
throw new ArgumentOutOfRangeException ("Rating", "Rating must be between zero and 100");
trackStruct.rating = value;
}
}
public uint SampleRate {
get { return trackStruct.samplerate; }
set { trackStruct.samplerate = value; }
}
public string Title {
get { return trackStruct.title; }
set { trackStruct.title = value; }
}
public ushort TrackNumber
{
get { return trackStruct.tracknumber; }
set { trackStruct.tracknumber = value; }
}
public uint WaveCodec {
get { return trackStruct.wavecodec; }
}
public uint UseCount {
get { return trackStruct.usecount; }
set { trackStruct.usecount = value; }
}
#if LIBMTP8
public string Composer {
get { return trackStruct.composer; }
set { trackStruct.composer = value; }
}
#endif
public Track (string filename, ulong filesize) : this (new TrackStruct (), null)
{
this.trackStruct.filename = filename;
this.trackStruct.filesize = filesize;
this.trackStruct.filetype = DetectFileType (this);
}
internal Track (TrackStruct track, MtpDevice device)
{
this.device = device;
this.trackStruct = track;
}
public bool InFolder (Folder folder)
{
return folder != null && trackStruct.parent_id == folder.FolderId;
}
public void Download (string path)
{
Download (path, null);
}
public void Download (string path, ProgressFunction callback)
{
if (String.IsNullOrEmpty (path))
throw new ArgumentException ("Cannot be null or empty", "path");
GetTrack (device.Handle, trackStruct.item_id, path, callback, IntPtr.Zero);
}
public void UpdateMetadata ()
{
UpdateTrackMetadata (device.Handle, ref trackStruct);
}
private static FileType DetectFileType (Track track)
{
string ext = System.IO.Path.GetExtension (track.FileName);
// Strip leading .
if (ext.Length > 0)
ext = ext.Substring (1, ext.Length - 1);
// this is a hack; catch all m4(a|b|v|p)
if (ext != null && ext.ToLower ().StartsWith ("m4"))
ext = "mp4";
FileType type = (FileType) Enum.Parse (typeof(FileType), ext, true);
//if (type == null)
// return FileType.UNKNOWN;
return type;
}
internal static void DestroyTrack (IntPtr track)
{
LIBMTP_destroy_track_t (track);
}
internal static void GetTrack (MtpDeviceHandle handle, uint trackId, string destPath, ProgressFunction callback, IntPtr data)
{
if (LIBMTP_Get_Track_To_File (handle, trackId, destPath, callback, data) != 0)
{
LibMtpException.CheckErrorStack (handle);
throw new LibMtpException (ErrorCode.General, "Could not download track from the device");
}
}
internal static IntPtr GetTrackListing (MtpDeviceHandle handle, ProgressFunction function, IntPtr data)
{
return LIBMTP_Get_Tracklisting_With_Callback (handle, function, data);
}
internal static void SendTrack (MtpDeviceHandle handle, string path, ref TrackStruct metadata, ProgressFunction callback, IntPtr data)
{
#if LIBMTP8
if (LIBMTP_Send_Track_From_File (handle, path, ref metadata, callback, data) != 0)
#else
if (LIBMTP_Send_Track_From_File (handle, path, ref metadata, callback, data, metadata.parent_id) != 0)
#endif
{
LibMtpException.CheckErrorStack (handle);
throw new LibMtpException (ErrorCode.General, "Could not upload the track");
}
}
internal static void UpdateTrackMetadata (MtpDeviceHandle handle, ref TrackStruct metadata)
{
if (LIBMTP_Update_Track_Metadata (handle, ref metadata) != 0)
throw new LibMtpException (ErrorCode.General);
}
//[DllImport("libmtp.dll")]
//private static extern IntPtr LIBMTP_new_track_t (); // LIBMTP_track_t *
[DllImport("libmtp.dll")]
private static extern void LIBMTP_destroy_track_t (IntPtr track); // LIBMTP_track_t *
//[DllImport("libmtp.dll")]
//private static extern IntPtr LIBMTP_Get_Tracklisting (MtpDeviceHandle handle); //LIBMTP_track_t *
[DllImport("libmtp.dll")]
private static extern IntPtr LIBMTP_Get_Tracklisting_With_Callback (MtpDeviceHandle handle, ProgressFunction callback, IntPtr data); // LIBMTP_track_t *
//[DllImport("libmtp.dll")]
//private static extern IntPtr LIBMTP_Get_Trackmetadata (MtpDeviceHandle handle, uint trackId); // LIBMTP_track_t *
[DllImport("libmtp.dll")]
private static extern int LIBMTP_Get_Track_To_File (MtpDeviceHandle handle, uint trackId, string path, ProgressFunction callback, IntPtr data);
#if LIBMTP8
[DllImport("libmtp.dll")]
private static extern int LIBMTP_Send_Track_From_File (MtpDeviceHandle handle, string path, ref TrackStruct track, ProgressFunction callback, IntPtr data);
#else
[DllImport("libmtp.dll")]
private static extern int LIBMTP_Send_Track_From_File (MtpDeviceHandle handle, string path, ref TrackStruct track, ProgressFunction callback, IntPtr data, uint parentHandle);
#endif
[DllImport("libmtp.dll")]
private static extern int LIBMTP_Update_Track_Metadata (MtpDeviceHandle handle, ref TrackStruct metadata);
//[DllImport("libmtp.dll")]
//private static extern int LIBMTP_Track_Exists (MtpDeviceHandle handle, uint trackId);
//int LIBMTP_Get_Track_To_File_Descriptor (MtpDeviceHandle handle, uint trackId, int const, LIBMTP_progressfunc_t const, void const *const)
//int LIBMTP_Send_Track_From_File_Descriptor (MtpDeviceHandle handle, int const, LIBMTP_track_t *const, LIBMTP_progressfunc_t const, void const *const, uint32_t const)
}
[StructLayout(LayoutKind.Sequential)]
internal struct TrackStruct
{
public uint item_id;
public uint parent_id;
#if LIBMTP8
public uint storage_id;
#endif
[MarshalAs(UnmanagedType.LPStr)] public string title;
[MarshalAs(UnmanagedType.LPStr)] public string artist;
#if LIBMTP8
[MarshalAs(UnmanagedType.LPStr)] public string composer;
#endif
[MarshalAs(UnmanagedType.LPStr)] public string genre;
[MarshalAs(UnmanagedType.LPStr)] public string album;
[MarshalAs(UnmanagedType.LPStr)] public string date;
[MarshalAs(UnmanagedType.LPStr)] public string filename;
public ushort tracknumber;
public uint duration;
public uint samplerate;
public ushort nochannels;
public uint wavecodec;
public uint bitrate;
public ushort bitratetype;
public ushort rating; // 0 -> 100
public uint usecount;
public ulong filesize;
#if LIBMTP_TRACK_HAS_MODDATE
public uint modificationdate;
#endif
public FileType filetype;
public IntPtr next; // Track Null if last
/*
public Track? Next
{
get
{
if (next == IntPtr.Zero)
return null;
return (Track)Marshal.PtrToStructure(next, typeof(Track));
}
}*/
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using IdentityServer4.Stores;
using IdentityServer4.Configuration;
using IdentityServer4.Logging.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication;
namespace IdentityServer4.Validation
{
internal class TokenValidator : ITokenValidator
{
private readonly ILogger _logger;
private readonly IdentityServerOptions _options;
private readonly IHttpContextAccessor _context;
private readonly IReferenceTokenStore _referenceTokenStore;
private readonly ICustomTokenValidator _customValidator;
private readonly IClientStore _clients;
private readonly IProfileService _profile;
private readonly IKeyMaterialService _keys;
private readonly ISystemClock _clock;
private readonly TokenValidationLog _log;
public TokenValidator(
IdentityServerOptions options,
IHttpContextAccessor context,
IClientStore clients,
IProfileService profile,
IReferenceTokenStore referenceTokenStore,
IRefreshTokenStore refreshTokenStore,
ICustomTokenValidator customValidator,
IKeyMaterialService keys,
ISystemClock clock,
ILogger<TokenValidator> logger)
{
_options = options;
_context = context;
_clients = clients;
_profile = profile;
_referenceTokenStore = referenceTokenStore;
_customValidator = customValidator;
_keys = keys;
_clock = clock;
_logger = logger;
_log = new TokenValidationLog();
}
public async Task<TokenValidationResult> ValidateIdentityTokenAsync(string token, string clientId = null, bool validateLifetime = true)
{
_logger.LogDebug("Start identity token validation");
if (token.Length > _options.InputLengthRestrictions.Jwt)
{
_logger.LogError("JWT too long");
return Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken);
}
if (clientId.IsMissing())
{
clientId = GetClientIdFromJwt(token);
if (clientId.IsMissing())
{
_logger.LogError("No clientId supplied, can't find id in identity token.");
return Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken);
}
}
_log.ClientId = clientId;
_log.ValidateLifetime = validateLifetime;
var client = await _clients.FindEnabledClientByIdAsync(clientId);
if (client == null)
{
_logger.LogError("Unknown or disabled client: {clientId}.", clientId);
return Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken);
}
_log.ClientName = client.ClientName;
_logger.LogDebug("Client found: {clientId} / {clientName}", client.ClientId, client.ClientName);
var keys = await _keys.GetValidationKeysAsync();
var result = await ValidateJwtAsync(token, keys, audience: clientId, validateLifetime: validateLifetime);
result.Client = client;
if (result.IsError)
{
LogError("Error validating JWT");
return result;
}
_logger.LogDebug("Calling into custom token validator: {type}", _customValidator.GetType().FullName);
var customResult = await _customValidator.ValidateIdentityTokenAsync(result);
if (customResult.IsError)
{
LogError("Custom validator failed: " + (customResult.Error ?? "unknown"));
return customResult;
}
_log.Claims = customResult.Claims.ToClaimsDictionary();
LogSuccess();
return customResult;
}
public async Task<TokenValidationResult> ValidateAccessTokenAsync(string token, string expectedScope = null)
{
_logger.LogTrace("Start access token validation");
_log.ExpectedScope = expectedScope;
_log.ValidateLifetime = true;
TokenValidationResult result;
if (token.Contains("."))
{
if (token.Length > _options.InputLengthRestrictions.Jwt)
{
_logger.LogError("JWT too long");
return new TokenValidationResult
{
IsError = true,
Error = OidcConstants.ProtectedResourceErrors.InvalidToken,
ErrorDescription = "Token too long"
};
}
_log.AccessTokenType = AccessTokenType.Jwt.ToString();
result = await ValidateJwtAsync(
token,
await _keys.GetValidationKeysAsync());
}
else
{
if (token.Length > _options.InputLengthRestrictions.TokenHandle)
{
_logger.LogError("token handle too long");
return new TokenValidationResult
{
IsError = true,
Error = OidcConstants.ProtectedResourceErrors.InvalidToken,
ErrorDescription = "Token too long"
};
}
_log.AccessTokenType = AccessTokenType.Reference.ToString();
result = await ValidateReferenceAccessTokenAsync(token);
}
_log.Claims = result.Claims.ToClaimsDictionary();
if (result.IsError)
{
return result;
}
// make sure client is still active (if client_id claim is present)
var clientClaim = result.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.ClientId);
if (clientClaim != null)
{
var client = await _clients.FindEnabledClientByIdAsync(clientClaim.Value);
if (client == null)
{
_logger.LogError("Client deleted or disabled: {clientId}", clientClaim.Value);
result.IsError = true;
result.Error = OidcConstants.ProtectedResourceErrors.InvalidToken;
result.Claims = null;
return result;
}
}
// make sure user is still active (if sub claim is present)
var subClaim = result.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject);
if (subClaim != null)
{
var principal = Principal.Create("tokenvalidator", result.Claims.ToArray());
if (result.ReferenceTokenId.IsPresent())
{
principal.Identities.First().AddClaim(new Claim(JwtClaimTypes.ReferenceTokenId, result.ReferenceTokenId));
}
var isActiveCtx = new IsActiveContext(principal, result.Client, IdentityServerConstants.ProfileIsActiveCallers.AccessTokenValidation);
await _profile.IsActiveAsync(isActiveCtx);
if (isActiveCtx.IsActive == false)
{
_logger.LogError("User marked as not active: {subject}", subClaim.Value);
result.IsError = true;
result.Error = OidcConstants.ProtectedResourceErrors.InvalidToken;
result.Claims = null;
return result;
}
}
// check expected scope(s)
if (expectedScope.IsPresent())
{
var scope = result.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Scope && c.Value == expectedScope);
if (scope == null)
{
LogError($"Checking for expected scope {expectedScope} failed");
return Invalid(OidcConstants.ProtectedResourceErrors.InsufficientScope);
}
}
_logger.LogDebug("Calling into custom token validator: {type}", _customValidator.GetType().FullName);
var customResult = await _customValidator.ValidateAccessTokenAsync(result);
if (customResult.IsError)
{
LogError("Custom validator failed: " + (customResult.Error ?? "unknown"));
return customResult;
}
// add claims again after custom validation
_log.Claims = customResult.Claims.ToClaimsDictionary();
LogSuccess();
return customResult;
}
private async Task<TokenValidationResult> ValidateJwtAsync(string jwt, IEnumerable<SecurityKeyInfo> validationKeys, bool validateLifetime = true, string audience = null)
{
var handler = new JwtSecurityTokenHandler();
handler.InboundClaimTypeMap.Clear();
var parameters = new TokenValidationParameters
{
ValidIssuer = _context.HttpContext.GetIdentityServerIssuerUri(),
IssuerSigningKeys = validationKeys.Select(k => k.Key),
ValidateLifetime = validateLifetime
};
if (audience.IsPresent())
{
parameters.ValidAudience = audience;
}
else
{
parameters.ValidateAudience = false;
}
try
{
var id = handler.ValidateToken(jwt, parameters, out var securityToken);
var jwtSecurityToken = securityToken as JwtSecurityToken;
// if no audience is specified, we make at least sure that it is an access token
if (audience.IsMissing())
{
if (_options.AccessTokenJwtType.IsPresent())
{
var type = jwtSecurityToken.Header.Typ;
if (!string.Equals(type, _options.AccessTokenJwtType))
{
return new TokenValidationResult
{
IsError = true,
Error = "invalid JWT token type"
};
}
}
}
// if access token contains an ID, log it
var jwtId = id.FindFirst(JwtClaimTypes.JwtId);
if (jwtId != null)
{
_log.JwtId = jwtId.Value;
}
// load the client that belongs to the client_id claim
Client client = null;
var clientId = id.FindFirst(JwtClaimTypes.ClientId);
if (clientId != null)
{
client = await _clients.FindEnabledClientByIdAsync(clientId.Value);
if (client == null)
{
throw new InvalidOperationException("Client does not exist anymore.");
}
}
var claims = id.Claims.ToList();
// check the scope format (array vs space delimited string)
var scopes = claims.Where(c => c.Type == JwtClaimTypes.Scope).ToArray();
if (scopes.Any())
{
foreach (var scope in scopes)
{
if (scope.Value.Contains(" "))
{
claims.Remove(scope);
var values = scope.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries);
foreach (var value in values)
{
claims.Add(new Claim(JwtClaimTypes.Scope, value));
}
}
}
}
return new TokenValidationResult
{
IsError = false,
Claims = claims,
Client = client,
Jwt = jwt
};
}
catch (SecurityTokenExpiredException expiredException)
{
_logger.LogInformation(expiredException, "JWT token validation error: {exception}", expiredException.Message);
return Invalid(OidcConstants.ProtectedResourceErrors.ExpiredToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "JWT token validation error: {exception}", ex.Message);
return Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken);
}
}
private async Task<TokenValidationResult> ValidateReferenceAccessTokenAsync(string tokenHandle)
{
_log.TokenHandle = tokenHandle;
var token = await _referenceTokenStore.GetReferenceTokenAsync(tokenHandle);
if (token == null)
{
LogError("Invalid reference token.");
return Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken);
}
if (token.CreationTime.HasExceeded(token.Lifetime, _clock.UtcNow.UtcDateTime))
{
LogError("Token expired.");
await _referenceTokenStore.RemoveReferenceTokenAsync(tokenHandle);
return Invalid(OidcConstants.ProtectedResourceErrors.ExpiredToken);
}
// load the client that is defined in the token
Client client = null;
if (token.ClientId != null)
{
client = await _clients.FindEnabledClientByIdAsync(token.ClientId);
}
if (client == null)
{
LogError($"Client deleted or disabled: {token.ClientId}");
return Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken);
}
return new TokenValidationResult
{
IsError = false,
Client = client,
Claims = ReferenceTokenToClaims(token),
ReferenceToken = token,
ReferenceTokenId = tokenHandle
};
}
private IEnumerable<Claim> ReferenceTokenToClaims(Token token)
{
var claims = new List<Claim>
{
new Claim(JwtClaimTypes.Issuer, token.Issuer),
new Claim(JwtClaimTypes.NotBefore, new DateTimeOffset(token.CreationTime).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
new Claim(JwtClaimTypes.Expiration, new DateTimeOffset(token.CreationTime).AddSeconds(token.Lifetime).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
};
foreach (var aud in token.Audiences)
{
claims.Add(new Claim(JwtClaimTypes.Audience, aud));
}
claims.AddRange(token.Claims);
return claims;
}
private string GetClientIdFromJwt(string token)
{
try
{
var jwt = new JwtSecurityToken(token);
var clientId = jwt.Audiences.FirstOrDefault();
return clientId;
}
catch (Exception ex)
{
_logger.LogError(ex, "Malformed JWT token: {exception}", ex.Message);
return null;
}
}
private TokenValidationResult Invalid(string error)
{
return new TokenValidationResult
{
IsError = true,
Error = error
};
}
private void LogError(string message)
{
_logger.LogError(message + "\n{@logMessage}", _log);
}
private void LogSuccess()
{
_logger.LogDebug("Token validation success\n{@logMessage}", _log);
}
}
}
| |
// 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.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using Internal.Runtime.CompilerServices;
#if BIT64
using nuint = System.UInt64;
using nint = System.Int64;
#else
using nuint = System.UInt32;
using nint = System.Int32;
#endif
namespace System
{
internal static partial class SpanHelpers // .Char
{
public static int IndexOf(ref char searchSpace, int searchSpaceLength, ref char value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
char valueHead = value;
ref char valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int remainingSearchSpaceLength = searchSpaceLength - valueTailLength;
int index = 0;
while (remainingSearchSpaceLength > 0)
{
// Do a quick search for the first element of "value".
int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
remainingSearchSpaceLength -= relativeIndex;
index += relativeIndex;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(
ref Unsafe.As<char, byte>(ref Unsafe.Add(ref searchSpace, index + 1)),
ref Unsafe.As<char, byte>(ref valueTail),
(nuint)valueTailLength * 2))
{
return index; // The tail matched. Return a successful find.
}
remainingSearchSpaceLength--;
index++;
}
return -1;
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe int SequenceCompareTo(ref char first, int firstLength, ref char second, int secondLength)
{
Debug.Assert(firstLength >= 0);
Debug.Assert(secondLength >= 0);
int lengthDelta = firstLength - secondLength;
if (Unsafe.AreSame(ref first, ref second))
goto Equal;
IntPtr minLength = (IntPtr)((firstLength < secondLength) ? firstLength : secondLength);
IntPtr i = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
if ((byte*)minLength >= (byte*)(sizeof(UIntPtr) / sizeof(char)))
{
if (Vector.IsHardwareAccelerated && (byte*)minLength >= (byte*)Vector<ushort>.Count)
{
IntPtr nLength = minLength - Vector<ushort>.Count;
do
{
if (Unsafe.ReadUnaligned<Vector<ushort>>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref first, i))) !=
Unsafe.ReadUnaligned<Vector<ushort>>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref second, i))))
{
break;
}
i += Vector<ushort>.Count;
}
while ((byte*)nLength >= (byte*)i);
}
while ((byte*)minLength >= (byte*)(i + sizeof(UIntPtr) / sizeof(char)))
{
if (Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref first, i))) !=
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref second, i))))
{
break;
}
i += sizeof(UIntPtr) / sizeof(char);
}
}
if (sizeof(UIntPtr) > sizeof(int) && (byte*)minLength >= (byte*)(i + sizeof(int) / sizeof(char)))
{
if (Unsafe.ReadUnaligned<int>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref first, i))) ==
Unsafe.ReadUnaligned<int>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref second, i))))
{
i += sizeof(int) / sizeof(char);
}
}
while ((byte*)i < (byte*)minLength)
{
int result = Unsafe.Add(ref first, i).CompareTo(Unsafe.Add(ref second, i));
if (result != 0)
return result;
i += 1;
}
Equal:
return lengthDelta;
}
// Adapted from IndexOf(...)
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe bool Contains(ref char searchSpace, char value, int length)
{
Debug.Assert(length >= 0);
fixed (char* pChars = &searchSpace)
{
char* pCh = pChars;
char* pEndCh = pCh + length;
if (Vector.IsHardwareAccelerated && length >= Vector<ushort>.Count * 2)
{
// Figure out how many characters to read sequentially until we are vector aligned
// This is equivalent to:
// unaligned = ((int)pCh % Unsafe.SizeOf<Vector<ushort>>()) / elementsPerByte
// length = (Vector<ushort>.Count - unaligned) % Vector<ushort>.Count
const int elementsPerByte = sizeof(ushort) / sizeof(byte);
int unaligned = ((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) / elementsPerByte;
length = (Vector<ushort>.Count - unaligned) & (Vector<ushort>.Count - 1);
}
SequentialScan:
while (length >= 4)
{
length -= 4;
if (value == *pCh ||
value == *(pCh + 1) ||
value == *(pCh + 2) ||
value == *(pCh + 3))
{
goto Found;
}
pCh += 4;
}
while (length > 0)
{
length -= 1;
if (value == *pCh)
goto Found;
pCh += 1;
}
// We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow
// the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated.
if (Vector.IsHardwareAccelerated && pCh < pEndCh)
{
// Get the highest multiple of Vector<ushort>.Count that is within the search space.
// That will be how many times we iterate in the loop below.
// This is equivalent to: length = Vector<ushort>.Count * ((int)(pEndCh - pCh) / Vector<ushort>.Count)
length = (int)((pEndCh - pCh) & ~(Vector<ushort>.Count - 1));
// Get comparison Vector
Vector<ushort> vComparison = new Vector<ushort>(value);
while (length > 0)
{
// Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh is always vector aligned
Debug.Assert(((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) == 0);
Vector<ushort> vMatches = Vector.Equals(vComparison, Unsafe.Read<Vector<ushort>>(pCh));
if (Vector<ushort>.Zero.Equals(vMatches))
{
pCh += Vector<ushort>.Count;
length -= Vector<ushort>.Count;
continue;
}
goto Found;
}
if (pCh < pEndCh)
{
length = (int)(pEndCh - pCh);
goto SequentialScan;
}
}
return false;
Found:
return true;
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe int IndexOf(ref char searchSpace, char value, int length)
{
Debug.Assert(length >= 0);
nint offset = 0;
nint lengthToExamine = length;
if (((int)Unsafe.AsPointer(ref searchSpace) & 1) != 0)
{
// Input isn't char aligned, we won't be able to align it to a Vector
}
else if (Sse2.IsSupported)
{
// Avx2 branch also operates on Sse2 sizes, so check is combined.
// Needs to be double length to allow us to align the data first.
if (length >= Vector128<ushort>.Count * 2)
{
lengthToExamine = UnalignedCountVector128(ref searchSpace);
}
}
else if (Vector.IsHardwareAccelerated)
{
// Needs to be double length to allow us to align the data first.
if (length >= Vector<ushort>.Count * 2)
{
lengthToExamine = UnalignedCountVector(ref searchSpace);
}
}
SequentialScan:
// In the non-vector case lengthToExamine is the total length.
// In the vector case lengthToExamine first aligns to Vector,
// then in a second pass after the Vector lengths is the
// remaining data that is shorter than a Vector length.
while (lengthToExamine >= 4)
{
ref char current = ref Add(ref searchSpace, offset);
if (value == current)
goto Found;
if (value == Add(ref current, 1))
goto Found1;
if (value == Add(ref current, 2))
goto Found2;
if (value == Add(ref current, 3))
goto Found3;
offset += 4;
lengthToExamine -= 4;
}
while (lengthToExamine > 0)
{
if (value == Add(ref searchSpace, offset))
goto Found;
offset += 1;
lengthToExamine -= 1;
}
// We get past SequentialScan only if IsHardwareAccelerated or intrinsic .IsSupported is true. However, we still have the redundant check to allow
// the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated.
if (Avx2.IsSupported)
{
if (offset < length)
{
Debug.Assert(length - offset >= Vector128<ushort>.Count);
if (((nint)Unsafe.AsPointer(ref Unsafe.Add(ref searchSpace, (IntPtr)offset)) & (nint)(Vector256<byte>.Count - 1)) != 0)
{
// Not currently aligned to Vector256 (is aligned to Vector128); this can cause a problem for searches
// with no upper bound e.g. String.wcslen. Start with a check on Vector128 to align to Vector256,
// before moving to processing Vector256.
// If the input searchSpan has been fixed or pinned, this ensures we do not fault across memory pages
// while searching for an end of string. Specifically that this assumes that the length is either correct
// or that the data is pinned otherwise it may cause an AccessViolation from crossing a page boundary into an
// unowned page. If the search is unbounded (e.g. null terminator in wcslen) and the search value is not found,
// again this will likely cause an AccessViolation. However, correctly bounded searches will return -1 rather
// than ever causing an AV.
// If the searchSpan has not been fixed or pinned the GC can relocate it during the execution of this
// method, so the alignment only acts as best endeavour. The GC cost is likely to dominate over
// the misalignment that may occur after; to we default to giving the GC a free hand to relocate and
// its up to the caller whether they are operating over fixed data.
Vector128<ushort> values = Vector128.Create((ushort)value);
Vector128<ushort> search = LoadVector128(ref searchSpace, offset);
// Same method as below
int matches = Sse2.MoveMask(Sse2.CompareEqual(values, search).AsByte());
if (matches == 0)
{
// Zero flags set so no matches
offset += Vector128<ushort>.Count;
}
else
{
// Find bitflag offset of first match and add to current offset
return (int)(offset + (BitOperations.TrailingZeroCount(matches) / sizeof(char)));
}
}
lengthToExamine = GetCharVector256SpanLength(offset, length);
if (lengthToExamine > 0)
{
Vector256<ushort> values = Vector256.Create((ushort)value);
do
{
Debug.Assert(lengthToExamine >= Vector256<ushort>.Count);
Vector256<ushort> search = LoadVector256(ref searchSpace, offset);
int matches = Avx2.MoveMask(Avx2.CompareEqual(values, search).AsByte());
// Note that MoveMask has converted the equal vector elements into a set of bit flags,
// So the bit position in 'matches' corresponds to the element offset.
if (matches == 0)
{
// Zero flags set so no matches
offset += Vector256<ushort>.Count;
lengthToExamine -= Vector256<ushort>.Count;
continue;
}
// Find bitflag offset of first match and add to current offset,
// flags are in bytes so divide for chars
return (int)(offset + (BitOperations.TrailingZeroCount(matches) / sizeof(char)));
} while (lengthToExamine > 0);
}
lengthToExamine = GetCharVector128SpanLength(offset, length);
if (lengthToExamine > 0)
{
Debug.Assert(lengthToExamine >= Vector128<ushort>.Count);
Vector128<ushort> values = Vector128.Create((ushort)value);
Vector128<ushort> search = LoadVector128(ref searchSpace, offset);
// Same method as above
int matches = Sse2.MoveMask(Sse2.CompareEqual(values, search).AsByte());
if (matches == 0)
{
// Zero flags set so no matches
offset += Vector128<ushort>.Count;
// Don't need to change lengthToExamine here as we don't use its current value again.
}
else
{
// Find bitflag offset of first match and add to current offset,
// flags are in bytes so divide for chars
return (int)(offset + (BitOperations.TrailingZeroCount(matches) / sizeof(char)));
}
}
if (offset < length)
{
lengthToExamine = length - offset;
goto SequentialScan;
}
}
}
else if (Sse2.IsSupported)
{
if (offset < length)
{
Debug.Assert(length - offset >= Vector128<ushort>.Count);
lengthToExamine = GetCharVector128SpanLength(offset, length);
if (lengthToExamine > 0)
{
Vector128<ushort> values = Vector128.Create((ushort)value);
do
{
Debug.Assert(lengthToExamine >= Vector128<ushort>.Count);
Vector128<ushort> search = LoadVector128(ref searchSpace, offset);
// Same method as above
int matches = Sse2.MoveMask(Sse2.CompareEqual(values, search).AsByte());
if (matches == 0)
{
// Zero flags set so no matches
offset += Vector128<ushort>.Count;
lengthToExamine -= Vector128<ushort>.Count;
continue;
}
// Find bitflag offset of first match and add to current offset,
// flags are in bytes so divide for chars
return (int)(offset + (BitOperations.TrailingZeroCount(matches) / sizeof(char)));
} while (lengthToExamine > 0);
}
if (offset < length)
{
lengthToExamine = length - offset;
goto SequentialScan;
}
}
}
else if (Vector.IsHardwareAccelerated)
{
if (offset < length)
{
Debug.Assert(length - offset >= Vector<ushort>.Count);
lengthToExamine = GetCharVectorSpanLength(offset, length);
if (lengthToExamine > 0)
{
Vector<ushort> values = new Vector<ushort>((ushort)value);
do
{
Debug.Assert(lengthToExamine >= Vector<ushort>.Count);
var matches = Vector.Equals(values, LoadVector(ref searchSpace, offset));
if (Vector<ushort>.Zero.Equals(matches))
{
offset += Vector<ushort>.Count;
lengthToExamine -= Vector<ushort>.Count;
continue;
}
// Find offset of first match
return (int)(offset + LocateFirstFoundChar(matches));
} while (lengthToExamine > 0);
}
if (offset < length)
{
lengthToExamine = length - offset;
goto SequentialScan;
}
}
}
return -1;
Found3:
return (int)(offset + 3);
Found2:
return (int)(offset + 2);
Found1:
return (int)(offset + 1);
Found:
return (int)(offset);
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe int IndexOfAny(ref char searchSpace, char value0, char value1, int length)
{
Debug.Assert(length >= 0);
fixed (char* pChars = &searchSpace)
{
char* pCh = pChars;
char* pEndCh = pCh + length;
if (Vector.IsHardwareAccelerated && length >= Vector<ushort>.Count * 2)
{
// Figure out how many characters to read sequentially until we are vector aligned
// This is equivalent to:
// unaligned = ((int)pCh % Unsafe.SizeOf<Vector<ushort>>()) / elementsPerByte
// length = (Vector<ushort>.Count - unaligned) % Vector<ushort>.Count
const int elementsPerByte = sizeof(ushort) / sizeof(byte);
int unaligned = ((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) / elementsPerByte;
length = (Vector<ushort>.Count - unaligned) & (Vector<ushort>.Count - 1);
}
SequentialScan:
while (length >= 4)
{
length -= 4;
if (pCh[0] == value0 || pCh[0] == value1)
goto Found;
if (pCh[1] == value0 || pCh[1] == value1)
goto Found1;
if (pCh[2] == value0 || pCh[2] == value1)
goto Found2;
if (pCh[3] == value0 || pCh[3] == value1)
goto Found3;
pCh += 4;
}
while (length > 0)
{
length--;
if (pCh[0] == value0 || pCh[0] == value1)
goto Found;
pCh++;
}
// We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow
// the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated.
if (Vector.IsHardwareAccelerated && pCh < pEndCh)
{
// Get the highest multiple of Vector<ushort>.Count that is within the search space.
// That will be how many times we iterate in the loop below.
// This is equivalent to: length = Vector<ushort>.Count * ((int)(pEndCh - pCh) / Vector<ushort>.Count)
length = (int)((pEndCh - pCh) & ~(Vector<ushort>.Count - 1));
// Get comparison Vector
Vector<ushort> values0 = new Vector<ushort>(value0);
Vector<ushort> values1 = new Vector<ushort>(value1);
while (length > 0)
{
// Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh is always vector aligned
Debug.Assert(((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) == 0);
Vector<ushort> vData = Unsafe.Read<Vector<ushort>>(pCh);
var vMatches = Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1));
if (Vector<ushort>.Zero.Equals(vMatches))
{
pCh += Vector<ushort>.Count;
length -= Vector<ushort>.Count;
continue;
}
// Find offset of first match
return (int)(pCh - pChars) + LocateFirstFoundChar(vMatches);
}
if (pCh < pEndCh)
{
length = (int)(pEndCh - pCh);
goto SequentialScan;
}
}
return -1;
Found3:
pCh++;
Found2:
pCh++;
Found1:
pCh++;
Found:
return (int)(pCh - pChars);
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe int IndexOfAny(ref char searchSpace, char value0, char value1, char value2, int length)
{
Debug.Assert(length >= 0);
fixed (char* pChars = &searchSpace)
{
char* pCh = pChars;
char* pEndCh = pCh + length;
if (Vector.IsHardwareAccelerated && length >= Vector<ushort>.Count * 2)
{
// Figure out how many characters to read sequentially until we are vector aligned
// This is equivalent to:
// unaligned = ((int)pCh % Unsafe.SizeOf<Vector<ushort>>()) / elementsPerByte
// length = (Vector<ushort>.Count - unaligned) % Vector<ushort>.Count
const int elementsPerByte = sizeof(ushort) / sizeof(byte);
int unaligned = ((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) / elementsPerByte;
length = (Vector<ushort>.Count - unaligned) & (Vector<ushort>.Count - 1);
}
SequentialScan:
while (length >= 4)
{
length -= 4;
if (pCh[0] == value0 || pCh[0] == value1 || pCh[0] == value2)
goto Found;
if (pCh[1] == value0 || pCh[1] == value1 || pCh[1] == value2)
goto Found1;
if (pCh[2] == value0 || pCh[2] == value1 || pCh[2] == value2)
goto Found2;
if (pCh[3] == value0 || pCh[3] == value1 || pCh[3] == value2)
goto Found3;
pCh += 4;
}
while (length > 0)
{
length--;
if (pCh[0] == value0 || pCh[0] == value1 || pCh[0] == value2)
goto Found;
pCh++;
}
// We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow
// the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated.
if (Vector.IsHardwareAccelerated && pCh < pEndCh)
{
// Get the highest multiple of Vector<ushort>.Count that is within the search space.
// That will be how many times we iterate in the loop below.
// This is equivalent to: length = Vector<ushort>.Count * ((int)(pEndCh - pCh) / Vector<ushort>.Count)
length = (int)((pEndCh - pCh) & ~(Vector<ushort>.Count - 1));
// Get comparison Vector
Vector<ushort> values0 = new Vector<ushort>(value0);
Vector<ushort> values1 = new Vector<ushort>(value1);
Vector<ushort> values2 = new Vector<ushort>(value2);
while (length > 0)
{
// Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh is always vector aligned
Debug.Assert(((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) == 0);
Vector<ushort> vData = Unsafe.Read<Vector<ushort>>(pCh);
var vMatches = Vector.BitwiseOr(
Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1)),
Vector.Equals(vData, values2));
if (Vector<ushort>.Zero.Equals(vMatches))
{
pCh += Vector<ushort>.Count;
length -= Vector<ushort>.Count;
continue;
}
// Find offset of first match
return (int)(pCh - pChars) + LocateFirstFoundChar(vMatches);
}
if (pCh < pEndCh)
{
length = (int)(pEndCh - pCh);
goto SequentialScan;
}
}
return -1;
Found3:
pCh++;
Found2:
pCh++;
Found1:
pCh++;
Found:
return (int)(pCh - pChars);
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe int IndexOfAny(ref char searchSpace, char value0, char value1, char value2, char value3, int length)
{
Debug.Assert(length >= 0);
fixed (char* pChars = &searchSpace)
{
char* pCh = pChars;
char* pEndCh = pCh + length;
if (Vector.IsHardwareAccelerated && length >= Vector<ushort>.Count * 2)
{
// Figure out how many characters to read sequentially until we are vector aligned
// This is equivalent to:
// unaligned = ((int)pCh % Unsafe.SizeOf<Vector<ushort>>()) / elementsPerByte
// length = (Vector<ushort>.Count - unaligned) % Vector<ushort>.Count
const int elementsPerByte = sizeof(ushort) / sizeof(byte);
int unaligned = ((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) / elementsPerByte;
length = (Vector<ushort>.Count - unaligned) & (Vector<ushort>.Count - 1);
}
SequentialScan:
while (length >= 4)
{
length -= 4;
if (pCh[0] == value0 || pCh[0] == value1 || pCh[0] == value2 || pCh[0] == value3)
goto Found;
if (pCh[1] == value0 || pCh[1] == value1 || pCh[1] == value2 || pCh[1] == value3)
goto Found1;
if (pCh[2] == value0 || pCh[2] == value1 || pCh[2] == value2 || pCh[2] == value3)
goto Found2;
if (pCh[3] == value0 || pCh[3] == value1 || pCh[3] == value2 || pCh[3] == value3)
goto Found3;
pCh += 4;
}
while (length > 0)
{
length--;
if (pCh[0] == value0 || pCh[0] == value1 || pCh[0] == value2 || pCh[0] == value3)
goto Found;
pCh++;
}
// We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow
// the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated.
if (Vector.IsHardwareAccelerated && pCh < pEndCh)
{
// Get the highest multiple of Vector<ushort>.Count that is within the search space.
// That will be how many times we iterate in the loop below.
// This is equivalent to: length = Vector<ushort>.Count * ((int)(pEndCh - pCh) / Vector<ushort>.Count)
length = (int)((pEndCh - pCh) & ~(Vector<ushort>.Count - 1));
// Get comparison Vector
Vector<ushort> values0 = new Vector<ushort>(value0);
Vector<ushort> values1 = new Vector<ushort>(value1);
Vector<ushort> values2 = new Vector<ushort>(value2);
Vector<ushort> values3 = new Vector<ushort>(value3);
while (length > 0)
{
// Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh is always vector aligned
Debug.Assert(((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) == 0);
Vector<ushort> vData = Unsafe.Read<Vector<ushort>>(pCh);
var vMatches = Vector.BitwiseOr(
Vector.BitwiseOr(
Vector.BitwiseOr(Vector.Equals(vData, values0), Vector.Equals(vData, values1)),
Vector.Equals(vData, values2)),
Vector.Equals(vData, values3));
if (Vector<ushort>.Zero.Equals(vMatches))
{
pCh += Vector<ushort>.Count;
length -= Vector<ushort>.Count;
continue;
}
// Find offset of first match
return (int)(pCh - pChars) + LocateFirstFoundChar(vMatches);
}
if (pCh < pEndCh)
{
length = (int)(pEndCh - pCh);
goto SequentialScan;
}
}
return -1;
Found3:
pCh++;
Found2:
pCh++;
Found1:
pCh++;
Found:
return (int)(pCh - pChars);
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe int IndexOfAny(ref char searchSpace, char value0, char value1, char value2, char value3, char value4, int length)
{
Debug.Assert(length >= 0);
fixed (char* pChars = &searchSpace)
{
char* pCh = pChars;
char* pEndCh = pCh + length;
if (Vector.IsHardwareAccelerated && length >= Vector<ushort>.Count * 2)
{
// Figure out how many characters to read sequentially until we are vector aligned
// This is equivalent to:
// unaligned = ((int)pCh % Unsafe.SizeOf<Vector<ushort>>()) / elementsPerByte
// length = (Vector<ushort>.Count - unaligned) % Vector<ushort>.Count
const int elementsPerByte = sizeof(ushort) / sizeof(byte);
int unaligned = ((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) / elementsPerByte;
length = (Vector<ushort>.Count - unaligned) & (Vector<ushort>.Count - 1);
}
SequentialScan:
while (length >= 4)
{
length -= 4;
if (pCh[0] == value0 || pCh[0] == value1 || pCh[0] == value2 || pCh[0] == value3 || pCh[0] == value4)
goto Found;
if (pCh[1] == value0 || pCh[1] == value1 || pCh[1] == value2 || pCh[1] == value3 || pCh[1] == value4)
goto Found1;
if (pCh[2] == value0 || pCh[2] == value1 || pCh[2] == value2 || pCh[2] == value3 || pCh[2] == value4)
goto Found2;
if (pCh[3] == value0 || pCh[3] == value1 || pCh[3] == value2 || pCh[3] == value3 || pCh[3] == value4)
goto Found3;
pCh += 4;
}
while (length > 0)
{
length--;
if (pCh[0] == value0 || pCh[0] == value1 || pCh[0] == value2 || pCh[0] == value3 || pCh[0] == value4)
goto Found;
pCh++;
}
// We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow
// the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated.
if (Vector.IsHardwareAccelerated && pCh < pEndCh)
{
// Get the highest multiple of Vector<ushort>.Count that is within the search space.
// That will be how many times we iterate in the loop below.
// This is equivalent to: length = Vector<ushort>.Count * ((int)(pEndCh - pCh) / Vector<ushort>.Count)
length = (int)((pEndCh - pCh) & ~(Vector<ushort>.Count - 1));
// Get comparison Vector
Vector<ushort> values0 = new Vector<ushort>(value0);
Vector<ushort> values1 = new Vector<ushort>(value1);
Vector<ushort> values2 = new Vector<ushort>(value2);
Vector<ushort> values3 = new Vector<ushort>(value3);
Vector<ushort> values4 = new Vector<ushort>(value4);
while (length > 0)
{
// Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh is always vector aligned
Debug.Assert(((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) == 0);
Vector<ushort> vData = Unsafe.Read<Vector<ushort>>(pCh);
var vMatches = Vector.BitwiseOr(
Vector.BitwiseOr(
Vector.BitwiseOr(
Vector.BitwiseOr(Vector.Equals(vData, values0), Vector.Equals(vData, values1)),
Vector.Equals(vData, values2)),
Vector.Equals(vData, values3)),
Vector.Equals(vData, values4));
if (Vector<ushort>.Zero.Equals(vMatches))
{
pCh += Vector<ushort>.Count;
length -= Vector<ushort>.Count;
continue;
}
// Find offset of first match
return (int)(pCh - pChars) + LocateFirstFoundChar(vMatches);
}
if (pCh < pEndCh)
{
length = (int)(pEndCh - pCh);
goto SequentialScan;
}
}
return -1;
Found3:
pCh++;
Found2:
pCh++;
Found1:
pCh++;
Found:
return (int)(pCh - pChars);
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe int LastIndexOf(ref char searchSpace, char value, int length)
{
Debug.Assert(length >= 0);
fixed (char* pChars = &searchSpace)
{
char* pCh = pChars + length;
char* pEndCh = pChars;
if (Vector.IsHardwareAccelerated && length >= Vector<ushort>.Count * 2)
{
// Figure out how many characters to read sequentially from the end until we are vector aligned
// This is equivalent to: length = ((int)pCh % Unsafe.SizeOf<Vector<ushort>>()) / elementsPerByte
const int elementsPerByte = sizeof(ushort) / sizeof(byte);
length = ((int)pCh & (Unsafe.SizeOf<Vector<ushort>>() - 1)) / elementsPerByte;
}
SequentialScan:
while (length >= 4)
{
length -= 4;
pCh -= 4;
if (*(pCh + 3) == value)
goto Found3;
if (*(pCh + 2) == value)
goto Found2;
if (*(pCh + 1) == value)
goto Found1;
if (*pCh == value)
goto Found;
}
while (length > 0)
{
length -= 1;
pCh -= 1;
if (*pCh == value)
goto Found;
}
// We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow
// the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated.
if (Vector.IsHardwareAccelerated && pCh > pEndCh)
{
// Get the highest multiple of Vector<ushort>.Count that is within the search space.
// That will be how many times we iterate in the loop below.
// This is equivalent to: length = Vector<ushort>.Count * ((int)(pCh - pEndCh) / Vector<ushort>.Count)
length = (int)((pCh - pEndCh) & ~(Vector<ushort>.Count - 1));
// Get comparison Vector
Vector<ushort> vComparison = new Vector<ushort>(value);
while (length > 0)
{
char* pStart = pCh - Vector<ushort>.Count;
// Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh (and hence pSart) is always vector aligned
Debug.Assert(((int)pStart & (Unsafe.SizeOf<Vector<ushort>>() - 1)) == 0);
Vector<ushort> vMatches = Vector.Equals(vComparison, Unsafe.Read<Vector<ushort>>(pStart));
if (Vector<ushort>.Zero.Equals(vMatches))
{
pCh -= Vector<ushort>.Count;
length -= Vector<ushort>.Count;
continue;
}
// Find offset of last match
return (int)(pStart - pEndCh) + LocateLastFoundChar(vMatches);
}
if (pCh > pEndCh)
{
length = (int)(pCh - pEndCh);
goto SequentialScan;
}
}
return -1;
Found:
return (int)(pCh - pEndCh);
Found1:
return (int)(pCh - pEndCh) + 1;
Found2:
return (int)(pCh - pEndCh) + 2;
Found3:
return (int)(pCh - pEndCh) + 3;
}
}
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundChar(Vector<ushort> match)
{
var vector64 = Vector.AsVectorUInt64(match);
ulong candidate = 0;
int i = 0;
// Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001
for (; i < Vector<ulong>.Count; i++)
{
candidate = vector64[i];
if (candidate != 0)
{
break;
}
}
// Single LEA instruction with jitted const (using function result)
return i * 4 + LocateFirstFoundChar(candidate);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundChar(ulong match)
{
// TODO: Arm variants
if (Bmi1.X64.IsSupported)
{
return (int)(Bmi1.X64.TrailingZeroCount(match) >> 4);
}
else
{
unchecked
{
// Flag least significant power of two bit
var powerOfTwoFlag = match ^ (match - 1);
// Shift all powers of two into the high byte and extract
return (int)((powerOfTwoFlag * XorPowerOfTwoToHighChar) >> 49);
}
}
}
private const ulong XorPowerOfTwoToHighChar = (0x03ul |
0x02ul << 16 |
0x01ul << 32) + 1;
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateLastFoundChar(Vector<ushort> match)
{
var vector64 = Vector.AsVectorUInt64(match);
ulong candidate = 0;
int i = Vector<ulong>.Count - 1;
// Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001
for (; i >= 0; i--)
{
candidate = vector64[i];
if (candidate != 0)
{
break;
}
}
// Single LEA instruction with jitted const (using function result)
return i * 4 + LocateLastFoundChar(candidate);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateLastFoundChar(ulong match)
{
return 3 - (BitOperations.LeadingZeroCount(match) >> 4);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref char Add(ref char source, nint elementOffset)
=> ref Unsafe.Add(ref source, (IntPtr)elementOffset);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe Vector<ushort> LoadVector(ref char start, nint offset)
=> Unsafe.ReadUnaligned<Vector<ushort>>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref start, (IntPtr)offset)));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe Vector128<ushort> LoadVector128(ref char start, nint offset)
=> Unsafe.ReadUnaligned<Vector128<ushort>>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref start, (IntPtr)offset)));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe Vector256<ushort> LoadVector256(ref char start, nint offset)
=> Unsafe.ReadUnaligned<Vector256<ushort>>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref start, (IntPtr)offset)));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe UIntPtr LoadUIntPtr(ref char start, nint offset)
=> Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.As<char, byte>(ref Unsafe.Add(ref start, (IntPtr)offset)));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe nint GetCharVectorSpanLength(nint offset, nint length)
=> ((length - offset) & ~(Vector<ushort>.Count - 1));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe nint GetCharVector128SpanLength(nint offset, nint length)
=> ((length - offset) & ~(Vector128<ushort>.Count - 1));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static nint GetCharVector256SpanLength(nint offset, nint length)
=> ((length - offset) & ~(Vector256<ushort>.Count - 1));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe nint UnalignedCountVector(ref char searchSpace)
{
const int ElementsPerByte = sizeof(ushort) / sizeof(byte);
// Figure out how many characters to read sequentially until we are vector aligned
// This is equivalent to:
// unaligned = ((int)pCh % Unsafe.SizeOf<Vector<ushort>>()) / ElementsPerByte
// length = (Vector<ushort>.Count - unaligned) % Vector<ushort>.Count
// This alignment is only valid if the GC does not relocate; so we use ReadUnaligned to get the data.
// If a GC does occur and alignment is lost, the GC cost will outweigh any gains from alignment so it
// isn't too important to pin to maintain the alignment.
return (nint)(uint)(-(int)Unsafe.AsPointer(ref searchSpace) / ElementsPerByte ) & (Vector<ushort>.Count - 1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe nint UnalignedCountVector128(ref char searchSpace)
{
const int ElementsPerByte = sizeof(ushort) / sizeof(byte);
// This alignment is only valid if the GC does not relocate; so we use ReadUnaligned to get the data.
// If a GC does occur and alignment is lost, the GC cost will outweigh any gains from alignment so it
// isn't too important to pin to maintain the alignment.
return (nint)(uint)(-(int)Unsafe.AsPointer(ref searchSpace) / ElementsPerByte ) & (Vector128<ushort>.Count - 1);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking.Contracted;
using osu.Game.Screens.Ranking.Expanded;
using osu.Game.Users;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Ranking
{
public class ScorePanel : CompositeDrawable, IStateful<PanelState>
{
/// <summary>
/// Width of the panel when contracted.
/// </summary>
public const float CONTRACTED_WIDTH = 130;
/// <summary>
/// Height of the panel when contracted.
/// </summary>
private const float contracted_height = 385;
/// <summary>
/// Width of the panel when expanded.
/// </summary>
public const float EXPANDED_WIDTH = 360;
/// <summary>
/// Height of the panel when expanded.
/// </summary>
private const float expanded_height = 586;
/// <summary>
/// Height of the top layer when the panel is expanded.
/// </summary>
private const float expanded_top_layer_height = 53;
/// <summary>
/// Height of the top layer when the panel is contracted.
/// </summary>
private const float contracted_top_layer_height = 30;
/// <summary>
/// Duration for the panel to resize into its expanded/contracted size.
/// </summary>
public const double RESIZE_DURATION = 200;
/// <summary>
/// Delay after <see cref="RESIZE_DURATION"/> before the top layer is expanded.
/// </summary>
public const double TOP_LAYER_EXPAND_DELAY = 100;
/// <summary>
/// Duration for the top layer expansion.
/// </summary>
private const double top_layer_expand_duration = 200;
/// <summary>
/// Duration for the panel contents to fade in.
/// </summary>
private const double content_fade_duration = 50;
private static readonly ColourInfo expanded_top_layer_colour = ColourInfo.GradientVertical(Color4Extensions.FromHex("#444"), Color4Extensions.FromHex("#333"));
private static readonly ColourInfo expanded_middle_layer_colour = ColourInfo.GradientVertical(Color4Extensions.FromHex("#555"), Color4Extensions.FromHex("#333"));
private static readonly Color4 contracted_top_layer_colour = Color4Extensions.FromHex("#353535");
private static readonly Color4 contracted_middle_layer_colour = Color4Extensions.FromHex("#353535");
public event Action<PanelState> StateChanged;
/// <summary>
/// An action to be invoked if this <see cref="ScorePanel"/> is clicked while in an expanded state.
/// </summary>
public Action PostExpandAction;
public readonly ScoreInfo Score;
private bool displayWithFlair;
private Container content;
private Container topLayerContainer;
private Drawable topLayerBackground;
private Container topLayerContentContainer;
private Drawable topLayerContent;
private Container middleLayerContainer;
private Drawable middleLayerBackground;
private Container middleLayerContentContainer;
private Drawable middleLayerContent;
public ScorePanel(ScoreInfo score, bool isNewLocalScore = false)
{
Score = score;
displayWithFlair = isNewLocalScore;
}
[BackgroundDependencyLoader]
private void load()
{
// ScorePanel doesn't include the top extruding area in its own size.
// Adding a manual offset here allows the expanded version to take on an "acceptable" vertical centre when at 100% UI scale.
const float vertical_fudge = 20;
InternalChild = content = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(40),
Y = vertical_fudge,
Children = new Drawable[]
{
topLayerContainer = new Container
{
Name = "Top layer",
RelativeSizeAxes = Axes.X,
Alpha = 0,
Height = 120,
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
CornerRadius = 20,
CornerExponent = 2.5f,
Masking = true,
Child = topLayerBackground = new Box { RelativeSizeAxes = Axes.Both }
},
topLayerContentContainer = new Container { RelativeSizeAxes = Axes.Both }
}
},
middleLayerContainer = new Container
{
Name = "Middle layer",
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
CornerRadius = 20,
CornerExponent = 2.5f,
Masking = true,
Children = new[]
{
middleLayerBackground = new Box { RelativeSizeAxes = Axes.Both },
new UserCoverBackground
{
RelativeSizeAxes = Axes.Both,
User = Score.User,
Colour = ColourInfo.GradientVertical(Color4.White.Opacity(0.5f), Color4Extensions.FromHex("#444").Opacity(0))
}
}
},
middleLayerContentContainer = new Container { RelativeSizeAxes = Axes.Both }
}
}
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
updateState();
topLayerBackground.FinishTransforms(false, nameof(Colour));
middleLayerBackground.FinishTransforms(false, nameof(Colour));
}
private PanelState state = PanelState.Contracted;
public PanelState State
{
get => state;
set
{
if (state == value)
return;
state = value;
if (IsLoaded)
updateState();
StateChanged?.Invoke(value);
}
}
private void updateState()
{
topLayerContent?.FadeOut(content_fade_duration).Expire();
middleLayerContent?.FadeOut(content_fade_duration).Expire();
switch (state)
{
case PanelState.Expanded:
Size = new Vector2(EXPANDED_WIDTH, expanded_height);
topLayerBackground.FadeColour(expanded_top_layer_colour, RESIZE_DURATION, Easing.OutQuint);
middleLayerBackground.FadeColour(expanded_middle_layer_colour, RESIZE_DURATION, Easing.OutQuint);
topLayerContentContainer.Add(topLayerContent = new ExpandedPanelTopContent(Score.User).With(d => d.Alpha = 0));
middleLayerContentContainer.Add(middleLayerContent = new ExpandedPanelMiddleContent(Score, displayWithFlair).With(d => d.Alpha = 0));
// only the first expanded display should happen with flair.
displayWithFlair = false;
break;
case PanelState.Contracted:
Size = new Vector2(CONTRACTED_WIDTH, contracted_height);
topLayerBackground.FadeColour(contracted_top_layer_colour, RESIZE_DURATION, Easing.OutQuint);
middleLayerBackground.FadeColour(contracted_middle_layer_colour, RESIZE_DURATION, Easing.OutQuint);
topLayerContentContainer.Add(topLayerContent = new ContractedPanelTopContent(Score).With(d => d.Alpha = 0));
middleLayerContentContainer.Add(middleLayerContent = new ContractedPanelMiddleContent(Score).With(d => d.Alpha = 0));
break;
}
content.ResizeTo(Size, RESIZE_DURATION, Easing.OutQuint);
bool topLayerExpanded = topLayerContainer.Y < 0;
// If the top layer was already expanded, then we don't need to wait for the resize and can instead transform immediately. This looks better when changing the panel state.
using (BeginDelayedSequence(topLayerExpanded ? 0 : RESIZE_DURATION + TOP_LAYER_EXPAND_DELAY, true))
{
topLayerContainer.FadeIn();
switch (state)
{
case PanelState.Expanded:
topLayerContainer.MoveToY(-expanded_top_layer_height / 2, top_layer_expand_duration, Easing.OutQuint);
middleLayerContainer.MoveToY(expanded_top_layer_height / 2, top_layer_expand_duration, Easing.OutQuint);
break;
case PanelState.Contracted:
topLayerContainer.MoveToY(-contracted_top_layer_height / 2, top_layer_expand_duration, Easing.OutQuint);
middleLayerContainer.MoveToY(contracted_top_layer_height / 2, top_layer_expand_duration, Easing.OutQuint);
break;
}
topLayerContent?.FadeIn(content_fade_duration);
middleLayerContent?.FadeIn(content_fade_duration);
}
}
public override Vector2 Size
{
get => base.Size;
set
{
base.Size = value;
// Auto-size isn't used to avoid 1-frame issues and because the score panel is removed/re-added to the container.
if (trackingContainer != null)
trackingContainer.Size = value;
}
}
protected override bool OnClick(ClickEvent e)
{
if (State == PanelState.Contracted)
{
State = PanelState.Expanded;
return true;
}
PostExpandAction?.Invoke();
return true;
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos)
=> base.ReceivePositionalInputAt(screenSpacePos)
|| topLayerContainer.ReceivePositionalInputAt(screenSpacePos)
|| middleLayerContainer.ReceivePositionalInputAt(screenSpacePos);
private ScorePanelTrackingContainer trackingContainer;
/// <summary>
/// Creates a <see cref="ScorePanelTrackingContainer"/> which this <see cref="ScorePanel"/> can reside inside.
/// The <see cref="ScorePanelTrackingContainer"/> will track the size of this <see cref="ScorePanel"/>.
/// </summary>
/// <remarks>
/// This <see cref="ScorePanel"/> is immediately added as a child of the <see cref="ScorePanelTrackingContainer"/>.
/// </remarks>
/// <returns>The <see cref="ScorePanelTrackingContainer"/>.</returns>
/// <exception cref="InvalidOperationException">If a <see cref="ScorePanelTrackingContainer"/> already exists.</exception>
public ScorePanelTrackingContainer CreateTrackingContainer()
{
if (trackingContainer != null)
throw new InvalidOperationException("A score panel container has already been created.");
return trackingContainer = new ScorePanelTrackingContainer(this);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Xml.Linq;
using NuGet.Resources;
namespace NuGet
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public class ProjectManager : IProjectManager
{
public event EventHandler<PackageOperationEventArgs> PackageReferenceAdding;
public event EventHandler<PackageOperationEventArgs> PackageReferenceAdded;
public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoving;
public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoved;
private ILogger _logger;
private IPackageConstraintProvider _constraintProvider;
private readonly IPackageReferenceRepository _packageReferenceRepository;
private readonly IDictionary<FileTransformExtensions, IPackageFileTransformer> _fileTransformers =
new Dictionary<FileTransformExtensions, IPackageFileTransformer>()
{
{ new FileTransformExtensions(".transform", ".transform"), new XmlTransformer(GetConfigMappings()) },
{ new FileTransformExtensions(".pp", ".pp"), new Preprocessor() },
{ new FileTransformExtensions(".install.xdt", ".uninstall.xdt"), new XdtTransformer() }
};
public ProjectManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IProjectSystem project, IPackageRepository localRepository)
{
if (sourceRepository == null)
{
throw new ArgumentNullException("sourceRepository");
}
if (pathResolver == null)
{
throw new ArgumentNullException("pathResolver");
}
if (project == null)
{
throw new ArgumentNullException("project");
}
if (localRepository == null)
{
throw new ArgumentNullException("localRepository");
}
SourceRepository = sourceRepository;
Project = project;
PathResolver = pathResolver;
LocalRepository = localRepository;
_packageReferenceRepository = LocalRepository as IPackageReferenceRepository;
}
public IPackagePathResolver PathResolver
{
get;
private set;
}
public IPackageRepository LocalRepository
{
get;
private set;
}
public IPackageRepository SourceRepository
{
get;
private set;
}
public IPackageConstraintProvider ConstraintProvider
{
get
{
return _constraintProvider ?? NullConstraintProvider.Instance;
}
set
{
_constraintProvider = value;
}
}
public IProjectSystem Project
{
get;
private set;
}
public ILogger Logger
{
get
{
return _logger ?? NullLogger.Instance;
}
set
{
_logger = value;
}
}
public virtual void AddPackageReference(string packageId)
{
AddPackageReference(packageId, version: null, ignoreDependencies: false, allowPrereleaseVersions: false);
}
public virtual void AddPackageReference(string packageId, SemanticVersion version)
{
AddPackageReference(packageId, version: version, ignoreDependencies: false, allowPrereleaseVersions: false);
}
public virtual void AddPackageReference(string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions)
{
IPackage package = PackageRepositoryHelper.ResolvePackage(SourceRepository, LocalRepository, NullConstraintProvider.Instance, packageId, version, allowPrereleaseVersions);
AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions);
}
public virtual void AddPackageReference(IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions)
{
Execute(package, new UpdateWalker(LocalRepository,
SourceRepository,
new DependentsWalker(LocalRepository, GetPackageTargetFramework(package.Id)),
ConstraintProvider,
Project.TargetFramework,
NullLogger.Instance,
!ignoreDependencies,
allowPrereleaseVersions)
{
AcceptedTargets = PackageTargets.Project
});
}
private void Execute(IPackage package, IPackageOperationResolver resolver)
{
IEnumerable<PackageOperation> operations = resolver.ResolveOperations(package);
if (operations.Any())
{
foreach (PackageOperation operation in operations)
{
Execute(operation);
}
}
else if (LocalRepository.Exists(package))
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, package.GetFullName());
}
}
protected void Execute(PackageOperation operation)
{
bool packageExists = LocalRepository.Exists(operation.Package);
if (operation.Action == PackageAction.Install)
{
// If the package is already installed, then skip it
if (packageExists)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, operation.Package.GetFullName());
}
else
{
AddPackageReferenceToProject(operation.Package);
}
}
else
{
if (packageExists)
{
RemovePackageReferenceFromProject(operation.Package);
}
}
}
protected void AddPackageReferenceToProject(IPackage package)
{
string packageFullName = package.GetFullName();
Logger.Log(MessageLevel.Info, NuGetResources.Log_BeginAddPackageReference, packageFullName, Project.ProjectName);
PackageOperationEventArgs args = CreateOperation(package);
OnPackageReferenceAdding(args);
if (args.Cancel)
{
return;
}
ExtractPackageFilesToProject(package);
Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyAddedPackageReference, packageFullName, Project.ProjectName);
OnPackageReferenceAdded(args);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
protected virtual void ExtractPackageFilesToProject(IPackage package)
{
// BUG 491: Installing a package with incompatible binaries still does a partial install.
// Resolve assembly references and content files first so that if this fails we never do anything to the project
List<IPackageAssemblyReference> assemblyReferences = Project.GetCompatibleItemsCore(package.AssemblyReferences).ToList();
List<FrameworkAssemblyReference> frameworkReferences = Project.GetCompatibleItemsCore(package.FrameworkAssemblies).ToList();
List<IPackageFile> contentFiles = Project.GetCompatibleItemsCore(package.GetContentFiles()).ToList();
List<IPackageFile> buildFiles = Project.GetCompatibleItemsCore(package.GetBuildFiles()).ToList();
// If the package doesn't have any compatible assembly references or content files,
// throw, unless it's a meta package.
if (assemblyReferences.Count == 0 && frameworkReferences.Count == 0 && contentFiles.Count == 0 && buildFiles.Count == 0 &&
(package.FrameworkAssemblies.Any() || package.AssemblyReferences.Any() || package.GetContentFiles().Any() || package.GetBuildFiles().Any()))
{
// for portable framework, we want to show the friendly short form (e.g. portable-win8+net45+wp8) instead of ".NETPortable, Profile=Profile104".
FrameworkName targetFramework = Project.TargetFramework;
string targetFrameworkString = targetFramework.IsPortableFramework()
? VersionUtility.GetShortFrameworkName(targetFramework)
: targetFramework != null ? targetFramework.ToString() : null;
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
NuGetResources.UnableToFindCompatibleItems, package.GetFullName(), targetFrameworkString));
}
// IMPORTANT: this filtering has to be done AFTER the 'if' statement above,
// so that we don't throw the exception in case the <References> filters out all assemblies.
FilterAssemblyReferences(assemblyReferences, package.PackageAssemblyReferences);
try
{
// Add content files
Project.AddFiles(contentFiles, _fileTransformers);
// Add the references to the reference path
foreach (IPackageAssemblyReference assemblyReference in assemblyReferences)
{
if (assemblyReference.IsEmptyFolder())
{
continue;
}
// Get the physical path of the assembly reference
string referencePath = Path.Combine(PathResolver.GetInstallPath(package), assemblyReference.Path);
string relativeReferencePath = PathUtility.GetRelativePath(Project.Root, referencePath);
if (Project.ReferenceExists(assemblyReference.Name))
{
Project.RemoveReference(assemblyReference.Name);
}
// The current implementation of all ProjectSystem does not use the Stream parameter at all.
// We can't change the API now, so just pass in a null stream.
Project.AddReference(relativeReferencePath, Stream.Null);
}
// Add GAC/Framework references
foreach (FrameworkAssemblyReference frameworkReference in frameworkReferences)
{
if (!Project.ReferenceExists(frameworkReference.AssemblyName))
{
Project.AddFrameworkReference(frameworkReference.AssemblyName);
}
}
foreach (var importFile in buildFiles)
{
string fullImportFilePath = Path.Combine(PathResolver.GetInstallPath(package), importFile.Path);
Project.AddImport(
fullImportFilePath,
importFile.Path.EndsWith(".props", StringComparison.OrdinalIgnoreCase) ? ProjectImportLocation.Top : ProjectImportLocation.Bottom);
}
}
finally
{
if (_packageReferenceRepository != null)
{
// save the used project's framework if the repository supports it.
_packageReferenceRepository.AddPackage(package.Id, package.Version, Project.TargetFramework);
}
else
{
// Add package to local repository in the finally so that the user can uninstall it
// if any exception occurs. This is easier than rolling back since the user can just
// manually uninstall things that may have failed.
// If this fails then the user is out of luck.
LocalRepository.AddPackage(package);
}
}
}
private void FilterAssemblyReferences(List<IPackageAssemblyReference> assemblyReferences, ICollection<PackageReferenceSet> packageAssemblyReferences)
{
if (packageAssemblyReferences != null && packageAssemblyReferences.Count > 0)
{
var packageReferences = Project.GetCompatibleItemsCore(packageAssemblyReferences).FirstOrDefault();
if (packageReferences != null)
{
// remove all assemblies of which names do not appear in the References list
assemblyReferences.RemoveAll(assembly => !packageReferences.References.Contains(assembly.Name, StringComparer.OrdinalIgnoreCase));
}
}
}
public bool IsInstalled(IPackage package)
{
return LocalRepository.Exists(package);
}
public void RemovePackageReference(string packageId)
{
RemovePackageReference(packageId, forceRemove: false, removeDependencies: false);
}
public void RemovePackageReference(string packageId, bool forceRemove)
{
RemovePackageReference(packageId, forceRemove: forceRemove, removeDependencies: false);
}
public virtual void RemovePackageReference(string packageId, bool forceRemove, bool removeDependencies)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
IPackage package = LocalRepository.FindPackage(packageId);
if (package == null)
{
throw new InvalidOperationException(String.Format(
CultureInfo.CurrentCulture,
NuGetResources.UnknownPackage, packageId));
}
RemovePackageReference(package, forceRemove, removeDependencies);
}
public virtual void RemovePackageReference(IPackage package, bool forceRemove, bool removeDependencies)
{
FrameworkName targetFramework = GetPackageTargetFramework(package.Id);
Execute(package, new UninstallWalker(LocalRepository,
new DependentsWalker(LocalRepository, targetFramework),
targetFramework,
NullLogger.Instance,
removeDependencies,
forceRemove));
}
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
private void RemovePackageReferenceFromProject(IPackage package)
{
string packageFullName = package.GetFullName();
Logger.Log(MessageLevel.Info, NuGetResources.Log_BeginRemovePackageReference, packageFullName, Project.ProjectName);
PackageOperationEventArgs args = CreateOperation(package);
OnPackageReferenceRemoving(args);
if (args.Cancel)
{
return;
}
// Get other packages
IEnumerable<IPackage> otherPackages = from p in LocalRepository.GetPackages()
where p.Id != package.Id
select p;
// Get other references
var otherAssemblyReferences = from p in otherPackages
let assemblyReferences = GetFilteredAssembliesToDelete(p)
from assemblyReference in assemblyReferences ?? Enumerable.Empty<IPackageAssemblyReference>() // This can happen if package installed left the project in a bad state
select assemblyReference;
// Get content files from other packages
// Exclude transform files since they are treated specially
var otherContentFiles = from p in otherPackages
from file in GetCompatibleInstalledItemsForPackage(p.Id, p.GetContentFiles())
where !IsTransformFile(file.Path)
select file;
// Get the files and references for this package, that aren't in use by any other packages so we don't have to do reference counting
var assemblyReferencesToDelete = GetFilteredAssembliesToDelete(package)
.Except(otherAssemblyReferences, PackageFileComparer.Default);
var contentFilesToDelete = GetCompatibleInstalledItemsForPackage(package.Id, package.GetContentFiles())
.Except(otherContentFiles, PackageFileComparer.Default);
var buildFilesToDelete = GetCompatibleInstalledItemsForPackage(package.Id, package.GetBuildFiles());
// Delete the content files
Project.DeleteFiles(contentFilesToDelete, otherPackages, _fileTransformers);
// Remove references
foreach (IPackageAssemblyReference assemblyReference in assemblyReferencesToDelete)
{
Project.RemoveReference(assemblyReference.Name);
}
// remove the <Import> statement from projects for the .targets and .props files
foreach (var importFile in buildFilesToDelete)
{
string fullImportFilePath = Path.Combine(PathResolver.GetInstallPath(package), importFile.Path);
Project.RemoveImport(fullImportFilePath);
}
// Remove package to the repository
LocalRepository.RemovePackage(package);
Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyRemovedPackageReference, packageFullName, Project.ProjectName);
OnPackageReferenceRemoved(args);
}
private bool IsTransformFile(string path)
{
return _fileTransformers.Keys.Any(
file => path.EndsWith(file.InstallExtension, StringComparison.OrdinalIgnoreCase) ||
path.EndsWith(file.UninstallExtension, StringComparison.OrdinalIgnoreCase));
}
private IList<IPackageAssemblyReference> GetFilteredAssembliesToDelete(IPackage package)
{
List<IPackageAssemblyReference> assemblyReferences = GetCompatibleInstalledItemsForPackage(package.Id, package.AssemblyReferences).ToList();
if (assemblyReferences.Count == 0)
{
return assemblyReferences;
}
var packageReferences = GetCompatibleInstalledItemsForPackage(package.Id, package.PackageAssemblyReferences).FirstOrDefault();
if (packageReferences != null)
{
assemblyReferences.RemoveAll(p => !packageReferences.References.Contains(p.Name, StringComparer.OrdinalIgnoreCase));
}
return assemblyReferences;
}
public void UpdatePackageReference(string packageId)
{
UpdatePackageReference(packageId, version: null, updateDependencies: true, allowPrereleaseVersions: false);
}
public void UpdatePackageReference(string packageId, SemanticVersion version)
{
UpdatePackageReference(packageId, version: version, updateDependencies: true, allowPrereleaseVersions: false);
}
public void UpdatePackageReference(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions)
{
UpdatePackageReference(
packageId,
() => SourceRepository.FindPackage(packageId, versionSpec, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
targetVersionSetExplicitly: versionSpec != null);
}
public virtual void UpdatePackageReference(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions)
{
UpdatePackageReference(packageId, () => SourceRepository.FindPackage(packageId, version, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: version != null);
}
private void UpdatePackageReference(string packageId, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, bool targetVersionSetExplicitly)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
IPackage oldPackage = LocalRepository.FindPackage(packageId);
// Check to see if this package is installed
if (oldPackage == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
NuGetResources.ProjectDoesNotHaveReference, Project.ProjectName, packageId));
}
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_LookingForUpdates, packageId);
IPackage package = resolvePackage();
// the condition (allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version)
// is to fix bug 1574. We want to do nothing if, let's say, you have package 2.0alpha installed, and you do:
// update-package
// without specifying a version explicitly, and the feed only has version 1.0 as the latest stable version.
if (package != null &&
oldPackage.Version != package.Version &&
(allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version))
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_UpdatingPackages, package.Id, oldPackage.Version, package.Version, Project.ProjectName);
UpdatePackageReference(package, updateDependencies, allowPrereleaseVersions);
}
else
{
IVersionSpec constraint = ConstraintProvider.GetConstraint(packageId);
if (constraint != null)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_ApplyingConstraints, packageId, VersionUtility.PrettyPrint(constraint), ConstraintProvider.Source);
}
Logger.Log(MessageLevel.Info, NuGetResources.Log_NoUpdatesAvailableForProject, packageId, Project.ProjectName);
}
}
protected void UpdatePackageReference(IPackage package)
{
UpdatePackageReference(package, updateDependencies: true, allowPrereleaseVersions: false);
}
protected void UpdatePackageReference(IPackage package, bool updateDependencies, bool allowPrereleaseVersions)
{
AddPackageReference(package, !updateDependencies, allowPrereleaseVersions);
}
private void OnPackageReferenceAdding(PackageOperationEventArgs e)
{
if (PackageReferenceAdding != null)
{
PackageReferenceAdding(this, e);
}
}
private void OnPackageReferenceAdded(PackageOperationEventArgs e)
{
if (PackageReferenceAdded != null)
{
PackageReferenceAdded(this, e);
}
}
private void OnPackageReferenceRemoved(PackageOperationEventArgs e)
{
if (PackageReferenceRemoved != null)
{
PackageReferenceRemoved(this, e);
}
}
private void OnPackageReferenceRemoving(PackageOperationEventArgs e)
{
if (PackageReferenceRemoving != null)
{
PackageReferenceRemoving(this, e);
}
}
private FrameworkName GetPackageTargetFramework(string packageId)
{
if (_packageReferenceRepository != null)
{
return _packageReferenceRepository.GetPackageTargetFramework(packageId) ?? Project.TargetFramework;
}
return Project.TargetFramework;
}
/// <summary>
/// This method uses the 'targetFramework' attribute in the packages.config to determine compatible items.
/// Hence, it's only good for uninstall operations.
/// </summary>
private IEnumerable<T> GetCompatibleInstalledItemsForPackage<T>(string packageId, IEnumerable<T> items) where T : IFrameworkTargetable
{
FrameworkName packageFramework = GetPackageTargetFramework(packageId);
if (packageFramework == null)
{
return items;
}
IEnumerable<T> compatibleItems;
if (VersionUtility.TryGetCompatibleItems(packageFramework, items, out compatibleItems))
{
return compatibleItems;
}
return Enumerable.Empty<T>();
}
private PackageOperationEventArgs CreateOperation(IPackage package)
{
return new PackageOperationEventArgs(package, Project, PathResolver.GetInstallPath(package));
}
private static IDictionary<XName, Action<XElement, XElement>> GetConfigMappings()
{
// REVIEW: This might be an edge case, but we're setting this rule for all xml files.
// If someone happens to do a transform where the xml file has a configSections node
// we will add it first. This is probably fine, but this is a config specific scenario
return new Dictionary<XName, Action<XElement, XElement>>() {
{ "configSections" , (parent, element) => parent.AddFirst(element) }
};
}
private class PackageFileComparer : IEqualityComparer<IPackageFile>
{
internal readonly static PackageFileComparer Default = new PackageFileComparer();
private PackageFileComparer()
{
}
public bool Equals(IPackageFile x, IPackageFile y)
{
// technically, this check will fail if, for example, 'x' is a content file and 'y' is a lib file.
// However, because we only use this comparer to compare files within the same folder type,
// this check is sufficient.
return x.TargetFramework == y.TargetFramework &&
x.EffectivePath.Equals(y.EffectivePath, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(IPackageFile obj)
{
return obj.Path.GetHashCode();
}
}
}
}
| |
using System;
using System.Reflection;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
using Rectangle = xTile.Dimensions.Rectangle;
namespace Pathoschild.Stardew.Common.UI
{
/// <summary>An interface which supports user interaction and overlays the active menu (if any).</summary>
internal abstract class BaseOverlay : IDisposable
{
/*********
** Fields
*********/
/// <summary>The SMAPI events available for mods.</summary>
private readonly IModEvents Events;
/// <summary>An API for checking and changing input state.</summary>
protected readonly IInputHelper InputHelper;
/// <summary>Simplifies access to private code.</summary>
protected readonly IReflectionHelper Reflection;
/// <summary>The screen ID for which the overlay was created, to support split-screen mode.</summary>
private readonly int ScreenId;
/// <summary>The last viewport bounds.</summary>
private Rectangle LastViewport;
/// <summary>Indicates whether to keep the overlay active. If <c>null</c>, the overlay is kept until explicitly disposed.</summary>
private readonly Func<bool> KeepAliveCheck;
/// <summary>The UI mode to use for pixel coordinates in <see cref="ReceiveLeftClick"/> and <see cref="ReceiveCursorHover"/>, or <c>null</c> to use the current UI mode at the time the event is raised.</summary>
private readonly bool? AssumeUiMode;
/*********
** Public methods
*********/
/// <summary>Release all resources.</summary>
public virtual void Dispose()
{
this.Events.Display.Rendered -= this.OnRendered;
this.Events.Display.RenderedWorld -= this.OnRenderedWorld;
this.Events.GameLoop.UpdateTicked -= this.OnUpdateTicked;
this.Events.Input.ButtonPressed -= this.OnButtonPressed;
this.Events.Input.ButtonsChanged -= this.OnButtonsChanged;
this.Events.Input.CursorMoved -= this.OnCursorMoved;
this.Events.Input.MouseWheelScrolled -= this.OnMouseWheelScrolled;
}
/*********
** Protected methods
*********/
/****
** Implementation
****/
/// <summary>Construct an instance.</summary>
/// <param name="events">The SMAPI events available for mods.</param>
/// <param name="inputHelper">An API for checking and changing input state.</param>
/// <param name="reflection">Simplifies access to private code.</param>
/// <param name="keepAlive">Indicates whether to keep the overlay active. If <c>null</c>, the overlay is kept until explicitly disposed.</param>
/// <param name="assumeUiMode">The UI mode to use for pixel coordinates in <see cref="ReceiveLeftClick"/> and <see cref="ReceiveCursorHover"/>, or <c>null</c> to use the current UI mode at the time the event is raised.</param>
protected BaseOverlay(IModEvents events, IInputHelper inputHelper, IReflectionHelper reflection, Func<bool> keepAlive = null, bool? assumeUiMode = null)
{
this.Events = events;
this.InputHelper = inputHelper;
this.Reflection = reflection;
this.KeepAliveCheck = keepAlive;
this.LastViewport = new Rectangle(Game1.uiViewport.X, Game1.uiViewport.Y, Game1.uiViewport.Width, Game1.uiViewport.Height);
this.ScreenId = Context.ScreenId;
this.AssumeUiMode = assumeUiMode;
events.GameLoop.UpdateTicked += this.OnUpdateTicked;
if (this.IsMethodOverridden(nameof(this.DrawUi)))
events.Display.Rendered += this.OnRendered;
if (this.IsMethodOverridden(nameof(this.DrawWorld)))
events.Display.RenderedWorld += this.OnRenderedWorld;
if (this.IsMethodOverridden(nameof(this.ReceiveLeftClick)))
events.Input.ButtonPressed += this.OnButtonPressed;
if (this.IsMethodOverridden(nameof(this.ReceiveButtonsChanged)))
events.Input.ButtonsChanged += this.OnButtonsChanged;
if (this.IsMethodOverridden(nameof(this.ReceiveCursorHover)))
events.Input.CursorMoved += this.OnCursorMoved;
if (this.IsMethodOverridden(nameof(this.ReceiveScrollWheelAction)))
events.Input.MouseWheelScrolled += this.OnMouseWheelScrolled;
}
/// <summary>Draw the overlay to the screen over the UI.</summary>
/// <param name="batch">The sprite batch being drawn.</param>
protected virtual void DrawUi(SpriteBatch batch) { }
/// <summary>Draw the overlay to the screen under the UI.</summary>
/// <param name="batch">The sprite batch being drawn.</param>
protected virtual void DrawWorld(SpriteBatch batch) { }
/// <summary>The method invoked when the player left-clicks.</summary>
/// <param name="x">The X-position of the cursor.</param>
/// <param name="y">The Y-position of the cursor.</param>
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
protected virtual bool ReceiveLeftClick(int x, int y)
{
return false;
}
/// <summary>Raised after the player presses any buttons on the keyboard, controller, or mouse.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
protected virtual void ReceiveButtonsChanged(object sender, ButtonsChangedEventArgs e) { }
/// <summary>The method invoked when the player uses the mouse scroll wheel.</summary>
/// <param name="amount">The scroll amount.</param>
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
protected virtual bool ReceiveScrollWheelAction(int amount)
{
return false;
}
/// <summary>The method invoked when the cursor is hovered.</summary>
/// <param name="x">The cursor's X position.</param>
/// <param name="y">The cursor's Y position.</param>
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
protected virtual bool ReceiveCursorHover(int x, int y)
{
return false;
}
/// <summary>The method invoked when the player resizes the game window.</summary>
protected virtual void ReceiveGameWindowResized() { }
/****
** Helpers
****/
/// <summary>Draw the mouse cursor.</summary>
/// <remarks>Derived from <see cref="StardewValley.Menus.IClickableMenu.drawMouse"/>.</remarks>
protected void DrawCursor()
{
if (Game1.options.hardwareCursor)
return;
Vector2 cursorPos = new Vector2(Game1.getMouseX(), Game1.getMouseY());
if (Constants.TargetPlatform == GamePlatform.Android)
cursorPos *= Game1.options.zoomLevel / this.Reflection.GetProperty<float>(typeof(Game1), "NativeZoomLevel").GetValue();
Game1.spriteBatch.Draw(Game1.mouseCursors, cursorPos, Game1.getSourceRectForStandardTileSheet(Game1.mouseCursors, Game1.options.SnappyMenus ? 44 : 0, 16, 16), Color.White * Game1.mouseCursorTransparency, 0.0f, Vector2.Zero, Game1.pixelZoom + Game1.dialogueButtonScale / 150f, SpriteEffects.None, 1f);
}
/****
** Event listeners
****/
/// <summary>The method called when the game finishes drawing components to the screen.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnRendered(object sender, RenderedEventArgs e)
{
if (Context.ScreenId != this.ScreenId)
return;
if (Constants.TargetPlatform == GamePlatform.Android)
{
object originMatrix = this.Reflection.GetField<object>(Game1.spriteBatch, "_matrix").GetValue() ?? Matrix.Identity;
float nativeZoomLevel = this.Reflection.GetProperty<float>(typeof(Game1), "NativeZoomLevel").GetValue();
Game1.spriteBatch.End();
Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, Matrix.CreateScale(nativeZoomLevel));
this.DrawUi(Game1.spriteBatch);
Game1.spriteBatch.End();
Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, (Matrix)originMatrix);
}
else
this.DrawUi(Game1.spriteBatch);
}
/// <summary>The method called when the game finishes drawing components to the screen.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnRenderedWorld(object sender, RenderedWorldEventArgs e)
{
if (Context.ScreenId != this.ScreenId)
return;
this.DrawWorld(e.SpriteBatch);
}
/// <summary>The method called once per event tick.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnUpdateTicked(object sender, UpdateTickedEventArgs e)
{
if (Context.ScreenId == this.ScreenId)
{
// detect end of life
if (this.KeepAliveCheck != null && !this.KeepAliveCheck())
{
this.Dispose();
return;
}
// trigger window resize event
Rectangle newViewport = Game1.uiViewport;
if (this.LastViewport.Width != newViewport.Width || this.LastViewport.Height != newViewport.Height)
{
newViewport = new Rectangle(newViewport.X, newViewport.Y, newViewport.Width, newViewport.Height);
this.ReceiveGameWindowResized();
this.LastViewport = newViewport;
}
}
else if (!Context.HasScreenId(this.ScreenId))
this.Dispose();
}
/// <summary>Raised after the player presses any buttons on the keyboard, controller, or mouse.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void OnButtonsChanged(object sender, ButtonsChangedEventArgs e)
{
if (Context.ScreenId != this.ScreenId)
return;
this.ReceiveButtonsChanged(sender, e);
}
/// <summary>The method invoked when the player presses a key.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnButtonPressed(object sender, ButtonPressedEventArgs e)
{
if (Context.ScreenId != this.ScreenId)
return;
if (e.Button != SButton.MouseLeft && !e.Button.IsUseToolButton())
return;
bool uiMode = this.AssumeUiMode ?? Game1.uiMode;
bool handled;
if (Constants.TargetPlatform == GamePlatform.Android)
{
float nativeZoomLevel = (float)typeof(Game1).GetProperty("NativeZoomLevel", BindingFlags.Public | BindingFlags.Static).GetValue(null);
handled = this.ReceiveLeftClick((int)(Game1.getMouseX() * Game1.options.zoomLevel / nativeZoomLevel), (int)(Game1.getMouseY() * Game1.options.zoomLevel / nativeZoomLevel));
}
else
handled = this.ReceiveLeftClick(Game1.getMouseX(uiMode), Game1.getMouseY(uiMode));
if (handled)
this.InputHelper.Suppress(e.Button);
}
/// <summary>The method invoked when the mouse wheel is scrolled.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnMouseWheelScrolled(object sender, MouseWheelScrolledEventArgs e)
{
if (Context.ScreenId != this.ScreenId)
return;
bool scrollHandled = this.ReceiveScrollWheelAction(e.Delta);
if (scrollHandled)
{
MouseState cur = Game1.oldMouseState;
Game1.oldMouseState = new MouseState(
x: cur.X,
y: cur.Y,
scrollWheel: e.NewValue,
leftButton: cur.LeftButton,
middleButton: cur.MiddleButton,
rightButton: cur.RightButton,
xButton1: cur.XButton1,
xButton2: cur.XButton2
);
}
}
/// <summary>The method invoked when the in-game cursor is moved.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void OnCursorMoved(object sender, CursorMovedEventArgs e)
{
if (Context.ScreenId != this.ScreenId)
return;
bool uiMode = this.AssumeUiMode ?? Game1.uiMode;
bool hoverHandled = this.ReceiveCursorHover(Game1.getMouseX(uiMode), Game1.getMouseY(uiMode));
if (hoverHandled)
Game1.InvalidateOldMouseMovement();
}
/// <summary>Get whether a method has been overridden by a subclass.</summary>
/// <param name="name">The method name.</param>
private bool IsMethodOverridden(string name)
{
MethodInfo method = this.GetType().GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if (method == null)
throw new InvalidOperationException($"Can't find method {this.GetType().FullName}.{name}.");
return method.DeclaringType != typeof(BaseOverlay);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="TableRow.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Table row implementation
//
// See spec at http://avalon/layout/Tables/WPP%20TableOM.doc
//
// History:
// 05/19/2003 : olego - Created
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.PtsHost;
using MS.Internal.PtsTable;
using MS.Internal.Text;
using MS.Utility;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Markup;
using System.Collections.Generic;
using MS.Internal.Documents;
using MS.Internal.PtsHost.UnsafeNativeMethods;
namespace System.Windows.Documents
{
/// <summary>
/// Table row
/// </summary>
[ContentProperty("Cells")]
public class TableRow : TextElement, IAddChild, IIndexedChild<TableRowGroup>, IAcceptInsertion
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Creates an instance of a Row
/// </summary>
public TableRow()
: base()
{
PrivateInitialize();
}
#endregion
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// <see cref="IAddChild.AddChild"/>
/// </summary>
void IAddChild.AddChild(object value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
TableCell cell = value as TableCell;
if (cell != null)
{
Cells.Add(cell);
return;
}
throw (new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(TableCell)), "value"));
}
/// <summary>
/// <see cref="IAddChild.AddText"/>
/// </summary>
void IAddChild.AddText(string text)
{
XamlSerializerUtil.ThrowIfNonWhiteSpaceInAddText(text, this);
}
/// <summary>
/// Called when tablerow gets new parent
/// </summary>
/// <param name="newParent">
/// New parent of cell
/// </param>
internal override void OnNewParent(DependencyObject newParent)
{
DependencyObject oldParent = this.Parent;
if (newParent != null && !(newParent is TableRowGroup))
{
throw new InvalidOperationException(SR.Get(SRID.TableInvalidParentNodeType, newParent.GetType().ToString()));
}
if (oldParent != null)
{
((TableRowGroup)oldParent).Rows.InternalRemove(this);
}
base.OnNewParent(newParent);
if (newParent != null)
{
((TableRowGroup)newParent).Rows.InternalAdd(this);
}
}
#endregion Public Methods
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
#endregion Protected Methods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#region IIndexedChild implementation
/// <summary>
/// Callback used to notify about entering model tree.
/// </summary>
void IIndexedChild<TableRowGroup>.OnEnterParentTree()
{
this.OnEnterParentTree();
}
/// <summary>
/// Callback used to notify about exitting model tree.
/// </summary>
void IIndexedChild<TableRowGroup>.OnExitParentTree()
{
this.OnExitParentTree();
}
void IIndexedChild<TableRowGroup>.OnAfterExitParentTree(TableRowGroup parent)
{
this.OnAfterExitParentTree(parent);
}
int IIndexedChild<TableRowGroup>.Index
{
get { return this.Index; }
set { this.Index = value; }
}
#endregion IIndexedChild implementation
/// <summary>
/// Callback used to notify the Row about entering model tree.
/// </summary>
internal void OnEnterParentTree()
{
if (Table != null)
{
Table.OnStructureChanged();
}
}
/// <summary>
/// Callback used to notify the RowGroup about exitting model tree.
/// </summary>
internal void OnExitParentTree()
{
}
/// <summary>
/// Callback used to notify the Row about exitting model tree.
/// </summary>
internal void OnAfterExitParentTree(TableRowGroup rowGroup)
{
if (rowGroup.Table != null)
{
Table.OnStructureChanged();
}
}
/// <summary>
/// ValidateStructure
/// </summary>
internal void ValidateStructure(RowSpanVector rowSpanVector)
{
Debug.Assert(rowSpanVector != null);
SetFlags(!rowSpanVector.Empty(), Flags.HasForeignCells);
SetFlags(false, Flags.HasRealCells);
_formatCellCount = 0;
_columnCount = 0;
int firstAvailableIndex;
int firstOccupiedIndex;
rowSpanVector.GetFirstAvailableRange(out firstAvailableIndex, out firstOccupiedIndex);
for (int i = 0; i < _cells.Count; ++i)
{
TableCell cell = _cells[i];
// Get cloumn span and row span. Row span is limited to the number of rows in the row group.
// Since we do not know the number of columns in the table at this point, column span is limited only
// by internal constants
int columnSpan = cell.ColumnSpan;
int rowSpan = cell.RowSpan;
while (firstAvailableIndex + columnSpan > firstOccupiedIndex)
{
rowSpanVector.GetNextAvailableRange(out firstAvailableIndex, out firstOccupiedIndex);
}
Debug.Assert(i <= firstAvailableIndex);
cell.ValidateStructure(firstAvailableIndex);
if (rowSpan > 1)
{
rowSpanVector.Register(cell);
}
else
{
_formatCellCount++;
}
firstAvailableIndex += columnSpan;
}
_columnCount = firstAvailableIndex;
bool isLastRowOfAnySpan = false;
rowSpanVector.GetSpanCells(out _spannedCells, out isLastRowOfAnySpan);
Debug.Assert(_spannedCells != null);
if ((_formatCellCount > 0) ||
isLastRowOfAnySpan == true)
{
SetFlags(true, Flags.HasRealCells);
}
_formatCellCount += _spannedCells.Length;
Debug.Assert(_cells.Count <= _formatCellCount);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// RowGroup owner accessor
/// </summary>
internal TableRowGroup RowGroup
{
get
{
return (Parent as TableRowGroup);
}
}
/// <summary>
/// Table owner accessor
/// </summary>
internal Table Table { get { return (RowGroup != null ? RowGroup.Table : null); } }
/// <summary>
/// Returns the row's cell collection
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TableCellCollection Cells { get { return (_cells); } }
/// <summary>
/// This method is used by TypeDescriptor to determine if this property should
/// be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeCells()
{
return (Cells.Count > 0);
}
/// <summary>
/// Row's index in the parents collection.
/// </summary>
internal int Index
{
get
{
return (_parentIndex);
}
set
{
Debug.Assert(value >= -1 && _parentIndex != value);
_parentIndex = value;
}
}
int IAcceptInsertion.InsertionIndex
{
get { return this.InsertionIndex; }
set { this.InsertionIndex = value; }
}
/// <summary>
/// Stores temporary data for where to insert a new cell
/// </summary>
internal int InsertionIndex
{
get { return _cellInsertionIndex; }
set { _cellInsertionIndex = value; }
}
/// <summary>
/// Returns span cells vector
/// </summary>
internal TableCell[] SpannedCells
{
get { return (_spannedCells); }
}
/// <summary>
/// Count of columns in the table
/// </summary>
internal int ColumnCount
{
get
{
return (_columnCount);
}
}
/// <summary>
/// Returns "true" if there are row spanned cells belonging to previous rows
/// </summary>
internal bool HasForeignCells
{
get { return (CheckFlags(Flags.HasForeignCells)); }
}
/// <summary>
/// Returns "true" if there are row spanned cells belonging to previous rows
/// </summary>
internal bool HasRealCells
{
get { return (CheckFlags(Flags.HasRealCells)); }
}
/// <summary>
/// Count of columns in the table
/// </summary>
internal int FormatCellCount
{
get
{
return (_formatCellCount);
}
}
/// <summary>
/// Marks this element's left edge as visible to IMEs.
/// This means element boundaries will act as word breaks.
/// </summary>
internal override bool IsIMEStructuralElement
{
get
{
return true;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Private ctor time initialization.
/// </summary>
private void PrivateInitialize()
{
_cells = new TableCellCollection(this);
_parentIndex = -1;
_cellInsertionIndex = -1;
}
/// <summary>
/// SetFlags is used to set or unset one or multiple flags on the row.
/// </summary>
private void SetFlags(bool value, Flags flags)
{
_flags = value ? (_flags | flags) : (_flags & (~flags));
}
/// <summary>
/// CheckFlags returns true if all flags in the bitmask flags are set.
/// </summary>
private bool CheckFlags(Flags flags)
{
return ((_flags & flags) == flags);
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private TableCellCollection _cells; // collection of cells belonging to the row
private TableCell[] _spannedCells; // row spanned cell storage
private int _parentIndex; // row's index in parent's children collection
private int _cellInsertionIndex; // Insertion index a cell
private int _columnCount;
private Flags _flags; // flags reflecting various aspects of row's state
private int _formatCellCount; // count of the cell to be formatted in this row
#endregion Private Fields
//------------------------------------------------------
//
// Private Structures / Classes
//
//------------------------------------------------------
#region Private Structures Classes
[System.Flags]
private enum Flags
{
//
// state flags
//
HasForeignCells = 0x00000010, // there are hanging cells from the previous rows
HasRealCells = 0x00000020, // real cells in row (not just spanning) (Only known by validation, not format)
}
#endregion Private Structures Classes
}
}
| |
//
// StatisticsPage.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
namespace Banshee.Gui.TrackEditor
{
internal class FixedTreeView : TreeView
{
public FixedTreeView (ListStore model) : base (model)
{
}
protected override bool OnKeyPressEvent (Gdk.EventKey evnt)
{
if ((evnt.State & Gdk.ModifierType.ControlMask) != 0 &&
(evnt.Key == Gdk.Key.Page_Up || evnt.Key == Gdk.Key.Page_Down)) {
return false;
}
return base.OnKeyPressEvent (evnt);
}
}
public class StatisticsPage : ScrolledWindow, ITrackEditorPage
{
private CellRendererText name_renderer;
private CellRendererText value_renderer;
private ListStore model;
private TreeView view;
public StatisticsPage ()
{
ShadowType = ShadowType.In;
VscrollbarPolicy = PolicyType.Automatic;
HscrollbarPolicy = PolicyType.Never;
BorderWidth = 2;
view = new FixedTreeView (model);
view.HeadersVisible = false;
view.RowSeparatorFunc = new TreeViewRowSeparatorFunc (RowSeparatorFunc);
view.HasTooltip = true;
view.QueryTooltip += HandleQueryTooltip;
name_renderer = new CellRendererText () {
Alignment = Pango.Alignment.Right,
Weight = (int)Pango.Weight.Bold,
Xalign = 1.0f,
Yalign = 0.0f,
Scale = Pango.Scale.Small
};
value_renderer = new CellRendererText ();
value_renderer.Editable = true;
value_renderer.Scale = Pango.Scale.Small;
value_renderer.Ellipsize = Pango.EllipsizeMode.End;
value_renderer.WrapMode = Pango.WrapMode.Word;
value_renderer.EditingStarted += delegate(object o, EditingStartedArgs args) {
var entry = args.Editable as Entry;
if (entry != null) {
entry.IsEditable = false;
}
};
view.SizeAllocated += delegate { UpdateWrapWidth (); };
view.Realized += delegate { UpdateWrapWidth (); };
view.AppendColumn (Catalog.GetString ("Name"), name_renderer, "text", 0);
view.AppendColumn (Catalog.GetString ("Value"), value_renderer, "text", 1, "ellipsize", 3, "ellipsize-set", 4, "wrap-width", 5);
Add (view);
ShowAll ();
}
public void UpdateWrapWidth ()
{
if (view.IsRealized && model != null) {
var width = GetValueWidth ();
model.Foreach ((ITreeModel m, TreePath path, TreeIter iter) => {
if ((Pango.EllipsizeMode) model.GetValue (iter, 3) != Pango.EllipsizeMode.End) {
model.SetValue (iter, 5, width);
}
return false;
});
}
}
public CellRendererText NameRenderer { get { return name_renderer; } }
public CellRendererText ValueRenderer { get { return value_renderer; } }
private bool RowSeparatorFunc (ITreeModel model, TreeIter iter)
{
return (bool)model.GetValue (iter, 2);
}
private int GetValueWidth ()
{
var column = view.GetColumn (1);
var column_width = column.Width - 2 * value_renderer.Xpad -
(int)view.StyleGetProperty ("horizontal-separator") -
2 * (int)view.StyleGetProperty ("focus-line-width");
return (int) column_width;
}
private void HandleQueryTooltip(object o, QueryTooltipArgs args)
{
TreePath path;
TreeIter iter;
if (view.GetPathAtPos (args.X, args.Y, out path) && view.Model.GetIter (out iter, path)) {
string text = (string)view.Model.GetValue (iter, 1);
if (!String.IsNullOrEmpty (text)) {
using (var layout = new Pango.Layout (view.PangoContext)) {
layout.FontDescription = value_renderer.FontDesc;
layout.SetText (text);
layout.Attributes = new Pango.AttrList ();
layout.Attributes.Insert (new Pango.AttrScale (value_renderer.Scale));
int width, height;
layout.GetPixelSize (out width, out height);
var column_width = GetValueWidth ();
if (width > column_width) {
var column = view.GetColumn (1);
args.Tooltip.Text = text;
view.SetTooltipCell (args.Tooltip, path, column, value_renderer);
args.RetVal = true;
}
}
}
}
// Work around ref counting SIGSEGV, see http://bugzilla.gnome.org/show_bug.cgi?id=478519#c9
if (args.Tooltip != null) {
args.Tooltip.Dispose ();
}
}
protected override void OnStyleUpdated ()
{
base.OnStyleUpdated ();
name_renderer.CellBackgroundRgba = StyleContext.GetBackgroundColor (StateFlags.Normal);
}
public void Initialize (TrackEditorDialog dialog)
{
}
public void LoadTrack (EditorTrackInfo track)
{
model = null;
CreateModel ();
TagLib.File file = track.GetTaglibFile ();
if (track.Uri.IsLocalPath) {
string path = track.Uri.AbsolutePath;
AddItem (Catalog.GetString ("File Name:"), System.IO.Path.GetFileName (path));
AddItem (Catalog.GetString ("Directory:"), System.IO.Path.GetDirectoryName (path));
AddItem (Catalog.GetString ("Full Path:"), path);
try {
AddFileSizeItem (Banshee.IO.File.GetSize (track.Uri));
} catch {
}
} else {
AddItem (Catalog.GetString ("URI:"), track.Uri.AbsoluteUri);
AddFileSizeItem (track.FileSize);
}
AddSeparator ();
if (file != null) {
System.Text.StringBuilder builder = new System.Text.StringBuilder ();
Banshee.Sources.DurationStatusFormatters.ConfusingPreciseFormatter (builder, file.Properties.Duration);
AddItem (Catalog.GetString ("Duration:"), String.Format ("{0} ({1}ms)",
builder, file.Properties.Duration.TotalMilliseconds));
AddItem (Catalog.GetString ("Audio Bitrate:"), String.Format ("{0} KB/sec",
file.Properties.AudioBitrate));
AddItem (Catalog.GetString ("Audio Sample Rate:"), String.Format ("{0} Hz",
file.Properties.AudioSampleRate));
AddItem (Catalog.GetString ("Audio Channels:"), file.Properties.AudioChannels);
if (file.Properties.BitsPerSample > 0) {
AddItem (Catalog.GetString ("Bits Per Sample:"), String.Format ("{0} bits",
file.Properties.BitsPerSample));
}
if ((file.Properties.MediaTypes & TagLib.MediaTypes.Video) != 0) {
AddItem (Catalog.GetString ("Video Dimensions:"), String.Format ("{0}x{1}",
file.Properties.VideoWidth, file.Properties.VideoHeight));
}
foreach (TagLib.ICodec codec in file.Properties.Codecs) {
if (codec != null) {
/* Translators: {0} is the description of the codec */
AddItem (String.Format (Catalog.GetString ("{0} Codec:"),
codec.MediaTypes.ToString ()), codec.Description);
}
}
AddItem (Catalog.GetString ("Container Formats:"), file.TagTypes.ToString ());
AddSeparator ();
file.Dispose ();
}
AddItem (Catalog.GetString ("Imported On:"), track.DateAdded > DateTime.MinValue
? track.DateAdded.ToString () : Catalog.GetString ("Unknown"));
AddItem (Catalog.GetString ("Last Played:"), track.LastPlayed > DateTime.MinValue
? track.LastPlayed.ToString () : Catalog.GetString ("Unknown"));
AddItem (Catalog.GetString ("Last Skipped:"), track.LastSkipped > DateTime.MinValue
? track.LastSkipped.ToString () : Catalog.GetString ("Unknown"));
AddItem (Catalog.GetString ("Play Count:"), track.PlayCount);
AddItem (Catalog.GetString ("Skip Count:"), track.SkipCount);
AddItem (Catalog.GetString ("Score:"), track.Score);
}
private void AddFileSizeItem (long bytes)
{
Hyena.Query.FileSizeQueryValue value = new Hyena.Query.FileSizeQueryValue (bytes);
AddItem (Catalog.GetString ("File Size:"), String.Format ("{0} ({1} {2})",
value.ToUserQuery (), bytes, Catalog.GetString ("bytes")));
}
private void CreateModel ()
{
if (model == null) {
model = new ListStore (typeof (string), typeof (string), typeof (bool), typeof (Pango.EllipsizeMode), typeof(bool), typeof (int));
view.Model = model;
}
}
public void AddItem (string name, object value)
{
AddItem (name, value, false);
}
public void AddItem (string name, object value, bool wrapText)
{
CreateModel ();
if (name != null && value != null) {
model.AppendValues (name, value.ToString (), false, wrapText ? Pango.EllipsizeMode.None : Pango.EllipsizeMode.End, true, wrapText ? 10 : -1);
}
}
public void AddSeparator ()
{
CreateModel ();
model.AppendValues (String.Empty, String.Empty, true, Pango.EllipsizeMode.End, false, -1);
}
public int Order {
get { return 40; }
}
public string Title {
get { return Catalog.GetString ("Properties"); }
}
public PageType PageType {
get { return PageType.View; }
}
public Gtk.Widget TabWidget {
get { return null; }
}
public Gtk.Widget Widget {
get { return this; }
}
}
}
| |
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Util;
using System;
using System.Diagnostics;
using System.Reflection;
namespace Lucene.Net.Analysis
{
/*
* 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.
*/
/// <summary>
/// <b>Expert:</b> this class provides a <see cref="TokenStream"/>
/// for indexing numeric values that can be used by <see cref="Search.NumericRangeQuery"/>
/// or <see cref="Search.NumericRangeFilter"/>.
///
/// <para/>Note that for simple usage, <see cref="Documents.Int32Field"/>, <see cref="Documents.Int64Field"/>,
/// <see cref="Documents.SingleField"/> or <see cref="Documents.DoubleField"/> is
/// recommended. These fields disable norms and
/// term freqs, as they are not usually needed during
/// searching. If you need to change these settings, you
/// should use this class.
///
/// <para/>Here's an example usage, for an <see cref="int"/> field:
///
/// <code>
/// IndexableFieldType fieldType = new IndexableFieldType(TextField.TYPE_NOT_STORED)
/// {
/// OmitNorms = true,
/// IndexOptions = IndexOptions.DOCS_ONLY
/// };
/// Field field = new Field(name, new NumericTokenStream(precisionStep).SetInt32Value(value), fieldType);
/// document.Add(field);
/// </code>
///
/// <para/>For optimal performance, re-use the <see cref="TokenStream"/> and <see cref="Documents.Field"/> instance
/// for more than one document:
///
/// <code>
/// NumericTokenStream stream = new NumericTokenStream(precisionStep);
/// IndexableFieldType fieldType = new IndexableFieldType(TextField.TYPE_NOT_STORED)
/// {
/// OmitNorms = true,
/// IndexOptions = IndexOptions.DOCS_ONLY
/// };
/// Field field = new Field(name, stream, fieldType);
/// Document document = new Document();
/// document.Add(field);
///
/// for(all documents)
/// {
/// stream.SetInt32Value(value)
/// writer.AddDocument(document);
/// }
/// </code>
///
/// <para>this stream is not intended to be used in analyzers;
/// it's more for iterating the different precisions during
/// indexing a specific numeric value.</para>
///
/// <para><b>NOTE</b>: as token streams are only consumed once
/// the document is added to the index, if you index more
/// than one numeric field, use a separate <see cref="NumericTokenStream"/>
/// instance for each.</para>
///
/// <para>See <see cref="Search.NumericRangeQuery"/> for more details on the
/// <c>precisionStep</c> parameter as well as how numeric fields work under the hood.
/// </para>
///
/// @since 2.9
/// </summary>
public sealed class NumericTokenStream : TokenStream
{
private void InitializeInstanceFields()
{
numericAtt = AddAttribute<INumericTermAttribute>();
typeAtt = AddAttribute<ITypeAttribute>();
posIncrAtt = AddAttribute<IPositionIncrementAttribute>();
}
/// <summary>
/// The full precision token gets this token type assigned. </summary>
public const string TOKEN_TYPE_FULL_PREC = "fullPrecNumeric";
/// <summary>
/// The lower precision tokens gets this token type assigned. </summary>
public const string TOKEN_TYPE_LOWER_PREC = "lowerPrecNumeric";
/// <summary>
/// <b>Expert:</b> Use this attribute to get the details of the currently generated token.
/// @lucene.experimental
/// @since 4.0
/// </summary>
public interface INumericTermAttribute : IAttribute
{
/// <summary>
/// Returns current shift value, undefined before first token </summary>
int Shift { get; set; }
/// <summary>
/// Returns current token's raw value as <see cref="long"/> with all <see cref="Shift"/> applied, undefined before first token </summary>
long RawValue { get; }
/// <summary>
/// Returns value size in bits (32 for <see cref="float"/>, <see cref="int"/>; 64 for <see cref="double"/>, <see cref="long"/>) </summary>
int ValueSize { get; }
/// <summary>
/// <em>Don't call this method!</em>
/// @lucene.internal
/// </summary>
void Init(long value, int valSize, int precisionStep, int shift);
/// <summary>
/// <em>Don't call this method!</em>
/// @lucene.internal
/// </summary>
int IncShift();
}
// just a wrapper to prevent adding CTA
private sealed class NumericAttributeFactory : AttributeSource.AttributeFactory
{
private readonly AttributeSource.AttributeFactory @delegate;
internal NumericAttributeFactory(AttributeSource.AttributeFactory @delegate)
{
this.@delegate = @delegate;
}
public override Util.Attribute CreateAttributeInstance<T>()
{
var attClass = typeof(T);
if (typeof(ICharTermAttribute).GetTypeInfo().IsAssignableFrom(attClass.GetTypeInfo()))
{
throw new System.ArgumentException("NumericTokenStream does not support CharTermAttribute.");
}
return @delegate.CreateAttributeInstance<T>();
}
}
/// <summary>
/// Implementation of <see cref="INumericTermAttribute"/>.
/// @lucene.internal
/// @since 4.0
/// </summary>
public sealed class NumericTermAttribute : Util.Attribute, INumericTermAttribute, ITermToBytesRefAttribute
{
private long _value = 0L;
private int _precisionStep = 0;
private readonly BytesRef _bytes = new BytesRef();
/// <summary>
/// Creates, but does not yet initialize this attribute instance
/// </summary>
/// <seealso cref="Init(long, int, int, int)"/>
public NumericTermAttribute()
{
ValueSize = 0;
}
public BytesRef BytesRef
{
get
{
return _bytes;
}
}
public void FillBytesRef()
{
Debug.Assert(ValueSize == 64 || ValueSize == 32);
if (ValueSize == 64)
{
NumericUtils.Int64ToPrefixCoded(_value, Shift, _bytes);
}
else
{
NumericUtils.Int32ToPrefixCoded((int)_value, Shift, _bytes);
}
}
public int Shift { get; set; }
public int IncShift()
{
return (Shift += _precisionStep);
}
public long RawValue
{
get
{
return _value & ~((1L << Shift) - 1L);
}
}
public int ValueSize { get; private set; }
public void Init(long value, int valueSize, int precisionStep, int shift)
{
this._value = value;
this.ValueSize = valueSize;
this._precisionStep = precisionStep;
this.Shift = shift;
}
public override void Clear()
{
// this attribute has no contents to clear!
// we keep it untouched as it's fully controlled by outer class.
}
public override void ReflectWith(IAttributeReflector reflector)
{
FillBytesRef();
reflector.Reflect(typeof(ITermToBytesRefAttribute), "bytes", BytesRef.DeepCopyOf(_bytes));
reflector.Reflect(typeof(INumericTermAttribute), "shift", Shift);
reflector.Reflect(typeof(INumericTermAttribute), "rawValue", RawValue);
reflector.Reflect(typeof(INumericTermAttribute), "valueSize", ValueSize);
}
public override void CopyTo(Util.IAttribute target)
{
var a = (NumericTermAttribute)target;
a.Init(_value, ValueSize, _precisionStep, Shift);
}
}
/// <summary>
/// Creates a token stream for numeric values using the default <seealso cref="precisionStep"/>
/// <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4). The stream is not yet initialized,
/// before using set a value using the various Set<em>???</em>Value() methods.
/// </summary>
public NumericTokenStream()
: this(AttributeSource.AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY, NumericUtils.PRECISION_STEP_DEFAULT)
{
InitializeInstanceFields();
}
/// <summary>
/// Creates a token stream for numeric values with the specified
/// <paramref name="precisionStep"/>. The stream is not yet initialized,
/// before using set a value using the various Set<em>???</em>Value() methods.
/// </summary>
public NumericTokenStream(int precisionStep)
: this(AttributeSource.AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY, precisionStep)
{
InitializeInstanceFields();
}
/// <summary>
/// Expert: Creates a token stream for numeric values with the specified
/// <paramref name="precisionStep"/> using the given
/// <see cref="Lucene.Net.Util.AttributeSource.AttributeFactory"/>.
/// The stream is not yet initialized,
/// before using set a value using the various Set<em>???</em>Value() methods.
/// </summary>
public NumericTokenStream(AttributeSource.AttributeFactory factory, int precisionStep)
: base(new NumericAttributeFactory(factory))
{
InitializeInstanceFields();
if (precisionStep < 1)
{
throw new System.ArgumentException("precisionStep must be >=1");
}
this.precisionStep = precisionStep;
numericAtt.Shift = -precisionStep;
}
/// <summary>
/// Initializes the token stream with the supplied <see cref="long"/> value.
/// <para/>
/// NOTE: This was setLongValue() in Lucene
/// </summary>
/// <param name="value"> the value, for which this <see cref="TokenStream"/> should enumerate tokens. </param>
/// <returns> this instance, because of this you can use it the following way:
/// <code>new Field(name, new NumericTokenStream(precisionStep).SetInt64Value(value))</code> </returns>
public NumericTokenStream SetInt64Value(long value)
{
numericAtt.Init(value, valSize = 64, precisionStep, -precisionStep);
return this;
}
/// <summary>
/// Initializes the token stream with the supplied <see cref="int"/> value.
/// <para/>
/// NOTE: This was setIntValue() in Lucene
/// </summary>
/// <param name="value"> the value, for which this <see cref="TokenStream"/> should enumerate tokens. </param>
/// <returns> this instance, because of this you can use it the following way:
/// <code>new Field(name, new NumericTokenStream(precisionStep).SetInt32Value(value))</code> </returns>
public NumericTokenStream SetInt32Value(int value)
{
numericAtt.Init(value, valSize = 32, precisionStep, -precisionStep);
return this;
}
/// <summary>
/// Initializes the token stream with the supplied <see cref="double"/> value. </summary>
/// <param name="value"> the value, for which this <see cref="TokenStream"/> should enumerate tokens. </param>
/// <returns> this instance, because of this you can use it the following way:
/// <code>new Field(name, new NumericTokenStream(precisionStep).SetDoubleValue(value))</code> </returns>
public NumericTokenStream SetDoubleValue(double value)
{
numericAtt.Init(NumericUtils.DoubleToSortableInt64(value), valSize = 64, precisionStep, -precisionStep);
return this;
}
/// <summary>
/// Initializes the token stream with the supplied <see cref="float"/> value.
/// <para/>
/// NOTE: This was setFloatValue() in Lucene
/// </summary>
/// <param name="value"> the value, for which this <see cref="TokenStream"/> should enumerate tokens. </param>
/// <returns> this instance, because of this you can use it the following way:
/// <code>new Field(name, new NumericTokenStream(precisionStep).SetSingleValue(value))</code> </returns>
public NumericTokenStream SetSingleValue(float value)
{
numericAtt.Init(NumericUtils.SingleToSortableInt32(value), valSize = 32, precisionStep, -precisionStep);
return this;
}
public override void Reset()
{
if (valSize == 0)
{
throw new Exception("call Set???Value() before usage");
}
numericAtt.Shift = -precisionStep;
}
public override bool IncrementToken()
{
if (valSize == 0)
{
throw new Exception("call Set???Value() before usage");
}
// this will only clear all other attributes in this TokenStream
ClearAttributes();
int shift = numericAtt.IncShift();
typeAtt.Type = (shift == 0) ? TOKEN_TYPE_FULL_PREC : TOKEN_TYPE_LOWER_PREC;
posIncrAtt.PositionIncrement = (shift == 0) ? 1 : 0;
return (shift < valSize);
}
/// <summary>
/// Returns the precision step. </summary>
public int PrecisionStep
{
get
{
return precisionStep;
}
}
// members
private INumericTermAttribute numericAtt;
private ITypeAttribute typeAtt;
private IPositionIncrementAttribute posIncrAtt;
private int valSize = 0; // valSize==0 means not initialized
private readonly int precisionStep;
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Orleans.AzureUtils;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
using Orleans.Runtime.Configuration;
using Orleans.Clustering.AzureStorage;
using Orleans.Clustering.AzureStorage.Utilities;
namespace Orleans.Runtime.MembershipService
{
internal class AzureBasedMembershipTable : IMembershipTable
{
private readonly ILogger logger;
private readonly ILoggerFactory loggerFactory;
private OrleansSiloInstanceManager tableManager;
private readonly AzureStorageClusteringOptions options;
private readonly string clusterId;
public AzureBasedMembershipTable(
ILoggerFactory loggerFactory,
IOptions<AzureStorageClusteringOptions> clusteringOptions,
IOptions<ClusterOptions> clusterOptions)
{
this.loggerFactory = loggerFactory;
logger = loggerFactory.CreateLogger<AzureBasedMembershipTable>();
this.options = clusteringOptions.Value;
this.clusterId = clusterOptions.Value.ClusterId;
}
public async Task InitializeMembershipTable(bool tryInitTableVersion)
{
AzureTableDefaultPolicies.MaxBusyRetries = options.MaxStorageBusyRetries;
LogFormatter.SetExceptionDecoder(typeof(StorageException), AzureStorageUtils.PrintStorageException);
tableManager = await OrleansSiloInstanceManager.GetManager(
this.clusterId, options.ConnectionString, this.loggerFactory);
// even if I am not the one who created the table,
// try to insert an initial table version if it is not already there,
// so we always have a first table version row, before this silo starts working.
if (tryInitTableVersion)
{
// ignore return value, since we don't care if I inserted it or not, as long as it is in there.
bool created = await tableManager.TryCreateTableVersionEntryAsync();
if(created) logger.Info("Created new table version row.");
}
}
public Task DeleteMembershipTableEntries(string clusterId)
{
return tableManager.DeleteTableEntries(clusterId);
}
public async Task<MembershipTableData> ReadRow(SiloAddress key)
{
try
{
var entries = await tableManager.FindSiloEntryAndTableVersionRow(key);
MembershipTableData data = Convert(entries);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Read my entry {0} Table=" + Environment.NewLine + "{1}", key.ToLongString(), data.ToString());
return data;
}
catch (Exception exc)
{
logger.Warn((int)TableStorageErrorCode.AzureTable_20,
$"Intermediate error reading silo entry for key {key.ToLongString()} from the table {tableManager.TableName}.", exc);
throw;
}
}
public async Task<MembershipTableData> ReadAll()
{
try
{
var entries = await tableManager.FindAllSiloEntries();
MembershipTableData data = Convert(entries);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("ReadAll Table=" + Environment.NewLine + "{0}", data.ToString());
return data;
}
catch (Exception exc)
{
logger.Warn((int)TableStorageErrorCode.AzureTable_21,
$"Intermediate error reading all silo entries {tableManager.TableName}.", exc);
throw;
}
}
public async Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion)
{
try
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("InsertRow entry = {0}, table version = {1}", entry.ToFullString(), tableVersion);
var tableEntry = Convert(entry, tableManager.DeploymentId);
var versionEntry = tableManager.CreateTableVersionEntry(tableVersion.Version);
bool result = await tableManager.InsertSiloEntryConditionally(
tableEntry, versionEntry, tableVersion.VersionEtag);
if (result == false)
logger.Warn((int)TableStorageErrorCode.AzureTable_22,
$"Insert failed due to contention on the table. Will retry. Entry {entry.ToFullString()}, table version = {tableVersion}");
return result;
}
catch (Exception exc)
{
logger.Warn((int)TableStorageErrorCode.AzureTable_23,
$"Intermediate error inserting entry {entry.ToFullString()} tableVersion {(tableVersion == null ? "null" : tableVersion.ToString())} to the table {tableManager.TableName}.", exc);
throw;
}
}
public async Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion)
{
try
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("UpdateRow entry = {0}, etag = {1}, table version = {2}", entry.ToFullString(), etag, tableVersion);
var siloEntry = Convert(entry, tableManager.DeploymentId);
var versionEntry = tableManager.CreateTableVersionEntry(tableVersion.Version);
bool result = await tableManager.UpdateSiloEntryConditionally(siloEntry, etag, versionEntry, tableVersion.VersionEtag);
if (result == false)
logger.Warn((int)TableStorageErrorCode.AzureTable_24,
$"Update failed due to contention on the table. Will retry. Entry {entry.ToFullString()}, eTag {etag}, table version = {tableVersion} ");
return result;
}
catch (Exception exc)
{
logger.Warn((int)TableStorageErrorCode.AzureTable_25,
$"Intermediate error updating entry {entry.ToFullString()} tableVersion {(tableVersion == null ? "null" : tableVersion.ToString())} to the table {tableManager.TableName}.", exc);
throw;
}
}
public async Task UpdateIAmAlive(MembershipEntry entry)
{
try
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Merge entry = {0}", entry.ToFullString());
var siloEntry = ConvertPartial(entry, tableManager.DeploymentId);
await tableManager.MergeTableEntryAsync(siloEntry);
}
catch (Exception exc)
{
logger.Warn((int)TableStorageErrorCode.AzureTable_26,
$"Intermediate error updating IAmAlive field for entry {entry.ToFullString()} to the table {tableManager.TableName}.", exc);
throw;
}
}
private MembershipTableData Convert(List<Tuple<SiloInstanceTableEntry, string>> entries)
{
try
{
var memEntries = new List<Tuple<MembershipEntry, string>>();
TableVersion tableVersion = null;
foreach (var tuple in entries)
{
var tableEntry = tuple.Item1;
if (tableEntry.RowKey.Equals(SiloInstanceTableEntry.TABLE_VERSION_ROW))
{
tableVersion = new TableVersion(Int32.Parse(tableEntry.MembershipVersion), tuple.Item2);
}
else
{
try
{
MembershipEntry membershipEntry = Parse(tableEntry);
memEntries.Add(new Tuple<MembershipEntry, string>(membershipEntry, tuple.Item2));
}
catch (Exception exc)
{
logger.Error((int)TableStorageErrorCode.AzureTable_61,
$"Intermediate error parsing SiloInstanceTableEntry to MembershipTableData: {tableEntry}. Ignoring this entry.", exc);
}
}
}
var data = new MembershipTableData(memEntries, tableVersion);
return data;
}
catch (Exception exc)
{
logger.Error((int)TableStorageErrorCode.AzureTable_60,
$"Intermediate error parsing SiloInstanceTableEntry to MembershipTableData: {Utils.EnumerableToString(entries, tuple => tuple.Item1.ToString())}.", exc);
throw;
}
}
private static MembershipEntry Parse(SiloInstanceTableEntry tableEntry)
{
var parse = new MembershipEntry
{
HostName = tableEntry.HostName,
Status = (SiloStatus) Enum.Parse(typeof (SiloStatus), tableEntry.Status)
};
if (!string.IsNullOrEmpty(tableEntry.ProxyPort))
parse.ProxyPort = int.Parse(tableEntry.ProxyPort);
int port = 0;
if (!string.IsNullOrEmpty(tableEntry.Port))
int.TryParse(tableEntry.Port, out port);
int gen = 0;
if (!string.IsNullOrEmpty(tableEntry.Generation))
int.TryParse(tableEntry.Generation, out gen);
parse.SiloAddress = SiloAddress.New(new IPEndPoint(IPAddress.Parse(tableEntry.Address), port), gen);
parse.RoleName = tableEntry.RoleName;
if (!string.IsNullOrEmpty(tableEntry.SiloName))
{
parse.SiloName = tableEntry.SiloName;
}else if (!string.IsNullOrEmpty(tableEntry.InstanceName))
{
// this is for backward compatability: in a mixed cluster of old and new version,
// some entries will have the old InstanceName column.
parse.SiloName = tableEntry.InstanceName;
}
if (!string.IsNullOrEmpty(tableEntry.UpdateZone))
parse.UpdateZone = int.Parse(tableEntry.UpdateZone);
if (!string.IsNullOrEmpty(tableEntry.FaultZone))
parse.FaultZone = int.Parse(tableEntry.FaultZone);
parse.StartTime = !string.IsNullOrEmpty(tableEntry.StartTime) ?
LogFormatter.ParseDate(tableEntry.StartTime) : default(DateTime);
parse.IAmAliveTime = !string.IsNullOrEmpty(tableEntry.IAmAliveTime) ?
LogFormatter.ParseDate(tableEntry.IAmAliveTime) : default(DateTime);
var suspectingSilos = new List<SiloAddress>();
var suspectingTimes = new List<DateTime>();
if (!string.IsNullOrEmpty(tableEntry.SuspectingSilos))
{
string[] silos = tableEntry.SuspectingSilos.Split('|');
foreach (string silo in silos)
{
suspectingSilos.Add(SiloAddress.FromParsableString(silo));
}
}
if (!string.IsNullOrEmpty(tableEntry.SuspectingTimes))
{
string[] times = tableEntry.SuspectingTimes.Split('|');
foreach (string time in times)
suspectingTimes.Add(LogFormatter.ParseDate(time));
}
if (suspectingSilos.Count != suspectingTimes.Count)
throw new OrleansException(String.Format("SuspectingSilos.Length of {0} as read from Azure table is not eqaul to SuspectingTimes.Length of {1}", suspectingSilos.Count, suspectingTimes.Count));
for (int i = 0; i < suspectingSilos.Count; i++)
parse.AddSuspector(suspectingSilos[i], suspectingTimes[i]);
return parse;
}
private static SiloInstanceTableEntry Convert(MembershipEntry memEntry, string deploymentId)
{
var tableEntry = new SiloInstanceTableEntry
{
DeploymentId = deploymentId,
Address = memEntry.SiloAddress.Endpoint.Address.ToString(),
Port = memEntry.SiloAddress.Endpoint.Port.ToString(CultureInfo.InvariantCulture),
Generation = memEntry.SiloAddress.Generation.ToString(CultureInfo.InvariantCulture),
HostName = memEntry.HostName,
Status = memEntry.Status.ToString(),
ProxyPort = memEntry.ProxyPort.ToString(CultureInfo.InvariantCulture),
RoleName = memEntry.RoleName,
SiloName = memEntry.SiloName,
// this is for backward compatability: in a mixed cluster of old and new version,
// we need to populate both columns.
InstanceName = memEntry.SiloName,
UpdateZone = memEntry.UpdateZone.ToString(CultureInfo.InvariantCulture),
FaultZone = memEntry.FaultZone.ToString(CultureInfo.InvariantCulture),
StartTime = LogFormatter.PrintDate(memEntry.StartTime),
IAmAliveTime = LogFormatter.PrintDate(memEntry.IAmAliveTime)
};
if (memEntry.SuspectTimes != null)
{
var siloList = new StringBuilder();
var timeList = new StringBuilder();
bool first = true;
foreach (var tuple in memEntry.SuspectTimes)
{
if (!first)
{
siloList.Append('|');
timeList.Append('|');
}
siloList.Append(tuple.Item1.ToParsableString());
timeList.Append(LogFormatter.PrintDate(tuple.Item2));
first = false;
}
tableEntry.SuspectingSilos = siloList.ToString();
tableEntry.SuspectingTimes = timeList.ToString();
}
else
{
tableEntry.SuspectingSilos = String.Empty;
tableEntry.SuspectingTimes = String.Empty;
}
tableEntry.PartitionKey = deploymentId;
tableEntry.RowKey = SiloInstanceTableEntry.ConstructRowKey(memEntry.SiloAddress);
return tableEntry;
}
private static SiloInstanceTableEntry ConvertPartial(MembershipEntry memEntry, string deploymentId)
{
return new SiloInstanceTableEntry
{
DeploymentId = deploymentId,
IAmAliveTime = LogFormatter.PrintDate(memEntry.IAmAliveTime),
PartitionKey = deploymentId,
RowKey = SiloInstanceTableEntry.ConstructRowKey(memEntry.SiloAddress)
};
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.ODBLayer;
using BTDB.StreamLayer;
namespace BTDB.EventStoreLayer
{
class ListTypeDescriptor : ITypeDescriptor, IPersistTypeDescriptor
{
readonly ITypeDescriptorCallbacks _typeSerializers;
Type? _type;
Type? _itemType;
ITypeDescriptor? _itemDescriptor;
string? _name;
readonly ITypeConvertorGenerator _convertGenerator;
public ListTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, Type type)
{
_convertGenerator = typeSerializers.ConvertorGenerator;
_typeSerializers = typeSerializers;
_type = type;
_itemType = GetItemType(type);
}
public ListTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ref SpanReader reader, DescriptorReader nestedDescriptorReader)
: this(typeSerializers, nestedDescriptorReader(ref reader))
{
}
ListTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ITypeDescriptor itemDesc)
{
_convertGenerator = typeSerializers.ConvertorGenerator;
_typeSerializers = typeSerializers;
InitFromItemDescriptor(itemDesc);
}
void InitFromItemDescriptor(ITypeDescriptor descriptor)
{
if (descriptor == _itemDescriptor && _name != null) return;
_itemDescriptor = descriptor;
if ((descriptor.Name?.Length ?? 0) == 0) return;
Sealed = _itemDescriptor.Sealed;
Name = $"List<{_itemDescriptor.Name}>";
}
public bool Equals(ITypeDescriptor other)
{
return Equals(other, new HashSet<ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance));
}
public override int GetHashCode()
{
#pragma warning disable RECS0025 // Non-readonly field referenced in 'GetHashCode()'
// ReSharper disable once NonReadonlyMemberInGetHashCode
return 33 * _itemDescriptor!.GetHashCode();
#pragma warning restore RECS0025 // Non-readonly field referenced in 'GetHashCode()'
}
public string Name
{
get
{
if (_name == null) InitFromItemDescriptor(_itemDescriptor!);
return _name!;
}
private set => _name = value;
}
public bool FinishBuildFromType(ITypeDescriptorFactory factory)
{
var descriptor = factory.Create(_itemType!);
if (descriptor == null) return false;
InitFromItemDescriptor(descriptor);
return true;
}
public void BuildHumanReadableFullName(StringBuilder text, HashSet<ITypeDescriptor> stack, uint indent)
{
text.Append("List<");
_itemDescriptor!.BuildHumanReadableFullName(text, stack, indent);
text.Append(">");
}
public bool Equals(ITypeDescriptor other, HashSet<ITypeDescriptor> stack)
{
if (!(other is ListTypeDescriptor o)) return false;
return _itemDescriptor!.Equals(o._itemDescriptor!, stack);
}
public Type GetPreferredType()
{
if (_type == null)
{
_itemType = _typeSerializers.LoadAsType(_itemDescriptor!);
_type = typeof(ICollection<>).MakeGenericType(_itemType);
}
return _type;
}
public Type GetPreferredType(Type targetType)
{
if (_type == targetType) return _type;
var targetICollection = targetType.GetInterface("ICollection`1") ?? targetType;
var targetTypeArguments = targetICollection.GetGenericArguments();
var itemType = _typeSerializers.LoadAsType(_itemDescriptor!, targetTypeArguments[0]);
return targetType.GetGenericTypeDefinition().MakeGenericType(itemType);
}
public bool AnyOpNeedsCtx()
{
return !_itemDescriptor!.StoredInline || _itemDescriptor.AnyOpNeedsCtx();
}
static Type GetInterface(Type type) => type.GetInterface("ICollection`1") ?? type;
public void GenerateLoad(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx, Action<IILGen> pushDescriptor, Type targetType)
{
if (targetType == typeof(object))
targetType = GetPreferredType();
var localCount = ilGenerator.DeclareLocal(typeof(int));
var targetICollection = GetInterface(targetType);
var targetTypeArguments = targetICollection.GetGenericArguments();
var itemType = _typeSerializers.LoadAsType(_itemDescriptor!, targetTypeArguments[0]);
if (targetType.IsArray)
{
var localArray = ilGenerator.DeclareLocal(targetType);
var loadFinished = ilGenerator.DefineLabel();
var localIndex = ilGenerator.DeclareLocal(typeof(int));
var next = ilGenerator.DefineLabel();
ilGenerator
.Ldnull()
.Stloc(localArray)
.LdcI4(0)
.Stloc(localIndex)
.Do(pushReader)
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!)
.ConvI4()
.Dup()
.Stloc(localCount)
.Brfalse(loadFinished)
.Ldloc(localCount)
.LdcI4(1)
.Sub()
.Dup()
.Stloc(localCount)
.Newarr(itemType)
.Stloc(localArray)
.Mark(next)
.Ldloc(localCount)
.Ldloc(localIndex)
.Sub()
.Brfalse(loadFinished)
.Ldloc(localArray)
.Ldloc(localIndex);
_itemDescriptor.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(0).Callvirt(() => default(ITypeDescriptor).NestedType(0)), itemType, _convertGenerator);
ilGenerator
.Stelem(itemType)
.Ldloc(localIndex)
.LdcI4(1)
.Add()
.Stloc(localIndex)
.Br(next)
.Mark(loadFinished)
.Ldloc(localArray)
.Castclass(targetType);
}
else
{
var isSet = targetType.InheritsOrImplements(typeof(ISet<>));
var listType = (isSet ? typeof(HashSetWithDescriptor<>) : typeof(ListWithDescriptor<>)).MakeGenericType(itemType);
if (!targetType.IsAssignableFrom(listType))
throw new NotSupportedException($"List type {listType.ToSimpleName()} is not assignable to {targetType.ToSimpleName()}.");
var localList = ilGenerator.DeclareLocal(listType);
var loadFinished = ilGenerator.DefineLabel();
var next = ilGenerator.DefineLabel();
ilGenerator
.Ldnull()
.Stloc(localList)
.Do(pushReader)
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!)
.ConvI4()
.Dup()
.Stloc(localCount)
.Brfalse(loadFinished)
.Ldloc(localCount)
.LdcI4(1)
.Sub()
.Dup()
.Stloc(localCount)
.Do(pushDescriptor)
.Newobj(listType.GetConstructor(new[] { typeof(int), typeof(ITypeDescriptor) })!)
.Stloc(localList)
.Mark(next)
.Ldloc(localCount)
.Brfalse(loadFinished)
.Ldloc(localCount)
.LdcI4(1)
.Sub()
.Stloc(localCount)
.Ldloc(localList);
_itemDescriptor.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(0).Callvirt(() => default(ITypeDescriptor).NestedType(0)), itemType, _convertGenerator);
ilGenerator
.Callvirt(listType.GetInterface("ICollection`1")!.GetMethod("Add")!)
.Br(next)
.Mark(loadFinished)
.Ldloc(localList)
.Castclass(targetType);
}
}
public ITypeNewDescriptorGenerator? BuildNewDescriptorGenerator()
{
if (_itemDescriptor!.Sealed) return null;
return new TypeNewDescriptorGenerator(this);
}
class TypeNewDescriptorGenerator : ITypeNewDescriptorGenerator
{
readonly ListTypeDescriptor _listTypeDescriptor;
public TypeNewDescriptorGenerator(ListTypeDescriptor listTypeDescriptor)
{
_listTypeDescriptor = listTypeDescriptor;
}
public void GenerateTypeIterator(IILGen ilGenerator, Action<IILGen> pushObj, Action<IILGen> pushCtx, Type type)
{
var finish = ilGenerator.DefineLabel();
var next = ilGenerator.DefineLabel();
if (type == typeof(object))
type = _listTypeDescriptor.GetPreferredType();
var targetInterface = GetInterface(type);
var targetTypeArguments = targetInterface.GetGenericArguments();
var itemType = _listTypeDescriptor._typeSerializers.LoadAsType(_listTypeDescriptor._itemDescriptor!, targetTypeArguments[0]);
if (_listTypeDescriptor._type == null) _listTypeDescriptor._type = type;
var isConcreteImplementation = type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) || type.GetGenericTypeDefinition() == typeof(HashSet<>));
var typeAsICollection = isConcreteImplementation ? type : typeof(ICollection<>).MakeGenericType(itemType);
var getEnumeratorMethod = isConcreteImplementation
? typeAsICollection.GetMethods()
.Single(
m => m.Name == nameof(IEnumerable.GetEnumerator) && m.ReturnType.IsValueType && m.GetParameters().Length == 0)
: typeAsICollection.GetInterface("IEnumerable`1")!.GetMethod(nameof(IEnumerable.GetEnumerator));
var typeAsIEnumerator = getEnumeratorMethod!.ReturnType;
var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod();
var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator);
ilGenerator
.Do(pushObj)
.Castclass(typeAsICollection)
.Callvirt(getEnumeratorMethod)
.Stloc(localEnumerator)
.Try()
.Mark(next)
.Do(il =>
{
if (isConcreteImplementation)
{
il
.Ldloca(localEnumerator)
.Call(typeAsIEnumerator.GetMethod(nameof(IEnumerator.MoveNext))!);
}
else
{
il
.Ldloc(localEnumerator)
.Callvirt(() => default(IEnumerator).MoveNext());
}
})
.Brfalse(finish)
.Do(pushCtx)
.Do(il =>
{
if (isConcreteImplementation)
{
il
.Ldloca(localEnumerator)
.Call(currentGetter!);
}
else
{
il
.Ldloc(localEnumerator)
.Callvirt(currentGetter!);
}
})
.Callvirt(typeof(IDescriptorSerializerLiteContext).GetMethod(nameof(IDescriptorSerializerLiteContext.StoreNewDescriptors))!)
.Br(next)
.Mark(finish)
.Finally()
.Do(il =>
{
if (isConcreteImplementation)
{
il
.Ldloca(localEnumerator)
.Constrained(typeAsIEnumerator);
}
else
{
il.Ldloc(localEnumerator);
}
})
.Callvirt(() => default(IDisposable).Dispose())
.EndTry();
}
}
public ITypeDescriptor? NestedType(int index)
{
return index == 0 ? _itemDescriptor : null;
}
public void MapNestedTypes(Func<ITypeDescriptor, ITypeDescriptor> map)
{
InitFromItemDescriptor(map(_itemDescriptor));
}
public bool Sealed { get; private set; }
public bool StoredInline => true;
public bool LoadNeedsHelpWithConversion => false;
public void ClearMappingToType()
{
_type = null;
_itemType = null;
}
public bool ContainsField(string name)
{
return false;
}
public IEnumerable<KeyValuePair<string, ITypeDescriptor>> Fields => Array.Empty<KeyValuePair<string, ITypeDescriptor>>();
public void Persist(ref SpanWriter writer, DescriptorWriter nestedDescriptorWriter)
{
nestedDescriptorWriter(ref writer, _itemDescriptor!);
}
public void GenerateSave(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx, Action<IILGen> pushValue, Type valueType)
{
var notnull = ilGenerator.DefineLabel();
var completeFinish = ilGenerator.DefineLabel();
var notList = ilGenerator.DefineLabel();
var notHashSet = ilGenerator.DefineLabel();
var itemType = GetItemType(valueType);
var typeAsICollection = typeof(ICollection<>).MakeGenericType(itemType);
var localCollection = ilGenerator.DeclareLocal(typeAsICollection);
ilGenerator
.Do(pushValue)
.Castclass(typeAsICollection)
.Stloc(localCollection)
.Ldloc(localCollection)
.Brtrue(notnull)
.Do(pushWriter)
.Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteByteZero))!)
.Br(completeFinish)
.Mark(notnull)
.Do(pushWriter)
.Ldloc(localCollection)
.Callvirt(typeAsICollection!.GetProperty(nameof(ICollection.Count))!.GetGetMethod()!)
.LdcI4(1)
.Add()
.Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteVUInt32))!);
{
var typeAsList = typeof(List<>).MakeGenericType(itemType);
var getEnumeratorMethod = typeAsList.GetMethods()
.Single(m => m.Name == nameof(IEnumerable.GetEnumerator) && m.ReturnType.IsValueType && m.GetParameters().Length == 0);
var typeAsIEnumerator = getEnumeratorMethod.ReturnType;
var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod();
var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator);
var finish = ilGenerator.DefineLabel();
var next = ilGenerator.DefineLabel();
ilGenerator
.Ldloc(localCollection)
.Isinst(typeAsList)
.Brfalse(notList)
.Ldloc(localCollection)
.Castclass(typeAsList)
.Callvirt(getEnumeratorMethod)
.Stloc(localEnumerator)
.Try()
.Mark(next)
.Ldloca(localEnumerator)
.Call(typeAsIEnumerator.GetMethod(nameof(IEnumerator.MoveNext))!)
.Brfalse(finish);
_itemDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx,
il => il.Ldloca(localEnumerator).Callvirt(currentGetter!), itemType);
ilGenerator
.Br(next)
.Mark(finish)
.Finally()
.Ldloca(localEnumerator)
.Constrained(typeAsIEnumerator)
.Callvirt(() => default(IDisposable).Dispose())
.EndTry()
.Br(completeFinish);
}
{
var typeAsHashSet = typeof(HashSet<>).MakeGenericType(itemType);
var getEnumeratorMethod = typeAsHashSet.GetMethods()
.Single(m => m.Name == nameof(IEnumerable.GetEnumerator) && m.ReturnType.IsValueType && m.GetParameters().Length == 0);
var typeAsIEnumerator = getEnumeratorMethod.ReturnType;
var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod();
var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator);
var finish = ilGenerator.DefineLabel();
var next = ilGenerator.DefineLabel();
ilGenerator
.Mark(notList)
.Ldloc(localCollection)
.Isinst(typeAsHashSet)
.Brfalse(notHashSet)
.Ldloc(localCollection)
.Castclass(typeAsHashSet)
.Callvirt(getEnumeratorMethod)
.Stloc(localEnumerator)
.Try()
.Mark(next)
.Ldloca(localEnumerator)
.Call(typeAsIEnumerator.GetMethod(nameof(IEnumerator.MoveNext))!)
.Brfalse(finish);
_itemDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx,
il => il.Ldloca(localEnumerator).Callvirt(currentGetter!), itemType);
ilGenerator
.Br(next)
.Mark(finish)
.Finally()
.Ldloca(localEnumerator)
.Constrained(typeAsIEnumerator)
.Callvirt(() => default(IDisposable).Dispose())
.EndTry()
.Br(completeFinish);
}
{
var getEnumeratorMethod = typeAsICollection.GetInterface("IEnumerable`1")!.GetMethod(nameof(IEnumerable.GetEnumerator));
var typeAsIEnumerator = getEnumeratorMethod!.ReturnType;
var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod();
var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator);
var finish = ilGenerator.DefineLabel();
var next = ilGenerator.DefineLabel();
ilGenerator
.Mark(notHashSet)
.Ldloc(localCollection)
.Callvirt(getEnumeratorMethod)
.Stloc(localEnumerator)
.Try()
.Mark(next)
.Ldloc(localEnumerator)
.Callvirt(() => default(IEnumerator).MoveNext())
.Brfalse(finish);
_itemDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx,
il => il.Ldloc(localEnumerator)
.Callvirt(currentGetter!), itemType);
ilGenerator
.Br(next)
.Mark(finish)
.Finally()
.Ldloc(localEnumerator)
.Callvirt(() => default(IDisposable).Dispose())
.EndTry()
.Mark(completeFinish);
}
}
static Type GetItemType(Type valueType)
{
if (valueType.IsArray)
{
return valueType.GetElementType()!;
}
return valueType.GetGenericArguments()[0];
}
public void GenerateSkip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx)
{
var localCount = ilGenerator.DeclareLocal(typeof(int));
var skipFinished = ilGenerator.DefineLabel();
var next = ilGenerator.DefineLabel();
ilGenerator
.Do(pushReader)
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!)
.ConvI4()
.Dup()
.Stloc(localCount)
.Brfalse(skipFinished)
.Ldloc(localCount)
.LdcI4(1)
.Sub()
.Stloc(localCount)
.Mark(next)
.Ldloc(localCount)
.Brfalse(skipFinished)
.Ldloc(localCount)
.LdcI4(1)
.Sub()
.Stloc(localCount);
_itemDescriptor!.GenerateSkipEx(ilGenerator, pushReader, pushCtx);
ilGenerator
.Br(next)
.Mark(skipFinished);
}
public ITypeDescriptor CloneAndMapNestedTypes(ITypeDescriptorCallbacks typeSerializers, Func<ITypeDescriptor, ITypeDescriptor> map)
{
var itemDesc = map(_itemDescriptor);
if (_typeSerializers == typeSerializers && itemDesc == _itemDescriptor)
return this;
return new ListTypeDescriptor(typeSerializers, itemDesc);
}
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using UIKit;
namespace ArcGISRuntime.Samples.ListRelatedFeatures
{
[Register("ListRelatedFeatures")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "List related features",
category: "Data",
description: "List features related to the selected feature.",
instructions: "Tap on a feature to select it. The related features will be displayed in a list.",
tags: new[] { "features", "identify", "query", "related", "relationship", "search" })]
public class ListRelatedFeatures : UIViewController
{
// Hold references to UI controls.
private MapView _myMapView;
private UITableView _tableView;
private NSLayoutConstraint[] _portraitConstraints;
private NSLayoutConstraint[] _landscapeConstraints;
// URL to the web map.
private readonly Uri _mapUri =
new Uri("https://arcgisruntime.maps.arcgis.com/home/item.html?id=dcc7466a91294c0ab8f7a094430ab437");
// Reference to the feature layer.
private FeatureLayer _myFeatureLayer;
// Hold a source for the UITableView that shows the related features.
private LayerListSource _layerListSource;
public ListRelatedFeatures()
{
Title = "List related features";
}
private async void Initialize()
{
try
{
// Create the portal item from the URL to the webmap.
PortalItem alaskaPortalItem = await PortalItem.CreateAsync(_mapUri);
// Create the map from the portal item.
Map myMap = new Map(alaskaPortalItem);
// Add the map to the mapview.
_myMapView.Map = myMap;
// Wait for the map to load.
await myMap.LoadAsync();
// Get the feature layer from the map.
_myFeatureLayer = (FeatureLayer) myMap.OperationalLayers.First();
// Update the selection color.
_myMapView.SelectionProperties.Color = Color.Yellow;
}
catch (Exception e)
{
new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
}
}
private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
{
// Clear any existing feature selection and results list.
_myFeatureLayer.ClearSelection();
_tableView.Source = null;
_tableView.ReloadData();
try
{
// Identify the tapped feature.
IdentifyLayerResult results = await _myMapView.IdentifyLayerAsync(_myFeatureLayer, e.Position, 10, false);
// Return if there are no results.
if (results.GeoElements.Count < 1)
{
return;
}
// Get the first result.
ArcGISFeature myFeature = (ArcGISFeature) results.GeoElements.First();
// Select the feature.
_myFeatureLayer.SelectFeature(myFeature);
// Get the feature table for the feature.
ArcGISFeatureTable myFeatureTable = (ArcGISFeatureTable) myFeature.FeatureTable;
// Query related features.
IReadOnlyList<RelatedFeatureQueryResult> relatedFeaturesResult = await myFeatureTable.QueryRelatedFeaturesAsync(myFeature);
// Create a list to hold the formatted results of the query.
List<string> queryResultsForUi = new List<string>();
// For each query result.
foreach (RelatedFeatureQueryResult result in relatedFeaturesResult)
{
// And then for each feature in the result.
foreach (Feature resultFeature in result)
{
// Get a reference to the feature's table.
ArcGISFeatureTable relatedTable = (ArcGISFeatureTable) resultFeature.FeatureTable;
// Get the display field name - this is the name of the field that is intended for display.
string displayFieldName = relatedTable.LayerInfo.DisplayFieldName;
// Get the name of the feature's table.
string tableName = relatedTable.TableName;
// Get the display name for the feature.
string featureDisplayName = resultFeature.Attributes[displayFieldName].ToString();
// Create a formatted result string.
string formattedResult = $"{tableName} - {featureDisplayName}";
// Add the result to the list.
queryResultsForUi.Add(formattedResult);
}
}
// Create the source for the display list.
_layerListSource = new LayerListSource(queryResultsForUi);
// Assign the source to the display view.
_tableView.Source = _layerListSource;
// Force the table view to refresh its data.
_tableView.ReloadData();
}
catch (Exception ex)
{
new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
}
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
_myMapView = new MapView();
_myMapView.TranslatesAutoresizingMaskIntoConstraints = false;
_tableView = new UITableView();
_tableView.TranslatesAutoresizingMaskIntoConstraints = false;
_tableView.RowHeight = 30;
View = new UIView() { BackgroundColor = ApplicationTheme.BackgroundColor };
// Add the views.
View.AddSubviews(_myMapView, _tableView);
// Lay out the views.
_portraitConstraints = new[]
{
_tableView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_tableView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_tableView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_tableView.HeightAnchor.ConstraintEqualTo(_tableView.RowHeight * 4),
_myMapView.TopAnchor.ConstraintEqualTo(_tableView.BottomAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor)
};
_landscapeConstraints = new[]
{
_tableView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_tableView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_tableView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor),
_tableView.TrailingAnchor.ConstraintEqualTo(View.CenterXAnchor),
_myMapView.TopAnchor.ConstraintEqualTo(View.TopAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(_tableView.TrailingAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor)
};
// Activate default constraints.
if (View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact)
{
NSLayoutConstraint.ActivateConstraints(_landscapeConstraints);
}
else
{
NSLayoutConstraint.ActivateConstraints(_portraitConstraints);
}
}
public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
{
base.TraitCollectionDidChange(previousTraitCollection);
// Reset constraints.
NSLayoutConstraint.DeactivateConstraints(_portraitConstraints);
NSLayoutConstraint.DeactivateConstraints(_landscapeConstraints);
if (View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact)
{
NSLayoutConstraint.ActivateConstraints(_landscapeConstraints);
}
else
{
NSLayoutConstraint.ActivateConstraints(_portraitConstraints);
}
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Subscribe to events.
_myMapView.GeoViewTapped += MyMapView_GeoViewTapped;
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
// Unsubscribe from events, per best practice.
_myMapView.GeoViewTapped -= MyMapView_GeoViewTapped;
}
}
/// <summary>
/// Class defines how a UITableView renders its contents.
/// This implements the UI for the list of related features.
/// </summary>
public class LayerListSource : UITableViewSource
{
private readonly List<string> _viewModelList = new List<string>();
// Used when re-using cells to ensure that a cell of the right type is used.
private const string CellId = "TableCell";
public LayerListSource(List<string> items)
{
// Set the items.
if (items != null)
{
_viewModelList = items;
}
}
/// <summary>
/// This method gets a table view cell for the suggestion at the specified index.
/// </summary>
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
// Try to get a re-usable cell (this is for performance). If there are no cells, create a new one.
UITableViewCell cell = tableView.DequeueReusableCell(CellId);
if (cell == null)
{
cell = new UITableViewCell(UITableViewCellStyle.Default, CellId);
}
// Set the text on the cell.
cell.TextLabel.Text = _viewModelList[indexPath.Row];
// Ensure that the label fits.
cell.TextLabel.AdjustsFontSizeToFitWidth = true;
// Return the cell.
return cell;
}
/// <summary>
/// This method allows the UITableView to know how many rows to render.
/// </summary>
public override nint RowsInSection(UITableView tableview, nint section)
{
return _viewModelList.Count;
}
}
}
| |
//---------------------------------------------------------------------------
// File: Hyperlink.cs
//
// Description:
// Implementation of Underline element.
//
// Copyright (C) 2004 by Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System.ComponentModel;
using System.Diagnostics;
using System.IO.Packaging;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Windows.Automation.Peers;
using System.Windows.Controls; //
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MS.Internal;
using MS.Internal.AppModel;
using System.Windows.Threading;
using CommonDependencyProperty=MS.Internal.PresentationFramework.CommonDependencyPropertyAttribute;
using SecurityHelper=MS.Internal.PresentationFramework.SecurityHelper;
namespace System.Windows.Documents
{
/// <summary>
/// Implements a Hyperlink element
/// </summary>
[UIPermissionAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)]
[TextElementEditingBehaviorAttribute(IsMergeable = false, IsTypographicOnly = false)]
public class Hyperlink : Span, ICommandSource, IUriContext
{
//--------------------------------------------------------------------
//
// Constructors
//
//---------------------------------------------------------------------
#region Constructors
//
// Static Ctor to create default style sheet
//
static Hyperlink()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Hyperlink), new FrameworkPropertyMetadata(typeof(Hyperlink)));
_dType = DependencyObjectType.FromSystemTypeInternal(typeof(Hyperlink));
FocusableProperty.OverrideMetadata(typeof(Hyperlink), new FrameworkPropertyMetadata(true));
EventManager.RegisterClassHandler(typeof(Hyperlink), Mouse.QueryCursorEvent, new QueryCursorEventHandler(OnQueryCursor));
}
/// <summary>
/// Initializes a new instance of Hyperlink element.
/// </summary>
/// <remarks>
/// To become fully functional this element requires at least one other Inline element
/// as its child, typically Run with some text.
/// </remarks>
public Hyperlink() : base()
{
}
/// <summary>
/// Initializes a new instance of Hyperlink element and adds a given Inline element as its first child.
/// </summary>
/// <param name="childInline">
/// Inline element added as an initial child to this Hyperlink element
/// </param>
public Hyperlink(Inline childInline) : base(childInline)
{
}
/// <summary>
/// Creates a new Span instance.
/// </summary>
/// <param name="childInline">
/// Optional child Inline for the new Span. May be null.
/// </param>
/// <param name="insertionPosition">
/// Optional position at which to insert the new Span. May be null.
/// </param>
public Hyperlink(Inline childInline, TextPointer insertionPosition) : base(childInline, insertionPosition)
{
}
/// <summary>
/// Creates a new Hyperlink instance covering existing content.
/// </summary>
/// <param name="start">
/// Start position of the new Hyperlink.
/// </param>
/// <param name="end">
/// End position of the new Hyperlink.
/// </param>
/// <remarks>
/// start and end must both be parented by the same Paragraph, otherwise
/// the method will raise an ArgumentException.
/// </remarks>
public Hyperlink(TextPointer start, TextPointer end) : base(start, end)
{
// After inserting this Hyperlink, we need to extract any child Hyperlinks.
TextPointer navigator = this.ContentStart.CreatePointer();
TextPointer stop = this.ContentEnd;
while (navigator.CompareTo(stop) < 0)
{
Hyperlink hyperlink = navigator.GetAdjacentElement(LogicalDirection.Forward) as Hyperlink;
if (hyperlink != null)
{
hyperlink.Reposition(null, null);
}
else
{
navigator.MoveToNextContextPosition(LogicalDirection.Forward);
}
}
}
#endregion Constructors
//--------------------------------------------------------------------
//
// Public Methods
//
//---------------------------------------------------------------------
#region Public Methods
/// <summary>
/// This method does exactly the same operation as clicking the Hyperlink with the mouse, except the navigation is not treated as user-initiated.
/// </summary>
public void DoClick()
{
DoNonUserInitiatedNavigation(this);
}
#region ICommandSource
/// <summary>
/// The DependencyProperty for RoutedCommand
/// </summary>
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register(
"Command",
typeof(ICommand),
typeof(Hyperlink),
new FrameworkPropertyMetadata((ICommand)null,
new PropertyChangedCallback(OnCommandChanged)));
/// <summary>
/// Get or set the Command property
/// </summary>
[Bindable(true), Category("Action")]
[Localizability(LocalizationCategory.NeverLocalize)]
public ICommand Command
{
get
{
return (ICommand)GetValue(CommandProperty);
}
set
{
SetValue(CommandProperty, value);
}
}
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Hyperlink h = (Hyperlink)d;
h.OnCommandChanged((ICommand)e.OldValue, (ICommand)e.NewValue);
}
private void OnCommandChanged(ICommand oldCommand, ICommand newCommand)
{
if (oldCommand != null)
{
UnhookCommand(oldCommand);
}
if (newCommand != null)
{
HookCommand(newCommand);
}
}
private void UnhookCommand(ICommand command)
{
CanExecuteChangedEventManager.RemoveHandler(command, OnCanExecuteChanged);
UpdateCanExecute();
}
private void HookCommand(ICommand command)
{
CanExecuteChangedEventManager.AddHandler(command, OnCanExecuteChanged);
UpdateCanExecute();
}
private void OnCanExecuteChanged(object sender, EventArgs e)
{
UpdateCanExecute();
}
private void UpdateCanExecute()
{
if (Command != null)
{
CanExecute = MS.Internal.Commands.CommandHelpers.CanExecuteCommandSource(this);
}
else
{
CanExecute = true;
}
}
private bool CanExecute
{
get { return _canExecute; }
set
{
if (_canExecute != value)
{
_canExecute = value;
CoerceValue(IsEnabledProperty);
}
}
}
// Returns true when this Hyperlink is hosted by an enabled
// TextEditor (eg, within a RichTextBox).
private bool IsEditable
{
get
{
return (this.TextContainer.TextSelection != null &&
!this.TextContainer.TextSelection.TextEditor.IsReadOnly);
}
}
/// <summary>
/// Fetches the value of the IsEnabled property
/// </summary>
/// <remarks>
/// The reason this property is overridden is so that Hyperlink
/// can infuse the value for CanExecute into it.
/// </remarks>
protected override bool IsEnabledCore
{
get
{
return base.IsEnabledCore && CanExecute;
}
}
/// <summary>
/// The DependencyProperty for the CommandParameter
/// </summary>
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register(
"CommandParameter",
typeof(object),
typeof(Hyperlink),
new FrameworkPropertyMetadata((object)null));
/// <summary>
/// Reflects the parameter to pass to the CommandProperty upon execution.
/// </summary>
[Bindable(true), Category("Action")]
[Localizability(LocalizationCategory.NeverLocalize)]
public object CommandParameter
{
get
{
return GetValue(CommandParameterProperty);
}
set
{
SetValue(CommandParameterProperty, value);
}
}
/// <summary>
/// The DependencyProperty for Target property
/// Flags: None
/// Default Value: null
/// </summary>
public static readonly DependencyProperty CommandTargetProperty =
DependencyProperty.Register(
"CommandTarget",
typeof(IInputElement),
typeof(Hyperlink),
new FrameworkPropertyMetadata((IInputElement)null));
/// <summary>
/// The target element on which to fire the command.
/// </summary>
[Bindable(true), Category("Action")]
public IInputElement CommandTarget
{
get
{
return (IInputElement)GetValue(CommandTargetProperty);
}
set
{
SetValue(CommandTargetProperty, value);
}
}
#endregion
#endregion Public Methods
//--------------------------------------------------------------------
//
// Public Properties
//
//---------------------------------------------------------------------
#region Public Properties
/// <summary>
/// Contains the target URI to navigate when hyperlink is clicked
/// </summary>
[CommonDependencyProperty]
public static readonly DependencyProperty NavigateUriProperty =
DependencyProperty.Register(
"NavigateUri",
typeof(Uri),
typeof(Hyperlink),
new FrameworkPropertyMetadata(
(Uri)null,
new PropertyChangedCallback(OnNavigateUriChanged),
new CoerceValueCallback(CoerceNavigateUri)));
/// <summary>
/// Coerce value callback for NavigateUri.
/// </summary>
/// <param name="d">Element to coerce NavigateUri for.</param>
/// <param name="value">New value for NavigateUri.</param>
/// <returns>Coerced value.</returns>
/// <SecurityNote>
/// Critical: Implements part of the anti-spoofing feature.
/// TreatAsSafe: This method changes no state and returns no protected info.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal static object CoerceNavigateUri(DependencyObject d, object value)
{
//
// If the element for which NavigateUri is being changed is the protected element,
// we don't let the update go through. This cancels NavigateUri modifications in
// the critical period when the URI is shown on the status bar.
// An example attack:
// void hl_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
// {
// hl.NavigateUri = null;
// hl.DoClick();
// hl.NavigateUri = new Uri("http://www.evil.com");
// }
// (Or, instead of setting NavigateUri=null, add a handler for Hyperlink.RequestNavigateEvent and
// set e.Handled=true.)
//
if (s_criticalNavigateUriProtectee.Value == d.GetHashCode() && ShouldPreventUriSpoofing)
{
value = DependencyProperty.UnsetValue;
}
return value;
}
/// <summary>
/// Provide public access to NavigateUriProperty property. Content the URI to navigate.
/// </summary>
[Bindable(true), CustomCategory("Navigation")]
[Localizability(LocalizationCategory.Hyperlink)]
public Uri NavigateUri
{
get
{
return (Uri)GetValue(NavigateUriProperty);
}
set
{
SetValue(NavigateUriProperty, value);
}
}
/// <summary>
/// Contains the target window to navigate when hyperlink is clicked
/// </summary>
public static readonly DependencyProperty TargetNameProperty
= DependencyProperty.Register("TargetName", typeof(String), typeof(Hyperlink),
new FrameworkPropertyMetadata(string.Empty));
/// <summary>
/// Provide public access to TargetNameProperty property. The target window to navigate.
/// </summary>
[Bindable(true), CustomCategory("Navigation")]
[Localizability(
LocalizationCategory.None,
Modifiability = Modifiability.Unmodifiable)
]
public string TargetName
{
get
{
return (string)GetValue(TargetNameProperty);
}
set
{
SetValue(TargetNameProperty, value);
}
}
#endregion Public Properties
//--------------------------------------------------------------------
//
// Public Events
//
//---------------------------------------------------------------------
#region Public Events
// **
/// <summary>
/// Navigate Event
/// </summary>
public static readonly RoutedEvent RequestNavigateEvent = EventManager.RegisterRoutedEvent(
"RequestNavigate",
RoutingStrategy.Bubble,
typeof(RequestNavigateEventHandler),
typeof(Hyperlink));
/// <summary>
/// Add / Remove RequestNavigateEvent handler
/// </summary>
public event RequestNavigateEventHandler RequestNavigate
{
add
{
AddHandler(RequestNavigateEvent, value);
}
remove
{
RemoveHandler(RequestNavigateEvent, value);
}
}
/// <summary>
/// Event correspond to left mouse button click
/// </summary>
public static readonly RoutedEvent ClickEvent = System.Windows.Controls.Primitives.ButtonBase.ClickEvent.AddOwner(typeof(Hyperlink));
/// <summary>
/// Add / Remove ClickEvent handler
/// </summary>
[Category("Behavior")]
public event RoutedEventHandler Click { add { AddHandler(ClickEvent, value); } remove { RemoveHandler(ClickEvent, value); } }
/// <summary>
/// StatusBar event
/// </summary>
internal static readonly RoutedEvent RequestSetStatusBarEvent = EventManager.RegisterRoutedEvent(
"RequestSetStatusBar",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(Hyperlink));
#endregion Public Events
//--------------------------------------------------------------------
//
// Protected Methods
//
//---------------------------------------------------------------------
#region Protected Methods
/// <summary>
/// This is the method that responds to the MouseButtonEvent event.
/// </summary>
/// <param name="e">Event arguments</param>
/// <remarks>Kept around for backward compatibility in derived classes.</remarks>
protected internal override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
if (IsEnabled && (!IsEditable || ((Keyboard.Modifiers & ModifierKeys.Control) != 0)))
{
OnMouseLeftButtonDown(this, e);
}
}
/// <summary>
/// This is the method that responds to the MouseButtonEvent event.
/// </summary>
/// <param name="e">Event arguments</param>
/// <remarks>
/// Added for the NavigateUri = null case, which won't have event handlers hooked
/// up since OnNavigateUriChanged isn't ever called. However, we want to have the
/// sequence of commands and Click event triggered even in this case for Hyperlink.
/// </remarks>
/// <SecurityNote>
/// Critical - Calls critical static OnMouseLeftButtonUp.
/// </SecurityNote>
[SecurityCritical]
protected internal override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonUp(e);
OnMouseLeftButtonUp(this, e);
}
#region Spoofing prevention and status bar access
/// <summary>
/// Cached URI for spoofing countermeasures.
/// </summary>
/// <remarks>
/// We keep one per thread in case multiple threads would be involved in the spoofing attack.
/// </remarks>
/// <SecurityNote>
/// Critical for set - Changing the cached URI can open up for spoofing attacks.
/// </SecurityNote>
[ThreadStatic]
private static SecurityCriticalDataForSet<Uri> s_cachedNavigateUri;
/// <summary>
/// Identification code of the hyperlink element currently protected against spoofing attacks.
/// This code is checked during the NavigateUri coerce value callback in order to protect the
/// NavigateUri from changing during the critical period between showing the URI on the status
/// bar and clearing it, which is the timeframe where spoofing attacks can occur.
/// </summary>
/// <remarks>
/// We keep one per thread in case multiple threads would be involved in the spoofing attack.
/// </remarks>
/// <SecurityNote>
/// Critical for set - Changing the identification code will make the element vulnerable
/// for spoofing.
/// </SecurityNote>
[ThreadStatic]
private static SecurityCriticalDataForSet<int?> s_criticalNavigateUriProtectee;
/// <summary>
/// Caches a target URI for spoofing prevention.
/// </summary>
/// <param name="d">Hyperlink object for which the target URI is to be cached.</param>
/// <param name="targetUri">Target URI the user expects to be navigate to.</param>
/// <SecurityNote>
/// Critical - Sets the cached URI that prevents spoofing attacks.
/// </SecurityNote>
[SecurityCritical]
private static void CacheNavigateUri(DependencyObject d, Uri targetUri)
{
//
// This prevents against multi-threaded spoofing attacks.
//
d.VerifyAccess();
s_cachedNavigateUri.Value = targetUri;
}
/// <summary>
/// Navigates to the specified URI if it matches the pre-registered cached target URI (spoofing prevention).
/// </summary>
/// <param name="sourceElement">Source for the RequestNavigateEventArgs.</param>
/// <param name="targetUri">URI to navigate to.</param>
/// <param name="targetWindow">Target window for the RequestNavigateEventArgs.</param>
/// <SecurityNote>
/// Critical - Implements the anti-spoofing mechanism and clears the anti-spoofing cache after navigation took place.
/// TreatAsSafe - Navigation is considered safe; if the target is a browser window the UserInitiatedNavigationPermission will be demanded.
/// Only if navigation took place, the anti-spoofing cache will be cleared.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private static void NavigateToUri(IInputElement sourceElement, Uri targetUri, string targetWindow)
{
Debug.Assert(targetUri != null);
//
// This prevents against multi-threaded spoofing attacks.
//
DependencyObject dObj = (DependencyObject)sourceElement;
dObj.VerifyAccess();
//
// Spoofing countermeasure makes sure the URI hasn't changed since display in the status bar.
//
Uri cachedUri = Hyperlink.s_cachedNavigateUri.Value;
// ShouldPreventUriSpoofing is checked last in order to avoid incurring a first-chance SecurityException
// in common scenarios.
if (cachedUri == null || cachedUri.Equals(targetUri) || !ShouldPreventUriSpoofing)
{
//
// We treat FixedPage seperately to maintain backward compatibility
// with the original separate FixedPage implementation of this, which
// calls the GetLinkUri method.
if (!(sourceElement is Hyperlink))
{
targetUri = FixedPage.GetLinkUri(sourceElement, targetUri);
}
RequestNavigateEventArgs navigateArgs = new RequestNavigateEventArgs(targetUri, targetWindow);
navigateArgs.Source = sourceElement;
sourceElement.RaiseEvent(navigateArgs);
if (navigateArgs.Handled)
{
//
// The browser's status bar should be cleared. Otherwise it will still show the
// hyperlink address after navigation has completed.
// !! We have to do this after the current callstack is unwound in order to keep
// the anti-spoofing state valid. A particular attach is to do a bogus call to
// DoClick() in a mouse click preview event and then change the NavigateUri.
//
dObj.Dispatcher.BeginInvoke(DispatcherPriority.Send,
new System.Threading.SendOrPostCallback(ClearStatusBarAndCachedUri), sourceElement);
}
}
}
/// <summary>
/// Updates the status bar to reflect the current NavigateUri.
/// </summary>
/// <SecurityNote>
/// Critical - Sets the cached URI (CacheNavigateUri) and s_criticalNavigateUriProtectee
/// which prevent spoofing attacks.
/// Calls the critical RequestSetStatusBarEventArgs ctor.
/// </SecurityNote>
[SecurityCritical]
private static void UpdateStatusBar(object sender)
{
IInputElement element = (IInputElement)sender;
DependencyObject dObject = (DependencyObject)sender;
Uri targetUri = (Uri)dObject.GetValue(GetNavigateUriProperty(element));
//
// Keep the identification code for the element that's to be protected against spoofing
// attacks because its URI is shown on the status bar.
//
s_criticalNavigateUriProtectee.Value = dObject.GetHashCode();
//
// Cache URI for spoofing countermeasures.
//
CacheNavigateUri(dObject, targetUri);
RequestSetStatusBarEventArgs args = new RequestSetStatusBarEventArgs(targetUri);
element.RaiseEvent(args);
}
// The implementation of Hyperlink.NavigateUri and FixedPage.NavigateUri are unified,
// but the DPs themselves are not. FixedPage.NavigateUri is attached; Hyperlink.Navigate
// is a regular DP. Use this method to get the property DP based on the element.
private static DependencyProperty GetNavigateUriProperty(object element)
{
Hyperlink hl = element as Hyperlink;
return (hl == null) ? FixedPage.NavigateUriProperty : NavigateUriProperty;
}
/// <summary>
/// Clears the status bar.
/// </summary>
/// <SecurityNote>
/// Critical - Clears the cached URI and s_criticalNavigateUriProtectee which prevent
/// spoofing attacks.
/// Note: Upstream spoofing should be prevented (e.g. OnMouseLeave) because
/// clearing the identification code in s_criticalNavigateUriProtectee
/// will disable spoofing detection.
/// </SecurityNote>
[SecurityCritical]
private static void ClearStatusBarAndCachedUri(object sender)
{
IInputElement element = (IInputElement)sender;
//
// Clear the status bar first, from this point on we're not protecting against spoofing
// anymore.
//
element.RaiseEvent(RequestSetStatusBarEventArgs.Clear);
//
// Invalidate cache URI for spoofing countermeasures.
//
CacheNavigateUri((DependencyObject)sender, null);
//
// Clear the identification code for the element that was protected against spoofing.
//
s_criticalNavigateUriProtectee.Value = null;
}
#endregion
/// <summary>
/// Navigate to URI specified in NavigateUri property and mark the hyperlink as visited
/// </summary>
/// <remarks>
/// Some forms of navigation are not allowed in the internet zone.
/// As such there are cases where this API will demand for fulltrust.
///
/// This method is kept of backward compatibility and isn't a real event handler anymore.
/// It should remain in here however for subclasses that want to override it either to
/// redefine behavior or to get notified about the click event.
/// </remarks>
protected virtual void OnClick()
{
if (AutomationPeer.ListenerExists(AutomationEvents.InvokePatternOnInvoked))
{
AutomationPeer peer = ContentElementAutomationPeer.CreatePeerForElement(this);
if (peer != null)
peer.RaiseAutomationEvent(AutomationEvents.InvokePatternOnInvoked);
}
DoNavigation(this);
RaiseEvent(new RoutedEventArgs(Hyperlink.ClickEvent, this));
MS.Internal.Commands.CommandHelpers.ExecuteCommandSource(this);
}
/// <summary>
/// This is the method that responds to the KeyDown event.
/// </summary>
/// <remarks>
/// This method is kept for backward compatibility.
/// </remarks>
/// <SecurityNote>
/// Critical - Calls into static critical OnKeyDown method.
/// </SecurityNote>
[SecurityCritical]
protected internal override void OnKeyDown(KeyEventArgs e)
{
if (!e.Handled && e.Key == Key.Enter)
{
OnKeyDown(this, e);
}
else
{
base.OnKeyDown(e);
}
}
//
// This property
// 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject
// 2. This is a performance optimization
//
internal override int EffectiveValuesInitialSize
{
get { return 19; }
}
/// <summary>
/// Creates AutomationPeer (<see cref="ContentElement.OnCreateAutomationPeer"/>)
/// </summary>
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return new System.Windows.Automation.Peers.HyperlinkAutomationPeer(this);
}
#endregion Protected Methods
#region IUriContext implementation
/// <summary>
/// IUriContext interface is implemented by Hyperlink element so that it
/// can hold on to the base URI used by parser.
/// The base URI is needed to resolve NavigateUri property
/// </summary>
/// <value>Base Uri</value>
Uri IUriContext.BaseUri
{
get
{
return BaseUri;
}
set
{
BaseUri = value;
}
}
/// <summary>
/// Implementation for BaseUri
/// </summary>
protected virtual Uri BaseUri
{
get
{
return (Uri)GetValue(BaseUriHelper.BaseUriProperty);
}
set
{
SetValue(BaseUriHelper.BaseUriProperty, value);
}
}
#endregion IUriContext implementation
//--------------------------------------------------------------------
//
// Internal Properties
//
//---------------------------------------------------------------------
#region Internal Properties
/// <summary>
/// The content spanned by this Hyperlink represented as plain text.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
internal string Text
{
get
{
return TextRangeBase.GetTextInternal(this.ContentStart, this.ContentEnd);
}
}
#endregion Internal Properties
//--------------------------------------------------------------------
//
// Private Methods
//
//---------------------------------------------------------------------
#region Private Methods
// QueryCursorEvent callback.
// If this Hyperlink is editable, use the editor cursor unless
// the control key is down.
private static void OnQueryCursor(object sender, QueryCursorEventArgs e)
{
Hyperlink link = (Hyperlink)sender;
if (link.IsEnabled && link.IsEditable)
{
if ((Keyboard.Modifiers & ModifierKeys.Control) == 0)
{
e.Cursor = link.TextContainer.TextSelection.TextEditor._cursor;
e.Handled = true;
}
}
}
#endregion Private Methods
#region Private Properties
//--------------------------------------------------------------------
//
// Private Properties
//
//---------------------------------------------------------------------
/// <SecurityNote>
/// Critical: Sets s_shouldPreventUriSpoofing.
/// Not TreatAsSafe just to help prevent the remote possibility of calling this under elevation
/// from framework code, since the result of the Demand is cached.
/// </SecurityNote>
static bool ShouldPreventUriSpoofing
{
[SecurityCritical]
get
{
if (!s_shouldPreventUriSpoofing.Value.HasValue)
{
try
{
(new System.Net.WebPermission(PermissionState.Unrestricted)).Demand();
s_shouldPreventUriSpoofing.Value = false;
}
catch (SecurityException)
{
s_shouldPreventUriSpoofing.Value = true;
}
}
return (bool)s_shouldPreventUriSpoofing.Value;
}
}
static SecurityCriticalDataForSet<bool?> s_shouldPreventUriSpoofing;
#endregion Private Properties
//--------------------------------------------------------------------
//
// Private Fields
//
//---------------------------------------------------------------------
#region Private Fields
private bool _canExecute = true;
#endregion Private Fields
//--------------------------------------------------------------------
//
// Navigation control
//
//---------------------------------------------------------------------
#region Navigation control
/// <summary>
/// Records the IsPressed property attached to elements with hyperlink functionality.
/// </summary>
private static readonly DependencyProperty IsHyperlinkPressedProperty =
DependencyProperty.Register(
"IsHyperlinkPressed",
typeof(bool),
typeof(Hyperlink),
new FrameworkPropertyMetadata(false));
internal static void OnNavigateUriChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
IInputElement element = d as IInputElement;
//
// We only set up spoofing prevention for known objects that are IInputElements.
// However, for backward compatibility we shouldn't make this callback fail since
// other places such as FixedTextBuilder use NavigateUri e.g. for serialization.
//
if (element != null)
{
Uri navigateUri = (Uri)e.NewValue;
//
// We use a different code path for Path, Canvas, Glyphs and FixedPage to maintain backward compatibility
// with the original separate Hyperlink implementation of this (which didn't execute CanNavigateToUri).
//
if (navigateUri != null)
{
FrameworkElement fe = d as FrameworkElement;
if (fe != null && ((fe is Path) || (fe is Canvas) || (fe is Glyphs) || (fe is FixedPage)))
{
if (FixedPage.CanNavigateToUri(navigateUri))
{
SetUpNavigationEventHandlers(element);
fe.Cursor = Cursors.Hand;
}
else
{
fe.Cursor = Cursors.No;
}
}
else
{
FrameworkContentElement fce = d as FrameworkContentElement;
if (fce != null && (fce is Hyperlink))
{
SetUpNavigationEventHandlers(element);
}
}
}
}
}
/// <SecurityNote>
/// Critical - Hooks up event handlers that are responsible to set up anti-spoofing mitigations
/// and event handlers that are critical because of the risk for replay attacks.
/// TreatAsSafe - We're hooking up event handlers for trusted events from the input system.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private static void SetUpNavigationEventHandlers(IInputElement element)
{
//
// We only support FixedPage.NavigateUri to be attached to those four elements (aka pseudo-hyperlinks):
// Path, Canvas, Glyph, FixedPage.
//
// We can get away with the UIElement events event for the Hyperlink which is a ContentElement
// because of the aliasing present on those.
//
//
// Hyperlink already has instance handlers for the following events. To avoid handling the event twice,
// we only hook up the static handlers for pseudo-hyperlinks.
//
if (!(element is Hyperlink))
{
SetUpEventHandler(element, UIElement.KeyDownEvent, new KeyEventHandler(OnKeyDown)); //initiates navigation
SetUpEventHandler(element, UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(OnMouseLeftButtonDown)); //capture hyperlink pressed state
SetUpEventHandler(element, UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(OnMouseLeftButtonUp)); //can initiate navigation
}
SetUpEventHandler(element, UIElement.MouseEnterEvent, new MouseEventHandler(OnMouseEnter)); //set status bar
SetUpEventHandler(element, UIElement.MouseLeaveEvent, new MouseEventHandler(OnMouseLeave)); //clear status bar
}
private static void SetUpEventHandler(IInputElement element, RoutedEvent routedEvent, Delegate handler)
{
//
// Setting NavigateUri causes navigation event handlers to be set up.
// Doing this repeatedly would keep adding handlers; therefore remove any handler first.
//
element.RemoveHandler(routedEvent, handler);
element.AddHandler(routedEvent, handler);
}
/// <summary>
/// This is the method that responds to the KeyDown event.
/// </summary>
/// <SecurityNote>
/// Critical - Calls DoUserInitiatedNavigation. We also want to protect against replay attacks.
/// </SecurityNote>
[SecurityCritical]
private static void OnKeyDown(object sender, KeyEventArgs e)
{
if (!e.Handled && e.Key == Key.Enter)
{
//
// Keyboard navigation doesn't reveal the URL on the status bar, so there's no spoofing
// attack possible. We clear the cache here and allow navigation to go through.
//
CacheNavigateUri((DependencyObject)sender, null);
if (e.UserInitiated)
{
DoUserInitiatedNavigation(sender);
}
else
{
DoNonUserInitiatedNavigation(sender);
}
e.Handled = true;
}
}
/// <summary>
/// This is the method that responds to the MouseLeftButtonEvent event.
/// </summary>
private static void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
IInputElement element = (IInputElement)sender;
DependencyObject dp = (DependencyObject)sender;
// Hyperlink should take focus when left mouse button is clicked on it
// This is consistent with all ButtonBase controls and current Win32 behavior
element.Focus();
// It is possible that the mouse state could have changed during all of
// the call-outs that have happened so far.
if (e.ButtonState == MouseButtonState.Pressed)
{
// Capture the mouse, and make sure we got it.
Mouse.Capture(element);
if (element.IsMouseCaptured)
{
// Though we have already checked this state, our call to CaptureMouse
// could also end up changing the state, so we check it again.
//
// ISSUE - Leave this here because of 1111993.
//
if (e.ButtonState == MouseButtonState.Pressed)
{
dp.SetValue(IsHyperlinkPressedProperty, true);
}
else
{
// Release capture since we decided not to press the button.
element.ReleaseMouseCapture();
}
}
}
e.Handled = true;
}
/// <summary>
/// This is the method that responds to the MouseLeftButtonUpEvent event.
/// </summary>
/// <SecurityNote>
/// Critical - Calls DoUserInitiatedNavigation. We also want to protect against replay attacks
/// and can't assume the IsHyperlinkPressed DP hasn't been tampered with.
/// </SecurityNote>
[SecurityCritical]
private static void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
IInputElement element = (IInputElement)sender;
DependencyObject dp = (DependencyObject)sender;
if (element.IsMouseCaptured)
{
element.ReleaseMouseCapture();
}
//
// ISSUE - Leave this here because of 1111993.
//
if ((bool)dp.GetValue(IsHyperlinkPressedProperty))
{
dp.SetValue(IsHyperlinkPressedProperty, false);
// Make sure we're mousing up over the hyperlink
if (element.IsMouseOver)
{
if (e.UserInitiated)
{
DoUserInitiatedNavigation(sender);
}
else
{
DoNonUserInitiatedNavigation(sender);
}
}
}
e.Handled = true;
}
/// <summary>
/// Fire the event to change the status bar.
/// </summary>
/// <SecurityNote>
/// Critical - Calls UpdateStatusBar to set the cached URI that prevents spoofing attacks.
/// </SecurityNote>
[SecurityCritical]
private static void OnMouseEnter(object sender, MouseEventArgs e)
{
UpdateStatusBar(sender);
}
/// <summary>
/// Set the status bar text back to empty
/// </summary>
/// <SecurityNote>
/// Critical - Calls ClearStatusBarAndCachedUri to clear the cached URI that prevents spoofing attacks.
/// </SecurityNote>
[SecurityCritical]
private static void OnMouseLeave(object sender, MouseEventArgs e)
{
IInputElement ee = (IInputElement)sender;
//
// Prevent against replay attacks. We expect the mouse not to be over the
// element, otherwise someone tries to circumvent the spoofing countermeasures
// while we're in the critical period between OnMouseEnter and OnMouseLeave.
//
if (!ee.IsMouseOver)
{
ClearStatusBarAndCachedUri(sender);
}
}
/// <SecurityNote>
/// Critical - Asserts UserInitatedNavigationPermission.
/// </SecurityNote>
[SecurityCritical]
private static void DoUserInitiatedNavigation(object sender)
{
CodeAccessPermission perm = SecurityHelper.CreateUserInitiatedNavigationPermission();
perm.Assert();
try
{
DispatchNavigation(sender);
}
finally
{
CodeAccessPermission.RevertAssert();
}
}
/// <SecurityNote>
/// Critical - Sets the cached URI that prevents spoofing attacks.
/// TreatAsSafe - We don't prevent spoofing in non user-initiated scenarios.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private static void DoNonUserInitiatedNavigation(object sender)
{
CacheNavigateUri((DependencyObject)sender, null);
DispatchNavigation(sender);
}
/// <summary>
/// Dispatches navigation; if the object is a Hyperlink we go through OnClick
/// to preserve the original event chain, otherwise we call our DoNavigation
/// method.
/// </summary>
private static void DispatchNavigation(object sender)
{
Hyperlink hl = sender as Hyperlink;
if (hl != null)
{
//
// Call the virtual OnClick on Hyperlink to keep old behavior.
//
hl.OnClick();
}
else
{
DoNavigation(sender);
}
}
/// <summary>
/// Navigate to URI specified in the object's NavigateUri property.
/// </summary>
private static void DoNavigation(object sender)
{
IInputElement element = (IInputElement)sender;
DependencyObject dObject = (DependencyObject)sender;
Uri inputUri = (Uri)dObject.GetValue(GetNavigateUriProperty(element));
string targetWindow = (string)dObject.GetValue(TargetNameProperty);
RaiseNavigate(element, inputUri, targetWindow);
}
/// <summary>
/// Navigate to URI. Used by OnClick and by automation.
/// </summary>
/// <param name="sourceElement">Source for the RequestNavigateEventArgs.</param>
/// <param name="targetUri">URI to navigate to.</param>
/// <param name="targetWindow">Target window for the RequestNavigateEventArgs.</param>
internal static void RaiseNavigate(IInputElement element, Uri targetUri, string targetWindow)
{
//
// Do secure (spoofing countermeasures) navigation.
//
if (targetUri != null)
{
NavigateToUri(element, targetUri, targetWindow);
}
}
#endregion
#region DTypeThemeStyleKey
// Returns the DependencyObjectType for the registered ThemeStyleKey's default
// value. Controls will override this method to return approriate types.
internal override DependencyObjectType DTypeThemeStyleKey
{
get { return _dType; }
}
private static DependencyObjectType _dType;
#endregion DTypeThemeStyleKey
}
}
| |
// 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.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Hosting;
using Xunit;
namespace System.ComponentModel.Composition
{
public class AllowNonPublicCompositionTests
{
[Fact]
public void PublicFromPublic()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var importer = new AllPublicImportOnly();
batch.AddPart(importer);
batch.AddPart(new AllPublicExportOnly() { ExportA = 5, ExportB = 10 });
container.Compose(batch);
Assert.Equal(5, importer.ImportA);
Assert.Equal(10, importer.ImportB);
}
[Fact]
public void PublicToSelf()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var importer = new AllPublic() { ExportA = 5, ExportB = 10 };
batch.AddPart(importer);
container.Compose(batch);
Assert.Equal(5, importer.ImportA);
Assert.Equal(10, importer.ImportB);
}
[Fact]
public void PublicFromPrivate()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var importer = new AllPublicImportOnly();
batch.AddPart(importer);
batch.AddPart(new AllPrivateExportOnly(5, 10));
container.Compose(batch);
Assert.Equal(5, importer.ImportA);
Assert.Equal(10, importer.ImportB);
}
[Fact]
public void PrivateFromPublic()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var importer = new AllPrivateImportOnly();
batch.AddPart(importer);
batch.AddPart(new AllPublicExportOnly() { ExportA = 5, ExportB = 10 });
container.Compose(batch);
Assert.Equal(5, importer.PublicImportA);
Assert.Equal(10, importer.PublicImportB);
}
[Fact]
public void PrivateToSelf()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var importer = new AllPrivate(5, 10);
batch.AddPart(importer);
container.Compose(batch);
Assert.Equal(5, importer.PublicImportA);
Assert.Equal(10, importer.PublicImportB);
}
[Fact]
public void PrivateData()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var importer = new PrivateDataImportExport(5);
batch.AddPart(importer);
container.Compose(batch);
Assert.Equal(5, importer.X);
}
[Fact]
[ActiveIssue(25498)]
public void TestPublicImportsExpectingPublicExportsFromCatalog()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var container = new CompositionContainer(cat);
container.GetExportedValue<PublicImportsExpectingPublicExports>().VerifyIsBound();
}
[Fact]
[ActiveIssue(25498)]
public void TestInternalImportsExpectingPublicExportsFromCatalog()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var container = new CompositionContainer(cat);
container.GetExportedValue<InternalImportsExpectingPublicExports>().VerifyIsBound();
}
[Fact]
[ActiveIssue(25498)]
public void TestPublicImportsExpectingInternalExportsFromCatalog()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var container = new CompositionContainer(cat);
container.GetExportedValue<PublicImportsExpectingInternalExports>().VerifyIsBound();
}
[Fact]
[ActiveIssue(25498)]
public void TestInternalImportsExpectingInternalExportsFromCatalog()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var container = new CompositionContainer(cat);
container.GetExportedValue<InternalImportsExpectingInternalExports>().VerifyIsBound();
}
[Fact]
[ActiveIssue(25498)]
public void TestPublicImportsExpectingProtectedExportsFromCatalog()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var container = new CompositionContainer(cat);
container.GetExportedValue<PublicImportsExpectingProtectedExports>().VerifyIsBound();
}
[Fact]
[ActiveIssue(25498)]
public void TestInternalImportsExpectingProtectedExportsFromCatalog()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var container = new CompositionContainer(cat);
container.GetExportedValue<InternalImportsExpectingProtectedExports>().VerifyIsBound();
}
[Fact]
[ActiveIssue(25498)]
public void TestPublicImportsExpectingProtectedInternalExportsFromCatalog()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var container = new CompositionContainer(cat);
container.GetExportedValue<PublicImportsExpectingProtectedInternalExports>().VerifyIsBound();
}
[Fact]
[ActiveIssue(25498)]
public void TestInternalImportsExpectingProtectedInternalExportsFromCatalog()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var container = new CompositionContainer(cat);
container.GetExportedValue<InternalImportsExpectingProtectedInternalExports>().VerifyIsBound();
}
[Fact]
[ActiveIssue(25498)]
public void TestPublicImportsExpectingPrivateExportsFromCatalog()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var container = new CompositionContainer(cat);
container.GetExportedValue<PublicImportsExpectingPrivateExports>().VerifyIsBound();
}
[Fact]
[ActiveIssue(25498)]
public void TestInternalImportsExpectingPrivateExportsFromCatalog()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var container = new CompositionContainer(cat);
container.GetExportedValue<InternalImportsExpectingPrivateExports>().VerifyIsBound();
}
}
public interface IData { int X { get; set; } }
public class PrivateDataImportExportWithContract
{
public PrivateDataImportExportWithContract(int x)
{
Out = new PrivateDataType() { X = x };
}
public int X { get { return In.X; } }
[Export("a")]
PrivateDataType Out { get; set; }
[Import("a")]
IData In { get; set; }
}
public class PrivateDataImportExport
{
public PrivateDataImportExport(int x)
{
Out = new PrivateDataType() { X = x };
}
public int X { get { return In.X; } }
[Export]
PrivateDataType Out { get; set; }
[Import]
PrivateDataType In { get; set; }
}
class PrivateDataType
{
public int X { get; set; }
}
public class AllPrivateNoAttribute
{
public AllPrivateNoAttribute(int exportA, int exportB) { ExportA = exportA; ExportB = exportB; }
public int PublicImportA { get { return ImportA; } }
public int PublicImportB { get { return ImportB; } }
[Import("a")]
int ImportA { get; set; }
[Import("b")]
int ImportB { get; set; }
[Export("a")]
int ExportA { get; set; }
[Export("b")]
int ExportB { get; set; }
}
public class AllPrivateNoAttributeImportOnly
{
public int PublicImportA { get { return ImportA; } }
public int PublicImportB { get { return ImportB; } }
[Import("a")]
int ImportA { get; set; }
[Import("b")]
int ImportB { get; set; }
}
public class AllPrivate
{
public AllPrivate(int exportA, int exportB) { ExportA = exportA; ExportB = exportB; }
public int PublicImportA { get { return ImportA; } }
public int PublicImportB { get { return ImportB; } }
[Import("a")]
int ImportA { get; set; }
[Import("b")]
int ImportB { get; set; }
[Export("a")]
int ExportA { get; set; }
[Export("b")]
int ExportB { get; set; }
}
public class AllPrivateImportOnly
{
public int PublicImportA { get { return ImportA; } }
public int PublicImportB { get { return ImportB; } }
[Import("a")]
int ImportA { get; set; }
[Import("b")]
int ImportB { get; set; }
}
public class AllPrivateExportOnly
{
public AllPrivateExportOnly(int exportA, int exportB) { ExportA = exportA; ExportB = exportB; }
[Export("a")]
int ExportA { get; set; }
[Export("b")]
int ExportB { get; set; }
}
public class AllPublic
{
[Import("a")]
public int ImportA { get; set; }
[Import("b")]
public int ImportB { get; set; }
[Export("a")]
public int ExportA { get; set; }
[Export("b")]
public int ExportB { get; set; }
}
public class AllPublicImportOnly
{
[Import("a")]
public int ImportA { get; set; }
[Import("b")]
public int ImportB { get; set; }
}
public class AllPublicExportOnly
{
[Export("a")]
public int ExportA { get; set; }
[Export("b")]
public int ExportB { get; set; }
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Executor.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System.Diagnostics;
using System;
using System.ComponentModel;
using System.Text;
using System.Threading;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Runtime.InteropServices;
using System.CodeDom;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
/// <devdoc>
/// <para>
/// Provides command execution functions for the CodeDom compiler.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
public static class Executor {
// How long (in milliseconds) do we wait for the program to terminate
private const int ProcessTimeOut = 600000;
/// <devdoc>
/// <para>
/// Gets the runtime install directory.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static string GetRuntimeInstallDirectory() {
return RuntimeEnvironment.GetRuntimeDirectory();
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static FileStream CreateInheritedFile(string file) {
return new FileStream(file, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
}
/// <devdoc>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void ExecWait(string cmd, TempFileCollection tempFiles) {
string outputName = null;
string errorName = null;
ExecWaitWithCapture(cmd, tempFiles, ref outputName, ref errorName);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int ExecWaitWithCapture(string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) {
return ExecWaitWithCapture(null, cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int ExecWaitWithCapture(string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) {
return ExecWaitWithCapture(null, cmd, currentDir, tempFiles, ref outputName, ref errorName, null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int ExecWaitWithCapture(IntPtr userToken, string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) {
return ExecWaitWithCapture(new SafeUserTokenHandle(userToken, false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) {
return ExecWaitWithCapture(new SafeUserTokenHandle(userToken, false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static int ExecWaitWithCapture(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) {
int retValue = 0;
// Undo any current impersonation, call ExecWaitWithCaptureUnimpersonated, and reimpersonate
#if !FEATURE_PAL
// the extra try-catch is here to mitigate exception filter injection attacks.
try {
WindowsImpersonationContext impersonation = RevertImpersonation();
try {
#endif
// Execute the process
retValue = ExecWaitWithCaptureUnimpersonated(userToken, cmd, currentDir, tempFiles, ref outputName, ref errorName, trueCmdLine);
#if !FEATURE_PAL
} finally {
ReImpersonate(impersonation);
}
}
catch {
throw;
}
#endif
return retValue;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) {
IntSecurity.UnmanagedCode.Demand();
FileStream output;
FileStream error;
int retValue = 0;
if (outputName == null || outputName.Length == 0)
outputName = tempFiles.AddExtension("out");
if (errorName == null || errorName.Length == 0)
errorName = tempFiles.AddExtension("err");
// Create the files
output = CreateInheritedFile(outputName);
error = CreateInheritedFile(errorName);
bool success = false;
SafeNativeMethods.PROCESS_INFORMATION pi = new SafeNativeMethods.PROCESS_INFORMATION();
SafeProcessHandle procSH = new SafeProcessHandle();
SafeThreadHandle threadSH = new SafeThreadHandle();
SafeUserTokenHandle primaryToken = null;
try {
// Output the command line...
StreamWriter sw = new StreamWriter(output, Encoding.UTF8);
sw.Write(currentDir);
sw.Write("> ");
// 'true' command line is used in case the command line points to
// a response file
sw.WriteLine(trueCmdLine != null ? trueCmdLine : cmd);
sw.WriteLine();
sw.WriteLine();
sw.Flush();
NativeMethods.STARTUPINFO si = new NativeMethods.STARTUPINFO();
si.cb = Marshal.SizeOf(si);
#if FEATURE_PAL
si.dwFlags = NativeMethods.STARTF_USESTDHANDLES;
#else //!FEATURE_PAL
si.dwFlags = NativeMethods.STARTF_USESTDHANDLES | NativeMethods.STARTF_USESHOWWINDOW;
si.wShowWindow = NativeMethods.SW_HIDE;
#endif //!FEATURE_PAL
si.hStdOutput = output.SafeFileHandle;
si.hStdError = error.SafeFileHandle;
si.hStdInput = new SafeFileHandle(UnsafeNativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), false);
//
// Prepare the environment
//
#if PLATFORM_UNIX
StringDictionary environment = new CaseSensitiveStringDictionary();
#else
StringDictionary environment = new StringDictionary ();
#endif // PLATFORM_UNIX
// Add the current environment
foreach ( DictionaryEntry entry in Environment.GetEnvironmentVariables () )
environment[(string) entry.Key] = (string) entry.Value;
// Add the flag to indicate restricted security in the process
environment["_ClrRestrictSecAttributes"] = "1";
#if DEBUG
environment["OANOCACHE"] = "1";
#endif
// set up the environment block parameter
byte[] environmentBytes = EnvironmentBlock.ToByteArray(environment, false);
fixed (byte* environmentBytesPtr = environmentBytes) {
IntPtr environmentPtr = new IntPtr((void*)environmentBytesPtr);
if (userToken == null || userToken.IsInvalid) {
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
success = NativeMethods.CreateProcess(
null, // String lpApplicationName,
new StringBuilder(cmd), // String lpCommandLine,
null, // SECURITY_ATTRIBUTES lpProcessAttributes,
null, // SECURITY_ATTRIBUTES lpThreadAttributes,
true, // bool bInheritHandles,
0, // int dwCreationFlags,
environmentPtr, // IntPtr lpEnvironment,
currentDir, // String lpCurrentDirectory,
si, // STARTUPINFO lpStartupInfo,
pi); // PROCESS_INFORMATION lpProcessInformation);
if ( pi.hProcess!= (IntPtr)0 && pi.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
procSH.InitialSetHandle(pi.hProcess);
if ( pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
threadSH.InitialSetHandle(pi.hThread);
}
}
else {
#if FEATURE_PAL
throw new NotSupportedException();
#else
success = SafeUserTokenHandle.DuplicateTokenEx(
userToken,
NativeMethods.TOKEN_ALL_ACCESS,
null,
NativeMethods.IMPERSONATION_LEVEL_SecurityImpersonation,
NativeMethods.TOKEN_TYPE_TokenPrimary,
out primaryToken
);
if (success) {
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
success = NativeMethods.CreateProcessAsUser(
primaryToken, // int token,
null, // String lpApplicationName,
cmd, // String lpCommandLine,
null, // SECURITY_ATTRIBUTES lpProcessAttributes,
null, // SECURITY_ATTRIBUTES lpThreadAttributes,
true, // bool bInheritHandles,
0, // int dwCreationFlags,
new HandleRef(null, environmentPtr), // IntPtr lpEnvironment,
currentDir, // String lpCurrentDirectory,
si, // STARTUPINFO lpStartupInfo,
pi); // PROCESS_INFORMATION lpProcessInformation);
if ( pi.hProcess!= (IntPtr)0 && pi.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
procSH.InitialSetHandle(pi.hProcess);
if ( pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
threadSH.InitialSetHandle(pi.hThread);
}
}
#endif // !FEATURE_PAL
}
}
}
finally {
// Close the file handles
if (!success && (primaryToken != null && !primaryToken.IsInvalid)) {
primaryToken.Close();
primaryToken = null;
}
output.Close();
error.Close();
}
if (success) {
try {
bool signaled;
ProcessWaitHandle pwh = null;
try {
pwh = new ProcessWaitHandle(procSH);
signaled = pwh.WaitOne(ProcessTimeOut, false);
} finally {
if (pwh != null)
pwh.Close();
}
// Check for timeout
if (!signaled) {
throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT);
}
// Check the process's exit code
int status = NativeMethods.STILL_ACTIVE;
if (!NativeMethods.GetExitCodeProcess(procSH, out status)) {
throw new ExternalException(SR.GetString(SR.ExecCantGetRetCode, cmd), Marshal.GetLastWin32Error());
}
retValue = status;
}
finally {
procSH.Close();
threadSH.Close();
if (primaryToken != null && !primaryToken.IsInvalid)
primaryToken.Close();
}
}
else {
int err = Marshal.GetLastWin32Error();
if (err == NativeMethods.ERROR_NOT_ENOUGH_MEMORY)
throw new OutOfMemoryException();
Win32Exception win32Exception = new Win32Exception(err);
ExternalException ex = new ExternalException(SR.GetString(SR.ExecCantExec, cmd), win32Exception);
throw ex;
}
return retValue;
}
#if !FEATURE_PAL
[PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
[SecurityPermission(SecurityAction.Assert, ControlPrincipal = true, UnmanagedCode = true)]
internal static WindowsImpersonationContext RevertImpersonation() {
return WindowsIdentity.Impersonate(new IntPtr(0));
}
#endif // !FEATURE_PAL
#if !FEATURE_PAL
internal static void ReImpersonate(WindowsImpersonationContext impersonation){
impersonation.Undo();
}
#endif // !FEATURE_PAL
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections;
using System.Collections.Specialized;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;
using System.Windows.Data;
using System.Windows.Automation.Peers;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;
using System.Windows.Shapes;
using MS.Utility;
using MS.Internal.KnownBoxes;
namespace System.Windows.Controls
{
/// <summary>
/// A control to display information when the user hovers over a control
/// </summary>
[DefaultEvent("Opened")]
[Localizability(LocalizationCategory.ToolTip)]
public class ToolTip : ContentControl
{
#region Constructors
static ToolTip()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ToolTip), new FrameworkPropertyMetadata(typeof(ToolTip)));
_dType = DependencyObjectType.FromSystemTypeInternal(typeof(ToolTip));
BackgroundProperty.OverrideMetadata(typeof(ToolTip), new FrameworkPropertyMetadata(SystemColors.InfoBrush));
FocusableProperty.OverrideMetadata(typeof(ToolTip), new FrameworkPropertyMetadata(false));
}
/// <summary>
/// Creates a default ToolTip
/// </summary>
public ToolTip() : base()
{
}
#endregion
#region Public Properties
/// <summary>
/// The DependencyProperty for the HorizontalOffset property.
/// Default: Length(0.0)
/// </summary>
public static readonly DependencyProperty HorizontalOffsetProperty =
ToolTipService.HorizontalOffsetProperty.AddOwner(typeof(ToolTip),
new FrameworkPropertyMetadata(null,
new CoerceValueCallback(CoerceHorizontalOffset)));
private static object CoerceHorizontalOffset(DependencyObject d, object value)
{
return PopupControlService.CoerceProperty(d, value, ToolTipService.HorizontalOffsetProperty);
}
/// <summary>
/// Horizontal offset from the default location when this ToolTIp is displayed
/// </summary>
[TypeConverter(typeof(LengthConverter))]
[Bindable(true), Category("Layout")]
public double HorizontalOffset
{
get
{
return (double)GetValue(HorizontalOffsetProperty);
}
set
{
SetValue(HorizontalOffsetProperty, value);
}
}
/// <summary>
/// The DependencyProperty for the VerticalOffset property.
/// Default: Length(0.0)
/// </summary>
public static readonly DependencyProperty VerticalOffsetProperty =
ToolTipService.VerticalOffsetProperty.AddOwner(typeof(ToolTip),
new FrameworkPropertyMetadata(null,
new CoerceValueCallback(CoerceVerticalOffset)));
private static object CoerceVerticalOffset(DependencyObject d, object value)
{
return PopupControlService.CoerceProperty(d, value, ToolTipService.VerticalOffsetProperty);
}
/// <summary>
/// Vertical offset from the default location when this ToolTip is displayed
/// </summary>
[TypeConverter(typeof(LengthConverter))]
[Bindable(true), Category("Layout")]
public double VerticalOffset
{
get
{
return (double)GetValue(VerticalOffsetProperty);
}
set
{
SetValue(VerticalOffsetProperty, value);
}
}
/// <summary>
/// DependencyProperty for the IsOpen property
/// Default value: false
/// </summary>
public static readonly DependencyProperty IsOpenProperty =
DependencyProperty.Register(
"IsOpen",
typeof(bool),
typeof(ToolTip),
new FrameworkPropertyMetadata(
false,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(OnIsOpenChanged)));
private static void OnIsOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ToolTip t = (ToolTip) d;
if ((bool)e.NewValue)
{
if (t._parentPopup == null)
{
t.HookupParentPopup();
}
}
else
{
// When ToolTip is about to close but still hooked up - we need to raise Accessibility event
if (AutomationPeer.ListenerExists(AutomationEvents.ToolTipClosed))
{
AutomationPeer peer = UIElementAutomationPeer.CreatePeerForElement(t);
if (peer != null)
peer.RaiseAutomationEvent(AutomationEvents.ToolTipClosed);
}
}
OnVisualStatePropertyChanged(d, e);
}
/// <summary>
/// Whether or not this ToolTip is visible
/// </summary>
[Bindable(true), Browsable(false), Category("Appearance")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsOpen
{
get { return (bool) GetValue(IsOpenProperty); }
set { SetValue(IsOpenProperty, value); }
}
/// <summary>
/// The DependencyProperty for HasDropShadow
/// </summary>
public static readonly DependencyProperty HasDropShadowProperty =
ToolTipService.HasDropShadowProperty.AddOwner(
typeof(ToolTip),
new FrameworkPropertyMetadata(null,
new CoerceValueCallback(CoerceHasDropShadow)));
private static object CoerceHasDropShadow(DependencyObject d, object value)
{
ToolTip tt = (ToolTip)d;
if (tt._parentPopup == null || !tt._parentPopup.AllowsTransparency || !SystemParameters.DropShadow)
{
return BooleanBoxes.FalseBox;
}
return PopupControlService.CoerceProperty(d, value, ToolTipService.HasDropShadowProperty);
}
/// <summary>
/// Whether the control has a drop shadow.
/// </summary>
public bool HasDropShadow
{
get { return (bool)GetValue(HasDropShadowProperty); }
set { SetValue(HasDropShadowProperty, value); }
}
/// <summary>
/// The DependencyProperty for the PlacementTarget property
/// Default value: null
/// </summary>
public static readonly DependencyProperty PlacementTargetProperty =
ToolTipService.PlacementTargetProperty.AddOwner(typeof(ToolTip),
new FrameworkPropertyMetadata(null,
new CoerceValueCallback(CoercePlacementTarget)));
private static object CoercePlacementTarget(DependencyObject d, object value)
{
return PopupControlService.CoerceProperty(d, value, ToolTipService.PlacementTargetProperty);
}
/// <summary>
/// The UIElement relative to which this ToolTip will be displayed.
/// </summary>
[Bindable(true), Category("Layout")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public UIElement PlacementTarget
{
get { return (UIElement) GetValue(PlacementTargetProperty); }
set { SetValue(PlacementTargetProperty, value); }
}
/// <summary>
/// The DependencyProperty for the PlacementRectangle property.
/// </summary>
public static readonly DependencyProperty PlacementRectangleProperty =
ToolTipService.PlacementRectangleProperty.AddOwner(typeof(ToolTip),
new FrameworkPropertyMetadata(null,
new CoerceValueCallback(CoercePlacementRectangle)));
private static object CoercePlacementRectangle(DependencyObject d, object value)
{
return PopupControlService.CoerceProperty(d, value, ToolTipService.PlacementRectangleProperty);
}
/// <summary>
/// Get or set PlacementRectangle property of the ToolTip
/// </summary>
[Bindable(true), Category("Layout")]
public Rect PlacementRectangle
{
get { return (Rect) GetValue(PlacementRectangleProperty); }
set { SetValue(PlacementRectangleProperty, value); }
}
/// <summary>
/// The DependencyProperty for the Placement property
/// Default value: null
/// </summary>
public static readonly DependencyProperty PlacementProperty =
ToolTipService.PlacementProperty.AddOwner(typeof(ToolTip),
new FrameworkPropertyMetadata(null,
new CoerceValueCallback(CoercePlacement)));
private static object CoercePlacement(DependencyObject d, object value)
{
return PopupControlService.CoerceProperty(d, value, ToolTipService.PlacementProperty);
}
/// <summary>
/// Chooses the behavior of where the Popup should be placed on screen.
/// </summary>
[Bindable(true), Category("Layout")]
public PlacementMode Placement
{
get { return (PlacementMode) GetValue(PlacementProperty); }
set { SetValue(PlacementProperty, value); }
}
/// <summary>
/// The DependencyProperty for the CustomPopupPlacementCallback property.
/// Flags: None
/// Default Value: null
/// </summary>
public static readonly DependencyProperty CustomPopupPlacementCallbackProperty =
Popup.CustomPopupPlacementCallbackProperty.AddOwner(typeof(ToolTip));
/// <summary>
/// Chooses the behavior of where the Popup should be placed on screen.
/// </summary>
[Bindable(false), Category("Layout")]
public CustomPopupPlacementCallback CustomPopupPlacementCallback
{
get { return (CustomPopupPlacementCallback) GetValue(CustomPopupPlacementCallbackProperty); }
set { SetValue(CustomPopupPlacementCallbackProperty, value); }
}
/// <summary>
/// The DependencyProperty for the StaysOpen property.
/// When false, the tool tip will close on the next mouse click
/// Flags: None
/// Default Value: true
/// </summary>
public static readonly DependencyProperty StaysOpenProperty =
Popup.StaysOpenProperty.AddOwner(typeof(ToolTip));
/// <summary>
/// Chooses the behavior of when the Popup should automatically close.
/// </summary>
[Bindable(true), Category("Behavior")]
public bool StaysOpen
{
get { return (bool) GetValue(StaysOpenProperty); }
set { SetValue(StaysOpenProperty, value); }
}
#endregion
#region Public Events
/// <summary>
/// Opened event
/// </summary>
public static readonly RoutedEvent OpenedEvent =
EventManager.RegisterRoutedEvent("Opened", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ToolTip));
/// <summary>
/// Add/Remove event handler for Opened event
/// </summary>
/// <value></value>
public event RoutedEventHandler Opened
{
add
{
AddHandler(OpenedEvent, value);
}
remove
{
RemoveHandler(OpenedEvent, value);
}
}
/// <summary>
/// Called when the Tooltip is opened. Also raises the OpenedEvent.
/// </summary>
/// <param name="e">Generic routed event arguments.</param>
protected virtual void OnOpened(RoutedEventArgs e)
{
RaiseEvent(e);
}
/// <summary>
/// Closed event
/// </summary>
public static readonly RoutedEvent ClosedEvent =
EventManager.RegisterRoutedEvent("Closed", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ToolTip));
/// <summary>
/// Add/Remove event handler for Closed event
/// </summary>
/// <value></value>
public event RoutedEventHandler Closed
{
add
{
AddHandler(ClosedEvent, value);
}
remove
{
RemoveHandler(ClosedEvent, value);
}
}
/// <summary>
/// Called when the ToolTip is closed. Also raises the ClosedEvent.
/// </summary>
/// <param name="e">Generic routed event arguments.</param>
protected virtual void OnClosed(RoutedEventArgs e)
{
RaiseEvent(e);
}
#endregion
#region Protected Methods
/// <summary>
/// Change to the correct visual state for the ButtonBase.
/// </summary>
/// <param name="useTransitions">
/// true to use transitions when updating the visual state, false to
/// snap directly to the new visual state.
/// </param>
internal override void ChangeVisualState(bool useTransitions)
{
if (IsOpen)
{
VisualStateManager.GoToState(this, VisualStates.StateOpen, useTransitions);
}
else
{
VisualStateManager.GoToState(this, VisualStates.StateClosed, useTransitions);
}
base.ChangeVisualState(useTransitions);
}
/// <summary>
/// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>)
/// </summary>
protected override AutomationPeer OnCreateAutomationPeer()
{
return new ToolTipAutomationPeer(this);
}
/// <summary>
/// Called when this element's visual parent changes
/// </summary>
/// <param name="oldParent"></param>
protected internal override void OnVisualParentChanged(DependencyObject oldParent)
{
base.OnVisualParentChanged(oldParent);
if (!Popup.IsRootedInPopup(_parentPopup, this))
{
throw new InvalidOperationException(SR.Get(SRID.ElementMustBeInPopup, "ToolTip"));
}
}
internal override void OnAncestorChanged()
{
base.OnAncestorChanged();
if (!Popup.IsRootedInPopup(_parentPopup, this))
{
throw new InvalidOperationException(SR.Get(SRID.ElementMustBeInPopup, "ToolTip"));
}
}
#endregion
#region Private Methods
protected override void OnContentChanged(object oldContent, object newContent)
{
PopupControlService popupControlService = PopupControlService.Current;
// Whenever the tooltip for a control is not an instance of a ToolTip, the framework creates a wrapper
// ToolTip instance. Such a ToolTip is tagged ServiceOwned and its Content property is bound to the
// ToolTipProperty of the Owner element. So while such a ServiceOwned ToolTip is visible if the
// ToolTipProperty on the Owner changes to be a real ToolTip instance then it causes a crash
// complaining that the ServiceOwned ToolTip is wrapping another nested ToolTip. The condition here
// detects this case and merely dismisses the old ToolTip and displays the new ToolTip instead thus
// avoiding the use of a wrapper ToolTip.
if (this == popupControlService.CurrentToolTip &&
(bool)GetValue(PopupControlService.ServiceOwnedProperty) &&
newContent is ToolTip)
{
popupControlService.OnRaiseToolTipClosingEvent(null, EventArgs.Empty);
popupControlService.OnRaiseToolTipOpeningEvent(null, EventArgs.Empty);
}
else
{
base.OnContentChanged(oldContent, newContent);
}
}
private void HookupParentPopup()
{
Debug.Assert(_parentPopup == null, "_parentPopup should be null");
_parentPopup = new Popup();
_parentPopup.AllowsTransparency = true;
// When StaysOpen is true (default), make the popup window WS_EX_Transparent
// to allow mouse input to go through the tooltip
_parentPopup.HitTestable = !StaysOpen;
// Coerce HasDropShadow property in case popup can't be transparent
CoerceValue(HasDropShadowProperty);
// Listening to the Opened and Closed events lets us guarantee that
// the popup is actually opened when we perform those functions.
_parentPopup.Opened += new EventHandler(OnPopupOpened);
_parentPopup.Closed += new EventHandler(OnPopupClosed);
_parentPopup.PopupCouldClose += new EventHandler(OnPopupCouldClose);
_parentPopup.SetResourceReference(Popup.PopupAnimationProperty, SystemParameters.ToolTipPopupAnimationKey);
// Hooks up the popup properties from this menu to the popup so that
// setting them on this control will also set them on the popup.
Popup.CreateRootPopup(_parentPopup, this);
}
internal void ForceClose()
{
if (_parentPopup != null)
{
_parentPopup.ForceClose();
}
}
private void OnPopupCouldClose(object sender, EventArgs e)
{
SetCurrentValueInternal(IsOpenProperty, BooleanBoxes.FalseBox);
}
private void OnPopupOpened(object source, EventArgs e)
{
// Raise Accessibility event
if (AutomationPeer.ListenerExists(AutomationEvents.ToolTipOpened))
{
AutomationPeer peer = UIElementAutomationPeer.CreatePeerForElement(this);
if (peer != null)
{
// We raise the event async to allow PopupRoot to hookup
Dispatcher.BeginInvoke(DispatcherPriority.Input, new DispatcherOperationCallback(delegate(object param)
{
peer.RaiseAutomationEvent(AutomationEvents.ToolTipOpened);
return null;
}), null);
}
}
OnOpened(new RoutedEventArgs(OpenedEvent, this));
}
private void OnPopupClosed(object source, EventArgs e)
{
OnClosed(new RoutedEventArgs(ClosedEvent, this));
}
#endregion
#region Data
private Popup _parentPopup;
#endregion
#region DTypeThemeStyleKey
// Returns the DependencyObjectType for the registered ThemeStyleKey's default
// value. Controls will override this method to return approriate types.
internal override DependencyObjectType DTypeThemeStyleKey
{
get { return _dType; }
}
private static DependencyObjectType _dType;
#endregion DTypeThemeStyleKey
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedViewAccessor.
/// </summary>
public class MemoryMappedViewAccessorTests : MemoryMappedFilesTestBase
{
/// <summary>
/// Test to validate the offset, size, and access parameters to MemoryMappedFile.CreateViewAccessor.
/// </summary>
[Fact]
public void InvalidArguments()
{
int mapLength = s_pageSize.Value;
foreach (MemoryMappedFile mmf in CreateSampleMaps(mapLength))
{
using (mmf)
{
// Offset
Assert.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewAccessor(-1, mapLength));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewAccessor(-1, mapLength, MemoryMappedFileAccess.ReadWrite));
// Size
Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, -1));
Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, -1, MemoryMappedFileAccess.ReadWrite));
if (IntPtr.Size == 4)
{
Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, 1 + (long)uint.MaxValue));
Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, 1 + (long)uint.MaxValue, MemoryMappedFileAccess.ReadWrite));
}
// Offset + Size
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, mapLength + 1));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, mapLength + 1, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(mapLength, 1));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(mapLength, 1, MemoryMappedFileAccess.ReadWrite));
// Access
Assert.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewAccessor(0, mapLength, (MemoryMappedFileAccess)(-1)));
Assert.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewAccessor(0, mapLength, (MemoryMappedFileAccess)(42)));
}
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void ValidAccessLevelCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity, viewAccess))
{
ValidateMemoryMappedViewAccessor(acc, Capacity, viewAccess);
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
public void InvalidAccessLevelsCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, Capacity, viewAccess));
}
}
/// <summary>
/// Test to verify the accessor's PointerOffset.
/// </summary>
[Fact]
public void PointerOffsetMatchesViewStart()
{
const int MapLength = 4096;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor())
{
Assert.Equal(0, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength))
{
Assert.Equal(0, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(1, MapLength - 1))
{
Assert.Equal(1, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(MapLength - 1, 1))
{
Assert.Equal(MapLength - 1, acc.PointerOffset);
}
// On Unix creating a view of size zero will result in an offset and capacity
// of 0 due to mmap behavior, whereas on Windows it's possible to create a
// zero-size view anywhere in the created file mapping.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(MapLength, 0))
{
Assert.Equal(
Interop.IsWindows ? MapLength : 0,
acc.PointerOffset);
}
}
}
}
/// <summary>
/// Test all of the Read/Write accessor methods against a variety of maps and accessors.
/// </summary>
[Theory]
[InlineData(0, 8192)]
[InlineData(8100, 92)]
[InlineData(0, 20)]
[InlineData(1, 8191)]
[InlineData(17, 8175)]
[InlineData(17, 20)]
public void AllReadWriteMethods(long offset, long size)
{
foreach (MemoryMappedFile mmf in CreateSampleMaps(8192))
{
using (mmf)
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(offset, size))
{
AssertWritesReads(acc);
}
}
}
/// <summary>Performs many reads and writes of various data types against the accessor.</summary>
private static unsafe void AssertWritesReads(MemoryMappedViewAccessor acc) // TODO: unsafe can be removed once using C# 6 compiler
{
// Successful reads and writes at the beginning for each data type
AssertWriteRead<bool>(false, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<bool>(true, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<byte>(42, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos));
AssertWriteRead<char>('c', 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos));
AssertWriteRead<decimal>(9, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos));
AssertWriteRead<double>(10, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos));
AssertWriteRead<short>(11, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos));
AssertWriteRead<int>(12, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos));
AssertWriteRead<long>(13, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos));
AssertWriteRead<sbyte>(14, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos));
AssertWriteRead<float>(15, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos));
AssertWriteRead<ushort>(16, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos));
AssertWriteRead<uint>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos));
AssertWriteRead<ulong>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos));
// Successful reads and writes at the end for each data type
long end = acc.Capacity;
AssertWriteRead<bool>(false, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<bool>(true, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<byte>(42, end - sizeof(byte), (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos));
AssertWriteRead<char>('c', end - sizeof(char), (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos));
AssertWriteRead<decimal>(9, end - sizeof(decimal), (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos));
AssertWriteRead<double>(10, end - sizeof(double), (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos));
AssertWriteRead<short>(11, end - sizeof(short), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos));
AssertWriteRead<int>(12, end - sizeof(int), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos));
AssertWriteRead<long>(13, end - sizeof(long), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos));
AssertWriteRead<sbyte>(14, end - sizeof(sbyte), (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos));
AssertWriteRead<float>(15, end - sizeof(float), (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos));
AssertWriteRead<ushort>(16, end - sizeof(ushort), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos));
AssertWriteRead<uint>(17, end - sizeof(uint), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos));
AssertWriteRead<ulong>(17, end - sizeof(ulong), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos));
// Failed reads and writes just at the border of the end. This triggers different exception types
// for some types than when we're completely beyond the end.
long beyondEnd = acc.Capacity + 1;
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte)));
Assert.Throws<ArgumentException>("position", () => acc.ReadChar(beyondEnd - sizeof(char)));
Assert.Throws<ArgumentException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal)));
Assert.Throws<ArgumentException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double)));
Assert.Throws<ArgumentException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short)));
Assert.Throws<ArgumentException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int)));
Assert.Throws<ArgumentException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long)));
Assert.Throws<ArgumentException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float)));
Assert.Throws<ArgumentException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort)));
Assert.Throws<ArgumentException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint)));
Assert.Throws<ArgumentException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c'));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0));
// Failed reads and writes well past the end
beyondEnd = acc.Capacity + 20;
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadChar(beyondEnd - sizeof(char)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c'));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0));
}
/// <summary>Performs and verifies a read and write against an accessor.</summary>
/// <typeparam name="T">The type of data being read and written.</typeparam>
/// <param name="expected">The data expected to be read.</param>
/// <param name="position">The position of the read and write.</param>
/// <param name="write">The function to perform the write, handed the position at which to write and the value to write.</param>
/// <param name="read">The function to perform the read, handed the position from which to read and returning the read value.</param>
private static void AssertWriteRead<T>(T expected, long position, Action<long, T> write, Func<long, T> read)
{
write(position, expected);
Assert.Equal(expected, read(position));
}
/// <summary>
/// Test to verify that Flush is supported regardless of the accessor's access level
/// </summary>
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite)]
public void FlushSupportedOnBothReadAndWriteAccessors(MemoryMappedFileAccess access)
{
const int Capacity = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(Capacity))
{
using (mmf)
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity, access))
{
acc.Flush();
}
}
}
/// <summary>
/// Test to validate that multiple accessors over the same map share data appropriately.
/// </summary>
[Fact]
public void ViewsShareData()
{
const int MapLength = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
// Create two views over the same map, and verify that data
// written to one is readable by the other.
using (MemoryMappedViewAccessor acc1 = mmf.CreateViewAccessor())
using (MemoryMappedViewAccessor acc2 = mmf.CreateViewAccessor())
{
for (int i = 0; i < MapLength; i++)
{
acc1.Write(i, (byte)i);
}
acc1.Flush();
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, acc2.ReadByte(i));
}
}
// Then verify that after those views have been disposed of,
// we can create another view and still read the same data.
using (MemoryMappedViewAccessor acc3 = mmf.CreateViewAccessor())
{
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, acc3.ReadByte(i));
}
}
// Finally, make sure such data is also visible to a stream view
// created subsequently from the same map.
using (MemoryMappedViewStream stream4 = mmf.CreateViewStream())
{
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, stream4.ReadByte());
}
}
}
}
}
/// <summary>
/// Test to verify copy-on-write behavior of accessors.
/// </summary>
[Fact]
public void CopyOnWrite()
{
const int MapLength = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
// Create a normal view, make sure the original data is there, then write some new data.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.ReadWrite))
{
Assert.Equal(0, acc.ReadInt32(0));
acc.Write(0, 42);
}
// In a CopyOnWrite view, verify the previously written data is there, then write some new data
// and verify it's visible through this view.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.CopyOnWrite))
{
Assert.Equal(42, acc.ReadInt32(0));
acc.Write(0, 84);
Assert.Equal(84, acc.ReadInt32(0));
}
// Finally, verify that the CopyOnWrite data is not visible to others using the map.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.Read))
{
Assert.Equal(42, acc.ReadInt32(0));
}
}
}
}
/// <summary>
/// Test to verify that we can dispose of an accessor multiple times.
/// </summary>
[Fact]
public void DisposeMultipleTimes()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
{
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
acc.Dispose();
acc.Dispose();
}
}
}
/// <summary>
/// Test to verify that a view becomes unusable after it's been disposed.
/// </summary>
[Fact]
public void InvalidAfterDisposal()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
{
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
SafeMemoryMappedViewHandle handle = acc.SafeMemoryMappedViewHandle;
Assert.False(handle.IsClosed);
acc.Dispose();
Assert.True(handle.IsClosed);
Assert.Throws<ObjectDisposedException>(() => acc.ReadByte(0));
Assert.Throws<ObjectDisposedException>(() => acc.Write(0, (byte)0));
Assert.Throws<ObjectDisposedException>(() => acc.Flush());
}
}
}
/// <summary>
/// Test to verify that we can still use a view after the associated map has been disposed.
/// </summary>
[Fact]
public void UseAfterMMFDisposal()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps(8192))
{
// Create the view, then dispose of the map
MemoryMappedViewAccessor acc;
using (mmf) acc = mmf.CreateViewAccessor();
// Validate we can still use the view
ValidateMemoryMappedViewAccessor(acc, 8192, MemoryMappedFileAccess.ReadWrite);
acc.Dispose();
}
}
/// <summary>
/// Test to allow a map and view to be finalized, just to ensure we don't crash.
/// </summary>
[Fact]
public void AllowFinaliation()
{
// Explicitly do not dispose, to allow finalization to happen, just to try to verify
// that nothing fails when it does.
MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096);
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
var mmfWeak = new WeakReference<MemoryMappedFile>(mmf);
var accWeak = new WeakReference<MemoryMappedViewAccessor>(acc);
mmf = null;
acc = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.False(mmfWeak.TryGetTarget(out mmf));
Assert.False(accWeak.TryGetTarget(out acc));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Xml;
using NUnit.Framework;
using Braintree;
using Params = System.Collections.Generic.Dictionary<string, object>;
namespace Braintree.Tests
{
public class TestHelper
{
public static string GenerateDecodedClientToken(BraintreeGateway gateway, ClientTokenRequest request = null)
{
var encodedClientToken = gateway.ClientToken.generate(request);
var decodedClientToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(encodedClientToken));
var unescapedClientToken = System.Text.RegularExpressions.Regex.Unescape(decodedClientToken);
return unescapedClientToken;
}
public static int CompareModificationsById(Modification left, Modification right)
{
return left.Id.CompareTo(right.Id);
}
public static string QueryStringForTR(Request trParams, Request req, string postURL, BraintreeService service)
{
string trData = TrUtil.BuildTrData(trParams, "http://example.com", service);
string postData = "tr_data=" + HttpUtility.UrlEncode(trData, Encoding.UTF8) + "&";
postData += req.ToQueryString();
var request = WebRequest.Create(postURL) as HttpWebRequest;
request.Method = "POST";
request.KeepAlive = false;
request.AllowAutoRedirect = false;
byte[] buffer = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = buffer.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
var response = request.GetResponse() as HttpWebResponse;
string query = new Uri(response.GetResponseHeader("Location")).Query;
response.Close();
return query;
}
public static void AreDatesEqual(DateTime expected, DateTime actual)
{
Assert.AreEqual(expected.Day, actual.Day);
Assert.AreEqual(expected.Month, actual.Month);
Assert.AreEqual(expected.Year, actual.Year);
}
public static void AssertIncludes(string expected, string all)
{
Assert.IsTrue(all.IndexOf(expected) >= 0, "Expected:\n" + all + "\nto include:\n" + expected);
}
public static bool IncludesSubscription(ResourceCollection<Subscription> collection, Subscription subscription)
{
foreach (Subscription item in collection)
{
if (item.Id.Equals(subscription.Id)) {
return true;
}
}
return false;
}
public static void Escrow(BraintreeService service, string transactionId)
{
NodeWrapper response = new NodeWrapper(service.Put(service.MerchantPath() + "/transactions/" + transactionId + "/escrow"));
Assert.IsTrue(response.IsSuccess());
}
public static string GetResponseContent(HttpWebResponse response)
{
using (var reader = new StreamReader(response.GetResponseStream()))
return reader.ReadToEnd();
}
public static string extractParamFromJson(string keyName, HttpWebResponse response)
{
var param = extractParamFromJson(keyName, GetResponseContent(response));
response.Close();
return param;
}
public static string extractParamFromJson(string keyName, string json)
{
string regex = string.Format("\"{0}\":\\s?\"([^\"]+)\"", keyName);
Match match = Regex.Match(json, regex);
string keyValue = match.Groups[1].Value;
return keyValue;
}
public static int extractIntParamFromJson(string keyName, string json)
{
string regex = string.Format("\"{0}\":\\s?(\\d+)", keyName);
Match match = Regex.Match(json, regex);
int keyValue = Convert.ToInt32(match.Groups[1].Value);
return keyValue;
}
public static string GetNonceForPayPalAccount(BraintreeGateway gateway, Params paypalAccountDetails)
{
var clientToken = GenerateDecodedClientToken(gateway);
var authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken);
var builder = new RequestBuilder();
builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint);
foreach (var param in paypalAccountDetails)
builder.AddTopLevelElement(string.Format("paypal_account[{0}]", param.Key), param.Value.ToString());
var response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/paypal_accounts", builder.ToQueryString());
return extractParamFromJson("nonce", response);
}
public static string GetNonceForNewCreditCard(BraintreeGateway gateway, Params creditCardDetails, string customerId = null)
{
var clientToken = TestHelper.GenerateDecodedClientToken(
gateway,
customerId == null ? null : new ClientTokenRequest { CustomerId = customerId });
var authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken);
var builder = new RequestBuilder();
builder.
AddTopLevelElement("authorization_fingerprint", authorizationFingerprint).
AddTopLevelElement("shared_customer_identifier", "test-identifier").
AddTopLevelElement("shared_customer_identifier_type", "testing");
foreach (var param in creditCardDetails) {
var nested = param.Value as Params;
if (null != nested) {
foreach (var nestedParam in nested) {
builder.AddTopLevelElement(string.Format("credit_card[{0}][{1}]", param.Key, nestedParam.Key), nestedParam.Value.ToString());
}
} else
builder.AddTopLevelElement(string.Format("credit_card[{0}]", param.Key), param.Value.ToString());
}
var response = new BraintreeTestHttpService().Post(
gateway.MerchantId,
"v1/payment_methods/credit_cards",
builder.ToQueryString());
return extractParamFromJson("nonce", response);
}
public static string GetNonceForNewPaymentMethod(BraintreeGateway gateway, Params @params, bool isCreditCard)
{
var clientToken = GenerateDecodedClientToken(gateway);
var authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken);
var paymentMethodType = isCreditCard ? "credit_card" : "paypal_account";
var paymentMethodTypePlural = paymentMethodType + "s";
var builder = new RequestBuilder();
builder.
AddTopLevelElement("authorization_fingerprint", authorizationFingerprint).
AddTopLevelElement("shared_customer_identifier", "test-identifier").
AddTopLevelElement("shared_customer_identifier_type", "testing");
foreach (var param in @params)
builder.AddTopLevelElement(string.Format("{0}[{1}]", paymentMethodType, param.Key), param.Value.ToString());
var response = new BraintreeTestHttpService().Post(
gateway.MerchantId,
"v1/payment_methods/" + paymentMethodTypePlural,
builder.ToQueryString());
return extractParamFromJson("nonce", response);
}
public static string GenerateUnlockedNonce(BraintreeGateway gateway, string creditCardNumber, string customerId)
{
var clientToken = "";
if (customerId == null) {
clientToken = TestHelper.GenerateDecodedClientToken(gateway);
} else {
clientToken = TestHelper.GenerateDecodedClientToken(gateway, new ClientTokenRequest
{
CustomerId = customerId
}
);
}
var authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken);
RequestBuilder builder = new RequestBuilder("");
builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint).
AddTopLevelElement("shared_customer_identifier_type", "testing").
AddTopLevelElement("shared_customer_identifier", "test-identifier").
AddTopLevelElement("credit_card[number]", creditCardNumber).
AddTopLevelElement("share", "true").
AddTopLevelElement("credit_card[expiration_month]", "11").
AddTopLevelElement("credit_card[expiration_year]", "2099");
HttpWebResponse response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/credit_cards.json", builder.ToQueryString());
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseBody = reader.ReadToEnd();
Regex regex = new Regex("nonce\":\"(?<nonce>[a-f0-9\\-]+)\"");
Match match = regex.Match(responseBody);
return match.Groups["nonce"].Value;
}
public static string GenerateUnlockedNonce(BraintreeGateway gateway)
{
return GenerateUnlockedNonce(gateway, "4111111111111111", null);
}
public static string GenerateOneTimePayPalNonce(BraintreeGateway gateway)
{
var clientToken = TestHelper.GenerateDecodedClientToken(gateway);
var authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken);
RequestBuilder builder = new RequestBuilder("");
builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint).
AddTopLevelElement("shared_customer_identifier_type", "testing").
AddTopLevelElement("shared_customer_identifier", "test-identifier").
AddTopLevelElement("paypal_account[access_token]", "access_token").
AddTopLevelElement("paypal_account[correlation_id]", System.Guid.NewGuid().ToString()).
AddTopLevelElement("paypal_account[options][validate]", "false");
HttpWebResponse response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/paypal_accounts", builder.ToQueryString());
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseBody = reader.ReadToEnd();
Regex regex = new Regex("nonce\":\"(?<nonce>[a-f0-9\\-]+)\"");
Match match = regex.Match(responseBody);
return match.Groups["nonce"].Value;
}
public static string GenerateFuturePaymentPayPalNonce(BraintreeGateway gateway)
{
var clientToken = TestHelper.GenerateDecodedClientToken(gateway);
var authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken);
RequestBuilder builder = new RequestBuilder("");
builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint).
AddTopLevelElement("shared_customer_identifier_type", "testing").
AddTopLevelElement("shared_customer_identifier", "test-identifier").
AddTopLevelElement("paypal_account[consent_code]", "consent").
AddTopLevelElement("paypal_account[correlation_id]", System.Guid.NewGuid().ToString()).
AddTopLevelElement("paypal_account[options][validate]", "false");
HttpWebResponse response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/paypal_accounts", builder.ToQueryString());
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseBody = reader.ReadToEnd();
Regex regex = new Regex("nonce\":\"(?<nonce>[a-f0-9\\-]+)\"");
Match match = regex.Match(responseBody);
return match.Groups["nonce"].Value;
}
public static string Create3DSVerification(BraintreeService service, string merchantAccountId, ThreeDSecureRequestForTests request)
{
string url = "/three_d_secure/create_verification/" + merchantAccountId;
NodeWrapper response = new NodeWrapper(service.Post(service.MerchantPath() + url, request));
Assert.IsTrue(response.IsSuccess());
return response.GetString("three-d-secure-token");
}
}
public class OAuthTestHelper
{
private class OAuthGrantRequest : Request
{
public string MerchantId { get; set; }
public string Scope { get; set; }
public override string ToXml()
{
return new RequestBuilder("grant")
.AddElement("merchant_public_id", MerchantId)
.AddElement("scope", Scope)
.ToXml();
}
}
public static string CreateGrant(BraintreeGateway gateway, string merchantId, string scope)
{
var service = new BraintreeService(gateway.Configuration);
XmlNode node = service.Post("/oauth_testing/grants", new OAuthGrantRequest {
MerchantId = merchantId,
Scope = scope
});
return node["code"].InnerText;
}
}
public class BraintreeTestHttpService
{
public string ApiVersion = "3";
public HttpWebResponse Get(string MerchantId, string URL)
{
return GetJsonResponse(MerchantId, URL, "GET", null);
}
public HttpWebResponse Post(string MerchantId, string URL, string requestBody)
{
return GetJsonResponse(MerchantId, URL, "POST", requestBody);
}
private HttpWebResponse GetJsonResponse(string MerchantId, string Path, string method, string requestBody)
{
try
{
var request = WebRequest.Create(Environment.DEVELOPMENT.GatewayURL + "/merchants/" + MerchantId + "/client_api/" + Path) as HttpWebRequest;
request.Headers.Add("X-ApiVersion", ApiVersion);
request.Accept = "application/json";
request.UserAgent = "Braintree .NET " + typeof(BraintreeService).Assembly.GetName().Version.ToString();
request.Method = method;
request.KeepAlive = false;
request.Timeout = 60000;
request.ReadWriteTimeout = 60000;
if (requestBody != null)
{
byte[] buffer = Encoding.UTF8.GetBytes(requestBody);
request.ContentLength = buffer.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
}
var response = request.GetResponse() as HttpWebResponse;
return response;
}
catch (WebException e)
{
var response = (HttpWebResponse)e.Response;
if (response == null) throw e;
return response;
}
}
}
}
| |
// 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.IO;
using Xunit;
namespace System.Security.Cryptography.Encoding.Tests
{
public class Base64TransformsTests
{
public static IEnumerable<object[]> TestData_Ascii()
{
// Test data taken from RFC 4648 Test Vectors
yield return new object[] { "", "" };
yield return new object[] { "f", "Zg==" };
yield return new object[] { "fo", "Zm8=" };
yield return new object[] { "foo", "Zm9v" };
yield return new object[] { "foob", "Zm9vYg==" };
yield return new object[] { "fooba", "Zm9vYmE=" };
yield return new object[] { "foobar", "Zm9vYmFy" };
}
public static IEnumerable<object[]> TestData_LongBlock_Ascii()
{
yield return new object[] { "fooba", "Zm9vYmE=" };
yield return new object[] { "foobar", "Zm9vYmFy" };
}
public static IEnumerable<object[]> TestData_Ascii_NoPadding()
{
// Test data without padding
yield return new object[] { "Zg" };
yield return new object[] { "Zm9vYg" };
yield return new object[] { "Zm9vYmE" };
}
public static IEnumerable<object[]> TestData_Ascii_Whitespace()
{
yield return new object[] { "fo", "\tZ\tm8=\r" };
yield return new object[] { "fo", "\tZ\tm8=\n" };
yield return new object[] { "fo", "\tZ\tm8=\r\n" };
yield return new object[] { "foo", " Z m 9 v" };
}
public static IEnumerable<object[]> TestData_Oversize()
{
// test data with extra chunks of data outside the selected range
yield return new object[] { "Zm9v////", 0, 4, "foo" };
yield return new object[] { "////Zm9v", 4, 4, "foo" };
yield return new object[] { "////Zm9v////", 4, 4, "foo" };
yield return new object[] { "Zm9vYmFyYm", 0, 10, "foobar" };
}
[Fact]
public void InvalidInput_ToBase64Transform()
{
byte[] data_5bytes = Text.Encoding.ASCII.GetBytes("aaaaa");
using (var transform = new ToBase64Transform())
{
InvalidInput_Base64Transform(transform);
// These exceptions only thrown in ToBase
AssertExtensions.Throws<ArgumentOutOfRangeException>("inputCount", () => transform.TransformFinalBlock(data_5bytes, 0, 5));
}
}
[Fact]
public void InvalidInput_FromBase64Transform()
{
byte[] data_4bytes = Text.Encoding.ASCII.GetBytes("aaaa");
ICryptoTransform transform = new FromBase64Transform();
InvalidInput_Base64Transform(transform);
// These exceptions only thrown in FromBase
transform.Dispose();
Assert.Throws<ObjectDisposedException>(() => transform.TransformBlock(data_4bytes, 0, 4, null, 0));
Assert.Throws<ObjectDisposedException>(() => transform.TransformFinalBlock(Array.Empty<byte>(), 0, 0));
}
private void InvalidInput_Base64Transform(ICryptoTransform transform)
{
byte[] data_4bytes = Text.Encoding.ASCII.GetBytes("aaaa");
AssertExtensions.Throws<ArgumentNullException>("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("inputOffset", () => transform.TransformBlock(Array.Empty<byte>(), -1, 0, null, 0));
AssertExtensions.Throws<ArgumentNullException>("outputBuffer", () => transform.TransformBlock(data_4bytes, 0, 4, null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("inputCount", () => transform.TransformBlock(Array.Empty<byte>(), 0, 1, null, 0));
AssertExtensions.Throws<ArgumentException>(null, () => transform.TransformBlock(Array.Empty<byte>(), 1, 0, null, 0));
AssertExtensions.Throws<ArgumentNullException>("inputBuffer", () => transform.TransformFinalBlock(null, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("inputOffset", () => transform.TransformFinalBlock(Array.Empty<byte>(), -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("inputOffset", () => transform.TransformFinalBlock(Array.Empty<byte>(), -1, 0));
AssertExtensions.Throws<ArgumentException>(null, () => transform.TransformFinalBlock(Array.Empty<byte>(), 1, 0));
}
[Theory, MemberData(nameof(TestData_Ascii))]
public static void ValidateToBase64CryptoStream(string data, string encoding)
{
using (var transform = new ToBase64Transform())
{
ValidateCryptoStream(encoding, data, transform);
}
}
[Theory, MemberData(nameof(TestData_Ascii))]
public static void ValidateFromBase64CryptoStream(string data, string encoding)
{
using (var transform = new FromBase64Transform())
{
ValidateCryptoStream(data, encoding, transform);
}
}
private static void ValidateCryptoStream(string expected, string data, ICryptoTransform transform)
{
byte[] inputBytes = Text.Encoding.ASCII.GetBytes(data);
byte[] outputBytes = new byte[100];
// Verify read mode
using (var ms = new MemoryStream(inputBytes))
using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Read))
{
int bytesRead = cs.Read(outputBytes, 0, outputBytes.Length);
string outputString = Text.Encoding.ASCII.GetString(outputBytes, 0, bytesRead);
Assert.Equal(expected, outputString);
}
// Verify write mode
using (var ms = new MemoryStream(outputBytes))
using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
{
cs.Write(inputBytes, 0, inputBytes.Length);
cs.FlushFinalBlock();
string outputString = Text.Encoding.ASCII.GetString(outputBytes, 0, (int)ms.Position);
Assert.Equal(expected, outputString);
}
}
[Theory, MemberData(nameof(TestData_LongBlock_Ascii))]
public static void ValidateToBase64TransformFinalBlock(string data, string expected)
{
using (var transform = new ToBase64Transform())
{
byte[] inputBytes = Text.Encoding.ASCII.GetBytes(data);
Assert.True(inputBytes.Length > 4);
// Test passing blocks > 4 characters to TransformFinalBlock (not supported)
_ = expected;
AssertExtensions.Throws<ArgumentOutOfRangeException>("inputCount", () => transform.TransformFinalBlock(inputBytes, 0, inputBytes.Length));
}
}
[Theory, MemberData(nameof(TestData_LongBlock_Ascii))]
public static void ValidateFromBase64TransformFinalBlock(string expected, string encoded)
{
using (var transform = new FromBase64Transform())
{
byte[] inputBytes = Text.Encoding.ASCII.GetBytes(encoded);
Assert.True(inputBytes.Length > 4);
// Test passing blocks > 4 characters to TransformFinalBlock (supported)
byte[] outputBytes = transform.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
string outputString = Text.Encoding.ASCII.GetString(outputBytes, 0, outputBytes.Length);
Assert.Equal(expected, outputString);
}
}
[Theory, MemberData(nameof(TestData_LongBlock_Ascii))]
public static void ValidateFromBase64TransformBlock(string expected, string encoded)
{
using (var transform = new FromBase64Transform())
{
byte[] inputBytes = Text.Encoding.ASCII.GetBytes(encoded);
Assert.True(inputBytes.Length > 4);
byte[] outputBytes = new byte[100];
int bytesWritten = transform.TransformBlock(inputBytes, 0, inputBytes.Length, outputBytes, 0);
string outputText = Text.Encoding.ASCII.GetString(outputBytes, 0, bytesWritten);
Assert.Equal(expected, outputText);
}
}
[Theory, MemberData(nameof(TestData_Ascii_NoPadding))]
public static void ValidateFromBase64_NoPadding(string data)
{
using (var transform = new FromBase64Transform())
{
byte[] inputBytes = Text.Encoding.ASCII.GetBytes(data);
byte[] outputBytes = new byte[100];
using (var ms = new MemoryStream(inputBytes))
using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Read))
{
int bytesRead = cs.Read(outputBytes, 0, outputBytes.Length);
// Missing padding bytes not supported (no exception, however)
Assert.NotEqual(inputBytes.Length, bytesRead);
}
}
}
[Theory, MemberData(nameof(TestData_Oversize))]
public static void ValidateFromBase64_OversizeBuffer(string input, int offset, int count, string expected)
{
using (var transform = new FromBase64Transform())
{
byte[] inputBytes = Text.Encoding.ASCII.GetBytes(input);
byte[] outputBytes = new byte[100];
int bytesWritten = transform.TransformBlock(inputBytes, offset, count, outputBytes, 0);
string outputText = Text.Encoding.ASCII.GetString(outputBytes, 0, bytesWritten);
Assert.Equal(expected, outputText);
}
}
[Theory, MemberData(nameof(TestData_Ascii_Whitespace))]
public static void ValidateWhitespace(string expected, string data)
{
byte[] inputBytes = Text.Encoding.ASCII.GetBytes(data);
byte[] outputBytes = new byte[100];
// Verify default of FromBase64TransformMode.IgnoreWhiteSpaces
using (var base64Transform = new FromBase64Transform())
using (var ms = new MemoryStream(inputBytes))
using (var cs = new CryptoStream(ms, base64Transform, CryptoStreamMode.Read))
{
int bytesRead = cs.Read(outputBytes, 0, outputBytes.Length);
string outputString = Text.Encoding.ASCII.GetString(outputBytes, 0, bytesRead);
Assert.Equal(expected, outputString);
}
// Verify explicit FromBase64TransformMode.IgnoreWhiteSpaces
using (var base64Transform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces))
using (var ms = new MemoryStream(inputBytes))
using (var cs = new CryptoStream(ms, base64Transform, CryptoStreamMode.Read))
{
int bytesRead = cs.Read(outputBytes, 0, outputBytes.Length);
string outputString = Text.Encoding.ASCII.GetString(outputBytes, 0, bytesRead);
Assert.Equal(expected, outputString);
}
// Verify FromBase64TransformMode.DoNotIgnoreWhiteSpaces
using (var base64Transform = new FromBase64Transform(FromBase64TransformMode.DoNotIgnoreWhiteSpaces))
using (var ms = new MemoryStream(inputBytes))
using (var cs = new CryptoStream(ms, base64Transform, CryptoStreamMode.Read))
{
Assert.Throws<FormatException>(() => cs.Read(outputBytes, 0, outputBytes.Length));
}
}
[Fact]
public void Blocksizes_ToBase64Transform()
{
using (var transform = new ToBase64Transform())
{
Assert.Equal(3, transform.InputBlockSize);
Assert.Equal(4, transform.OutputBlockSize);
}
}
[Fact]
public void Blocksizes_FromBase64Transform()
{
using (var transform = new FromBase64Transform())
{
Assert.Equal(4, transform.InputBlockSize);
Assert.Equal(3, transform.OutputBlockSize);
}
}
[Fact]
public void TransformUsageFlags_ToBase64Transform()
{
using (var transform = new ToBase64Transform())
{
Assert.False(transform.CanTransformMultipleBlocks);
Assert.True(transform.CanReuseTransform);
}
}
[Fact]
public void TransformUsageFlags_FromBase64Transform()
{
using (var transform = new FromBase64Transform())
{
Assert.True(transform.CanTransformMultipleBlocks);
Assert.True(transform.CanReuseTransform);
}
}
}
}
| |
//
// Pop3Engine.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.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.IO;
using System.Text;
using System.Threading;
using System.Collections.Generic;
#if NETFX_CORE
using Encoding = Portable.Text.Encoding;
using EncoderExceptionFallback = Portable.Text.EncoderExceptionFallback;
using DecoderExceptionFallback = Portable.Text.DecoderExceptionFallback;
using DecoderFallbackException = Portable.Text.DecoderFallbackException;
#endif
namespace MailKit.Net.Pop3 {
/// <summary>
/// The state of the <see cref="Pop3Engine"/>.
/// </summary>
enum Pop3EngineState {
/// <summary>
/// The Pop3Engine is in the disconnected state.
/// </summary>
Disconnected,
/// <summary>
/// The Pop3Engine is in the connected state.
/// </summary>
Connected,
/// <summary>
/// The Pop3Engine is in the transaction state, indicating that it is
/// authenticated and may retrieve messages from the server.
/// </summary>
Transaction
}
/// <summary>
/// A POP3 command engine.
/// </summary>
class Pop3Engine
{
static readonly Encoding Latin1;
static readonly Encoding UTF8;
readonly List<Pop3Command> queue;
Pop3Stream stream;
int nextId;
static Pop3Engine ()
{
UTF8 = Encoding.GetEncoding (65001, new EncoderExceptionFallback (), new DecoderExceptionFallback ());
try {
Latin1 = Encoding.GetEncoding (28591);
} catch (NotSupportedException) {
Latin1 = Encoding.GetEncoding (1252);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.Net.Pop3.Pop3Engine"/> class.
/// </summary>
public Pop3Engine ()
{
AuthenticationMechanisms = new HashSet<string> ();
Capabilities = Pop3Capabilities.User;
queue = new List<Pop3Command> ();
nextId = 1;
}
/// <summary>
/// Gets the URI of the POP3 server.
/// </summary>
/// <remarks>
/// Gets the URI of the POP3 server.
/// </remarks>
/// <value>The URI of the POP3 server.</value>
public Uri Uri {
get; internal set;
}
/// <summary>
/// Gets the authentication mechanisms supported by the POP3 server.
/// </summary>
/// <remarks>
/// The authentication mechanisms are queried durring the
/// <see cref="Connect"/> method.
/// </remarks>
/// <value>The authentication mechanisms.</value>
public HashSet<string> AuthenticationMechanisms {
get; private set;
}
/// <summary>
/// Gets the capabilities supported by the POP3 server.
/// </summary>
/// <remarks>
/// The capabilities will not be known until a successful connection
/// has been made via the <see cref="Connect"/> method.
/// </remarks>
/// <value>The capabilities.</value>
public Pop3Capabilities Capabilities {
get; set;
}
/// <summary>
/// Gets the underlying POP3 stream.
/// </summary>
/// <remarks>
/// Gets the underlying POP3 stream.
/// </remarks>
/// <value>The pop3 stream.</value>
public Pop3Stream Stream {
get { return stream; }
}
/// <summary>
/// Gets or sets the state of the engine.
/// </summary>
/// <remarks>
/// Gets or sets the state of the engine.
/// </remarks>
/// <value>The engine state.</value>
public Pop3EngineState State {
get; internal set;
}
/// <summary>
/// Gets whether or not the engine is currently connected to a POP3 server.
/// </summary>
/// <remarks>
/// Gets whether or not the engine is currently connected to a POP3 server.
/// </remarks>
/// <value><c>true</c> if the engine is connected; otherwise, <c>false</c>.</value>
public bool IsConnected {
get { return stream != null && stream.IsConnected; }
}
/// <summary>
/// Gets the APOP authentication token.
/// </summary>
/// <remarks>
/// Gets the APOP authentication token.
/// </remarks>
/// <value>The APOP authentication token.</value>
public string ApopToken {
get; private set;
}
/// <summary>
/// Gets the EXPIRE extension policy value.
/// </summary>
/// <remarks>
/// Gets the EXPIRE extension policy value.
/// </remarks>
/// <value>The EXPIRE policy.</value>
public int ExpirePolicy {
get; private set;
}
/// <summary>
/// Gets the implementation details of the server.
/// </summary>
/// <remarks>
/// Gets the implementation details of the server.
/// </remarks>
/// <value>The implementation details.</value>
public string Implementation {
get; private set;
}
/// <summary>
/// Gets the login delay.
/// </summary>
/// <remarks>
/// Gets the login delay.
/// </remarks>
/// <value>The login delay.</value>
public int LoginDelay {
get; private set;
}
/// <summary>
/// Takes posession of the <see cref="Pop3Stream"/> and reads the greeting.
/// </summary>
/// <remarks>
/// Takes posession of the <see cref="Pop3Stream"/> and reads the greeting.
/// </remarks>
/// <param name="pop3">The pop3 stream.</param>
/// <param name="cancellationToken">The cancellation token</param>
public void Connect (Pop3Stream pop3, CancellationToken cancellationToken)
{
if (stream != null)
stream.Dispose ();
Capabilities = Pop3Capabilities.User;
AuthenticationMechanisms.Clear ();
State = Pop3EngineState.Disconnected;
ApopToken = null;
stream = pop3;
// read the pop3 server greeting
var greeting = ReadLine (cancellationToken).TrimEnd ();
int index = greeting.IndexOf (' ');
string token, text;
if (index != -1) {
token = greeting.Substring (0, index);
while (index < greeting.Length && char.IsWhiteSpace (greeting[index]))
index++;
if (index < greeting.Length)
text = greeting.Substring (index);
else
text = string.Empty;
} else {
text = string.Empty;
token = greeting;
}
if (token != "+OK") {
stream.Dispose ();
stream = null;
throw new Pop3ProtocolException (string.Format ("Unexpected greeting from server: {0}", greeting));
}
index = text.IndexOf ('>');
if (text.Length > 0 && text[0] == '<' && index != -1) {
ApopToken = text.Substring (0, index + 1);
Capabilities |= Pop3Capabilities.Apop;
}
State = Pop3EngineState.Connected;
}
public event EventHandler<EventArgs> Disconnected;
void OnDisconnected ()
{
var handler = Disconnected;
if (handler != null)
handler (this, EventArgs.Empty);
}
/// <summary>
/// Disconnects the <see cref="Pop3Engine"/>.
/// </summary>
/// <remarks>
/// Disconnects the <see cref="Pop3Engine"/>.
/// </remarks>
public void Disconnect ()
{
Uri = null;
if (stream != null) {
stream.Dispose ();
stream = null;
}
if (State != Pop3EngineState.Disconnected) {
State = Pop3EngineState.Disconnected;
OnDisconnected ();
}
}
/// <summary>
/// Reads a single line from the <see cref="Pop3Stream"/>.
/// </summary>
/// <returns>The line.</returns>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.InvalidOperationException">
/// The engine is not connected.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public string ReadLine (CancellationToken cancellationToken)
{
if (stream == null)
throw new InvalidOperationException ();
using (var memory = new MemoryStream ()) {
int offset, count;
byte[] buf;
while (!stream.ReadLine (out buf, out offset, out count, cancellationToken))
memory.Write (buf, offset, count);
memory.Write (buf, offset, count);
count = (int) memory.Length;
#if !NETFX_CORE && !COREFX
buf = memory.GetBuffer ();
#else
buf = memory.ToArray ();
#endif
// Trim the <CR><LF> sequence from the end of the line.
if (buf[count - 1] == (byte) '\n') {
count--;
if (buf[count - 1] == (byte) '\r')
count--;
}
try {
return UTF8.GetString (buf, 0, count);
} catch (DecoderFallbackException) {
return Latin1.GetString (buf, 0, count);
}
}
}
public static Pop3CommandStatus GetCommandStatus (string response, out string text)
{
int index = response.IndexOf (' ');
string token;
if (index != -1) {
token = response.Substring (0, index);
while (index < response.Length && char.IsWhiteSpace (response[index]))
index++;
if (index < response.Length)
text = response.Substring (index);
else
text = string.Empty;
} else {
text = string.Empty;
token = response;
}
if (token == "+OK")
return Pop3CommandStatus.Ok;
if (token == "-ERR")
return Pop3CommandStatus.Error;
if (token == "+")
return Pop3CommandStatus.Continue;
return Pop3CommandStatus.ProtocolError;
}
void SendCommand (Pop3Command pc)
{
var buf = pc.Encoding.GetBytes (pc.Command + "\r\n");
stream.Write (buf, 0, buf.Length);
}
void ReadResponse (Pop3Command pc)
{
string response, text;
try {
response = ReadLine (pc.CancellationToken).TrimEnd ();
} catch {
pc.Status = Pop3CommandStatus.ProtocolError;
Disconnect ();
throw;
}
pc.Status = GetCommandStatus (response, out text);
pc.StatusText = text;
switch (pc.Status) {
case Pop3CommandStatus.ProtocolError:
Disconnect ();
throw new Pop3ProtocolException (string.Format ("Unexpected response from server: {0}", response));
case Pop3CommandStatus.Continue:
case Pop3CommandStatus.Ok:
if (pc.Handler != null) {
try {
pc.Handler (this, pc, text);
} catch {
pc.Status = Pop3CommandStatus.ProtocolError;
Disconnect ();
throw;
}
}
break;
}
}
public int Iterate ()
{
if (stream == null)
throw new InvalidOperationException ();
if (queue.Count == 0)
return 0;
int count = (Capabilities & Pop3Capabilities.Pipelining) != 0 ? queue.Count : 1;
var cancellationToken = queue[0].CancellationToken;
var active = new List<Pop3Command> ();
if (cancellationToken.IsCancellationRequested) {
queue.RemoveAll (x => x.CancellationToken.IsCancellationRequested);
cancellationToken.ThrowIfCancellationRequested ();
}
for (int i = 0; i < count; i++) {
var pc = queue[0];
if (i > 0 && !pc.CancellationToken.Equals (cancellationToken))
break;
queue.RemoveAt (0);
pc.Status = Pop3CommandStatus.Active;
active.Add (pc);
SendCommand (pc);
}
stream.Flush (cancellationToken);
for (int i = 0; i < active.Count; i++)
ReadResponse (active[i]);
return active[active.Count - 1].Id;
}
public Pop3Command QueueCommand (CancellationToken cancellationToken, Pop3CommandHandler handler, Encoding encoding, string format, params object[] args)
{
var pc = new Pop3Command (cancellationToken, handler, encoding, format, args);
pc.Id = nextId++;
queue.Add (pc);
return pc;
}
public Pop3Command QueueCommand (CancellationToken cancellationToken, Pop3CommandHandler handler, string format, params object[] args)
{
return QueueCommand (cancellationToken, handler, Encoding.ASCII, format, args);
}
static void CapaHandler (Pop3Engine engine, Pop3Command pc, string text)
{
if (pc.Status != Pop3CommandStatus.Ok)
return;
string response;
do {
if ((response = engine.ReadLine (pc.CancellationToken)) == ".")
break;
int index = response.IndexOf (' ');
string token, data;
int value;
if (index != -1) {
token = response.Substring (0, index);
while (index < response.Length && char.IsWhiteSpace (response[index]))
index++;
if (index < response.Length)
data = response.Substring (index);
else
data = string.Empty;
} else {
data = string.Empty;
token = response;
}
switch (token) {
case "EXPIRE":
engine.Capabilities |= Pop3Capabilities.Expire;
var tokens = data.Split (' ');
if (int.TryParse (tokens[0], out value))
engine.ExpirePolicy = value;
else if (tokens[0] == "NEVER")
engine.ExpirePolicy = -1;
break;
case "IMPLEMENTATION":
engine.Implementation = data;
break;
case "LOGIN-DELAY":
if (int.TryParse (data, out value)) {
engine.Capabilities |= Pop3Capabilities.LoginDelay;
engine.LoginDelay = value;
}
break;
case "PIPELINING":
engine.Capabilities |= Pop3Capabilities.Pipelining;
break;
case "RESP-CODES":
engine.Capabilities |= Pop3Capabilities.ResponseCodes;
break;
case "SASL":
engine.Capabilities |= Pop3Capabilities.Sasl;
foreach (var authmech in data.Split (new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
engine.AuthenticationMechanisms.Add (authmech);
break;
case "STLS":
engine.Capabilities |= Pop3Capabilities.StartTLS;
break;
case "TOP":
engine.Capabilities |= Pop3Capabilities.Top;
break;
case "UIDL":
engine.Capabilities |= Pop3Capabilities.UIDL;
break;
case "USER":
engine.Capabilities |= Pop3Capabilities.User;
break;
case "UTF8":
engine.Capabilities |= Pop3Capabilities.UTF8;
foreach (var item in data.Split (' ')) {
if (item == "USER")
engine.Capabilities |= Pop3Capabilities.UTF8User;
}
break;
case "LANG":
engine.Capabilities |= Pop3Capabilities.Lang;
break;
}
} while (true);
}
public Pop3CommandStatus QueryCapabilities (CancellationToken cancellationToken)
{
if (stream == null)
throw new InvalidOperationException ();
// clear all CAPA response capabilities (except the APOP capability)
Capabilities &= Pop3Capabilities.Apop;
AuthenticationMechanisms.Clear ();
Implementation = null;
ExpirePolicy = 0;
LoginDelay = 0;
var pc = QueueCommand (cancellationToken, CapaHandler, "CAPA");
while (Iterate () < pc.Id) {
// continue processing commands...
}
return pc.Status;
}
}
}
| |
using Android.Content.Res;
using System;
using System.IO;
using Uri = Android.Net.Uri;
namespace Plugin.SimpleAudioPlayer
{
/// <summary>
/// Implementation for Feature
/// </summary>
[Android.Runtime.Preserve(AllMembers = true)]
public class SimpleAudioPlayerImplementation : ISimpleAudioPlayer
{
///<Summary>
/// Raised when audio playback completes successfully
///</Summary>
public event EventHandler PlaybackEnded;
Android.Media.MediaPlayer player;
static int index = 0;
///<Summary>
/// Length of audio in seconds
///</Summary>
public double Duration
{ get { return player == null ? 0 : ((double)player.Duration) / 1000.0; } }
///<Summary>
/// Current position of audio playback in seconds
///</Summary>
public double CurrentPosition
{ get { return player == null ? 0 : ((double)player.CurrentPosition) / 1000.0; } }
///<Summary>
/// Playback volume (0 to 1)
///</Summary>
public double Volume
{
get { return _volume; }
set { SetVolume(_volume = value, Balance); }
}
double _volume = 0.5;
///<Summary>
/// Balance left/right: -1 is 100% left : 0% right, 1 is 100% right : 0% left, 0 is equal volume left/right
///</Summary>
public double Balance
{
get { return _balance; }
set { SetVolume(Volume, _balance = value); }
}
double _balance = 0;
///<Summary>
/// Indicates if the currently loaded audio file is playing
///</Summary>
public bool IsPlaying
{ get { return player == null ? false : player.IsPlaying; } }
///<Summary>
/// Continously repeats the currently playing sound
///</Summary>
public bool Loop
{
get { return _loop; }
set { _loop = value; if (player != null) player.Looping = _loop; }
}
bool _loop;
///<Summary>
/// Indicates if the position of the loaded audio file can be updated
///</Summary>
public bool CanSeek
{ get { return player == null ? false : true; } }
string path;
/// <summary>
/// Instantiates a new SimpleAudioPlayer
/// </summary>
public SimpleAudioPlayerImplementation()
{
player = new Android.Media.MediaPlayer() { Looping = Loop };
player.Completion += OnPlaybackEnded;
}
///<Summary>
/// Load wav or mp3 audio file as a stream
///</Summary>
public bool Load(Stream audioStream)
{
player.Reset();
DeleteFile(path);
//cache to the file system
path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), $"cache{index++}.wav");
var fileStream = File.Create(path);
audioStream.CopyTo(fileStream);
fileStream.Close();
try
{
player.SetDataSource(path);
}
catch
{
try
{
var context = Android.App.Application.Context;
player?.SetDataSource(context, Uri.Parse(Uri.Encode(path)));
}
catch
{
return false;
}
}
return PreparePlayer();
}
///<Summary>
/// Load wav or mp3 audio file from the iOS Resources folder
///</Summary>
public bool Load(string fileName)
{
player.Reset();
AssetFileDescriptor afd = Android.App.Application.Context.Assets.OpenFd(fileName);
player?.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
return PreparePlayer();
}
bool PreparePlayer()
{
player?.Prepare();
return (player == null) ? false : true;
}
void DeletePlayer()
{
Stop();
if (player != null)
{
player.Completion -= OnPlaybackEnded;
player.Release();
player.Dispose();
player = null;
}
DeleteFile(path);
path = string.Empty;
}
void DeleteFile(string path)
{
if (string.IsNullOrWhiteSpace(path) == false)
{
try
{
File.Delete(path);
}
catch
{
}
}
}
///<Summary>
/// Begin playback or resume if paused
///</Summary>
public void Play()
{
if (player == null)
return;
if (IsPlaying)
{
Pause();
Seek(0);
}
player.Start();
}
///<Summary>
/// Stop playack and set the current position to the beginning
///</Summary>
public void Stop()
{
if(!IsPlaying)
return;
Pause();
Seek(0);
}
///<Summary>
/// Pause playback if playing (does not resume)
///</Summary>
public void Pause()
{
player?.Pause();
}
///<Summary>
/// Set the current playback position (in seconds)
///</Summary>
public void Seek(double position)
{
if(CanSeek)
player?.SeekTo((int)(position * 1000D));
}
///<Summary>
/// Sets the playback volume as a double between 0 and 1
/// Sets both left and right channels
///</Summary>
void SetVolume(double volume, double balance)
{
volume = Math.Max(0, volume);
volume = Math.Min(1, volume);
balance = Math.Max(-1, balance);
balance = Math.Min(1, balance);
// Using the "constant power pan rule." See: http://www.rs-met.com/documents/tutorials/PanRules.pdf
var left = Math.Cos((Math.PI * (balance + 1)) / 4) * volume;
var right = Math.Sin((Math.PI * (balance + 1)) / 4) * volume;
player?.SetVolume((float)left, (float)right);
}
void OnPlaybackEnded(object sender, EventArgs e)
{
PlaybackEnded?.Invoke(sender, e);
//this improves stability on older devices but has minor performance impact
// We need to check whether the player is null or not as the user might have dipsosed it in an event handler to PlaybackEnded above.
if (player != null && Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.M)
{
player.SeekTo(0);
player.Stop();
player.Prepare();
}
}
bool isDisposed = false;
///<Summary>
/// Dispose SimpleAudioPlayer and release resources
///</Summary>
protected virtual void Dispose(bool disposing)
{
if (isDisposed || player == null)
return;
if (disposing)
DeletePlayer();
isDisposed = true;
}
~SimpleAudioPlayerImplementation()
{
Dispose(false);
}
///<Summary>
/// Dispose SimpleAudioPlayer and release resources
///</Summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.