context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.EventHubBasedInvalidation
{
using System;
using System.Threading;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using Adxstudio.Xrm.AspNet;
using Adxstudio.Xrm.Web;
/// <summary>
/// The Event Hub context.
/// </summary>
public class EventHubJobManager : IDisposable
{
/// <summary>
/// The settings.
/// </summary>
public EventHubJobSettings Settings { get; private set; }
/// <summary>
/// The organization Id field.
/// </summary>
private readonly Lazy<Guid> organizationId;
/// <summary>
/// The organization Id.
/// </summary>
public Guid OrganizationId
{
get
{
try
{
return this.organizationId.Value;
}
catch (Exception e)
{
WebEventSource.Log.GenericErrorException(e);
return Guid.Empty;
}
}
}
/// <summary>
/// The namespace manager field.
/// </summary>
private Lazy<NamespaceManager> namespaceManager;
/// <summary>
/// The namespace manager.
/// </summary>
public NamespaceManager NamespaceManager
{
get
{
try
{
return this.namespaceManager.Value;
}
catch (Exception e)
{
WebEventSource.Log.GenericErrorException(e);
return null;
}
}
}
/// <summary>
/// The topic exists field.
/// </summary>
private Lazy<bool> topicExists;
/// <summary>
/// The topic exists flag.
/// </summary>
public bool TopicExists
{
get
{
try
{
return this.topicExists.Value;
}
catch (Exception e)
{
WebEventSource.Log.GenericErrorException(e);
return false;
}
}
}
/// <summary>
/// The subscription field.
/// </summary>
private Lazy<SubscriptionDescription> subscription;
/// <summary>
/// The subscription.
/// </summary>
public SubscriptionDescription Subscription
{
get
{
try
{
return this.subscription.Value;
}
catch (Exception e)
{
WebEventSource.Log.GenericErrorException(e);
return null;
}
}
}
/// <summary>
/// The subscription client field.
/// </summary>
private Lazy<SubscriptionClient> subscriptionClient;
/// <summary>
/// The subscription client.
/// </summary>
public SubscriptionClient SubscriptionClient
{
get
{
try
{
return this.subscriptionClient.Value;
}
catch (Exception e)
{
WebEventSource.Log.GenericErrorException(e);
return null;
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubJobManager" /> class.
/// </summary>
/// <param name="context">The organization service context.</param>
/// <param name="settings">The settings.</param>
public EventHubJobManager(CrmDbContext context, EventHubJobSettings settings)
{
this.Settings = settings;
this.organizationId = new Lazy<Guid>(() => GetOrganizationId(context), LazyThreadSafetyMode.PublicationOnly);
this.Reset();
}
/// <summary>
/// Resets the properties.
/// </summary>
public void Reset()
{
this.namespaceManager = new Lazy<NamespaceManager>(CreateNamespaceManager(this.Settings), LazyThreadSafetyMode.PublicationOnly);
this.topicExists = new Lazy<bool>(() => this.GetTopicExists(this.Settings), LazyThreadSafetyMode.PublicationOnly);
this.subscription = new Lazy<SubscriptionDescription>(() => this.GetSubscription(this.Settings), LazyThreadSafetyMode.PublicationOnly);
this.subscriptionClient = new Lazy<SubscriptionClient>(() => this.GetSubscriptionClient(this.Settings), LazyThreadSafetyMode.PublicationOnly);
}
/// <summary>
/// Retrieves the organization Id.
/// </summary>
/// <param name="context">The organization service context.</param>
/// <returns>The organization Id.</returns>
private static Guid GetOrganizationId(CrmDbContext context)
{
var response = context.Service.Execute(new WhoAmIRequest()) as WhoAmIResponse;
return response.OrganizationId;
}
/// <summary>
/// Initializes the namespace manager field.
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns>The namespace manager.</returns>
private static Func<NamespaceManager> CreateNamespaceManager(EventHubJobSettings settings)
{
return () => NamespaceManager.CreateFromConnectionString(settings.ConnectionString);
}
/// <summary>
/// Initializes the topic exists field.
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns>The topic exists flag.</returns>
private bool GetTopicExists(EventHubJobSettings settings)
{
var topicPath = settings.Subscription.TopicPath;
var exists = this.NamespaceManager.TopicExists(topicPath);
if (!exists)
{
throw new InvalidOperationException(string.Format("The topic '{0}' does not exist.", topicPath));
}
return true;
}
/// <summary>
/// Initializes the subscription field.
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns>The subscription.</returns>
private SubscriptionDescription GetSubscription(EventHubJobSettings settings)
{
var topicPath = settings.Subscription.TopicPath;
var subscriptionName = settings.Subscription.Name;
if (!this.TopicExists)
{
throw new InvalidOperationException(string.Format("The topic '{0}' does not exist.", topicPath));
}
var subscriptionExists = this.NamespaceManager.SubscriptionExists(topicPath, subscriptionName);
if (!subscriptionExists)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Creating Subscription '{0}' for topic '{1}'.", subscriptionName, topicPath));
return this.CreateSubscription(settings.Subscription);
}
if (settings.RecreateSubscription)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Deleting Subscription '{0}' for topic '{1}'.", subscriptionName, topicPath));
this.NamespaceManager.DeleteSubscription(topicPath, subscriptionName);
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Creating Subscription '{0}' for topic '{1}'.", subscriptionName, topicPath));
return this.CreateSubscription(settings.Subscription);
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Using Subscription '{0}' for topic '{1}'.", subscriptionName, topicPath));
return this.NamespaceManager.GetSubscription(topicPath, subscriptionName);
}
/// <summary>
/// Creates the subscription.
/// </summary>
/// <param name="description">The subscription description.</param>
/// <returns>The subscription.</returns>
private SubscriptionDescription CreateSubscription(SubscriptionDescription description)
{
try
{
return this.NamespaceManager.CreateSubscription(description, this.CreateFilter());
}
catch (MessagingEntityAlreadyExistsException e)
{
WebEventSource.Log.GenericWarningException(e, string.Format("MessagingEntityAlreadyExistsException: Using Subscription '{0}' for topic '{1}'.", description.Name, description.TopicPath));
return this.NamespaceManager.GetSubscription(description.TopicPath, description.Name);
}
}
/// <summary>
/// Creates the filter.
/// </summary>
/// <returns>The filter.</returns>
private Filter CreateFilter()
{
return new SqlFilter(string.Format("OrganizationId = '{0}'", this.OrganizationId));
}
/// <summary>
/// Creates the subscription client.
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns>The subscription client.</returns>
private SubscriptionClient GetSubscriptionClient(EventHubJobSettings settings)
{
if (this.Subscription != null)
{
var topicPath = this.Subscription.TopicPath;
var subscriptionName = this.Subscription.Name;
return SubscriptionClient.CreateFromConnectionString(settings.ConnectionString, topicPath, subscriptionName);
}
throw new InvalidOperationException(string.Format("The subscription '{0}' for topic '{1}' is not ready.", settings.Subscription.Name, settings.Subscription.TopicPath));
}
/// <summary>
/// Internal use only.
/// </summary>
void IDisposable.Dispose()
{
// IDisposable is only required to satisfy the IdentityFactoryOptions<T> constraint
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_CTYPES
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting.Ast;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
namespace IronPython.Modules {
/// <summary>
/// Provides support for interop with native code from Python code.
/// </summary>
public static partial class CTypes {
[PythonType("CFuncPtr")]
public abstract class _CFuncPtr : CData, IDynamicMetaObjectProvider, ICodeFormattable {
private readonly Delegate _delegate;
private readonly int _comInterfaceIndex = -1;
private object _errcheck, _restype = _noResType;
private IList<object> _argtypes;
private int _id;
private static int _curId = 0;
internal static object _noResType = new object();
// __bool__
/// <summary>
/// Creates a new CFuncPtr object from a tuple. The 1st element of the
/// tuple is the ordinal or function name. The second is an object with
/// a _handle property. The _handle property is the handle of the module
/// from which the function will be loaded.
/// </summary>
public _CFuncPtr(PythonTuple args) {
if (args == null) {
throw PythonOps.TypeError("expected sequence, got None");
} else if (args.Count != 2) {
throw PythonOps.TypeError($"argument 1 must be a sequence of length 2, not {args.Count}");
}
object nameOrOrdinal = args[0];
object dll = args[1];
IntPtr intPtrHandle = GetHandleFromObject(dll, "the _handle attribute of the second element must be an integer");
IntPtr tmpAddr;
string funcName = args[0] as string;
if (funcName != null) {
tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, funcName);
} else {
tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, new IntPtr((int)nameOrOrdinal));
}
if (tmpAddr == IntPtr.Zero) {
if (CallingConvention == CallingConvention.StdCall && funcName != null) {
// apply std call name mangling - prepend a _, append @bytes where
// bytes is the number of bytes of the argument list.
string mangled = "_" + funcName + "@";
for (int i = 0; i < 128 && tmpAddr == IntPtr.Zero; i += 4) {
tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, mangled + i);
}
}
if (tmpAddr == IntPtr.Zero) {
throw PythonOps.AttributeError($"function {args[0]} is not defined");
}
}
_memHolder = new MemoryHolder(IntPtr.Size);
addr = tmpAddr;
_id = Interlocked.Increment(ref _curId);
}
public _CFuncPtr() {
_id = Interlocked.Increment(ref _curId);
_memHolder = new MemoryHolder(IntPtr.Size);
}
public _CFuncPtr(CodeContext context, object function) {
_memHolder = new MemoryHolder(IntPtr.Size);
if (function != null) {
if (!PythonOps.IsCallable(context, function)) {
throw PythonOps.TypeError("argument must be called or address of function");
}
_delegate = ((CFuncPtrType)DynamicHelpers.GetPythonType(this)).MakeReverseDelegate(context, function);
addr = Marshal.GetFunctionPointerForDelegate(_delegate);
CFuncPtrType myType = (CFuncPtrType)NativeType;
PythonType resType = myType._restype;
if (resType != null) {
if (!(resType is INativeType) || resType is PointerType) {
throw PythonOps.TypeError($"invalid result type {resType.Name} for callback function");
}
}
}
_id = Interlocked.Increment(ref _curId);
}
/// <summary>
/// Creates a new CFuncPtr which calls a COM method.
/// </summary>
public _CFuncPtr(int index, string name) {
_memHolder = new MemoryHolder(IntPtr.Size);
_comInterfaceIndex = index;
_id = Interlocked.Increment(ref _curId);
}
/// <summary>
/// Creates a new CFuncPtr with the specfied address.
/// </summary>
public _CFuncPtr(int handle) {
_memHolder = new MemoryHolder(IntPtr.Size);
addr = new IntPtr(handle);
_id = Interlocked.Increment(ref _curId);
}
/// <summary>
/// Creates a new CFuncPtr with the specfied address.
/// </summary>
public _CFuncPtr([NotNull] BigInteger handle) {
_memHolder = new MemoryHolder(IntPtr.Size);
addr = new IntPtr((long)handle);
_id = Interlocked.Increment(ref _curId);
}
public _CFuncPtr(IntPtr handle) {
_memHolder = new MemoryHolder(IntPtr.Size);
addr = handle;
_id = Interlocked.Increment(ref _curId);
}
public bool __bool__() {
return addr != IntPtr.Zero;
}
#region Public APIs
[SpecialName, PropertyMethod]
public object Geterrcheck() {
return _errcheck;
}
[SpecialName, PropertyMethod]
public void Seterrcheck(object value) {
_errcheck = value;
}
[SpecialName, PropertyMethod]
public void Deleteerrcheck() {
_errcheck = null;
_id = Interlocked.Increment(ref _curId);
}
[PropertyMethod, SpecialName]
public object Getrestype() {
if (_restype == _noResType) {
return ((CFuncPtrType)NativeType)._restype;
}
return _restype;
}
[PropertyMethod, SpecialName]
public void Setrestype(object value) {
INativeType nt = value as INativeType;
if (nt != null || value == null || PythonOps.IsCallable(((PythonType)NativeType).Context.SharedContext, value)) {
_restype = value;
_id = Interlocked.Increment(ref _curId);
} else {
throw PythonOps.TypeError("restype must be a type, a callable, or None");
}
}
[SpecialName, PropertyMethod]
public void Deleterestype() {
_restype = _noResType;
_id = Interlocked.Increment(ref _curId);
}
public object argtypes {
get {
if (_argtypes != null) {
return _argtypes;
}
if (((CFuncPtrType)NativeType)._argtypes != null) {
return PythonTuple.MakeTuple(((CFuncPtrType)NativeType)._argtypes);
}
return null;
}
set {
if (value != null) {
IList<object> argValues = value as IList<object>;
if (argValues == null) {
throw PythonOps.TypeErrorForTypeMismatch("sequence", value);
}
foreach (object o in argValues) {
if (!(o is INativeType)) {
if (!PythonOps.HasAttr(DefaultContext.Default, o, "from_param")) {
throw PythonOps.TypeErrorForTypeMismatch("ctype or object with from_param", o);
}
}
}
_argtypes = argValues;
} else {
_argtypes = null;
}
_id = Interlocked.Increment(ref _curId);
}
}
#endregion
#region Internal APIs
internal CallingConvention CallingConvention {
get {
return ((CFuncPtrType)DynamicHelpers.GetPythonType(this)).CallingConvention;
}
}
internal int Flags {
get {
return ((CFuncPtrType)DynamicHelpers.GetPythonType(this))._flags;
}
}
// TODO: access via PythonOps
public IntPtr addr {
[PythonHidden]
get {
return _memHolder.ReadIntPtr(0);
}
[PythonHidden]
set {
_memHolder.WriteIntPtr(0, value);
}
}
internal int Id {
get {
return _id;
}
}
#endregion
#region IDynamicObject Members
// needs to be public so that derived base classes can call it.
[PythonHidden]
public DynamicMetaObject GetMetaObject(Expression parameter) {
return new Meta(parameter, this);
}
#endregion
#region MetaObject
private class Meta : MetaPythonObject {
public Meta(Expression parameter, _CFuncPtr func)
: base(parameter, BindingRestrictions.Empty, func) {
}
public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) {
CodeContext context = PythonContext.GetPythonContext(binder).SharedContext;
ArgumentMarshaller[] signature = GetArgumentMarshallers(args);
BindingRestrictions restrictions = BindingRestrictions.GetTypeRestriction(
Expression,
Value.GetType()
).Merge(
BindingRestrictions.GetExpressionRestriction(
Expression.Call(
typeof(ModuleOps).GetMethod(nameof(ModuleOps.CheckFunctionId)),
Expression.Convert(Expression, typeof(_CFuncPtr)),
Expression.Constant(Value.Id)
)
)
);
foreach (var arg in signature) {
restrictions = restrictions.Merge(arg.GetRestrictions());
}
int argCount = args.Length;
if (Value._comInterfaceIndex != -1) {
argCount--;
}
// need to verify we have the correct # of args
if (Value._argtypes != null) {
if (argCount < Value._argtypes.Count || (Value.CallingConvention != CallingConvention.Cdecl && argCount > Value._argtypes.Count)) {
return IncorrectArgCount(binder, restrictions, Value._argtypes.Count, argCount);
}
} else {
CFuncPtrType funcType = ((CFuncPtrType)Value.NativeType);
if (funcType._argtypes != null &&
(argCount < funcType._argtypes.Length || (Value.CallingConvention != CallingConvention.Cdecl && argCount > funcType._argtypes.Length))) {
return IncorrectArgCount(binder, restrictions, funcType._argtypes.Length, argCount);
}
}
if (Value._comInterfaceIndex != -1 && args.Length == 0) {
return NoThisParam(binder, restrictions);
}
Expression call = MakeCall(signature, GetNativeReturnType(), Value.Getrestype() == null, GetFunctionAddress(args));
List<Expression> block = new List<Expression>();
Expression res;
if (call.Type != typeof(void)) {
ParameterExpression tmp = Expression.Parameter(call.Type, "ret");
block.Add(Expression.Assign(tmp, call));
AddKeepAlives(signature, block);
block.Add(tmp);
res = Expression.Block(new[] { tmp }, block);
} else {
block.Add(call);
AddKeepAlives(signature, block);
res = Expression.Block(block);
}
res = AddReturnChecks(context, args, res);
return new DynamicMetaObject(Utils.Convert(res, typeof(object)), restrictions);
}
private Expression AddReturnChecks(CodeContext context, DynamicMetaObject[] args, Expression res) {
PythonContext ctx = context.LanguageContext;
object resType = Value.Getrestype();
if (resType != null) {
// res type can be callable, a type with _check_retval_, or
// it can be just be a type which doesn't require post-processing.
INativeType nativeResType = resType as INativeType;
object checkRetVal = null;
if (nativeResType == null) {
checkRetVal = resType;
} else if (!PythonOps.TryGetBoundAttr(context, nativeResType, "_check_retval_", out checkRetVal)) {
// we just wanted to try and get the value, don't need to do anything here.
checkRetVal = null;
}
if (checkRetVal != null) {
res = Expression.Dynamic(
ctx.CompatInvoke(new CallInfo(1)),
typeof(object),
Expression.Constant(checkRetVal),
res
);
}
}
object errCheck = Value.Geterrcheck();
if (errCheck != null) {
res = Expression.Dynamic(
ctx.CompatInvoke(new CallInfo(3)),
typeof(object),
Expression.Constant(errCheck),
res,
Expression,
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.MakeTuple)),
Expression.NewArrayInit(
typeof(object),
Microsoft.Scripting.Utils.ArrayUtils.ConvertAll(args, x => Utils.Convert(x.Expression, typeof(object)))
)
)
);
}
return res;
}
private static DynamicMetaObject IncorrectArgCount(DynamicMetaObjectBinder binder, BindingRestrictions restrictions, int expected, int got) {
return new DynamicMetaObject(
binder.Throw(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.TypeError)),
Expression.Constant($"this function takes {expected} arguments ({got} given)"),
Expression.NewArrayInit(typeof(object))
),
typeof(object)
),
restrictions
);
}
private static DynamicMetaObject NoThisParam(DynamicMetaObjectBinder binder, BindingRestrictions restrictions) {
return new DynamicMetaObject(
binder.Throw(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.ValueError)),
Expression.Constant("native com method call without 'this' parameter"),
Expression.NewArrayInit(typeof(object))
),
typeof(object)
),
restrictions
);
}
/// <summary>
/// we need to keep alive any methods which have arguments for the duration of the
/// call. Otherwise they could be collected on the finalizer thread before we come back.
/// </summary>
private void AddKeepAlives(ArgumentMarshaller[] signature, List<Expression> block) {
foreach (ArgumentMarshaller marshaller in signature) {
Expression keepAlive = marshaller.GetKeepAlive();
if (keepAlive != null) {
block.Add(keepAlive);
}
}
}
private Expression MakeCall(ArgumentMarshaller[] signature, INativeType nativeRetType, bool retVoid, Expression address) {
List<object> constantPool = new List<object>();
MethodInfo interopInvoker = CreateInteropInvoker(
GetCallingConvention(),
signature,
nativeRetType,
retVoid,
constantPool
);
// build the args - IntPtr, user Args, constant pool
Expression[] callArgs = new Expression[signature.Length + 2];
callArgs[0] = address;
for (int i = 0; i < signature.Length; i++) {
callArgs[i + 1] = signature[i].ArgumentExpression;
}
callArgs[callArgs.Length - 1] = Expression.Constant(constantPool.ToArray());
return Expression.Call(interopInvoker, callArgs);
}
private Expression GetFunctionAddress(DynamicMetaObject[] args) {
Expression address;
if (Value._comInterfaceIndex != -1) {
Debug.Assert(args.Length != 0); // checked earlier
address = Expression.Call(
typeof(ModuleOps).GetMethod(nameof(ModuleOps.GetInterfacePointer)),
Expression.Call(
typeof(ModuleOps).GetMethod(nameof(ModuleOps.GetPointer)),
args[0].Expression
),
Expression.Constant(Value._comInterfaceIndex)
);
} else {
address = Expression.Property(
Expression.Convert(Expression, typeof(_CFuncPtr)),
"addr"
);
}
return address;
}
private CallingConvention GetCallingConvention() {
return Value.CallingConvention;
}
private INativeType GetNativeReturnType() {
return Value.Getrestype() as INativeType;
}
private ArgumentMarshaller/*!*/[]/*!*/ GetArgumentMarshallers(DynamicMetaObject/*!*/[]/*!*/ args) {
CFuncPtrType funcType = ((CFuncPtrType)Value.NativeType);
ArgumentMarshaller[] res = new ArgumentMarshaller[args.Length];
// first arg is taken by self if we're a com method
for (int i = 0; i < args.Length; i++) {
DynamicMetaObject mo = args[i];
object argType = null;
if (Value._comInterfaceIndex == -1 || i != 0) {
int argtypeIndex = Value._comInterfaceIndex == -1 ? i : i - 1;
if (Value._argtypes != null && argtypeIndex < Value._argtypes.Count) {
argType = Value._argtypes[argtypeIndex];
} else if (funcType._argtypes != null && argtypeIndex < funcType._argtypes.Length) {
argType = funcType._argtypes[argtypeIndex];
}
}
res[i] = GetMarshaller(mo.Expression, mo.Value, i, argType);
}
return res;
}
private ArgumentMarshaller/*!*/ GetMarshaller(Expression/*!*/ expr, object value, int index, object nativeType) {
if (nativeType != null) {
if (nativeType is INativeType nt) {
return new CDataMarshaller(expr, CompilerHelpers.GetType(value), nt);
}
return new FromParamMarshaller(expr);
}
if (value is CData data) {
return new CDataMarshaller(expr, CompilerHelpers.GetType(value), data.NativeType);
}
if (value is NativeArgument arg) {
return new NativeArgumentMarshaller(expr);
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object val)) {
throw new NotImplementedException("_as_parameter");
//return new UserDefinedMarshaller(GetMarshaller(..., value, index));
}
// Marshalling primitive or an object
return new PrimitiveMarshaller(expr, CompilerHelpers.GetType(value));
}
public new _CFuncPtr/*!*/ Value {
get {
return (_CFuncPtr)base.Value;
}
}
/// <summary>
/// Creates a method for calling with the specified signature. The returned method has a signature
/// of the form:
///
/// (IntPtr funcAddress, arg0, arg1, ..., object[] constantPool)
///
/// where IntPtr is the address of the function to be called. The arguments types are based upon
/// the types that the ArgumentMarshaller requires.
/// </summary>
private static MethodInfo/*!*/ CreateInteropInvoker(CallingConvention convention, ArgumentMarshaller/*!*/[]/*!*/ sig, INativeType nativeRetType, bool retVoid, List<object> constantPool) {
Type[] sigTypes = new Type[sig.Length + 2];
sigTypes[0] = typeof(IntPtr);
for (int i = 0; i < sig.Length; i++) {
sigTypes[i + 1] = sig[i].ArgumentExpression.Type;
}
sigTypes[sigTypes.Length - 1] = typeof(object[]);
Type retType = retVoid ? typeof(void) :
nativeRetType != null ? nativeRetType.GetPythonType() : typeof(int);
Type calliRetType = retVoid ? typeof(void) :
nativeRetType != null ? nativeRetType.GetNativeType() : typeof(int);
#if !CTYPES_USE_SNIPPETS
DynamicMethod dm = new DynamicMethod("InteropInvoker", retType, sigTypes, DynamicModule);
#else
TypeGen tg = Snippets.Shared.DefineType("InteropInvoker", typeof(object), false, false);
MethodBuilder dm = tg.TypeBuilder.DefineMethod("InteropInvoker", CompilerHelpers.PublicStatic, retType, sigTypes);
#endif
ILGenerator method = dm.GetILGenerator();
LocalBuilder calliRetTmp = null, finalRetValue = null;
if (dm.ReturnType != typeof(void)) {
calliRetTmp = method.DeclareLocal(calliRetType);
finalRetValue = method.DeclareLocal(dm.ReturnType);
}
// try {
// emit all of the arguments, save their cleanups
method.BeginExceptionBlock();
List<MarshalCleanup> cleanups = null;
for (int i = 0; i < sig.Length; i++) {
#if DEBUG
method.Emit(OpCodes.Ldstr, String.Format("Argument #{0}, Marshaller: {1}, Native Type: {2}", i, sig[i], sig[i].NativeType));
method.Emit(OpCodes.Pop);
#endif
MarshalCleanup cleanup = sig[i].EmitCallStubArgument(method, i + 1, constantPool, sigTypes.Length - 1);
if (cleanup != null) {
if (cleanups == null) {
cleanups = new List<MarshalCleanup>();
}
cleanups.Add(cleanup);
}
}
// emit the target function pointer and the calli
#if DEBUG
method.Emit(OpCodes.Ldstr, "!!! CALLI !!!");
method.Emit(OpCodes.Pop);
#endif
method.Emit(OpCodes.Ldarg_0);
method.EmitCalli(OpCodes.Calli, convention, calliRetType, sig.Select(x => x.NativeType).ToArray());
// if we have a return value we need to store it and marshal to Python
// before we run any cleanup code.
if (retType != typeof(void)) {
#if DEBUG
method.Emit(OpCodes.Ldstr, "!!! Return !!!");
method.Emit(OpCodes.Pop);
#endif
if (nativeRetType != null) {
method.Emit(OpCodes.Stloc, calliRetTmp);
nativeRetType.EmitReverseMarshalling(method, new Local(calliRetTmp), constantPool, sig.Length + 1);
method.Emit(OpCodes.Stloc, finalRetValue);
} else {
Debug.Assert(retType == typeof(int));
// no marshalling necessary
method.Emit(OpCodes.Stloc, finalRetValue);
}
}
// } finally {
// emit the cleanup code
method.BeginFinallyBlock();
if (cleanups != null) {
foreach (MarshalCleanup mc in cleanups) {
mc.Cleanup(method);
}
}
method.EndExceptionBlock();
// }
// load the temporary value and return it.
if (retType != typeof(void)) {
method.Emit(OpCodes.Ldloc, finalRetValue);
}
method.Emit(OpCodes.Ret);
#if CTYPES_USE_SNIPPETS
return tg.TypeBuilder.CreateType().GetMethod("InteropInvoker");
#else
return dm;
#endif
}
#region Argument Marshalling
/// <summary>
/// Base class for marshalling arguments from the user provided value to the
/// call stub. This class provides the logic for creating the call stub and
/// calling it.
/// </summary>
private abstract class ArgumentMarshaller {
private readonly Expression/*!*/ _argExpr;
public ArgumentMarshaller(Expression/*!*/ container) {
_argExpr = container;
}
/// <summary>
/// Emits the IL to get the argument for the call stub generated into
/// a dynamic method.
/// </summary>
public abstract MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument);
public abstract Type/*!*/ NativeType {
get;
}
/// <summary>
/// Gets the expression used to provide the argument. This is the expression
/// from an incoming DynamicMetaObject.
/// </summary>
public Expression/*!*/ ArgumentExpression {
get {
return _argExpr;
}
}
/// <summary>
/// Gets an expression which keeps alive the argument for the duration of the call.
///
/// Returns null if a keep alive is not necessary.
/// </summary>
public virtual Expression GetKeepAlive() {
return null;
}
public virtual BindingRestrictions GetRestrictions() {
return BindingRestrictions.Empty;
}
}
/// <summary>
/// Provides marshalling of primitive values when the function type
/// has no type information or when the user has provided us with
/// an explicit cdata instance.
/// </summary>
private class PrimitiveMarshaller : ArgumentMarshaller {
private readonly Type/*!*/ _type;
private static MethodInfo _bigIntToInt32;
private static MethodInfo BigIntToInt32 {
get {
if (_bigIntToInt32 == null) {
MemberInfo[] mis = typeof(BigInteger).GetMember(
"op_Explicit",
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static
);
foreach (MethodInfo mi in mis) {
if (mi.ReturnType == typeof(int)) {
_bigIntToInt32 = mi;
break;
}
}
Debug.Assert(_bigIntToInt32 != null);
}
return _bigIntToInt32;
}
}
public PrimitiveMarshaller(Expression/*!*/ container, Type/*!*/ type)
: base(container) {
_type = type;
}
private static readonly MethodInfo StringGetPinnableReference = typeof(string).GetMethod("GetPinnableReference");
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
if (_type == typeof(DynamicNull)) {
generator.Emit(OpCodes.Ldc_I4_0);
generator.Emit(OpCodes.Conv_I);
return null;
}
generator.Emit(OpCodes.Ldarg, argIndex);
if (ArgumentExpression.Type != _type) {
generator.Emit(OpCodes.Unbox_Any, _type);
}
if (_type == typeof(string)) {
// pin the string and convert to a wchar*. We could let the CLR do this
// but we need the string to be pinned longer than the duration of the the CLR's
// p/invoke. This is because the function could return the same pointer back
// to us and we need to create a new string from it.
if (StringGetPinnableReference is null) {
LocalBuilder lb = generator.DeclareLocal(typeof(string), true);
generator.Emit(OpCodes.Stloc, lb);
generator.Emit(OpCodes.Ldloc, lb);
generator.Emit(OpCodes.Conv_I);
#pragma warning disable CS0618 // Type or member is obsolete
generator.Emit(OpCodes.Ldc_I4, RuntimeHelpers.OffsetToStringData);
#pragma warning restore CS0618 // Type or member is obsolete
generator.Emit(OpCodes.Add);
} else {
generator.Emit(OpCodes.Call, StringGetPinnableReference);
}
} else if (_type == typeof(Bytes)) {
LocalBuilder lb = generator.DeclareLocal(typeof(byte).MakeByRefType(), true);
generator.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod(nameof(ModuleOps.GetBytes)));
generator.Emit(OpCodes.Ldc_I4_0);
generator.Emit(OpCodes.Ldelema, typeof(Byte));
generator.Emit(OpCodes.Stloc, lb);
generator.Emit(OpCodes.Ldloc, lb);
} else if (_type == typeof(BigInteger)) {
generator.Emit(OpCodes.Call, BigIntToInt32);
} else if (!_type.IsValueType) {
generator.Emit(OpCodes.Call, typeof(CTypes).GetMethod(nameof(CTypes.PyObj_ToPtr)));
}
return null;
}
public override Type NativeType {
get {
if (_type == typeof(BigInteger)) {
return typeof(int);
} else if (!_type.IsValueType) {
return typeof(IntPtr);
}
return _type;
}
}
public override BindingRestrictions GetRestrictions() {
if (_type == typeof(DynamicNull)) {
return BindingRestrictions.GetExpressionRestriction(Expression.Equal(ArgumentExpression, Expression.Constant(null)));
}
return BindingRestrictions.GetTypeRestriction(ArgumentExpression, _type);
}
}
private class FromParamMarshaller : ArgumentMarshaller {
public FromParamMarshaller(Expression/*!*/ container)
: base(container) {
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator generator, int argIndex, List<object> constantPool, int constantPoolArgument) {
throw new NotImplementedException();
}
public override Type NativeType {
get { throw new NotImplementedException(); }
}
}
/// <summary>
/// Provides marshalling for when the function type provide argument information.
/// </summary>
private class CDataMarshaller : ArgumentMarshaller {
private readonly Type/*!*/ _type;
private readonly INativeType/*!*/ _cdataType;
public CDataMarshaller(Expression/*!*/ container, Type/*!*/ type, INativeType/*!*/cdataType)
: base(container) {
_type = type;
_cdataType = cdataType;
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
return _cdataType.EmitMarshalling(generator, new Arg(argIndex, ArgumentExpression.Type), constantPool, constantPoolArgument);
}
public override Type NativeType {
get {
return _cdataType.GetNativeType();
}
}
public override Expression GetKeepAlive() {
// Future possible optimization - we could just keep alive the MemoryHolder
if (_type.IsValueType) {
return null;
}
return Expression.Call(
typeof(GC).GetMethod("KeepAlive"),
ArgumentExpression
);
}
public override BindingRestrictions GetRestrictions() {
// we base this off of the type marshalling which can handle anything.
return BindingRestrictions.Empty;
}
}
/// <summary>
/// Provides marshalling for when the user provides a native argument object
/// (usually gotten by byref or pointer) and the function type has no type information.
/// </summary>
private class NativeArgumentMarshaller : ArgumentMarshaller {
public NativeArgumentMarshaller(Expression/*!*/ container)
: base(container) {
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
// We access UnsafeAddress here but ensure the object is kept
// alive via the expression returned in GetKeepAlive.
generator.Emit(OpCodes.Ldarg, argIndex);
generator.Emit(OpCodes.Castclass, typeof(NativeArgument));
generator.Emit(OpCodes.Call, typeof(NativeArgument).GetProperty(nameof(NativeArgument._obj)).GetGetMethod());
generator.Emit(OpCodes.Call, typeof(CData).GetProperty(nameof(CData.UnsafeAddress)).GetGetMethod());
return null;
}
public override Type/*!*/ NativeType {
get {
return typeof(IntPtr);
}
}
public override Expression GetKeepAlive() {
// Future possible optimization - we could just keep alive the MemoryHolder
return Expression.Call(
typeof(GC).GetMethod("KeepAlive"),
ArgumentExpression
);
}
public override BindingRestrictions GetRestrictions() {
return BindingRestrictions.GetTypeRestriction(ArgumentExpression, typeof(NativeArgument));
}
}
#if FALSE // TODO: not implemented yet
/// <summary>
/// Provides the marshalling for a user defined object which has an _as_parameter_
/// value.
/// </summary>
class UserDefinedMarshaller : ArgumentMarshaller {
private readonly ArgumentMarshaller/*!*/ _marshaller;
public UserDefinedMarshaller(Expression/*!*/ container, ArgumentMarshaller/*!*/ marshaller)
: base(container) {
_marshaller = marshaller;
}
public override Type NativeType {
get { throw new NotImplementedException("user defined marshaller sig type"); }
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
throw new NotImplementedException("user defined marshaller");
}
}
#endif
#endregion
}
#endregion
public string __repr__(CodeContext context) {
if (_comInterfaceIndex != -1) {
return string.Format("<COM method offset {0}: {1} at {2}>", _comInterfaceIndex, DynamicHelpers.GetPythonType(this).Name, _id);
}
return ObjectOps.__repr__(this);
}
}
}
#if NETSTANDARD2_0
#nullable enable
internal static class ILGeneratorExtensions {
private static MethodInfo? EmitCalliMethodInfo = typeof(ILGenerator).GetMethod("EmitCalli", new Type[] { typeof(OpCode), typeof(CallingConvention), typeof(Type), typeof(Type[]) });
public static void EmitCalli(this ILGenerator ilgen, OpCode opcode, CallingConvention unmanagedCallConv, Type? returnType, Type[]? parameterTypes) {
// should exist in runtimes of interest, but just in case, let it throw if the method doesn't exist...
EmitCalliMethodInfo!.Invoke(ilgen, new object[] { opcode, unmanagedCallConv, returnType!, parameterTypes! });
}
}
#nullable restore
#endif
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Text;
using System.Runtime.Serialization;
using System.Globalization;
namespace System.Xml
{
public delegate void OnXmlDictionaryReaderClose(XmlDictionaryReader reader);
public abstract class XmlDictionaryReader : XmlReader
{
internal const int MaxInitialArrayLength = 65535;
static public XmlDictionaryReader CreateDictionaryReader(XmlReader reader)
{
if (reader == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader;
if (dictionaryReader == null)
{
dictionaryReader = new XmlWrappedReader(reader, null);
}
return dictionaryReader;
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, XmlDictionaryReaderQuotas quotas)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
return CreateBinaryReader(buffer, 0, buffer.Length, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(buffer, offset, count, null, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(buffer, offset, count, dictionary, quotas, null);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session)
{
XmlBinaryReader reader = new XmlBinaryReader();
reader.SetInput(buffer, offset, count, dictionary, quotas, session);
return reader;
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(stream, null, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(stream, dictionary, quotas, null);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session)
{
XmlBinaryReader reader = new XmlBinaryReader();
reader.SetInput(stream, dictionary, quotas, session);
return reader;
}
static public XmlDictionaryReader CreateTextReader(byte[] buffer, XmlDictionaryReaderQuotas quotas)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
return CreateTextReader(buffer, 0, buffer.Length, quotas);
}
static public XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas)
{
MemoryStream ms = new MemoryStream(buffer, offset, count);
return CreateTextReader(ms, quotas);
}
static public XmlDictionaryReader CreateTextReader(Stream stream, XmlDictionaryReaderQuotas quotas)
{
return CreateTextReader(stream, null, quotas, null);
}
static public XmlDictionaryReader CreateTextReader(Stream stream, Encoding encoding,
XmlDictionaryReaderQuotas quotas,
OnXmlDictionaryReaderClose onClose)
{
XmlUTF8TextReader reader = new XmlUTF8TextReader();
reader.SetInput(stream, encoding, quotas, onClose);
return reader;
}
public virtual bool CanCanonicalize
{
get
{
return false;
}
}
public virtual XmlDictionaryReaderQuotas Quotas
{
get
{
return XmlDictionaryReaderQuotas.Max;
}
}
public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void EndCanonicalization()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void MoveToStartElement()
{
if (!IsStartElement())
XmlExceptionHelper.ThrowStartElementExpected(this);
}
public virtual void MoveToStartElement(string name)
{
if (!IsStartElement(name))
XmlExceptionHelper.ThrowStartElementExpected(this, name);
}
public virtual void MoveToStartElement(string localName, string namespaceUri)
{
if (!IsStartElement(localName, namespaceUri))
XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri);
}
public virtual void MoveToStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (!IsStartElement(localName, namespaceUri))
XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri);
}
public virtual bool IsLocalName(string localName)
{
return this.LocalName == localName;
}
public virtual bool IsLocalName(XmlDictionaryString localName)
{
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName");
return IsLocalName(localName.Value);
}
public virtual bool IsNamespaceUri(string namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri");
return this.NamespaceURI == namespaceUri;
}
public virtual bool IsNamespaceUri(XmlDictionaryString namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri");
return IsNamespaceUri(namespaceUri.Value);
}
public virtual void ReadFullStartElement()
{
MoveToStartElement();
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this);
Read();
}
public virtual void ReadFullStartElement(string name)
{
MoveToStartElement(name);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, name);
Read();
}
public virtual void ReadFullStartElement(string localName, string namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri);
Read();
}
public virtual void ReadFullStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri);
Read();
}
public virtual void ReadStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
Read();
}
public virtual bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return IsStartElement(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public virtual int IndexOfLocalName(string[] localNames, string namespaceUri)
{
if (localNames == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localNames");
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri");
if (this.NamespaceURI == namespaceUri)
{
string localName = this.LocalName;
for (int i = 0; i < localNames.Length; i++)
{
string value = localNames[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i));
if (localName == value)
{
return i;
}
}
}
return -1;
}
public virtual int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString namespaceUri)
{
if (localNames == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localNames");
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri");
if (this.NamespaceURI == namespaceUri.Value)
{
string localName = this.LocalName;
for (int i = 0; i < localNames.Length; i++)
{
XmlDictionaryString value = localNames[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i));
if (localName == value.Value)
{
return i;
}
}
}
return -1;
}
public virtual string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return GetAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public virtual bool TryGetBase64ContentLength(out int length)
{
length = 0;
return false;
}
public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual byte[] ReadContentAsBase64()
{
return ReadContentAsBase64(Quotas.MaxArrayLength, MaxInitialArrayLength);
}
internal byte[] ReadContentAsBase64(int maxByteArrayContentLength, int maxInitialCount)
{
int length;
if (TryGetBase64ContentLength(out length))
{
if (length <= maxInitialCount)
{
byte[] buffer = new byte[length];
int read = 0;
while (read < length)
{
int actual = ReadContentAsBase64(buffer, read, length - read);
if (actual == 0)
XmlExceptionHelper.ThrowBase64DataExpected(this);
read += actual;
}
return buffer;
}
}
return ReadContentAsBytes(true, maxByteArrayContentLength);
}
public override string ReadContentAsString()
{
return ReadContentAsString(Quotas.MaxStringContentLength);
}
protected string ReadContentAsString(int maxStringContentLength)
{
StringBuilder sb = null;
string result = string.Empty;
bool done = false;
while (true)
{
switch (this.NodeType)
{
case XmlNodeType.Attribute:
result = this.Value;
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
// merge text content
string value = this.Value;
if (result.Length == 0)
{
result = value;
}
else
{
if (sb == null)
sb = new StringBuilder(result);
sb.Append(value);
}
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.EndEntity:
// skip comments, pis and end entity nodes
break;
case XmlNodeType.EntityReference:
if (this.CanResolveEntity)
{
this.ResolveEntity();
break;
}
goto default;
case XmlNodeType.Element:
case XmlNodeType.EndElement:
default:
done = true;
break;
}
if (done)
break;
if (this.AttributeCount != 0)
ReadAttributeValue();
else
Read();
}
if (sb != null)
result = sb.ToString();
return result;
}
public virtual byte[] ReadContentAsBinHex()
{
return ReadContentAsBinHex(Quotas.MaxArrayLength);
}
protected byte[] ReadContentAsBinHex(int maxByteArrayContentLength)
{
return ReadContentAsBytes(false, maxByteArrayContentLength);
}
private byte[] ReadContentAsBytes(bool base64, int maxByteArrayContentLength)
{
byte[][] buffers = new byte[32][];
byte[] buffer;
// Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text
int count = 384;
int bufferCount = 0;
int totalRead = 0;
while (true)
{
buffer = new byte[count];
buffers[bufferCount++] = buffer;
int read = 0;
while (read < buffer.Length)
{
int actual;
if (base64)
actual = ReadContentAsBase64(buffer, read, buffer.Length - read);
else
actual = ReadContentAsBinHex(buffer, read, buffer.Length - read);
if (actual == 0)
break;
read += actual;
}
totalRead += read;
if (read < buffer.Length)
break;
count = count * 2;
}
buffer = new byte[totalRead];
int offset = 0;
for (int i = 0; i < bufferCount - 1; i++)
{
Buffer.BlockCopy(buffers[i], 0, buffer, offset, buffers[i].Length);
offset += buffers[i].Length;
}
Buffer.BlockCopy(buffers[bufferCount - 1], 0, buffer, offset, totalRead - offset);
return buffer;
}
protected bool IsTextNode(XmlNodeType nodeType)
{
return nodeType == XmlNodeType.Text ||
nodeType == XmlNodeType.Whitespace ||
nodeType == XmlNodeType.SignificantWhitespace ||
nodeType == XmlNodeType.CDATA ||
nodeType == XmlNodeType.Attribute;
}
public virtual int ReadContentAsChars(char[] chars, int offset, int count)
{
int read = 0;
while (true)
{
XmlNodeType nodeType = this.NodeType;
if (nodeType == XmlNodeType.Element || nodeType == XmlNodeType.EndElement)
break;
if (IsTextNode(nodeType))
{
read = ReadValueChunk(chars, offset, count);
if (read > 0)
break;
if (nodeType == XmlNodeType.Attribute /* || inAttributeText */)
break;
if (!Read())
break;
}
else
{
if (!Read())
break;
}
}
return read;
}
public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
{
if (type == typeof(Guid[]))
{
string[] values = (string[])ReadContentAs(typeof(string[]), namespaceResolver);
Guid[] guids = new Guid[values.Length];
for (int i = 0; i < values.Length; i++)
guids[i] = XmlConverter.ToGuid(values[i]);
return guids;
}
if (type == typeof(UniqueId[]))
{
string[] values = (string[])ReadContentAs(typeof(string[]), namespaceResolver);
UniqueId[] uniqueIds = new UniqueId[values.Length];
for (int i = 0; i < values.Length; i++)
uniqueIds[i] = XmlConverter.ToUniqueId(values[i]);
return uniqueIds;
}
return base.ReadContentAs(type, namespaceResolver);
}
public virtual string ReadContentAsString(string[] strings, out int index)
{
if (strings == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("strings");
string s = ReadContentAsString();
index = -1;
for (int i = 0; i < strings.Length; i++)
{
string value = strings[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i));
if (value == s)
{
index = i;
return value;
}
}
return s;
}
public virtual string ReadContentAsString(XmlDictionaryString[] strings, out int index)
{
if (strings == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("strings");
string s = ReadContentAsString();
index = -1;
for (int i = 0; i < strings.Length; i++)
{
XmlDictionaryString value = strings[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i));
if (value.Value == s)
{
index = i;
return value.Value;
}
}
return s;
}
public override decimal ReadContentAsDecimal()
{
return XmlConverter.ToDecimal(ReadContentAsString());
}
public override Single ReadContentAsFloat()
{
return XmlConverter.ToSingle(ReadContentAsString());
}
public virtual UniqueId ReadContentAsUniqueId()
{
return XmlConverter.ToUniqueId(ReadContentAsString());
}
public virtual Guid ReadContentAsGuid()
{
return XmlConverter.ToGuid(ReadContentAsString());
}
public virtual TimeSpan ReadContentAsTimeSpan()
{
return XmlConverter.ToTimeSpan(ReadContentAsString());
}
public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri)
{
string prefix;
XmlConverter.ToQualifiedName(ReadContentAsString(), out prefix, out localName);
namespaceUri = LookupNamespace(prefix);
if (namespaceUri == null)
XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix);
}
/* string, bool, int, long, float, double, decimal, DateTime, base64, binhex, uniqueID, object, list*/
public override string ReadElementContentAsString()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
string value;
if (isEmptyElement)
{
Read();
value = string.Empty;
}
else
{
ReadStartElement();
value = ReadContentAsString();
ReadEndElement();
}
return value;
}
public override bool ReadElementContentAsBoolean()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
bool value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToBoolean(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsBoolean();
ReadEndElement();
}
return value;
}
public override int ReadElementContentAsInt()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
int value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToInt32(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsInt();
ReadEndElement();
}
return value;
}
public override long ReadElementContentAsLong()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
long value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToInt64(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsLong();
ReadEndElement();
}
return value;
}
public override float ReadElementContentAsFloat()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
float value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToSingle(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsFloat();
ReadEndElement();
}
return value;
}
public override double ReadElementContentAsDouble()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
double value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToDouble(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsDouble();
ReadEndElement();
}
return value;
}
public override decimal ReadElementContentAsDecimal()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
decimal value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToDecimal(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsDecimal();
ReadEndElement();
}
return value;
}
public virtual DateTime ReadElementContentAsDateTime()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
DateTime value;
if (isEmptyElement)
{
Read();
try
{
value = DateTime.Parse(string.Empty, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsDateTimeOffset().DateTime;
ReadEndElement();
}
return value;
}
public virtual UniqueId ReadElementContentAsUniqueId()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
UniqueId value;
if (isEmptyElement)
{
Read();
try
{
value = new UniqueId(string.Empty);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsUniqueId();
ReadEndElement();
}
return value;
}
public virtual Guid ReadElementContentAsGuid()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
Guid value;
if (isEmptyElement)
{
Read();
try
{
value = new Guid(string.Empty);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsGuid();
ReadEndElement();
}
return value;
}
public virtual TimeSpan ReadElementContentAsTimeSpan()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
TimeSpan value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToTimeSpan(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsTimeSpan();
ReadEndElement();
}
return value;
}
public virtual byte[] ReadElementContentAsBase64()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
Read();
buffer = Array.Empty<byte>();
}
else
{
ReadStartElement();
buffer = ReadContentAsBase64();
ReadEndElement();
}
return buffer;
}
public virtual byte[] ReadElementContentAsBinHex()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
Read();
buffer = Array.Empty<byte>();
}
else
{
ReadStartElement();
buffer = ReadContentAsBinHex();
ReadEndElement();
}
return buffer;
}
public virtual bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName)
{
localName = null;
return false;
}
public virtual bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString namespaceUri)
{
namespaceUri = null;
return false;
}
public virtual bool TryGetValueAsDictionaryString(out XmlDictionaryString value)
{
value = null;
return false;
}
private void CheckArray(Array array, int offset, int count)
{
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array"));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.ValueMustBeNonNegative)));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.ValueMustBeNonNegative)));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
public virtual bool IsStartArray(out Type type)
{
type = null;
return false;
}
public virtual bool TryGetArrayLength(out int count)
{
count = 0;
return false;
}
// Boolean
public virtual bool[] ReadBooleanArray(string localName, string namespaceUri)
{
return BooleanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual bool[] ReadBooleanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return BooleanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsBoolean();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int16
public virtual Int16[] ReadInt16Array(string localName, string namespaceUri)
{
return Int16ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Int16[] ReadInt16Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int16ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Int16[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
int i = ReadElementContentAsInt();
if (i < Int16.MinValue || i > Int16.MaxValue)
XmlExceptionHelper.ThrowConversionOverflow(this, i.ToString(NumberFormatInfo.CurrentInfo), "Int16");
array[offset + actual] = (Int16)i;
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int16[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int32
public virtual Int32[] ReadInt32Array(string localName, string namespaceUri)
{
return Int32ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Int32[] ReadInt32Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int32ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Int32[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsInt();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int32[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int64
public virtual Int64[] ReadInt64Array(string localName, string namespaceUri)
{
return Int64ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Int64[] ReadInt64Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int64ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Int64[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsLong();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Single
public virtual float[] ReadSingleArray(string localName, string namespaceUri)
{
return SingleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual float[] ReadSingleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return SingleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsFloat();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Double
public virtual double[] ReadDoubleArray(string localName, string namespaceUri)
{
return DoubleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual double[] ReadDoubleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DoubleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDouble();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Decimal
public virtual decimal[] ReadDecimalArray(string localName, string namespaceUri)
{
return DecimalArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual decimal[] ReadDecimalArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DecimalArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDecimal();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// DateTime
public virtual DateTime[] ReadDateTimeArray(string localName, string namespaceUri)
{
return DateTimeArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual DateTime[] ReadDateTimeArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DateTimeArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDateTime();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Guid
public virtual Guid[] ReadGuidArray(string localName, string namespaceUri)
{
return GuidArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Guid[] ReadGuidArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return GuidArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsGuid();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// TimeSpan
public virtual TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri)
{
return TimeSpanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual TimeSpan[] ReadTimeSpanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return TimeSpanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsTimeSpan();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
public virtual void Close()
{
base.Dispose();
}
private class XmlWrappedReader : XmlDictionaryReader, IXmlLineInfo
{
private XmlReader _reader;
private XmlNamespaceManager _nsMgr;
public XmlWrappedReader(XmlReader reader, XmlNamespaceManager nsMgr)
{
_reader = reader;
_nsMgr = nsMgr;
}
public override int AttributeCount
{
get
{
return _reader.AttributeCount;
}
}
public override string BaseURI
{
get
{
return _reader.BaseURI;
}
}
public override bool CanReadBinaryContent
{
get { return _reader.CanReadBinaryContent; }
}
public override bool CanReadValueChunk
{
get { return _reader.CanReadValueChunk; }
}
public override void Close()
{
_reader.Dispose();
_nsMgr = null;
}
public override int Depth
{
get
{
return _reader.Depth;
}
}
public override bool EOF
{
get
{
return _reader.EOF;
}
}
public override string GetAttribute(int index)
{
return _reader.GetAttribute(index);
}
public override string GetAttribute(string name)
{
return _reader.GetAttribute(name);
}
public override string GetAttribute(string name, string namespaceUri)
{
return _reader.GetAttribute(name, namespaceUri);
}
public override bool HasValue
{
get
{
return _reader.HasValue;
}
}
public override bool IsDefault
{
get
{
return _reader.IsDefault;
}
}
public override bool IsEmptyElement
{
get
{
return _reader.IsEmptyElement;
}
}
public override bool IsStartElement(string name)
{
return _reader.IsStartElement(name);
}
public override bool IsStartElement(string localName, string namespaceUri)
{
return _reader.IsStartElement(localName, namespaceUri);
}
public override string LocalName
{
get
{
return _reader.LocalName;
}
}
public override string LookupNamespace(string namespaceUri)
{
return _reader.LookupNamespace(namespaceUri);
}
public override void MoveToAttribute(int index)
{
_reader.MoveToAttribute(index);
}
public override bool MoveToAttribute(string name)
{
return _reader.MoveToAttribute(name);
}
public override bool MoveToAttribute(string name, string namespaceUri)
{
return _reader.MoveToAttribute(name, namespaceUri);
}
public override bool MoveToElement()
{
return _reader.MoveToElement();
}
public override bool MoveToFirstAttribute()
{
return _reader.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute()
{
return _reader.MoveToNextAttribute();
}
public override string Name
{
get
{
return _reader.Name;
}
}
public override string NamespaceURI
{
get
{
return _reader.NamespaceURI;
}
}
public override XmlNameTable NameTable
{
get
{
return _reader.NameTable;
}
}
public override XmlNodeType NodeType
{
get
{
return _reader.NodeType;
}
}
public override string Prefix
{
get
{
return _reader.Prefix;
}
}
public override bool Read()
{
return _reader.Read();
}
public override bool ReadAttributeValue()
{
return _reader.ReadAttributeValue();
}
public override string ReadInnerXml()
{
return _reader.ReadInnerXml();
}
public override string ReadOuterXml()
{
return _reader.ReadOuterXml();
}
public override void ReadStartElement(string name)
{
_reader.ReadStartElement(name);
}
public override void ReadStartElement(string localName, string namespaceUri)
{
_reader.ReadStartElement(localName, namespaceUri);
}
public override void ReadEndElement()
{
_reader.ReadEndElement();
}
public override ReadState ReadState
{
get
{
return _reader.ReadState;
}
}
public override void ResolveEntity()
{
_reader.ResolveEntity();
}
public override string this[int index]
{
get
{
return _reader[index];
}
}
public override string this[string name]
{
get
{
return _reader[name];
}
}
public override string this[string name, string namespaceUri]
{
get
{
return _reader[name, namespaceUri];
}
}
public override string Value
{
get
{
return _reader.Value;
}
}
public override string XmlLang
{
get
{
return _reader.XmlLang;
}
}
public override XmlSpace XmlSpace
{
get
{
return _reader.XmlSpace;
}
}
public override int ReadElementContentAsBase64(byte[] buffer, int offset, int count)
{
return _reader.ReadElementContentAsBase64(buffer, offset, count);
}
public override int ReadContentAsBase64(byte[] buffer, int offset, int count)
{
return _reader.ReadContentAsBase64(buffer, offset, count);
}
public override int ReadElementContentAsBinHex(byte[] buffer, int offset, int count)
{
return _reader.ReadElementContentAsBinHex(buffer, offset, count);
}
public override int ReadContentAsBinHex(byte[] buffer, int offset, int count)
{
return _reader.ReadContentAsBinHex(buffer, offset, count);
}
public override int ReadValueChunk(char[] chars, int offset, int count)
{
return _reader.ReadValueChunk(chars, offset, count);
}
public override Type ValueType
{
get
{
return _reader.ValueType;
}
}
public override Boolean ReadContentAsBoolean()
{
try
{
return _reader.ReadContentAsBoolean();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Boolean", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Boolean", exception));
}
}
public DateTime ReadContentAsDateTime()
{
try
{
return _reader.ReadContentAsDateTimeOffset().DateTime;
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("DateTime", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("DateTime", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("DateTime", exception));
}
}
public override Decimal ReadContentAsDecimal()
{
try
{
return (Decimal)_reader.ReadContentAs(typeof(Decimal), null);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Decimal", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Decimal", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Decimal", exception));
}
}
public override Double ReadContentAsDouble()
{
try
{
return _reader.ReadContentAsDouble();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Double", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Double", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Double", exception));
}
}
public override Int32 ReadContentAsInt()
{
try
{
return _reader.ReadContentAsInt();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int32", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int32", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int32", exception));
}
}
public override Int64 ReadContentAsLong()
{
try
{
return _reader.ReadContentAsLong();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int64", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int64", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int64", exception));
}
}
public override Single ReadContentAsFloat()
{
try
{
return _reader.ReadContentAsFloat();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Single", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Single", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Single", exception));
}
}
public override string ReadContentAsString()
{
try
{
return _reader.ReadContentAsString();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("String", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("String", exception));
}
}
public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
{
return _reader.ReadContentAs(type, namespaceResolver);
}
public bool HasLineInfo()
{
IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
if (lineInfo == null)
return false;
return lineInfo.HasLineInfo();
}
public int LineNumber
{
get
{
IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
if (lineInfo == null)
return 1;
return lineInfo.LineNumber;
}
}
public int LinePosition
{
get
{
IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
if (lineInfo == null)
return 1;
return lineInfo.LinePosition;
}
}
}
}
}
| |
/* ====================================================================
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 NPOI.HWPF.UserModel
{
using System;
using NPOI.HWPF.Model.Types;
/**
* @author Ryan Ackley
*/
public class CharacterProperties
: CHPAbstractType //, ICloneable
{
public static short SPRM_FRMARKDEL = (short)0x0800;
public static short SPRM_FRMARK = 0x0801;
public static short SPRM_FFLDVANISH = 0x0802;
public static short SPRM_PICLOCATION = 0x6A03;
public static short SPRM_IBSTRMARK = 0x4804;
public static short SPRM_DTTMRMARK = 0x6805;
public static short SPRM_FDATA = 0x0806;
public static short SPRM_SYMBOL = 0x6A09;
public static short SPRM_FOLE2 = 0x080A;
public static short SPRM_HIGHLIGHT = 0x2A0C;
public static short SPRM_OBJLOCATION = 0x680E;
public static short SPRM_ISTD = 0x4A30;
public static short SPRM_FBOLD = 0x0835;
public static short SPRM_FITALIC = 0x0836;
public static short SPRM_FSTRIKE = 0x0837;
public static short SPRM_FOUTLINE = 0x0838;
public static short SPRM_FSHADOW = 0x0839;
public static short SPRM_FSMALLCAPS = 0x083A;
public static short SPRM_FCAPS = 0x083B;
public static short SPRM_FVANISH = 0x083C;
public static short SPRM_KUL = 0x2A3E;
public static short SPRM_DXASPACE = unchecked((short)0x8840);
public static short SPRM_LID = 0x4A41;
public static short SPRM_ICO = 0x2A42;
public static short SPRM_HPS = 0x4A43;
public static short SPRM_HPSPOS = 0x4845;
public static short SPRM_ISS = 0x2A48;
public static short SPRM_HPSKERN = 0x484B;
public static short SPRM_YSRI = 0x484E;
public static short SPRM_RGFTCASCII = 0x4A4F;
public static short SPRM_RGFTCFAREAST = 0x4A50;
public static short SPRM_RGFTCNOTFAREAST = 0x4A51;
public static short SPRM_CHARSCALE = 0x4852;
public static short SPRM_FDSTRIKE = 0x2A53;
public static short SPRM_FIMPRINT = 0x0854;
public static short SPRM_FSPEC = 0x0855;
public static short SPRM_FOBJ = 0x0856;
public static short SPRM_PROPRMARK = unchecked((short)0xCA57);
public static short SPRM_FEMBOSS = 0x0858;
public static short SPRM_SFXTEXT = 0x2859;
public static short SPRM_DISPFLDRMARK = unchecked((short)0xCA62);
public static short SPRM_IBSTRMARKDEL = 0x4863;
public static short SPRM_DTTMRMARKDEL = 0x6864;
public static short SPRM_BRC = 0x6865;
public static short SPRM_SHD = 0x4866;
public static short SPRM_IDSIRMARKDEL = 0x4867;
public static short SPRM_CPG = 0x486B;
public static short SPRM_NONFELID = 0x486D;
public static short SPRM_FELID = 0x486E;
public static short SPRM_IDCTHINT = 0x286F;
int _ico24 = -1; // default to -1 so we can ignore it for word 97 files
public CharacterProperties()
{
field_17_fcPic = -1;
field_22_dttmRMark = new DateAndTime();
field_23_dttmRMarkDel = new DateAndTime();
field_36_dttmPropRMark = new DateAndTime();
field_40_dttmDispFldRMark = new DateAndTime();
field_41_xstDispFldRMark = new byte[36];
field_42_shd = new ShadingDescriptor();
field_43_brc = new BorderCode();
field_7_hps = 20;
field_24_istd = 10;
field_16_wCharScale = 100;
field_13_lidDefault = 0x0400;
field_14_lidFE = 0x0400;
}
public bool IsMarkedDeleted()
{
return IsFRMarkDel();
}
public void markDeleted(bool mark)
{
base.SetFRMarkDel(mark);
}
public bool IsBold()
{
return IsFBold();
}
public void SetBold(bool bold)
{
base.SetFBold(bold);
}
public bool IsItalic()
{
return IsFItalic();
}
public void SetItalic(bool italic)
{
base.SetFItalic(italic);
}
public bool IsOutlined()
{
return IsFOutline();
}
public void SetOutline(bool outlined)
{
base.SetFOutline(outlined);
}
public bool IsFldVanished()
{
return IsFFldVanish();
}
public void SetFldVanish(bool fldVanish)
{
base.SetFFldVanish(fldVanish);
}
public bool IsSmallCaps()
{
return IsFSmallCaps();
}
public void SetSmallCaps(bool smallCaps)
{
base.SetFSmallCaps(smallCaps);
}
public bool IsCapitalized()
{
return IsFCaps();
}
public void SetCapitalized(bool caps)
{
base.SetFCaps(caps);
}
public bool IsVanished()
{
return IsFVanish();
}
public void SetVanished(bool vanish)
{
base.SetFVanish(vanish);
}
public bool IsMarkedInserted()
{
return IsFRMark();
}
public void markInserted(bool mark)
{
base.SetFRMark(mark);
}
public bool IsStrikeThrough()
{
return IsFStrike();
}
public void strikeThrough(bool strike)
{
base.SetFStrike(strike);
}
public bool IsShadowed()
{
return IsFShadow();
}
public void SetShadow(bool shadow)
{
base.SetFShadow(shadow);
}
public bool IsEmbossed()
{
return IsFEmboss();
}
public void SetEmbossed(bool emboss)
{
base.SetFEmboss(emboss);
}
public bool IsImprinted()
{
return IsFImprint();
}
public void SetImprinted(bool imprint)
{
base.SetFImprint(imprint);
}
public bool IsDoubleStrikeThrough()
{
return IsFDStrike();
}
public void SetDoubleStrikeThrough(bool dstrike)
{
base.SetFDStrike(dstrike);
}
public int GetFontSize()
{
return GetHps();
}
public void SetFontSize(int halfPoints)
{
base.SetHps(halfPoints);
}
public int GetCharacterSpacing()
{
return GetDxaSpace();
}
public void SetCharacterSpacing(int twips)
{
base.SetDxaSpace(twips);
}
public short GetSubSuperScriptIndex()
{
return GetIss();
}
public void SetSubSuperScriptIndex(short Iss)
{
base.SetDxaSpace(Iss);
}
public int GetUnderlineCode()
{
return base.GetKul();
}
public void SetUnderlineCode(int kul)
{
base.SetKul((byte)kul);
}
public int GetColor()
{
return base.GetIco();
}
public void SetColor(int color)
{
base.SetIco((byte)color);
}
public int GetVerticalOffset()
{
return base.GetHpsPos();
}
public void SetVerticalOffset(int hpsPos)
{
base.SetHpsPos(hpsPos);
}
public int GetKerning()
{
return base.GetHpsKern();
}
public void SetKerning(int kern)
{
base.SetHpsKern(kern);
}
public bool IsHighlighted()
{
return base.IsFHighlight();
}
public void SetHighlighted(byte color)
{
base.SetIcoHighlight(color);
}
/**
* Get the ico24 field for the CHP record.
*/
public int GetIco24()
{
if (_ico24 == -1)
{
switch (field_11_ico) // convert word 97 colour numbers to 0xBBGGRR value
{
case 0: // auto
return -1;
case 1: // black
return 0x000000;
case 2: // blue
return 0xFF0000;
case 3: // cyan
return 0xFFFF00;
case 4: // green
return 0x00FF00;
case 5: // magenta
return 0xFF00FF;
case 6: // red
return 0x0000FF;
case 7: // yellow
return 0x00FFFF;
case 8: // white
return 0x0FFFFFF;
case 9: // dark blue
return 0x800000;
case 10: // dark cyan
return 0x808000;
case 11: // dark green
return 0x008000;
case 12: // dark magenta
return 0x800080;
case 13: // dark red
return 0x000080;
case 14: // dark yellow
return 0x008080;
case 15: // dark grey
return 0x808080;
case 16: // light grey
return 0xC0C0C0;
}
}
return _ico24;
}
/**
* Set the ico24 field for the CHP record.
*/
public void SetIco24(int colour24)
{
_ico24 = colour24 & 0xFFFFFF; // only keep the 24bit 0xBBGGRR colour
}
//public Object Clone()
//{
// CharacterProperties cp = (CharacterProperties)base.Clone();
// cp.field_22_dttmRMark = (DateAndTime)field_22_dttmRMark.Clone();
// cp.field_23_dttmRMarkDel = (DateAndTime)field_23_dttmRMarkDel.Clone();
// cp.field_36_dttmPropRMark = (DateAndTime)field_36_dttmPropRMark.Clone();
// cp.field_40_dttmDispFldRMark = (DateAndTime)field_40_dttmDispFldRMark.Clone();
// cp.field_41_xstDispFldRMark = (byte[])field_41_xstDispFldRMark.Clone();
// cp.field_42_shd = (ShadingDescriptor)field_42_shd.Clone();
// cp._ico24 = _ico24;
// return cp;
//}
}
}
| |
#region MIT License
/*
MIT License
Copyright (c) 2017 Darin Higgins
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.IO;
using System.Xml;
using ExceptionExtensions.Internal;
/// <summary>
/// This file will need to be included in your project to allow you to retrieve
/// Line number and source file information from the embedded GenerateLineMap resource
///
/// REFERENCES REQUIRED:
/// System.Runtime.Serialization
/// </summary>
namespace ExceptionExtensions
{
public static partial class ExceptionExtensions
{
/// <summary>
/// really only for debugging
/// </summary>
public static void IgnorePDB(this Exception ex)
{
LineMap.IgnorePDB = true;
}
public static int GetLine(this Exception ex)
{
return LineMap.InfoFrom(ex).Line;
}
public static string GetSourceFile(this Exception ex)
{
return LineMap.InfoFrom(ex).SourceFile;
}
}
}
namespace ExceptionExtensions.Internal
{
/// <summary>
/// This file contains the necessary logic to deserialize a line map resource from an
/// assembly and resolve a line number from a stack trace, if possible.
///
/// This File (and ONLY this file) is included in the NUGET as a content item
/// that gets inserted into the target project.
///
/// </summary>
/// <remarks></remarks>
/// <editHistory></editHistory>
public static class LineMap
{
private const string LINEMAPNAMESPACE = "http://schemas.linemap.net";
public static bool IgnorePDB = false;
/// <summary>
/// Resolve a Line number from the stack trace of an exception
/// </summary>
/// <param name="sf"></param>
/// <param name="Line"></param>
/// <param name="SourceFile"></param>
/// <remarks></remarks>
public static SourceInfo InfoFrom(Exception ex)
{
var sl = new SourceInfo();
//get stack frame from the Exception
var stackTrace = new StackTrace(ex);
var stackFrame = stackTrace.GetFrame(0);
if (!IgnorePDB)
{
sl.Line = stackFrame.GetFileLineNumber();
if (sl.Line != 0) return sl;
}
// first, get the base addr of the method
// if possible
// you have to have symbols to do this
if (AssemblyLineMaps.Count == 0)
return sl;
// first, check if for symbols for the assembly for this stack frame
if (!AssemblyLineMaps.Keys.Contains(stackFrame.GetMethod().DeclaringType.Assembly.CodeBase))
{
AssemblyLineMaps.Add(stackFrame.GetMethod().DeclaringType.Assembly);
}
// if it's still not available, not much else we can do
if (!AssemblyLineMaps.Keys.Contains(stackFrame.GetMethod().DeclaringType.Assembly.CodeBase))
{
return sl;
}
// retrieve the cache
var alm = AssemblyLineMaps[stackFrame.GetMethod().DeclaringType.Assembly.CodeBase];
// does the symbols list contain the metadata token for this method?
MemberInfo mi = stackFrame.GetMethod();
// Don't call this mdtoken or PostSharp will barf on it! Jeez
long mdtokn = mi.MetadataToken;
if (!alm.Symbols.ContainsKey(mdtokn))
return sl;
// all is good so get the line offset (as close as possible, considering any optimizations that
// might be in effect)
var ILOffset = stackFrame.GetILOffset();
if (ILOffset != StackFrame.OFFSET_UNKNOWN)
{
Int64 Addr = alm.Symbols[mdtokn].Address + ILOffset;
// now start hunting down the line number entry
// use a simple search. LINQ might make this easier
// but I'm not sure how. Also, a binary search would be faster
// but this isn't something that's really performance dependent
int i = 1;
for (i = alm.AddressToLineMap.Count - 1; i >= 0; i += -1)
{
if (alm.AddressToLineMap[i].Address <= Addr)
{
break;
}
}
// since the address may end up between line numbers,
// always return the line num found
// even if it's not an exact match
sl.Line = alm.AddressToLineMap[i].Line;
sl.SourceFile = alm.Names[alm.AddressToLineMap[i].SourceFileIndex];
}
return sl;
}
/// <summary>
/// Used to pass linemap information to the stackframe renderer
/// </summary>
public class SourceInfo
{
public string SourceFile = string.Empty;
public int Line = 0;
}
#region " API Declarations for working with Resources"
[DllImport("kernel32", EntryPoint = "FindResourceExA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern IntPtr FindResourceEx(Int32 hModule, [MarshalAs(UnmanagedType.LPStr)]
string lpType, [MarshalAs(UnmanagedType.LPStr)]
string lpName, Int16 wLanguage);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern IntPtr LoadResource(IntPtr hInstance, IntPtr hResInfo);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern IntPtr LockResource(IntPtr hResData);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern IntPtr FreeResource(IntPtr hResData);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 SizeofResource(IntPtr hInstance, IntPtr hResInfo);
[DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern void CopyMemory(ref byte pvDest, IntPtr pvSrc, Int32 cbCopy);
#endregion
/// <summary>
/// The class simply defines several values we need to share between
/// the GenerateLineMap utility and whatever project needs to read line numbers
/// </summary>
/// <remarks></remarks>
/// <editHistory></editHistory>
internal class LineMapKeys
{
public static byte[] ENCKEY = new byte[32] {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32
};
public static byte[] ENCIV = new byte[16] {
65, 2, 68, 26, 7, 178, 200, 3, 65, 110, 68, 13, 69, 16, 200, 219
};
public static string ResTypeName = "LINEMAP";
public static string ResName = "LINEMAPDATA";
public static short ResLang = 0;
}
/// <summary>
/// Tracks symbol cache entries for all assemblies that appear in a stack frame
/// </summary>
/// <remarks></remarks>
/// <editHistory></editHistory>
[DataContract(Namespace = LINEMAPNAMESPACE)]
public class AssemblyLineMap
{
/// <summary>
/// Track the assembly this map is for
/// no need to persist this information
/// </summary>
/// <remarks></remarks>
public string FileName;
[DataContract(Namespace = LINEMAPNAMESPACE)]
public class AddressToLine
{
// these members must get serialized
[DataMember()]
public Int64 Address;
[DataMember()]
public Int32 Line;
[DataMember()]
public int SourceFileIndex;
[DataMember()]
public int ObjectNameIndex;
// these members do not need to be serialized
public string SourceFile;
public string ObjectName;
/// <summary>
/// Parameterless constructor for serialization
/// </summary>
/// <remarks></remarks>
public AddressToLine()
{
}
public AddressToLine(Int32 Line, Int64 Address, string SourceFile, int SourceFileIndex, string ObjectName, int ObjectNameIndex)
{
this.Line = Line;
this.Address = Address;
this.SourceFile = SourceFile;
this.SourceFileIndex = SourceFileIndex;
this.ObjectName = ObjectName;
this.ObjectNameIndex = ObjectNameIndex;
}
}
/// <summary>
/// Track the Line number list enumerated from the PDB
/// Note, the list is already sorted
/// </summary>
/// <remarks></remarks>
[DataMember()]
public List<AddressToLine> AddressToLineMap = new List<AddressToLine>();
/// <summary>
/// Private class to track Symbols read from the PDB file
/// </summary>
/// <remarks></remarks>
/// <editHistory></editHistory>
[DataContract(Namespace = LINEMAPNAMESPACE)]
public class SymbolInfo
{
// these need to be persisted
[DataMember()]
public long Address;
[DataMember()]
public long Token;
// these aren't persisted
public string Name;
/// <summary>
/// Parameterless constructor for serialization
/// </summary>
/// <remarks></remarks>
public SymbolInfo()
{
}
public SymbolInfo(string Name, long Address, long Token)
{
this.Name = Name;
this.Address = Address;
this.Token = Token;
}
}
/// <summary>
/// Track the Symbols enumerated from the PDB keyed by their token
/// </summary>
/// <remarks></remarks>
[DataMember()]
public Dictionary<long, SymbolInfo> Symbols = new Dictionary<long, SymbolInfo>();
/// <summary>
/// Track a list of string values
/// </summary>
/// <remarks></remarks>
/// <editHistory></editHistory>
public class NamesList : List<string>
{
/// <summary>
/// When adding names, if the name already exists in the list
/// don't bother to add it again
/// </summary>
/// <param name="Name"></param>
/// <returns></returns>
public new int Add(string Name)
{
//Don't lower case everything
//Name = Name.ToLower();
var i = this.IndexOf(Name);
if (i >= 0)
return i;
// gotta add the name
base.Add(Name);
return this.Count - 1;
}
/// <summary>
/// Override this prop so that requested an index that doesn't exist just
/// returns a blank string
/// </summary>
/// <param name="Index"></param>
/// <value></value>
/// <remarks></remarks>
public new string this[int Index]
{
get
{
if (Index >= 0 & Index < this.Count)
{
return base[Index];
}
else
{
return string.Empty;
}
}
set
{
base[Index] = value;
}
}
}
/// <summary>
/// Tracks various string values in a flat list that is indexed into
/// </summary>
/// <remarks></remarks>
[DataMember()]
public NamesList Names = new NamesList();
/// <summary>
/// Create a new map based on an assembly filename
/// </summary>
/// <param name="FileName"></param>
/// <remarks></remarks>
public AssemblyLineMap(string FileName)
{
this.FileName = FileName;
Load();
}
/// <summary>
/// Parameterless constructor for serialization
/// </summary>
/// <remarks></remarks>
public AssemblyLineMap()
{
}
/// <summary>
/// Clear out all internal information
/// </summary>
/// <remarks></remarks>
public void Clear()
{
this.Symbols.Clear();
this.AddressToLineMap.Clear();
this.Names.Clear();
}
/// <summary>
/// Load a LINEMAP file
/// </summary>
/// <remarks></remarks>
private void Load()
{
Stream buf = FileToStream(this.FileName + ".linemap");
var buf2 = DecryptStream(buf);
Transfer(Depersist(DecompressStream(buf2)));
}
/// <summary>
/// Create a new assemblylinemap based on an assembly
/// </summary>
/// <remarks></remarks>
public AssemblyLineMap(Assembly Assembly)
{
//LoadLineMapResource(Assembly.GetExecutingAssembly(), Symbols, Lines)
this.FileName = Assembly.CodeBase.Replace("file:///", "");
try
{
// Get the hInstance of the indicated exe/dll image
var curmodule = Assembly.GetLoadedModules()[0];
var hInst = System.Runtime.InteropServices.Marshal.GetHINSTANCE(curmodule);
// retrieve a handle to the Linemap resource
// Since it's a standard Win32 resource, the nice .NET resource functions
// can't be used
//
// Important Note: The FindResourceEx function appears to be case
// sensitive in that you really HAVE to pass in UPPER CASE search
// arguments
var hres = FindResourceEx(hInst.ToInt32(), LineMapKeys.ResTypeName, LineMapKeys.ResName, LineMapKeys.ResLang);
byte[] bytes = null;
if (hres != IntPtr.Zero)
{
// Load the resource to get it into memory
var hresdata = LoadResource(hInst, hres);
IntPtr lpdata = LockResource(hresdata);
var sz = SizeofResource(hInst, hres);
if (lpdata != IntPtr.Zero & sz > 0)
{
// able to lock it,
// so copy the data into a byte array
bytes = new byte[sz];
CopyMemory(ref bytes[0], lpdata, sz);
FreeResource(hresdata);
}
}
else
{
//Check for a side by side linemap file
string mapfile = this.FileName + ".linemap";
if (File.Exists(mapfile))
{
//load it from there
bytes = File.ReadAllBytes(mapfile);
}
}
// deserialize the symbol map and line num list
using (System.IO.MemoryStream MemStream = new MemoryStream(bytes))
{
// release the byte array to free up the memory
bytes = null;
// and depersist the object
Stream temp = MemStream;
var temp2 = DecryptStream(temp);
Transfer(Depersist(DecompressStream(temp2)));
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(string.Format("ERROR: {0}", ex.ToString()));
// yes, it's bad form to catch all exceptions like this
// but this is part of an exception handler
// so it really can't be allowed to fail with an exception!
}
try
{
if (this.Symbols.Count == 0)
{
// weren't able to load resources, so try the LINEMAP file
Load();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(string.Format("ERROR: {0}", ex.ToString()));
}
}
/// <summary>
/// Transfer a given AssemblyLineMap's contents to this one
/// </summary>
/// <param name="alm"></param>
/// <remarks></remarks>
private void Transfer(AssemblyLineMap alm)
{
// transfer Internal variables over
this.AddressToLineMap = alm.AddressToLineMap;
this.Symbols = alm.Symbols;
this.Names = alm.Names;
}
/// <summary>
/// Read an entire file into a memory stream
/// </summary>
/// <param name="Filename"></param>
/// <returns></returns>
private MemoryStream FileToStream(string Filename)
{
if (File.Exists(Filename))
{
using (System.IO.FileStream FileStream = new System.IO.FileStream(Filename, FileMode.Open))
{
if (FileStream.Length > 0)
{
byte[] Buffer = null;
Buffer = new byte[Convert.ToInt32(FileStream.Length - 1) + 1];
FileStream.Read(Buffer, 0, Convert.ToInt32(FileStream.Length));
return new MemoryStream(Buffer);
}
}
}
// just return an empty stream
return new MemoryStream();
}
/// <summary>
/// Decrypt a stream based on fixed internal keys
/// </summary>
/// <param name="EncryptedStream"></param>
/// <returns></returns>
private MemoryStream DecryptStream(Stream EncryptedStream)
{
try
{
System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged();
Enc.KeySize = 256;
// KEY is 32 byte array
Enc.Key = LineMapKeys.ENCKEY;
// IV is 16 byte array
Enc.IV = LineMapKeys.ENCIV;
var cryptoStream = new System.Security.Cryptography.CryptoStream(EncryptedStream, Enc.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read);
byte[] buf = null;
buf = new byte[1024];
MemoryStream DecryptedStream = new MemoryStream();
while (EncryptedStream.Length > 0)
{
var l = cryptoStream.Read(buf, 0, 1024);
if (l == 0)
break; // TODO: might not be correct. Was : Exit Do
if (l < 1024)
Array.Resize(ref buf, l);
DecryptedStream.Write(buf, 0, buf.GetUpperBound(0) + 1);
if (l < 1024)
break; // TODO: might not be correct. Was : Exit Do
}
DecryptedStream.Position = 0;
return DecryptedStream;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(string.Format("ERROR: {0}", ex.ToString()));
// any problems, nothing much to do, so return an empty stream
return new MemoryStream();
}
}
/// <summary>
/// Uncompress a memory stream
/// </summary>
/// <param name="CompressedStream"></param>
/// <returns></returns>
private MemoryStream DecompressStream(MemoryStream CompressedStream)
{
System.IO.Compression.GZipStream GZip = new System.IO.Compression.GZipStream(CompressedStream, System.IO.Compression.CompressionMode.Decompress);
byte[] buf = null;
buf = new byte[1024];
MemoryStream UncompressedStream = new MemoryStream();
while (CompressedStream.Length > 0)
{
var l = GZip.Read(buf, 0, 1024);
if (l == 0)
break; // TODO: might not be correct. Was : Exit Do
if (l < 1024)
Array.Resize(ref buf, l);
UncompressedStream.Write(buf, 0, buf.GetUpperBound(0) + 1);
if (l < 1024)
break; // TODO: might not be correct. Was : Exit Do
}
UncompressedStream.Position = 0;
return UncompressedStream;
}
private AssemblyLineMap Depersist(MemoryStream MemoryStream)
{
MemoryStream.Position = 0;
if (MemoryStream.Length != 0)
{
var binaryDictionaryreader = XmlDictionaryReader.CreateBinaryReader(MemoryStream, new XmlDictionaryReaderQuotas());
var serializer = new DataContractSerializer(typeof(AssemblyLineMap));
return (AssemblyLineMap)serializer.ReadObject(binaryDictionaryreader);
}
else
{
// jsut return an empty object
return new AssemblyLineMap();
}
}
/// <summary>
/// Stream this object to a memory stream and return it
/// All other persistence is handled externally because none of that
/// is necessary under normal usage, only when generating a linemap
/// </summary>
/// <returns></returns>
public MemoryStream ToStream()
{
System.IO.MemoryStream MemStream = new System.IO.MemoryStream();
var binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(MemStream);
var serializer = new DataContractSerializer(typeof(AssemblyLineMap));
serializer.WriteObject(binaryDictionaryWriter, this);
binaryDictionaryWriter.Flush();
return MemStream;
}
/// <summary>
/// Helper function to add an address to line map entry
/// </summary>
/// <param name="Line"></param>
/// <param name="Address"></param>
/// <param name="SourceFile"></param>
/// <param name="ObjectName"></param>
/// <remarks></remarks>
public void AddAddressToLine(Int32 Line, Int64 Address, string SourceFile, string ObjectName)
{
var SourceFileIndex = this.Names.Add(SourceFile);
var ObjectNameIndex = this.Names.Add(ObjectName);
var atl = new AssemblyLineMap.AddressToLine(Line, Address, SourceFile, SourceFileIndex, ObjectName, ObjectNameIndex);
this.AddressToLineMap.Add(atl);
}
}
/// <summary>
/// Define a collection of assemblylinemaps (one for each assembly we
/// need to generate a stack trace through)
/// </summary>
/// <remarks></remarks>
/// <editHistory></editHistory>
public class AssemblyLineMapCollection : Dictionary<string, AssemblyLineMap>
{
/// <summary>
/// Load a linemap file given the NAME of an assembly
/// obviously, the Assembly must exist.
/// </summary>
/// <param name="FileName"></param>
/// <remarks></remarks>
public AssemblyLineMap Add(string FileName)
{
if (!File.Exists(FileName))
{
throw new FileNotFoundException("The file could not be found.", FileName);
}
if (this.ContainsKey(FileName))
{
// no need, already loaded (should it reload?)
return this[FileName];
}
else
{
var alm = new AssemblyLineMap(FileName);
this.Add(FileName, alm);
return alm;
}
}
public AssemblyLineMap Add(Assembly Assembly)
{
var FileName = Assembly.CodeBase;
if (this.ContainsKey(FileName))
{
// no need, already loaded (should it reload?)
return this[FileName];
}
else
{
var alm = new AssemblyLineMap(Assembly);
this.Add(FileName, alm);
return alm;
}
}
}
public static AssemblyLineMapCollection AssemblyLineMaps = new AssemblyLineMapCollection();
}
}
| |
// Copyright (C) 2011-2019 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
namespace OpenGL.Objects
{
/// <summary>
/// The types available in a ShaderPrograms.
/// </summary>
public enum ShaderUniformType
{
/// <summary>
///
/// </summary>
Unknown = 0,
#region Single-Precision Floating-Point Types
/// <summary>
/// A single single-precision floating-point value.
/// </summary>
Float = Gl.FLOAT,
/// <summary>
/// A vector of two single-precision floating-point values.
/// </summary>
Vec2 = Gl.FLOAT_VEC2,
/// <summary>
/// A vector of three single-precision floating-point values.
/// </summary>
Vec3 = Gl.FLOAT_VEC3,
/// <summary>
/// A vector of four single-precision floating-point values.
/// </summary>
Vec4 = Gl.FLOAT_VEC4,
#endregion
#if !MONODROID
#region Double Precision Floating-Point Types
/// <summary>
/// A single double-precision floating-point value.
/// </summary>
Double = Gl.DOUBLE,
/// <summary>
/// A vector of two double-precision floating-point values.
/// </summary>
DoubleVec2 = Gl.DOUBLE_VEC2,
/// <summary>
/// A vector of three double-precision floating-point values.
/// </summary>
DoubleVec3 = Gl.DOUBLE_VEC3,
/// <summary>
/// A vector of four double-precision floating-point values.
/// </summary>
DoubleVec4 = Gl.DOUBLE_VEC4,
#endregion
#endif
#region Signed Integer Types
/// <summary>
/// A single signed integer value.
/// </summary>
Int = Gl.INT,
/// <summary>
/// A vector of two signed integer values.
/// </summary>
IntVec2 = Gl.INT_VEC2,
/// <summary>
/// A vector of three signed integer values.
/// </summary>
IntVec3 = Gl.INT_VEC3,
/// <summary>
/// A vector of four signed integer values.
/// </summary>
IntVec4 = Gl.INT_VEC4,
#endregion
#region Unsigned Integer Types
/// <summary>
/// A single unsigned integer value.
/// </summary>
UInt = Gl.UNSIGNED_INT,
/// <summary>
/// A vector of two unsigned integer values.
/// </summary>
UIntVec2 = Gl.UNSIGNED_INT_VEC2,
/// <summary>
/// A vector of three unsigned integer values.
/// </summary>
UIntVec3 = Gl.UNSIGNED_INT_VEC3,
/// <summary>
/// A vector of four unsigned integer values.
/// </summary>
UIntVec4 = Gl.UNSIGNED_INT_VEC4,
#endregion
#region Boolean Types
/// <summary>
/// A single boolean value.
/// </summary>
Bool = Gl.BOOL,
/// <summary>
/// A vector of two boolean values.
/// </summary>
BoolVec2 = Gl.BOOL_VEC2,
/// <summary>
/// A vector of three boolean values.
/// </summary>
BoolVec3 = Gl.BOOL_VEC3,
/// <summary>
/// A vector of four boolean values.
/// </summary>
BoolVec4 = Gl.BOOL_VEC4,
#endregion
#region Square Single-Precision Floating-Point Matrix Types
/// <summary>
/// A matrix of two rows and two columns of single-precision floating-point values.
/// </summary>
Mat2x2 = Gl.FLOAT_MAT2,
/// <summary>
/// A matrix of three rows and three columns of single-precision floating-point values.
/// </summary>
Mat3x3 = Gl.FLOAT_MAT3,
/// <summary>
/// A matrix of four rows and four columns of single-precision floating-point values.
/// </summary>
Mat4x4 = Gl.FLOAT_MAT4,
#endregion
#region Non-Square Single-Precision Floating-Point Matrix Types
/// <summary>
/// A matrix of three rows and two columns of single-precision floating-point values.
/// </summary>
Mat2x3 = Gl.FLOAT_MAT2x3,
/// <summary>
/// A matrix of four rows and two columns of single-precision floating-point values.
/// </summary>
Mat2x4 = Gl.FLOAT_MAT2x4,
/// <summary>
/// A matrix of two rows and three columns of single-precision floating-point values.
/// </summary>
Mat3x2 = Gl.FLOAT_MAT3x2,
/// <summary>
/// A matrix of four rows and three columns of single-precision floating-point values.
/// </summary>
Mat3x4 = Gl.FLOAT_MAT3x4,
/// <summary>
/// A matrix of four rows and two columns of single-precision floating-point values.
/// </summary>
Mat4x2 = Gl.FLOAT_MAT4x2,
/// <summary>
/// A matrix of four rows and three columns of single-precision floating-point values.
/// </summary>
Mat4x3 = Gl.FLOAT_MAT4x3,
#endregion
#if !MONODROID
#region Square Double-Precision Floating-Point Matrix Types
/// <summary>
/// A matrix of two rows and two columns of double-precision floating-point values.
/// </summary>
DoubleMat2x2 = Gl.DOUBLE_MAT2,
/// <summary>
/// A matrix of three rows and three columns of double-precision floating-point values.
/// </summary>
DoubleMat3x3 = Gl.DOUBLE_MAT3,
/// <summary>
/// A matrix of four rows and four columns of double-precision floating-point values.
/// </summary>
DoubleMat4x4 = Gl.DOUBLE_MAT4,
#endregion
#region Non-Square Double-Precision Floating-Point Matrix Types
/// <summary>
/// A matrix of three rows and two columns of double-precision floating-point values.
/// </summary>
DoubleMat2x3 = Gl.DOUBLE_MAT2x3,
/// <summary>
/// A matrix of four rows and two columns of double-precision floating-point values.
/// </summary>
DoubleMat2x4 = Gl.DOUBLE_MAT2x4,
/// <summary>
/// A matrix of two rows and three columns of double-precision floating-point values.
/// </summary>
DoubleMat3x2 = Gl.DOUBLE_MAT3x2,
/// <summary>
/// A matrix of four rows and three columns of double-precision floating-point values.
/// </summary>
DoubleMat3x4 = Gl.DOUBLE_MAT3x4,
/// <summary>
/// A matrix of four rows and two columns of double-precision floating-point values.
/// </summary>
DoubleMat4x2 = Gl.DOUBLE_MAT4x2,
/// <summary>
/// A matrix of four rows and three columns of double-precision floating-point values.
/// </summary>
DoubleMat4x3 = Gl.DOUBLE_MAT4x3,
#endregion
#endif
#region Floating-Point (Normalized) Texture Samplers
#if !MONODROID
/// <summary>
/// Texture 1D sampler.
/// </summary>
Sampler1D = Gl.SAMPLER_1D,
#endif
/// <summary>
/// Texture 2D sampler.
/// </summary>
Sampler2D = Gl.SAMPLER_2D,
/// <summary>
/// Texture 3D sampler.
/// </summary>
Sampler3D = Gl.SAMPLER_3D,
/// <summary>
/// Texture cube sampler.
/// </summary>
SamplerCube = Gl.SAMPLER_CUBE,
#if !MONODROID
/// <summary>
/// Texture rectangle sampler.
/// </summary>
Sampler2DRect = Gl.SAMPLER_2D_RECT,
#endif
#endregion
#region Shadow Texture Samplers
#if !MONODROID
/// <summary>
/// Depth texture 1D sampler.
/// </summary>
Sampler1DShadow = Gl.SAMPLER_1D_SHADOW,
#endif
/// <summary>
/// Depth texture 2D sampler.
/// </summary>
Sampler2DShadow = Gl.SAMPLER_2D_SHADOW,
/// <summary>
/// Depth texture cube sampler.
/// </summary>
SamplerCubeShadow = Gl.SAMPLER_CUBE_SHADOW,
#if !MONODROID
/// <summary>
/// Depth texture rectangle sampler.
/// </summary>
Sampler2DRectShadow = Gl.SAMPLER_2D_RECT_SHADOW,
#endif
#endregion
#if !MONODROID
#region Texture Array Samplers
/// <summary>
/// Texture 1D array sampler.
/// </summary>
Sampler1DArray = Gl.SAMPLER_1D_ARRAY,
/// <summary>
/// Texture 2D array sampler.
/// </summary>
Sampler2DArray = Gl.SAMPLER_2D_ARRAY,
/// <summary>
/// Texture 2D array sampler.
/// </summary>
SamplerCubeMapArray = Gl.SAMPLER_CUBE_MAP_ARRAY,
#endregion
#endif
#region Shadow Texture Array Samplers
#if !MONODROID
/// <summary>
/// Depth texture 1D array sampler.
/// </summary>
Sampler1DArrayShadow = Gl.SAMPLER_1D_ARRAY_SHADOW,
#endif
/// <summary>
/// Depth texture 2D array sampler.
/// </summary>
Sampler2DArrayShadow = Gl.SAMPLER_2D_ARRAY_SHADOW,
#endregion
#region Multisample Texture Samplers
/// <summary>
/// Multisample texture 2D sampler.
/// </summary>
Sampler2DMultisample = Gl.SAMPLER_2D_MULTISAMPLE,
/// <summary>
/// Multisample texture 2D array sampler.
/// </summary>
Sampler2DMultisampleArray = Gl.SAMPLER_2D_MULTISAMPLE_ARRAY,
#endregion
#region Texture Buffer Sampler
/// <summary>
/// Texture buffer sampler.
/// </summary>
SamplerBuffer = Gl.SAMPLER_BUFFER,
#endregion
#region Integer Texture Sampler
#if !MONODROID
/// <summary>
/// Texture 1D sampler.
/// </summary>
IntSampler1D = Gl.INT_SAMPLER_1D,
#endif
/// <summary>
/// Texture 2D sampler.
/// </summary>
IntSampler2D = Gl.INT_SAMPLER_2D,
#if !MONODROID
/// <summary>
/// Texture rectangle sampler.
/// </summary>
IntSampler2DRect = Gl.INT_SAMPLER_2D_RECT,
#endif
/// <summary>
/// Texture 3D sampler.
/// </summary>
IntSampler3D = Gl.INT_SAMPLER_3D,
/// <summary>
/// Texture cube sampler.
/// </summary>
IntSamplerCube = Gl.INT_SAMPLER_CUBE,
#endregion
#region Integer Texture Array Sampler
#if !MONODROID
/// <summary>
/// Texture 1D sampler.
/// </summary>
IntSampler1DArray = Gl.INT_SAMPLER_1D_ARRAY,
#endif
/// <summary>
/// Texture 2D sampler.
/// </summary>
IntSampler2DArray = Gl.INT_SAMPLER_2D_ARRAY,
#endregion
#region Unsigned Integer Texture Sampler
#if !MONODROID
/// <summary>
/// Texture 1D sampler.
/// </summary>
UIntSampler1D = Gl.UNSIGNED_INT_SAMPLER_1D,
#endif
/// <summary>
/// Texture 2D sampler.
/// </summary>
UIntSampler2D = Gl.UNSIGNED_INT_SAMPLER_2D,
#if !MONODROID
/// <summary>
/// Texture rectangle sampler.
/// </summary>
UIntSampler2DRect = Gl.UNSIGNED_INT_SAMPLER_2D_RECT,
#endif
/// <summary>
/// Texture 3D sampler.
/// </summary>
UIntSampler3D = Gl.UNSIGNED_INT_SAMPLER_3D,
/// <summary>
/// Texture cube sampler.
/// </summary>
UIntSamplerCube = Gl.UNSIGNED_INT_SAMPLER_CUBE,
#endregion
#region Images
Image2D = Gl.IMAGE_2D,
Image3D = Gl.IMAGE_3D,
ImageCube = Gl.IMAGE_CUBE,
ImageBuffer = Gl.IMAGE_BUFFER,
Image2DArray = Gl.IMAGE_2D_ARRAY,
ImageCubeMapArray = Gl.IMAGE_CUBE_MAP_ARRAY,
IntImage2D = Gl.INT_IMAGE_2D,
IntImage3D = Gl.INT_IMAGE_3D,
IntImageCube = Gl.INT_IMAGE_CUBE,
IntImageBuffer = Gl.INT_IMAGE_BUFFER,
IntImage2DArray = Gl.INT_IMAGE_2D_ARRAY,
IntImageCubeMapArray = Gl.INT_IMAGE_CUBE_MAP_ARRAY,
UIntImage2D = Gl.UNSIGNED_INT_IMAGE_2D,
UIntImage3D = Gl.UNSIGNED_INT_IMAGE_3D,
UIntImageCube = Gl.UNSIGNED_INT_IMAGE_CUBE,
UIntImageBuffer = Gl.UNSIGNED_INT_IMAGE_BUFFER,
UIntImage2DArray = Gl.UNSIGNED_INT_IMAGE_2D_ARRAY,
UIntImageCubeMapArray = Gl.UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY,
UintAtomicCounter = Gl.UNSIGNED_INT_ATOMIC_COUNTER,
#if !MONODROID
Image1D = Gl.IMAGE_1D,
Image1DArray = Gl.IMAGE_1D_ARRAY,
Image2DRect = Gl.IMAGE_2D_RECT,
Image2DMultisample = Gl.IMAGE_2D_MULTISAMPLE,
Image2DMultisampleArray = Gl.IMAGE_2D_MULTISAMPLE_ARRAY,
IntImage1D = Gl.INT_IMAGE_1D,
IntImage1DArray = Gl.INT_IMAGE_1D_ARRAY,
IntImage2DRect = Gl.INT_IMAGE_2D_RECT,
IntImage2DMultisample = Gl.INT_IMAGE_2D_MULTISAMPLE,
IntImage2DMultisampleArray = Gl.INT_IMAGE_2D_MULTISAMPLE_ARRAY,
UIntImage1D = Gl.UNSIGNED_INT_IMAGE_1D,
UIntImage2DRect = Gl.UNSIGNED_INT_IMAGE_2D_RECT,
UIntImage1DArray = Gl.UNSIGNED_INT_IMAGE_1D_ARRAY,
UIntImage2DMultisample = Gl.UNSIGNED_INT_IMAGE_2D_MULTISAMPLE,
UIntImage2DMultisampleArray = Gl.UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY,
#endif
#endregion
}
}
| |
/*
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModules.SharedBase;
namespace OpenSim.Region.PhysicsModule.POS
{
public class POSCharacter : PhysicsActor
{
private Vector3 _position;
public Vector3 _velocity;
public Vector3 _target_velocity = Vector3.Zero;
public Vector3 _size = Vector3.Zero;
private Vector3 _acceleration;
private Vector3 m_rotationalVelocity = Vector3.Zero;
private bool flying;
private bool isColliding;
public POSCharacter()
{
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Agent; }
set { return; }
}
public override Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return flying; }
set { flying = value; }
}
public override bool IsColliding
{
get { return isColliding; }
set { isColliding = value; }
}
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override bool Stopped
{
get { return false; }
}
public override Vector3 Position
{
get { return _position; }
set { _position = value; }
}
public override Vector3 Size
{
get { return _size; }
set
{
_size = value;
_size.Z = _size.Z / 2.0f;
}
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void VehicleFlags(int param, bool remove) { }
public override void SetVolumeDetect(int param)
{
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override Vector3 Velocity
{
get { return _velocity; }
set { _target_velocity = value; }
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set { }
}
public override Vector3 Acceleration
{
get { return _acceleration; }
set { _acceleration = value; }
}
public override bool Kinematic
{
get { return true; }
set { }
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override void SetMomentum(Vector3 momentum)
{
}
public override void CrossingFailure()
{
}
public override Vector3 PIDTarget
{
set { return; }
}
public override bool PIDActive
{
get { return false; }
set { return; }
}
public override float PIDTau
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override bool PIDHoverActive
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
public override Quaternion APIDTarget
{
set { return; }
}
public override bool APIDActive
{
set { return; }
}
public override float APIDStrength
{
set { return; }
}
public override float APIDDamping
{
set { return; }
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Abp.Events.Bus.Factories;
using Abp.Events.Bus.Factories.Internals;
using Abp.Events.Bus.Handlers;
using Abp.Events.Bus.Handlers.Internals;
using Castle.Core.Logging;
namespace Abp.Events.Bus
{
/// <summary>
/// Implements EventBus as Singleton pattern.
/// </summary>
public class EventBus : IEventBus
{
#region Public properties
/// <summary>
/// Gets the default <see cref="EventBus"/> instance.
/// </summary>
public static EventBus Default { get { return DefaultInstance; } }
private static readonly EventBus DefaultInstance = new EventBus();
/// <summary>
/// Reference to the Logger.
/// </summary>
public ILogger Logger { get; set; }
#endregion
#region Private fields
/// <summary>
/// All registered handler factories.
/// </summary>
private readonly Dictionary<Type, List<IEventHandlerFactory>> _handlerFactories;
#endregion
#region Constructor
/// <summary>
/// Creates a new <see cref="EventBus"/> instance.
/// Instead of creating a new instace, you can use <see cref="Default"/> to use Global <see cref="EventBus"/>.
/// </summary>
public EventBus()
{
_handlerFactories = new Dictionary<Type, List<IEventHandlerFactory>>();
Logger = NullLogger.Instance;
}
#endregion
#region Public methods
#region Register
public IDisposable Register<TEventData>(Action<TEventData> action) where TEventData : IEventData
{
return Register(typeof(TEventData), new ActionEventHandler<TEventData>(action));
}
public IDisposable Register<TEventData>(IEventHandler<TEventData> handler) where TEventData : IEventData
{
return Register(typeof(TEventData), handler);
}
public IDisposable Register<TEventData, THandler>()
where TEventData : IEventData
where THandler : IEventHandler<TEventData>, new()
{
return Register(typeof(TEventData), new TransientEventHandlerFactory<THandler>());
}
public IDisposable Register(Type eventType, IEventHandler handler)
{
return Register(eventType, new SingleInstanceHandlerFactory(handler));
}
public IDisposable Register<TEventData>(IEventHandlerFactory handlerFactory) where TEventData : IEventData
{
return Register(typeof(TEventData), handlerFactory);
}
public IDisposable Register(Type eventType, IEventHandlerFactory handlerFactory)
{
lock (_handlerFactories)
{
GetOrCreateHandlerFactories(eventType).Add(handlerFactory);
return new FactoryUnregistrar(this, eventType, handlerFactory);
}
}
#endregion
#region Unregister
public void Unregister<TEventData>(Action<TEventData> action) where TEventData : IEventData
{
lock (_handlerFactories)
{
GetOrCreateHandlerFactories(typeof(TEventData))
.RemoveAll(
factory =>
{
if (factory is SingleInstanceHandlerFactory)
{
var singleInstanceFactoru = factory as SingleInstanceHandlerFactory;
if (singleInstanceFactoru.HandlerInstance is ActionEventHandler<TEventData>)
{
var actionHandler = singleInstanceFactoru.HandlerInstance as ActionEventHandler<TEventData>;
if (actionHandler.Action == action)
{
return true;
}
}
}
return false;
});
}
}
public void Unregister<TEventData>(IEventHandler<TEventData> handler) where TEventData : IEventData
{
Unregister(typeof(TEventData), handler);
}
public void Unregister(Type eventType, IEventHandler handler)
{
lock (_handlerFactories)
{
GetOrCreateHandlerFactories(eventType)
.RemoveAll(
factory =>
factory is SingleInstanceHandlerFactory && (factory as SingleInstanceHandlerFactory).HandlerInstance == handler
);
}
}
public void Unregister<TEventData>(IEventHandlerFactory factory) where TEventData : IEventData
{
Unregister(typeof(TEventData), factory);
}
public void Unregister(Type eventType, IEventHandlerFactory factory)
{
lock (_handlerFactories)
{
GetOrCreateHandlerFactories(eventType).Remove(factory);
}
}
public void UnregisterAll<TEventData>() where TEventData : IEventData
{
UnregisterAll(typeof(TEventData));
}
public void UnregisterAll(Type eventType)
{
lock (_handlerFactories)
{
GetOrCreateHandlerFactories(eventType).Clear();
}
}
#endregion
#region Trigger
public void Trigger<TEventData>(TEventData eventData) where TEventData : IEventData
{
Trigger(null, eventData);
}
public void Trigger<TEventData>(object eventSource, TEventData eventData) where TEventData : IEventData
{
var eventType = typeof(TEventData);
eventData.EventSource = eventSource;
foreach (var factoryToTrigger in GetHandlerFactories(eventType))
{
var eventHandler = factoryToTrigger.GetHandler() as IEventHandler<TEventData>;
if (eventHandler == null)
{
throw new Exception("Registered event handler for event type " + eventType.Name + " does not implement IEventHandler<" + eventType.Name + "> interface!");
}
try
{
eventHandler.HandleEvent(eventData);
}
finally
{
factoryToTrigger.ReleaseHandler(eventHandler);
}
}
}
public void Trigger(Type eventType, EventData eventData)
{
Trigger(eventType, null, eventData);
}
public void Trigger(Type eventType, object eventSource, EventData eventData)
{
eventData.EventSource = eventSource;
foreach (var factoryToTrigger in GetHandlerFactories(eventType))
{
var eventHandler = factoryToTrigger.GetHandler();
if (eventHandler == null)
{
throw new Exception("Registered event handler for event type " + eventType.Name + " does not implement IEventHandler<" + eventType.Name + "> interface!");
}
var handlerType = typeof (IEventHandler<>).MakeGenericType(eventType);
try
{
var method = handlerType.GetMethod("HandleEvent", BindingFlags.Public | BindingFlags.Instance);
method.Invoke(eventHandler, new object[] { eventData });
}
finally
{
factoryToTrigger.ReleaseHandler(eventHandler);
}
}
}
private IEnumerable<IEventHandlerFactory> GetHandlerFactories(Type eventType)
{
var handlerFactoryList = new List<IEventHandlerFactory>();
lock (_handlerFactories)
{
foreach (var handlerFactory in _handlerFactories)
{
if (handlerFactory.Key.IsAssignableFrom(eventType))
{
handlerFactoryList.AddRange(handlerFactory.Value);
}
}
}
return handlerFactoryList.ToArray();
}
public Task TriggerAsync<TEventData>(TEventData eventData) where TEventData : IEventData
{
return TriggerAsync(null, eventData);
}
public Task TriggerAsync<TEventData>(object eventSource, TEventData eventData) where TEventData : IEventData
{
return Task.Factory.StartNew(
() =>
{
try
{
Trigger(eventSource, eventData);
}
catch (Exception ex)
{
Logger.Warn(ex.Message, ex);
}
});
}
public Task TriggerAsync(Type eventType, EventData eventData)
{
return TriggerAsync(eventType, null, eventData);
}
public Task TriggerAsync(Type eventType, object eventSource, EventData eventData)
{
return Task.Factory.StartNew(
() =>
{
try
{
Trigger(eventType, eventSource, eventData);
}
catch (Exception ex)
{
Logger.Warn(ex.Message, ex);
}
});
}
#endregion
#endregion
#region Private methods
private List<IEventHandlerFactory> GetOrCreateHandlerFactories(Type eventType)
{
List<IEventHandlerFactory> handlers;
if (!_handlerFactories.TryGetValue(eventType, out handlers))
{
_handlerFactories[eventType] = handlers = new List<IEventHandlerFactory>();
}
return handlers;
}
#endregion
}
}
| |
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.Common;
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 Cobertura.
/// </summary>
internal class CoberturaParser : ParserBase
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(CoberturaParser));
/// <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(@"(?<ClassName>.+)/<(?<CompilerGeneratedName>.+)>.+__.+MoveNext\(\)$", RegexOptions.Compiled);
/// <summary>
/// Regex to analyze the branch coverage of a line element.
/// </summary>
private static readonly Regex BranchCoverageRegex = new Regex("\\((?<NumberOfCoveredBranches>\\d+)/(?<NumberOfTotalBranches>\\d+)\\)$", RegexOptions.Compiled);
/// <summary>
/// Initializes a new instance of the <see cref="CoberturaParser" /> class.
/// </summary>
/// <param name="assemblyFilter">The assembly filter.</param>
/// <param name="classFilter">The class filter.</param>
/// <param name="fileFilter">The file filter.</param>
internal CoberturaParser(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("package")
.ToArray();
var assemblyNames = modules
.Select(m => m.Attribute("name").Value)
.Distinct()
.Where(a => this.AssemblyFilter.IsElementIncludedInReport(a))
.OrderBy(a => a)
.ToArray();
foreach (var assemblyName in assemblyNames)
{
assemblies.Add(this.ProcessAssembly(modules, assemblyName));
}
var result = new ParserResult(assemblies.OrderBy(a => a.Name).ToList(), true, this.ToString());
foreach (var sourceElement in report.Elements("sources").Elements("source"))
{
result.AddSourceDirectory(sourceElement.Value);
}
return result;
}
/// <summary>
/// Processes the given assembly.
/// </summary>
/// <param name="modules">The modules.</param>
/// <param name="assemblyName">Name of the assembly.</param>
/// <returns>The <see cref="Assembly"/>.</returns>
private Assembly ProcessAssembly(XElement[] modules, string assemblyName)
{
Logger.DebugFormat(Resources.CurrentAssembly, assemblyName);
var classNames = modules
.Where(m => m.Attribute("name").Value.Equals(assemblyName))
.Elements("classes")
.Elements("class")
.Select(c =>
{
string fullname = c.Attribute("name").Value;
int nestedClassSeparatorIndex = fullname.IndexOf('/');
return nestedClassSeparatorIndex > -1 ? fullname.Substring(0, nestedClassSeparatorIndex) : fullname;
})
.Where(name => !name.Contains("$") && !name.Contains("<"))
.Distinct()
.Where(c => this.ClassFilter.IsElementIncludedInReport(c))
.OrderBy(name => name)
.ToArray();
var assembly = new Assembly(assemblyName);
Parallel.ForEach(classNames, className => this.ProcessClass(modules, assembly, className));
return assembly;
}
/// <summary>
/// Processes the given class.
/// </summary>
/// <param name="modules">The modules.</param>
/// <param name="assembly">The assembly.</param>
/// <param name="className">Name of the class.</param>
private void ProcessClass(XElement[] modules, Assembly assembly, string className)
{
var files = modules
.Where(m => m.Attribute("name").Value.Equals(assembly.Name))
.Elements("classes")
.Elements("class")
.Where(c => c.Attribute("name").Value.Equals(className)
|| c.Attribute("name").Value.StartsWith(className + "$", StringComparison.Ordinal)
|| c.Attribute("name").Value.StartsWith(className + "/", StringComparison.Ordinal))
.Select(c => c.Attribute("filename").Value)
.Distinct()
.ToArray();
var filteredFiles = files
.Where(f => this.FileFilter.IsElementIncludedInReport(f))
.ToArray();
// If all files are removed by filters, then the whole class is omitted
if ((files.Length == 0 && !this.FileFilter.HasCustomFilters) || filteredFiles.Length > 0)
{
var @class = new Class(className, assembly);
foreach (var file in filteredFiles)
{
@class.AddFile(ProcessFile(modules, @class, file));
}
assembly.AddClass(@class);
}
}
/// <summary>
/// Processes the file.
/// </summary>
/// <param name="modules">The modules.</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, Class @class, string filePath)
{
var classes = modules
.Where(m => m.Attribute("name").Value.Equals(@class.Assembly.Name))
.Elements("classes")
.Elements("class")
.Where(c => c.Attribute("name").Value.Equals(@class.Name)
|| c.Attribute("name").Value.StartsWith(@class.Name + "$", StringComparison.Ordinal)
|| c.Attribute("name").Value.StartsWith(@class.Name + "/", StringComparison.Ordinal)
|| c.Attribute("name").Value.StartsWith(@class.Name + ".", StringComparison.Ordinal))
.Where(c => c.Attribute("filename").Value.Equals(filePath))
.ToArray();
var lines = classes.Elements("lines")
.Elements("line")
.ToArray();
var linesOfFile = lines
.Select(line => new
{
LineNumber = int.Parse(line.Attribute("number").Value, CultureInfo.InvariantCulture),
Visits = line.Attribute("hits").Value.ParseLargeInteger()
})
.OrderBy(seqpnt => seqpnt.LineNumber)
.ToArray();
var branches = GetBranches(lines);
int[] coverage = new int[] { };
LineVisitStatus[] lineVisitStatus = new LineVisitStatus[] { };
if (linesOfFile.Length > 0)
{
coverage = new int[linesOfFile[linesOfFile.LongLength - 1].LineNumber + 1];
lineVisitStatus = new LineVisitStatus[linesOfFile[linesOfFile.LongLength - 1].LineNumber + 1];
for (int i = 0; i < coverage.Length; i++)
{
coverage[i] = -1;
}
foreach (var line in linesOfFile)
{
coverage[line.LineNumber] = line.Visits;
bool partiallyCovered = false;
if (branches.TryGetValue(line.LineNumber, out ICollection<Branch> branchesOfLine))
{
partiallyCovered = branchesOfLine.Any(b => b.BranchVisits == 0);
}
LineVisitStatus statusOfLine = line.Visits > 0 ? (partiallyCovered ? LineVisitStatus.PartiallyCovered : LineVisitStatus.Covered) : LineVisitStatus.NotCovered;
lineVisitStatus[line.LineNumber] = statusOfLine;
}
}
var methodsOfFile = classes
.Elements("methods")
.Elements("method")
.ToArray();
var codeFile = new CodeFile(filePath, coverage, lineVisitStatus, branches);
SetMethodMetrics(codeFile, methodsOfFile);
SetCodeElements(codeFile, methodsOfFile);
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.Attribute("name").Value + method.Attribute("signature").Value;
fullName = ExtractMethodName(fullName, method.Parent.Parent.Attribute("name").Value);
if (fullName.Contains("__") && LambdaMethodNameRegex.IsMatch(fullName))
{
continue;
}
string shortName = GetShortMethodName(fullName);
var metrics = new List<Metric>();
var lineRate = method.Attribute("line-rate");
if (lineRate != null)
{
decimal? value = null;
if (!"NaN".Equals(lineRate.Value, StringComparison.OrdinalIgnoreCase))
{
value = Math.Round(100 * decimal.Parse(lineRate.Value.Replace(',', '.'), NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture), 2, MidpointRounding.AwayFromZero);
}
metrics.Add(new Metric(
ReportResources.Coverage,
ParserBase.CodeCoverageUri,
MetricType.CoveragePercentual,
value));
}
var branchRate = method.Attribute("branch-rate");
if (branchRate != null)
{
decimal? value = null;
if (!"NaN".Equals(branchRate.Value, StringComparison.OrdinalIgnoreCase))
{
value = Math.Round(100 * decimal.Parse(branchRate.Value.Replace(',', '.'), NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture), 2, MidpointRounding.AwayFromZero);
}
metrics.Add(new Metric(
ReportResources.BranchCoverage,
ParserBase.CodeCoverageUri,
MetricType.CoveragePercentual,
value));
}
var cyclomaticComplexityAttribute = method.Attribute("complexity");
if (cyclomaticComplexityAttribute != null)
{
decimal? value = null;
if (!"NaN".Equals(cyclomaticComplexityAttribute.Value, StringComparison.OrdinalIgnoreCase))
{
value = Math.Round(decimal.Parse(cyclomaticComplexityAttribute.Value.Replace(',', '.'), NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture), 2, MidpointRounding.AwayFromZero);
}
metrics.Insert(
0,
new Metric(
ReportResources.CyclomaticComplexity,
ParserBase.CyclomaticComplexityUri,
MetricType.CodeQuality,
value,
MetricMergeOrder.LowerIsBetter));
}
var methodMetric = new MethodMetric(fullName, shortName, metrics);
var line = method
.Elements("lines")
.Elements("line")
.FirstOrDefault();
if (line != null)
{
methodMetric.Line = int.Parse(line.Attribute("number").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)
{
string methodName = method.Attribute("name").Value + method.Attribute("signature").Value;
methodName = ExtractMethodName(methodName, method.Parent.Parent.Attribute("name").Value);
if (methodName.Contains("__") && LambdaMethodNameRegex.IsMatch(methodName))
{
continue;
}
var lines = method.Elements("lines")
.Elements("line");
if (lines.Any())
{
int firstLine = int.Parse(lines.First().Attribute("number").Value, CultureInfo.InvariantCulture);
int lastLine = int.Parse(lines.Last().Attribute("number").Value, CultureInfo.InvariantCulture);
codeFile.AddCodeElement(new CodeElement(
methodName,
CodeElementType.Method,
firstLine,
lastLine,
codeFile.CoverageQuota(firstLine, lastLine)));
}
}
}
/// <summary>
/// Gets the branches by line number.
/// </summary>
/// <param name="lines">The lines.</param>
/// <returns>The branches by line number.</returns>
private static Dictionary<int, ICollection<Branch>> GetBranches(IEnumerable<XElement> lines)
{
var result = new Dictionary<int, ICollection<Branch>>();
foreach (var line in lines)
{
if (line.Attribute("condition-coverage") == null
|| line.Attribute("branch") == null
|| !line.Attribute("branch").Value.Equals("true", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var match = BranchCoverageRegex.Match(line.Attribute("condition-coverage").Value);
if (match.Success)
{
int lineNumber = int.Parse(line.Attribute("number").Value, CultureInfo.InvariantCulture);
int numberOfCoveredBranches = int.Parse(match.Groups["NumberOfCoveredBranches"].Value, CultureInfo.InvariantCulture);
int numberOfTotalBranches = int.Parse(match.Groups["NumberOfTotalBranches"].Value, CultureInfo.InvariantCulture);
var branches = new HashSet<Branch>();
for (int i = 0; i < numberOfTotalBranches; i++)
{
string identifier = string.Format(
CultureInfo.InvariantCulture,
"{0}_{1}",
lineNumber,
i);
branches.Add(new Branch(i < numberOfCoveredBranches ? 1 : 0, identifier));
}
/* If cobertura file is merged from different files, a class and therefore each line can exist several times.
* The best result is used. */
if (result.TryGetValue(lineNumber, out ICollection<Branch> existingBranches))
{
if (numberOfCoveredBranches > existingBranches.Count(b => b.BranchVisits == 1))
{
result[lineNumber] = branches;
}
}
else
{
result.Add(lineNumber, branches);
}
}
}
return result;
}
/// <summary>
/// Extracts the method name. For async methods the original name is returned.
/// </summary>
/// <param name="methodName">The full method name.</param>
/// <param name="className">The name of the class.</param>
/// <returns>The method name.</returns>
private static string ExtractMethodName(string methodName, string className)
{
// Quick check before expensive regex is called
if (methodName.EndsWith("MoveNext()"))
{
Match match = CompilerGeneratedMethodNameRegex.Match(className + methodName);
if (match.Success)
{
methodName = match.Groups["CompilerGeneratedName"].Value + "()";
}
}
return methodName;
}
private static string GetShortMethodName(string fullName)
{
int indexOpen = fullName.IndexOf('(');
if (indexOpen <= 0)
{
return fullName;
}
int indexClose = fullName.IndexOf(')');
string signature = indexClose - indexOpen > 1 ? "(...)" : "()";
return $"{fullName.Substring(0, indexOpen)}{signature}";
}
}
}
| |
// 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.Numerics.Hashing;
namespace System.Drawing
{
/**
* Represents a dimension in 2D coordinate space
*/
/// <summary>
/// Represents the size of a rectangular region
/// with an ordered pair of width and height.
/// </summary>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public struct Size : IEquatable<Size>
{
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.Size'/> class.
/// </summary>
public static readonly Size Empty = new Size();
private int width; // Do not rename (binary serialization)
private int height; // Do not rename (binary serialization)
/**
* Create a new Size object from a point
*/
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.Size'/> class from
/// the specified <see cref='System.Drawing.Point'/>.
/// </para>
/// </summary>
public Size(Point pt)
{
width = pt.X;
height = pt.Y;
}
/**
* Create a new Size object of the specified dimension
*/
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.Size'/> class from
/// the specified dimensions.
/// </summary>
public Size(int width, int height)
{
this.width = width;
this.height = height;
}
/// <summary>
/// Converts the specified <see cref='System.Drawing.Size'/> to a
/// <see cref='System.Drawing.SizeF'/>.
/// </summary>
public static implicit operator SizeF(Size p) => new SizeF(p.Width, p.Height);
/// <summary>
/// <para>
/// Performs vector addition of two <see cref='System.Drawing.Size'/> objects.
/// </para>
/// </summary>
public static Size operator +(Size sz1, Size sz2) => Add(sz1, sz2);
/// <summary>
/// <para>
/// Contracts a <see cref='System.Drawing.Size'/> by another <see cref='System.Drawing.Size'/>
/// </para>
/// </summary>
public static Size operator -(Size sz1, Size sz2) => Subtract(sz1, sz2);
/// <summary>
/// Multiplies a <see cref="Size"/> by an <see cref="int"/> producing <see cref="Size"/>.
/// </summary>
/// <param name="left">Multiplier of type <see cref="int"/>.</param>
/// <param name="right">Multiplicand of type <see cref="Size"/>.</param>
/// <returns>Product of type <see cref="Size"/>.</returns>
public static Size operator *(int left, Size right) => Multiply(right, left);
/// <summary>
/// Multiplies <see cref="Size"/> by an <see cref="int"/> producing <see cref="Size"/>.
/// </summary>
/// <param name="left">Multiplicand of type <see cref="Size"/>.</param>
/// <param name="right">Multiplier of type <see cref="int"/>.</param>
/// <returns>Product of type <see cref="Size"/>.</returns>
public static Size operator *(Size left, int right) => Multiply(left, right);
/// <summary>
/// Divides <see cref="Size"/> by an <see cref="int"/> producing <see cref="Size"/>.
/// </summary>
/// <param name="left">Dividend of type <see cref="Size"/>.</param>
/// <param name="right">Divisor of type <see cref="int"/>.</param>
/// <returns>Result of type <see cref="Size"/>.</returns>
public static Size operator /(Size left, int right) => new Size(unchecked(left.width / right), unchecked(left.height / right));
/// <summary>
/// Multiplies <see cref="Size"/> by a <see cref="float"/> producing <see cref="SizeF"/>.
/// </summary>
/// <param name="left">Multiplier of type <see cref="float"/>.</param>
/// <param name="right">Multiplicand of type <see cref="Size"/>.</param>
/// <returns>Product of type <see cref="SizeF"/>.</returns>
public static SizeF operator *(float left, Size right) => Multiply(right, left);
/// <summary>
/// Multiplies <see cref="Size"/> by a <see cref="float"/> producing <see cref="SizeF"/>.
/// </summary>
/// <param name="left">Multiplicand of type <see cref="Size"/>.</param>
/// <param name="right">Multiplier of type <see cref="float"/>.</param>
/// <returns>Product of type <see cref="SizeF"/>.</returns>
public static SizeF operator *(Size left, float right) => Multiply(left, right);
/// <summary>
/// Divides <see cref="Size"/> by a <see cref="float"/> producing <see cref="SizeF"/>.
/// </summary>
/// <param name="left">Dividend of type <see cref="Size"/>.</param>
/// <param name="right">Divisor of type <see cref="int"/>.</param>
/// <returns>Result of type <see cref="SizeF"/>.</returns>
public static SizeF operator /(Size left, float right)
=> new SizeF(left.width / right, left.height / right);
/// <summary>
/// Tests whether two <see cref='System.Drawing.Size'/> objects
/// are identical.
/// </summary>
public static bool operator ==(Size sz1, Size sz2) => sz1.Width == sz2.Width && sz1.Height == sz2.Height;
/// <summary>
/// <para>
/// Tests whether two <see cref='System.Drawing.Size'/> objects are different.
/// </para>
/// </summary>
public static bool operator !=(Size sz1, Size sz2) => !(sz1 == sz2);
/// <summary>
/// Converts the specified <see cref='System.Drawing.Size'/> to a
/// <see cref='System.Drawing.Point'/>.
/// </summary>
public static explicit operator Point(Size size) => new Point(size.Width, size.Height);
/// <summary>
/// Tests whether this <see cref='System.Drawing.Size'/> has zero
/// width and height.
/// </summary>
[Browsable(false)]
public bool IsEmpty => width == 0 && height == 0;
/**
* Horizontal dimension
*/
/// <summary>
/// <para>
/// Represents the horizontal component of this
/// <see cref='System.Drawing.Size'/>.
/// </para>
/// </summary>
public int Width
{
get { return width; }
set { width = value; }
}
/**
* Vertical dimension
*/
/// <summary>
/// Represents the vertical component of this
/// <see cref='System.Drawing.Size'/>.
/// </summary>
public int Height
{
get { return height; }
set { height = value; }
}
/// <summary>
/// <para>
/// Performs vector addition of two <see cref='System.Drawing.Size'/> objects.
/// </para>
/// </summary>
public static Size Add(Size sz1, Size sz2) =>
new Size(unchecked(sz1.Width + sz2.Width), unchecked(sz1.Height + sz2.Height));
/// <summary>
/// Converts a SizeF to a Size by performing a ceiling operation on
/// all the coordinates.
/// </summary>
public static Size Ceiling(SizeF value) =>
new Size(unchecked((int)Math.Ceiling(value.Width)), unchecked((int)Math.Ceiling(value.Height)));
/// <summary>
/// <para>
/// Contracts a <see cref='System.Drawing.Size'/> by another <see cref='System.Drawing.Size'/> .
/// </para>
/// </summary>
public static Size Subtract(Size sz1, Size sz2) =>
new Size(unchecked(sz1.Width - sz2.Width), unchecked(sz1.Height - sz2.Height));
/// <summary>
/// Converts a SizeF to a Size by performing a truncate operation on
/// all the coordinates.
/// </summary>
public static Size Truncate(SizeF value) => new Size(unchecked((int)value.Width), unchecked((int)value.Height));
/// <summary>
/// Converts a SizeF to a Size by performing a round operation on
/// all the coordinates.
/// </summary>
public static Size Round(SizeF value) =>
new Size(unchecked((int)Math.Round(value.Width)), unchecked((int)Math.Round(value.Height)));
/// <summary>
/// <para>
/// Tests to see whether the specified object is a
/// <see cref='System.Drawing.Size'/>
/// with the same dimensions as this <see cref='System.Drawing.Size'/>.
/// </para>
/// </summary>
public override bool Equals(object obj) => obj is Size && Equals((Size)obj);
public bool Equals(Size other) => this == other;
/// <summary>
/// <para>
/// Returns a hash code.
/// </para>
/// </summary>
public override int GetHashCode() => HashHelpers.Combine(Width, Height);
/// <summary>
/// <para>
/// Creates a human-readable string that represents this
/// <see cref='System.Drawing.Size'/>.
/// </para>
/// </summary>
public override string ToString() => "{Width=" + width.ToString() + ", Height=" + height.ToString() + "}";
/// <summary>
/// Multiplies <see cref="Size"/> by an <see cref="int"/> producing <see cref="Size"/>.
/// </summary>
/// <param name="size">Multiplicand of type <see cref="Size"/>.</param>
/// <param name="multiplier">Multiplier of type <see cref='int'>.</param>
/// <returns>Product of type <see cref="Size"/>.</returns>
private static Size Multiply(Size size, int multiplier) =>
new Size(unchecked(size.width * multiplier), unchecked(size.height * multiplier));
/// <summary>
/// Multiplies <see cref="Size"/> by a <see cref="float"/> producing <see cref="SizeF"/>.
/// </summary>
/// <param name="size">Multiplicand of type <see cref="Size"/>.</param>
/// <param name="multiplier">Multiplier of type <see cref="float"/>.</param>
/// <returns>Product of type SizeF.</returns>
private static SizeF Multiply(Size size, float multiplier) =>
new SizeF(size.width * multiplier, size.height * multiplier);
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ConfigResponse.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace TeamNote.Protocol {
/// <summary>Holder for reflection information generated from ConfigResponse.proto</summary>
public static partial class ConfigResponseReflection {
#region Descriptor
/// <summary>File descriptor for ConfigResponse.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ConfigResponseReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChRDb25maWdSZXNwb25zZS5wcm90byJECg5Db25maWdSZXNwb25zZRIRCglJ",
"UEFkZHJlc3MYASABKAkSDAoEUG9ydBgCIAEoBRIRCglTZXJ2aWNlSWQYAyAB",
"KAVCFkgBqgIRVGVhbU5vdGUuUHJvdG9jb2xiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::TeamNote.Protocol.ConfigResponse), global::TeamNote.Protocol.ConfigResponse.Parser, new[]{ "IPAddress", "Port", "ServiceId" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ConfigResponse : pb::IMessage<ConfigResponse> {
private static readonly pb::MessageParser<ConfigResponse> _parser = new pb::MessageParser<ConfigResponse>(() => new ConfigResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ConfigResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::TeamNote.Protocol.ConfigResponseReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConfigResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConfigResponse(ConfigResponse other) : this() {
iPAddress_ = other.iPAddress_;
port_ = other.port_;
serviceId_ = other.serviceId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConfigResponse Clone() {
return new ConfigResponse(this);
}
/// <summary>Field number for the "IPAddress" field.</summary>
public const int IPAddressFieldNumber = 1;
private string iPAddress_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string IPAddress {
get { return iPAddress_; }
set {
iPAddress_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Port" field.</summary>
public const int PortFieldNumber = 2;
private int port_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Port {
get { return port_; }
set {
port_ = value;
}
}
/// <summary>Field number for the "ServiceId" field.</summary>
public const int ServiceIdFieldNumber = 3;
private int serviceId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int ServiceId {
get { return serviceId_; }
set {
serviceId_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ConfigResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ConfigResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (IPAddress != other.IPAddress) return false;
if (Port != other.Port) return false;
if (ServiceId != other.ServiceId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (IPAddress.Length != 0) hash ^= IPAddress.GetHashCode();
if (Port != 0) hash ^= Port.GetHashCode();
if (ServiceId != 0) hash ^= ServiceId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (IPAddress.Length != 0) {
output.WriteRawTag(10);
output.WriteString(IPAddress);
}
if (Port != 0) {
output.WriteRawTag(16);
output.WriteInt32(Port);
}
if (ServiceId != 0) {
output.WriteRawTag(24);
output.WriteInt32(ServiceId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (IPAddress.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(IPAddress);
}
if (Port != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Port);
}
if (ServiceId != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(ServiceId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ConfigResponse other) {
if (other == null) {
return;
}
if (other.IPAddress.Length != 0) {
IPAddress = other.IPAddress;
}
if (other.Port != 0) {
Port = other.Port;
}
if (other.ServiceId != 0) {
ServiceId = other.ServiceId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
IPAddress = input.ReadString();
break;
}
case 16: {
Port = input.ReadInt32();
break;
}
case 24: {
ServiceId = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Reactive.Disposables;
using Avalonia.Platform;
namespace Avalonia.Threading
{
/// <summary>
/// A timer that uses a <see cref="Dispatcher"/> to fire at a specified interval.
/// </summary>
public class DispatcherTimer
{
private IDisposable _timer;
private readonly DispatcherPriority _priority;
private TimeSpan _interval;
/// <summary>
/// Initializes a new instance of the <see cref="DispatcherTimer"/> class.
/// </summary>
public DispatcherTimer() : this(DispatcherPriority.Background)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DispatcherTimer"/> class.
/// </summary>
/// <param name="priority">The priority to use.</param>
public DispatcherTimer(DispatcherPriority priority)
{
_priority = priority;
}
/// <summary>
/// Initializes a new instance of the <see cref="DispatcherTimer"/> class.
/// </summary>
/// <param name="interval">The interval at which to tick.</param>
/// <param name="priority">The priority to use.</param>
/// <param name="callback">The event to call when the timer ticks.</param>
public DispatcherTimer(TimeSpan interval, DispatcherPriority priority, EventHandler callback) : this(priority)
{
_priority = priority;
Interval = interval;
Tick += callback;
}
/// <summary>
/// Finalizes an instance of the <see cref="DispatcherTimer"/> class.
/// </summary>
~DispatcherTimer()
{
if (_timer != null)
{
Stop();
}
}
/// <summary>
/// Raised when the timer ticks.
/// </summary>
public event EventHandler Tick;
/// <summary>
/// Gets or sets the interval at which the timer ticks.
/// </summary>
public TimeSpan Interval
{
get
{
return _interval;
}
set
{
bool enabled = IsEnabled;
Stop();
_interval = value;
IsEnabled = enabled;
}
}
/// <summary>
/// Gets or sets a value indicating whether the timer is running.
/// </summary>
public bool IsEnabled
{
get
{
return _timer != null;
}
set
{
if (IsEnabled != value)
{
if (value)
{
Start();
}
else
{
Stop();
}
}
}
}
/// <summary>
/// Gets or sets user-defined data associated with the timer.
/// </summary>
public object Tag
{
get;
set;
}
/// <summary>
/// Starts a new timer.
/// </summary>
/// <param name="action">
/// The method to call on timer tick. If the method returns false, the timer will stop.
/// </param>
/// <param name="interval">The interval at which to tick.</param>
/// <param name="priority">The priority to use.</param>
/// <returns>An <see cref="IDisposable"/> used to cancel the timer.</returns>
public static IDisposable Run(Func<bool> action, TimeSpan interval, DispatcherPriority priority = DispatcherPriority.Normal)
{
var timer = new DispatcherTimer(priority) { Interval = interval };
timer.Tick += (s, e) =>
{
if (!action())
{
timer.Stop();
}
};
timer.Start();
return Disposable.Create(() => timer.Stop());
}
/// <summary>
/// Runs a method once, after the specified interval.
/// </summary>
/// <param name="action">
/// The method to call after the interval has elapsed.
/// </param>
/// <param name="interval">The interval after which to call the method.</param>
/// <param name="priority">The priority to use.</param>
/// <returns>An <see cref="IDisposable"/> used to cancel the timer.</returns>
public static IDisposable RunOnce(
Action action,
TimeSpan interval,
DispatcherPriority priority = DispatcherPriority.Normal)
{
interval = (interval != TimeSpan.Zero) ? interval : TimeSpan.FromTicks(1);
var timer = new DispatcherTimer(priority) { Interval = interval };
timer.Tick += (s, e) =>
{
action();
timer.Stop();
};
timer.Start();
return Disposable.Create(() => timer.Stop());
}
/// <summary>
/// Starts the timer.
/// </summary>
public void Start()
{
if (!IsEnabled)
{
IPlatformThreadingInterface threading = AvaloniaLocator.Current.GetService<IPlatformThreadingInterface>();
if (threading == null)
{
throw new Exception("Could not start timer: IPlatformThreadingInterface is not registered.");
}
_timer = threading.StartTimer(_priority, Interval, InternalTick);
}
}
/// <summary>
/// Stops the timer.
/// </summary>
public void Stop()
{
if (IsEnabled)
{
_timer.Dispose();
_timer = null;
}
}
/// <summary>
/// Raises the <see cref="Tick"/> event on the dispatcher thread.
/// </summary>
private void InternalTick()
{
Dispatcher.UIThread.EnsurePriority(_priority);
Tick?.Invoke(this, EventArgs.Empty);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.CognitiveServices.Vision.Face
{
using Microsoft.CognitiveServices;
using Microsoft.CognitiveServices.Vision;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for PersonGroup.
/// </summary>
public static partial class PersonGroupExtensions
{
/// <summary>
/// Create a new person group with specified personGroupId, name and
/// user-provided userData.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// User-provided personGroupId as a string.
/// </param>
/// <param name='name'>
/// Name of the face list, maximum length is 128.
/// </param>
/// <param name='userData'>
/// Optional user defined data for the face list. Length should not exceed
/// 16KB.
/// </param>
public static void Create(this IPersonGroup operations, string personGroupId, string name = default(string), string userData = default(string))
{
operations.CreateAsync(personGroupId, name, userData).GetAwaiter().GetResult();
}
/// <summary>
/// Create a new person group with specified personGroupId, name and
/// user-provided userData.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// User-provided personGroupId as a string.
/// </param>
/// <param name='name'>
/// Name of the face list, maximum length is 128.
/// </param>
/// <param name='userData'>
/// Optional user defined data for the face list. Length should not exceed
/// 16KB.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateAsync(this IPersonGroup operations, string personGroupId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateWithHttpMessagesAsync(personGroupId, name, userData, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Delete an existing person group. Persisted face images of all people in the
/// person group will also be deleted.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// The personGroupId of the person group to be deleted.
/// </param>
public static void Delete(this IPersonGroup operations, string personGroupId)
{
operations.DeleteAsync(personGroupId).GetAwaiter().GetResult();
}
/// <summary>
/// Delete an existing person group. Persisted face images of all people in the
/// person group will also be deleted.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// The personGroupId of the person group to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IPersonGroup operations, string personGroupId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(personGroupId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieve the information of a person group, including its name and
/// userData.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// personGroupId of the target person group.
/// </param>
public static PersonGroupResult Get(this IPersonGroup operations, string personGroupId)
{
return operations.GetAsync(personGroupId).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the information of a person group, including its name and
/// userData.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// personGroupId of the target person group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PersonGroupResult> GetAsync(this IPersonGroup operations, string personGroupId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(personGroupId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update an existing person group's display name and userData. The properties
/// which does not appear in request body will not be updated.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// personGroupId of the person group to be updated.
/// </param>
/// <param name='name'>
/// Name of the face list, maximum length is 128.
/// </param>
/// <param name='userData'>
/// Optional user defined data for the face list. Length should not exceed
/// 16KB.
/// </param>
public static void Update(this IPersonGroup operations, string personGroupId, string name = default(string), string userData = default(string))
{
operations.UpdateAsync(personGroupId, name, userData).GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing person group's display name and userData. The properties
/// which does not appear in request body will not be updated.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// personGroupId of the person group to be updated.
/// </param>
/// <param name='name'>
/// Name of the face list, maximum length is 128.
/// </param>
/// <param name='userData'>
/// Optional user defined data for the face list. Length should not exceed
/// 16KB.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateAsync(this IPersonGroup operations, string personGroupId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateWithHttpMessagesAsync(personGroupId, name, userData, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieve the training status of a person group (completed or ongoing).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// personGroupId of target person group.
/// </param>
public static TrainingStatus GetTrainingStatus(this IPersonGroup operations, string personGroupId)
{
return operations.GetTrainingStatusAsync(personGroupId).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the training status of a person group (completed or ongoing).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// personGroupId of target person group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<TrainingStatus> GetTrainingStatusAsync(this IPersonGroup operations, string personGroupId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetTrainingStatusWithHttpMessagesAsync(personGroupId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List person groups and their information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='start'>
/// List person groups from the least personGroupId greater than the "start".
/// </param>
/// <param name='top'>
/// The number of person groups to list.
/// </param>
public static IList<PersonGroupResult> List(this IPersonGroup operations, string start = default(string), int? top = 1000)
{
return operations.ListAsync(start, top).GetAwaiter().GetResult();
}
/// <summary>
/// List person groups and their information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='start'>
/// List person groups from the least personGroupId greater than the "start".
/// </param>
/// <param name='top'>
/// The number of person groups to list.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<PersonGroupResult>> ListAsync(this IPersonGroup operations, string start = default(string), int? top = 1000, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(start, top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Queue a person group training task, the training task may not be started
/// immediately.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Target person group to be trained.
/// </param>
public static void Train(this IPersonGroup operations, string personGroupId)
{
operations.TrainAsync(personGroupId).GetAwaiter().GetResult();
}
/// <summary>
/// Queue a person group training task, the training task may not be started
/// immediately.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Target person group to be trained.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task TrainAsync(this IPersonGroup operations, string personGroupId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.TrainWithHttpMessagesAsync(personGroupId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| |
namespace SDKSample
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.CirclesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.FillWithCirclesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.AddCircleChildToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SettingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.circleSizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SmallToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MediumToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LargeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.RandomToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.numberofRingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ThreeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.FiveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.EightToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.behaviorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.TopmostLayerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.AllLayersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.CirclesToolStripMenuItem,
this.SettingToolStripMenuItem,
this.behaviorToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(634, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// CirclesToolStripMenuItem
//
this.CirclesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FillWithCirclesToolStripMenuItem,
this.AddCircleChildToolStripMenuItem});
this.CirclesToolStripMenuItem.Name = "CirclesToolStripMenuItem";
this.CirclesToolStripMenuItem.Text = "Circles";
//
// FillWithCirclesToolStripMenuItem
//
this.FillWithCirclesToolStripMenuItem.Name = "FillWithCirclesToolStripMenuItem";
this.FillWithCirclesToolStripMenuItem.Text = "Fill with Circles";
this.FillWithCirclesToolStripMenuItem.Click += new System.EventHandler(this.FillWithCirclesToolStripMenuItem_Click);
//
// AddCircleChildToolStripMenuItem
//
this.AddCircleChildToolStripMenuItem.Name = "AddCircleChildToolStripMenuItem";
this.AddCircleChildToolStripMenuItem.Text = "Add a Circle";
this.AddCircleChildToolStripMenuItem.Click += new System.EventHandler(this.AddChildToolStripMenuItem_Click);
//
// SettingToolStripMenuItem
//
this.SettingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.circleSizeToolStripMenuItem,
this.numberofRingsToolStripMenuItem});
this.SettingToolStripMenuItem.Name = "SettingToolStripMenuItem";
this.SettingToolStripMenuItem.Text = "Setting";
//
// circleSizeToolStripMenuItem
//
this.circleSizeToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SmallToolStripMenuItem,
this.MediumToolStripMenuItem,
this.LargeToolStripMenuItem,
this.RandomToolStripMenuItem});
this.circleSizeToolStripMenuItem.Name = "circleSizeToolStripMenuItem";
this.circleSizeToolStripMenuItem.Text = "Circle Size";
//
// SmallToolStripMenuItem
//
this.SmallToolStripMenuItem.Name = "SmallToolStripMenuItem";
this.SmallToolStripMenuItem.Text = "Small";
this.SmallToolStripMenuItem.Click += new System.EventHandler(this.SmallToolStripMenuItem_Click);
//
// MediumToolStripMenuItem
//
this.MediumToolStripMenuItem.Checked = true;
this.MediumToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.MediumToolStripMenuItem.Name = "MediumToolStripMenuItem";
this.MediumToolStripMenuItem.Text = "Medium";
this.MediumToolStripMenuItem.Click += new System.EventHandler(this.MediumToolStripMenuItem_Click);
//
// LargeToolStripMenuItem
//
this.LargeToolStripMenuItem.Name = "LargeToolStripMenuItem";
this.LargeToolStripMenuItem.Text = "Large";
this.LargeToolStripMenuItem.Click += new System.EventHandler(this.LargeToolStripMenuItem_Click);
//
// RandomToolStripMenuItem
//
this.RandomToolStripMenuItem.Name = "RandomToolStripMenuItem";
this.RandomToolStripMenuItem.Text = "Random";
this.RandomToolStripMenuItem.Click += new System.EventHandler(this.RandomToolStripMenuItem_Click);
//
// numberofRingsToolStripMenuItem
//
this.numberofRingsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ThreeToolStripMenuItem,
this.FiveToolStripMenuItem,
this.EightToolStripMenuItem});
this.numberofRingsToolStripMenuItem.Name = "numberofRingsToolStripMenuItem";
this.numberofRingsToolStripMenuItem.Text = "Number of Rings";
//
// ThreeToolStripMenuItem
//
this.ThreeToolStripMenuItem.Name = "ThreeToolStripMenuItem";
this.ThreeToolStripMenuItem.Text = "3";
this.ThreeToolStripMenuItem.Click += new System.EventHandler(this.ThreeToolStripMenuItem_Click);
//
// FiveToolStripMenuItem
//
this.FiveToolStripMenuItem.Checked = true;
this.FiveToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.FiveToolStripMenuItem.Name = "FiveToolStripMenuItem";
this.FiveToolStripMenuItem.Text = "5";
this.FiveToolStripMenuItem.Click += new System.EventHandler(this.FiveToolStripMenuItem_Click);
//
// EightToolStripMenuItem
//
this.EightToolStripMenuItem.Name = "EightToolStripMenuItem";
this.EightToolStripMenuItem.Text = "8";
this.EightToolStripMenuItem.Click += new System.EventHandler(this.EightToolStripMenuItem_Click);
//
// behaviorToolStripMenuItem
//
this.behaviorToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.TopmostLayerToolStripMenuItem,
this.AllLayersToolStripMenuItem});
this.behaviorToolStripMenuItem.Name = "behaviorToolStripMenuItem";
this.behaviorToolStripMenuItem.Text = "Behavior";
//
// TopmostLayerToolStripMenuItem
//
this.TopmostLayerToolStripMenuItem.Checked = true;
this.TopmostLayerToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.TopmostLayerToolStripMenuItem.Name = "TopmostLayerToolStripMenuItem";
this.TopmostLayerToolStripMenuItem.Text = "Top-most Layer";
this.TopmostLayerToolStripMenuItem.Click += new System.EventHandler(this.TopmostLayerToolStripMenuItem_Click);
//
// AllLayersToolStripMenuItem
//
this.AllLayersToolStripMenuItem.Name = "AllLayersToolStripMenuItem";
this.AllLayersToolStripMenuItem.Text = "All Layers";
this.AllLayersToolStripMenuItem.Click += new System.EventHandler(this.AllLayersToolStripMenuItem_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.OldLace;
this.ClientSize = new System.Drawing.Size(634, 448);
this.Controls.Add(this.menuStrip1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MainMenuStrip = this.menuStrip1;
this.MaximizeBox = false;
this.Name = "Form1";
this.Text = "Visual Hit Test";
this.menuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem CirclesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem AddCircleChildToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem FillWithCirclesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem SettingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem circleSizeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem SmallToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem MediumToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem LargeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem numberofRingsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem ThreeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem FiveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem EightToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem RandomToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem behaviorToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem TopmostLayerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem AllLayersToolStripMenuItem;
}
}
| |
// 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.IO;
using Test.IO.Streams;
using Xunit;
namespace System.Security.Cryptography.Rsa.Tests
{
public class SignVerify
{
[Fact]
public static void InvalidKeySize_DoesNotInvalidateKey()
{
using (RSA rsa = RSAFactory.Create())
{
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
// A 2049-bit key is hard to describe, none of the providers support it.
Assert.ThrowsAny<CryptographicException>(() => rsa.KeySize = 2049);
Assert.True(rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1));
}
}
[Fact]
public static void ExpectedSignature_SHA1_384()
{
byte[] expectedSignature =
{
0x79, 0xD9, 0x3C, 0xBF, 0x54, 0xFA, 0x55, 0x8C,
0x44, 0xC3, 0xC3, 0x83, 0x85, 0xBB, 0x78, 0x44,
0xCD, 0x0F, 0x5A, 0x8E, 0x71, 0xC9, 0xC2, 0x68,
0x68, 0x0A, 0x33, 0x93, 0x19, 0x37, 0x02, 0x06,
0xE2, 0xF7, 0x67, 0x97, 0x3C, 0x67, 0xB3, 0xF4,
0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C,
};
try
{
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA1", TestData.RSA384Parameters);
Assert.True(RSAFactory.Supports384PrivateKey, "RSAFactory.Supports384PrivateKey");
}
catch (CryptographicException)
{
// If the provider is not known to fail loading a 384-bit key, let the exception be the
// test failure. (If it is known to fail loading that key, we've now suppressed the throw,
// and the test will pass.)
if (RSAFactory.Supports384PrivateKey)
{
throw;
}
}
}
[Fact]
public static void ExpectedSignature_SHA1_1032()
{
byte[] expectedSignature =
{
0x49, 0xBC, 0x1C, 0xBE, 0x72, 0xEF, 0x83, 0x6E,
0x2D, 0xFA, 0xE7, 0xFA, 0xEB, 0xBC, 0xF0, 0x16,
0xF7, 0x2C, 0x07, 0x6D, 0x9F, 0xA6, 0x68, 0x71,
0xDC, 0x78, 0x9C, 0xA3, 0x42, 0x9E, 0xBB, 0xF5,
0x72, 0xE0, 0xAB, 0x4B, 0x4B, 0x6A, 0xE7, 0x3C,
0xE2, 0xC8, 0x1F, 0xA2, 0x07, 0xED, 0xD3, 0x98,
0xE9, 0xDF, 0x9A, 0x7A, 0x86, 0xB8, 0x06, 0xED,
0x97, 0x46, 0xF9, 0x8A, 0xED, 0x53, 0x1D, 0x90,
0xC3, 0x57, 0x7E, 0x5A, 0xE4, 0x7C, 0xEC, 0xB9,
0x45, 0x95, 0xAB, 0xCC, 0xBA, 0x9B, 0x2C, 0x1A,
0x64, 0xC2, 0x2C, 0xA0, 0x36, 0x7C, 0x56, 0xF0,
0x78, 0x77, 0x0B, 0x27, 0xB8, 0x1C, 0xCA, 0x7D,
0xD4, 0x71, 0x37, 0xBF, 0xC6, 0x4C, 0x64, 0x76,
0xBC, 0x8A, 0x87, 0xA0, 0x81, 0xF9, 0x4A, 0x94,
0x7B, 0xAA, 0x80, 0x95, 0x47, 0x51, 0xF9, 0x02,
0xA3, 0x44, 0x5C, 0x56, 0x60, 0xFB, 0x94, 0xA8,
0x52,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA1", TestData.RSA1032Parameters);
}
[Fact]
public static void ExpectedSignature_SHA1_2048()
{
byte[] expectedSignature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void ExpectedSignature_SHA256_1024()
{
byte[] expectedSignature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void ExpectedSignature_SHA256_2048()
{
byte[] expectedSignature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA256", TestData.RSA2048Params);
}
[Fact]
public static void ExpectSignature_SHA256_1024_Stream()
{
byte[] expectedSignature = new byte[]
{
0x78, 0x6F, 0x42, 0x00, 0xF4, 0x5A, 0xDB, 0x09,
0x72, 0xB9, 0xCD, 0xBE, 0xB8, 0x46, 0x54, 0xE0,
0xCF, 0x02, 0xB5, 0xA1, 0xF1, 0x7C, 0xA7, 0x5A,
0xCF, 0x09, 0x60, 0xB6, 0xFF, 0x6B, 0x8A, 0x92,
0x8E, 0xB4, 0xD5, 0x2C, 0x64, 0x90, 0x3E, 0x38,
0x8B, 0x1D, 0x7D, 0x0E, 0xE8, 0x3C, 0xF0, 0xB9,
0xBB, 0xEF, 0x90, 0x49, 0x7E, 0x6A, 0x1C, 0xEC,
0x51, 0xB9, 0x13, 0x9B, 0x02, 0x02, 0x66, 0x59,
0xC6, 0xB1, 0x51, 0xBD, 0x17, 0x2E, 0x03, 0xEC,
0x93, 0x2B, 0xE9, 0x41, 0x28, 0x57, 0x8C, 0xB2,
0x42, 0x60, 0xDE, 0xB4, 0x18, 0x85, 0x81, 0x55,
0xAE, 0x09, 0xD9, 0xC4, 0x87, 0x57, 0xD1, 0x90,
0xB3, 0x18, 0xD2, 0x96, 0x18, 0x91, 0x2D, 0x38,
0x98, 0x0E, 0x68, 0x3C, 0xA6, 0x2E, 0xFE, 0x0D,
0xD0, 0x50, 0x18, 0x55, 0x75, 0xA9, 0x85, 0x40,
0xAB, 0x72, 0xE6, 0x7F, 0x9F, 0xDC, 0x30, 0xB9,
};
byte[] signature;
using (Stream stream = new PositionValueStream(10))
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA1024Params);
signature = rsa.SignData(stream, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
Assert.Equal(expectedSignature, signature);
}
[Fact]
public static void VerifySignature_SHA1_384()
{
byte[] signature =
{
0x79, 0xD9, 0x3C, 0xBF, 0x54, 0xFA, 0x55, 0x8C,
0x44, 0xC3, 0xC3, 0x83, 0x85, 0xBB, 0x78, 0x44,
0xCD, 0x0F, 0x5A, 0x8E, 0x71, 0xC9, 0xC2, 0x68,
0x68, 0x0A, 0x33, 0x93, 0x19, 0x37, 0x02, 0x06,
0xE2, 0xF7, 0x67, 0x97, 0x3C, 0x67, 0xB3, 0xF4,
0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C,
};
VerifySignature(signature, TestData.HelloBytes, "SHA1", TestData.RSA384Parameters);
}
[Fact]
public static void VerifySignature_SHA1_1032()
{
byte[] signature =
{
0x49, 0xBC, 0x1C, 0xBE, 0x72, 0xEF, 0x83, 0x6E,
0x2D, 0xFA, 0xE7, 0xFA, 0xEB, 0xBC, 0xF0, 0x16,
0xF7, 0x2C, 0x07, 0x6D, 0x9F, 0xA6, 0x68, 0x71,
0xDC, 0x78, 0x9C, 0xA3, 0x42, 0x9E, 0xBB, 0xF5,
0x72, 0xE0, 0xAB, 0x4B, 0x4B, 0x6A, 0xE7, 0x3C,
0xE2, 0xC8, 0x1F, 0xA2, 0x07, 0xED, 0xD3, 0x98,
0xE9, 0xDF, 0x9A, 0x7A, 0x86, 0xB8, 0x06, 0xED,
0x97, 0x46, 0xF9, 0x8A, 0xED, 0x53, 0x1D, 0x90,
0xC3, 0x57, 0x7E, 0x5A, 0xE4, 0x7C, 0xEC, 0xB9,
0x45, 0x95, 0xAB, 0xCC, 0xBA, 0x9B, 0x2C, 0x1A,
0x64, 0xC2, 0x2C, 0xA0, 0x36, 0x7C, 0x56, 0xF0,
0x78, 0x77, 0x0B, 0x27, 0xB8, 0x1C, 0xCA, 0x7D,
0xD4, 0x71, 0x37, 0xBF, 0xC6, 0x4C, 0x64, 0x76,
0xBC, 0x8A, 0x87, 0xA0, 0x81, 0xF9, 0x4A, 0x94,
0x7B, 0xAA, 0x80, 0x95, 0x47, 0x51, 0xF9, 0x02,
0xA3, 0x44, 0x5C, 0x56, 0x60, 0xFB, 0x94, 0xA8,
0x52,
};
VerifySignature(signature, TestData.HelloBytes, "SHA1", TestData.RSA1032Parameters);
}
[Fact]
public static void VerifySignature_SHA1_2048()
{
byte[] signature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
VerifySignature(signature, TestData.HelloBytes, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void VerifySignature_SHA256_1024()
{
byte[] signature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
VerifySignature(signature, TestData.HelloBytes, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void VerifySignature_SHA256_2048()
{
byte[] signature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
VerifySignature(signature, TestData.HelloBytes, "SHA256", TestData.RSA2048Params);
}
[Fact]
public static void SignAndVerify_SHA1_1024()
{
SignAndVerify(TestData.HelloBytes, "SHA1", TestData.RSA1024Params);
}
[Fact]
public static void SignAndVerify_SHA1_2048()
{
SignAndVerify(TestData.HelloBytes, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void SignAndVerify_SHA256_1024()
{
SignAndVerify(TestData.HelloBytes, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void NegativeVerify_WrongAlgorithm()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
bool signatureMatched = rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void NegativeVerify_WrongSignature()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
// Invalidate the signature.
signature[0] = unchecked((byte)~signature[0]);
bool signatureMatched = rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void NegativeVerify_TamperedData()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
bool signatureMatched = rsa.VerifyData(Array.Empty<byte>(), signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void NegativeVerify_BadKeysize()
{
byte[] signature;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
}
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA1024Params);
bool signatureMatched = rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void ExpectedHashSignature_SHA1_2048()
{
byte[] expectedHashSignature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA1.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
ExpectHashSignature(expectedHashSignature, dataHash, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void ExpectedHashSignature_SHA256_1024()
{
byte[] expectedHashSignature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
ExpectHashSignature(expectedHashSignature, dataHash, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void ExpectedHashSignature_SHA256_2048()
{
byte[] expectedHashSignature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
ExpectHashSignature(expectedHashSignature, dataHash, "SHA256", TestData.RSA2048Params);
}
[Fact]
public static void VerifyHashSignature_SHA1_2048()
{
byte[] hashSignature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA1.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
VerifyHashSignature(hashSignature, dataHash, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void VerifyHashSignature_SHA256_1024()
{
byte[] hashSignature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
VerifyHashSignature(hashSignature, dataHash, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void VerifyHashSignature_SHA256_2048()
{
byte[] hashSignature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
VerifyHashSignature(hashSignature, dataHash, "SHA256", TestData.RSA2048Params);
}
private static void ExpectSignature(
byte[] expectedSignature,
byte[] data,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
// RSA signatures use PKCS 1.5 EMSA encoding (encoding method, signature algorithm).
// EMSA specifies a fixed filler type of { 0x01, 0xFF, 0xFF ... 0xFF, 0x00 } whose length
// is as long as it needs to be to match the block size. Since the filler is deterministic,
// the signature is deterministic, so we can safely verify it here.
byte[] signature;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(rsaParameters);
signature = rsa.SignData(data, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.Equal(expectedSignature, signature);
}
private static void ExpectHashSignature(
byte[] expectedSignature,
byte[] dataHash,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
// RSA signatures use PKCS 1.5 EMSA encoding (encoding method, signature algorithm).
// EMSA specifies a fixed filler type of { 0x01, 0xFF, 0xFF ... 0xFF, 0x00 } whose length
// is as long as it needs to be to match the block size. Since the filler is deterministic,
// the signature is deterministic, so we can safely verify it here.
byte[] signature;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(rsaParameters);
signature = rsa.SignHash(dataHash, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.Equal(expectedSignature, signature);
}
private static void VerifySignature(
byte[] signature,
byte[] data,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
RSAParameters publicOnly = new RSAParameters
{
Modulus = rsaParameters.Modulus,
Exponent = rsaParameters.Exponent,
};
bool signatureMatched;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(publicOnly);
signatureMatched = rsa.VerifyData(data, signature, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.True(signatureMatched);
}
private static void VerifyHashSignature(
byte[] signature,
byte[] dataHash,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
RSAParameters publicOnly = new RSAParameters
{
Modulus = rsaParameters.Modulus,
Exponent = rsaParameters.Exponent,
};
bool signatureMatched;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(publicOnly);
signatureMatched = rsa.VerifyHash(dataHash, signature, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.True(signatureMatched);
}
private static void SignAndVerify(byte[] data, string hashAlgorithmName, RSAParameters rsaParameters)
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(rsaParameters);
byte[] signature = rsa.SignData(data, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
bool signatureMatched = rsa.VerifyData(data, signature, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
Assert.True(signatureMatched);
}
}
}
}
| |
#region Copyright (c) 2002-2005, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net)
/*
Copyright (c) 2002-2005, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net)
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 names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE. */
#endregion
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections;
using Org.Mentalis.Network.ProxySocket;
using XihSolutions.DotMSN;
using XihSolutions.DotMSN.DataTransfer;
namespace XihSolutions.DotMSN.Core
{
/// <summary>
/// Processes I/O of network message through a network connection.
/// </summary>
/// <remarks>
/// SocketMessageProcessor is a message processor which sends over and receives messages
/// from a socket connection. This is usually across the internet, but for file transfers
/// or alternative messenger servers this can also be a LAN connection.
/// A SocketMessageProcess object uses the connection settings in the <see cref="Connection"/> class.
/// Proxyservers and Webproxies are supported.
/// </remarks>
public class SocketMessageProcessor : IMessageProcessor
{
#region Private
/// <summary>
/// </summary>
private ConnectivitySettings connectivitySettings = new ConnectivitySettings();
/// <summary>
/// The buffer in which the socket writes the data.
/// Default buffer size is 1500 bytes.
/// We can use a buffer at class level because data is received synchronized.
/// E.g.: there are no multiple calls to BeginReceive().
/// </summary>
private byte[] socketBuffer = new byte[1500];
#endregion
#region Protected
/// <summary>
/// Set when a socket is prepared with proxy server enabled. This caches the ip adress of the proxyserver and eliminates resolving it everytime a socket is prepared.
/// </summary>
protected IPEndPoint ProxyEndPoint
{
get { return proxyEndPoint; }
set { proxyEndPoint = value;}
}
/// <summary>
/// </summary>
private IPEndPoint proxyEndPoint = null;
/// <summary>
/// The socket used for exchanging messages.
/// </summary>
private ProxySocket socket = null;
/// <summary>
/// The messagepool used to buffer messages.
/// </summary>
protected MessagePool MessagePool
{
get { return messagePool; }
set { messagePool = value;}
}
/// <summary>
/// </summary>
private MessagePool messagePool = null;
/// <summary>
/// Returns a socket which is setup using the settings in the ConnectivitySettings field.
/// Always use this method when you want to use sockets.
/// </summary>
/// <exception cref="ConnectivityException">Raised when the proxy server can not be resolved</exception>
/// <returns></returns>
protected virtual ProxySocket GetPreparedSocket()
{
//Creates the Socket for sending data over TCP.
ProxySocket socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
// incorporate the connection settings like proxy's
// Note: ProxyType is in DotMSN namespace, ProxyTypes in ProxySocket namespace.
if(ConnectivitySettings.ProxyType != ProxyType.None)
{
// set the proxy type
socket.ProxyType = (ConnectivitySettings.ProxyType == ProxyType.Socks4) ? Org.Mentalis.Network.ProxySocket.ProxyTypes.Socks4 : Org.Mentalis.Network.ProxySocket.ProxyTypes.Socks5;
socket.ProxyUser = ConnectivitySettings.ProxyUsername;
socket.ProxyPass = ConnectivitySettings.ProxyPassword;
// resolve the proxy host
if(proxyEndPoint == null)
{
try
{
System.Net.IPHostEntry ipHostEntry = System.Net.Dns.GetHostEntry(ConnectivitySettings.ProxyHost);
System.Net.IPAddress ipAddress = ipHostEntry.AddressList[0];
// assign to the connection object so other sockets can make use of it quickly
proxyEndPoint = new IPEndPoint(ipAddress, ConnectivitySettings.ProxyPort);
}
catch(Exception e)
{
throw new ConnectivityException("DNS Resolve for the proxy server failed: " + ConnectivitySettings.ProxyHost + " failed.", e);
}
}
socket.ProxyEndPoint = proxyEndPoint;
}
else
socket.ProxyType = ProxyTypes.None;
// set socket options
//Send operations will timeout of confirmation is not received within 3000 milliseconds.
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 3000);
//Socket will linger for 2 seconds after close is called.
LingerOption lingerOption = new LingerOption(true, 2);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
//socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.DontLinger, 0);
// don't linger after close
//socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
return socket;
}
/// <summary>
/// The callback used by the Socket.BeginReceive method.
/// </summary>
/// <param name="ar">The used socket.</param>
protected virtual void EndSendCallback(IAsyncResult ar)
{
ProxySocket socket = (ProxySocket)ar.AsyncState;
socket.EndSend(ar);
}
/// <summary>
/// Used by descendants classes to send raw byte data over the socket connection.
/// This function is at the moment blocking. This method uses the default socket in the SocketMessageProcessor class.
/// </summary>
/// <param name="data"></param>
protected void SendSocketData(byte[] data)
{
SendSocketData(socket, data);
}
/// <summary>
/// Used by descendants classes to send raw byte data over the socket connection.
/// This function is at the moment blocking. The data is send over the specified socket connection.
/// </summary>
protected void SendSocketData(Socket socket, byte[] data)
{
try
{
lock(socket)
{
socket.Send(data, 0, data.Length, SocketFlags.None);
}
}
catch(SocketException e)
{
throw e;
}
catch(Exception e)
{
throw new DotMSNException("Error while sending network message. See the inner exception for more details.", e);
}
}
/// <summary>
/// This methods is called when data is retreived from the message pool.
/// It represents a single message. The processor has to convert this to
/// a NetworkMessage object and pass it on to a MessageHandler.
/// </summary>
/// <param name="data"></param>
protected virtual void OnMessageReceived(byte[] data)
{
// do nothing since this is a base class
}
/// <summary>
/// The callback used by the Socket.BeginReceive method.
/// </summary>
/// <param name="ar">The used socket.</param>
protected virtual void EndReceiveCallback(IAsyncResult ar)
{
int cnt = 0;
try
{
System.Diagnostics.Debug.Assert(messagePool != null, "Field messagepool must be defined in derived class of SocketMessageProcessor.");
Socket socket = (Socket)ar.AsyncState;
cnt = socket.EndReceive(ar);
if(cnt == 0)
{
// No data is received. We are disconnected.
OnDisconnected();
return;
}
// read the messages and dispatch to handlers
using(BinaryReader reader = new BinaryReader(new MemoryStream(socketBuffer, 0, cnt)))
{
messagePool.BufferData(reader);
}
while(messagePool.MessageAvailable)
{
// retrieve the message
byte[] incomingMessage = messagePool.GetNextMessageData();
// call the virtual method to perform polymorphism, descendant classes can take care of it
OnMessageReceived(incomingMessage);
}
// start a new read
BeginDataReceive(socket);
}
catch(SocketException e)
{
// close the socket upon a exception
if(socket != null && socket.Connected) socket.Close();
OnDisconnected();
// an exception Occurred, pass it through
if(ConnectionException != null)
ConnectionException(this, new ExceptionEventArgs(new ConnectivityException("SocketMessageProcessor encountered a socket exception while retrieving data. See the inner exception for more information.",e)));
}
catch(ObjectDisposedException)
{
// the connection is closed
OnDisconnected();
}
catch(Exception e)
{
// close the socket upon a exception
if(socket != null && socket.Connected) socket.Close();
if(Settings.TraceSwitch.TraceError)
System.Diagnostics.Trace.WriteLine(e.ToString() + "\r\n" + e.StackTrace + "\r\n", "SocketMessageProcessor");
OnDisconnected();
if(ConnectionException != null)
ConnectionException(this, new ExceptionEventArgs(new ConnectivityException("SocketMessageProcessor encountered a general exception while retrieving data. See the inner exception for more information.",e)));
}
}
/// <summary>
/// The callback used by the Socket.BeginConnect() method.
/// The ProxySocket class behaves different from the standard Socket class.
/// The callback is called after a connection has already been established.
/// </summary>
/// <param name="ar">The used socket.</param>
protected virtual void EndConnectCallback(IAsyncResult ar)
{
try
{
if (Settings.TraceSwitch.TraceVerbose)
System.Diagnostics.Trace.WriteLine("End Connect Callback", "SocketMessageProcessor");
((ProxySocket)socket).EndConnect(ar);
if (Settings.TraceSwitch.TraceVerbose)
System.Diagnostics.Trace.WriteLine("End Connect Callback Daarna", "SocketMessageProcessor");
OnConnected();
// Begin receiving data
BeginDataReceive(socket);
}
catch(Exception e)
{
if (Settings.TraceSwitch.TraceError)
System.Diagnostics.Trace.WriteLine("** EndConnectCallback exception **" + e.ToString(), "SocketMessageProessor");
// an exception was raised while connecting to the endpoint
// fire the event to notify the client programmer
if(ConnectingException != null)
ConnectingException(this, new ExceptionEventArgs(new ConnectivityException("SocketMessageProcessor failed to connect to the specified endpoint. See the inner exception for more information.",e)));
}
}
/// <summary>
/// Starts an a-synchronous receive.
/// </summary>
/// <param name="socket"></param>
protected virtual void BeginDataReceive(Socket socket)
{
// now go retrieve data
socketBuffer = new byte[socketBuffer.Length];
socket.BeginReceive(socketBuffer, 0, socketBuffer.Length, SocketFlags.None, new AsyncCallback(EndReceiveCallback), socket);
}
/// <summary>
/// Fires the Connected event.
/// </summary>
protected virtual void OnConnected()
{
if(Settings.TraceSwitch.TraceInfo)
System.Diagnostics.Trace.WriteLine("Connected", "SocketMessageProcessor");
if(ConnectionEstablished != null)
ConnectionEstablished(this, new EventArgs());
}
/// <summary>
/// Fires the Disconnected event.
/// </summary>
protected virtual void OnDisconnected()
{
if(Settings.TraceSwitch.TraceInfo)
System.Diagnostics.Trace.WriteLine("Disconnected", "SocketMessageProcessor");
if(ConnectionClosed != null)
ConnectionClosed(this, new EventArgs());
}
#endregion
#region Public
/// <summary>
/// Specifies the connection configuration used to set up the socket connection.
/// By default the basic constructor is called.
/// </summary>
public ConnectivitySettings ConnectivitySettings
{
get { return connectivitySettings; }
set { connectivitySettings = value;}
}
/// <summary>
/// Determines whether the socket is connected
/// </summary>
public bool Connected
{
get { return socket != null && socket.Connected; }
}
/// <summary>
/// The local end point of the connection
/// </summary>
public EndPoint LocalEndPoint
{
get
{
return socket.LocalEndPoint;
}
}
/// <summary>
/// Constructor to instantiate a SocketMessageProcessor object.
/// </summary>
public SocketMessageProcessor()
{
}
/// <summary>
/// Holds all messagehandlers for this socket processor
/// </summary>
protected ArrayList MessageHandlers
{
get { return messageHandlers; }
//set { messageHandlers = value;}
}
/// <summary>
/// </summary>
private ArrayList messageHandlers = new ArrayList();
/// <summary>
/// Registers a message handler with this processor.
/// </summary>
/// <param name="handler"></param>
public virtual void RegisterHandler(IMessageHandler handler)
{
lock(messageHandlers)
{
if(messageHandlers.Contains(handler))
return;
// add the handler
messageHandlers.Add(handler);
}
}
/// <summary>
/// Unregisters the message handler from this processor.
/// </summary>
/// <param name="handler"></param>
public virtual void UnregisterHandler(IMessageHandler handler)
{
lock(messageHandlers)
{
// remove from the collection
messageHandlers.Remove(handler);
}
}
/// <summary>
/// Connect to the endpoint specified in the ConnectivitySettings field.
/// If the socket is already connected this method will return immediately and leave the current connection open.
/// </summary>
public virtual void Connect()
{
if (socket != null && socket.Connected)
{
if (Settings.TraceSwitch.TraceWarning)
System.Diagnostics.Trace.WriteLine("SocketMessageProcess.Connect() called, but already a socket available.", "NS9MessageHandler");
return;
}
try
{
// create a socket
socket = GetPreparedSocket(); //
IPAddress hostIP = null;
if (IPAddress.TryParse(ConnectivitySettings.Host, out hostIP))
{
// start connecting
((ProxySocket)socket).BeginConnect(new System.Net.IPEndPoint(IPAddress.Parse(ConnectivitySettings.Host), ConnectivitySettings.Port), new AsyncCallback(EndConnectCallback), socket);
}
else
{
((ProxySocket)socket).BeginConnect(ConnectivitySettings.Host, ConnectivitySettings.Port, new AsyncCallback(EndConnectCallback), socket);
}
}
catch(Exception e)
{
if(Settings.TraceSwitch.TraceVerbose)
System.Diagnostics.Trace.WriteLine("Connecting exception: " + e.ToString(), "SocketMessageProcessor");
// an exception was raised while connecting to the endpoint
// fire the event to notify the client programmer
if(ConnectingException != null)
ConnectingException(this, new ExceptionEventArgs(e));
// re-throw the exception since the exception is thrown while in a blocking call
throw e;
}
finally
{
}
}
/// <summary>
/// Disconnect the current connection by sending the OUT command and closing the socket. If the connection is already closed
/// nothing happens (<i>no</i> exception is thrown).
/// </summary>
public virtual void Disconnect()
{
// clean up the socket properly
if(socket != null && socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
socket = null;
OnDisconnected();
}
}
/// <summary>
/// The base class does nothing here. Descendant classes should implement this function
/// by encoding the message in a byte array and send it using the <see cref="XihSolutions.DotMSN.Core.SocketMessageProcessor.SendSocketData(byte[])"/> method.
/// </summary>
/// <param name="message"></param>
public virtual void SendMessage(NetworkMessage message)
{
throw new NotImplementedException("SendMessage() on the base class SocketMessageProcessor is invalid.");
}
/// <summary>
/// Occurs when a connection is established with the remote endpoint.
/// </summary>
public event EventHandler ConnectionEstablished;
/// <summary>
/// Occurs when a connection is closed with the remote endpoint.
/// </summary>
public event EventHandler ConnectionClosed;
/// <summary>
/// Occurs when an exception was raised while <i>connecting</i> to the endpoint.
/// </summary>
public event ProcessorExceptionEventHandler ConnectingException;
/// <summary>
/// Occurs when an exception was raised which caused the open connection to become invalid.
/// </summary>
public event ProcessorExceptionEventHandler ConnectionException;
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using log4net.Config;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenSim.Framework;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.CoreModules.World.Land;
using OpenSim.Region.CoreModules.World.Serialiser;
using OpenSim.Region.CoreModules.World.Terrain;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using ArchiveConstants = OpenSim.Framework.Serialization.ArchiveConstants;
using TarArchiveReader = OpenSim.Framework.Serialization.TarArchiveReader;
using TarArchiveWriter = OpenSim.Framework.Serialization.TarArchiveWriter;
using RegionSettings = OpenSim.Framework.RegionSettings;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.CoreModules.World.Archiver.Tests
{
[TestFixture]
public class ArchiverTests : OpenSimTestCase
{
private Guid m_lastRequestId;
private string m_lastErrorMessage;
protected SceneHelpers m_sceneHelpers;
protected TestScene m_scene;
protected ArchiverModule m_archiverModule;
protected SerialiserModule m_serialiserModule;
protected TaskInventoryItem m_soundItem;
[SetUp]
public override void SetUp()
{
base.SetUp();
m_archiverModule = new ArchiverModule();
m_serialiserModule = new SerialiserModule();
TerrainModule terrainModule = new TerrainModule();
m_sceneHelpers = new SceneHelpers();
m_scene = m_sceneHelpers.SetupScene();
SceneHelpers.SetupSceneModules(m_scene, m_archiverModule, m_serialiserModule, terrainModule);
}
private void LoadCompleted(Guid requestId, List<UUID> loadedScenes, string errorMessage)
{
lock (this)
{
m_lastRequestId = requestId;
m_lastErrorMessage = errorMessage;
Console.WriteLine("About to pulse ArchiverTests on LoadCompleted");
Monitor.PulseAll(this);
}
}
private void SaveCompleted(Guid requestId, string errorMessage)
{
lock (this)
{
m_lastRequestId = requestId;
m_lastErrorMessage = errorMessage;
Console.WriteLine("About to pulse ArchiverTests on SaveCompleted");
Monitor.PulseAll(this);
}
}
protected SceneObjectPart CreateSceneObjectPart1()
{
string partName = "My Little Pony";
UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000015");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
Vector3 groupPosition = new Vector3(10, 20, 30);
Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
// Vector3 offsetPosition = new Vector3(5, 10, 15);
return new SceneObjectPart(ownerId, shape, groupPosition, rotationOffset, Vector3.Zero) { Name = partName };
}
protected SceneObjectPart CreateSceneObjectPart2()
{
string partName = "Action Man";
UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000016");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateCylinder();
Vector3 groupPosition = new Vector3(90, 80, 70);
Quaternion rotationOffset = new Quaternion(60, 70, 80, 90);
Vector3 offsetPosition = new Vector3(20, 25, 30);
return new SceneObjectPart(ownerId, shape, groupPosition, rotationOffset, offsetPosition) { Name = partName };
}
private void CreateTestObjects(Scene scene, out SceneObjectGroup sog1, out SceneObjectGroup sog2, out UUID ncAssetUuid)
{
SceneObjectPart part1 = CreateSceneObjectPart1();
sog1 = new SceneObjectGroup(part1);
scene.AddNewSceneObject(sog1, false);
AssetNotecard nc = new AssetNotecard();
nc.BodyText = "Hello World!";
nc.Encode();
ncAssetUuid = UUID.Random();
UUID ncItemUuid = UUID.Random();
AssetBase ncAsset
= AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);
m_scene.AssetService.Store(ncAsset);
TaskInventoryItem ncItem
= new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid };
SceneObjectPart part2 = CreateSceneObjectPart2();
sog2 = new SceneObjectGroup(part2);
part2.Inventory.AddInventoryItem(ncItem, true);
scene.AddNewSceneObject(sog2, false);
}
private static void CreateSoundAsset(TarArchiveWriter tar, Assembly assembly, string soundDataResourceName, out byte[] soundData, out UUID soundUuid)
{
using (Stream resource = assembly.GetManifestResourceStream(soundDataResourceName))
{
using (BinaryReader br = new BinaryReader(resource))
{
// FIXME: Use the inspector instead
soundData = br.ReadBytes(99999999);
soundUuid = UUID.Parse("00000000-0000-0000-0000-000000000001");
string soundAssetFileName
= ArchiveConstants.ASSETS_PATH + soundUuid
+ ArchiveConstants.ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.SoundWAV];
tar.WriteFile(soundAssetFileName, soundData);
/*
AssetBase soundAsset = AssetHelpers.CreateAsset(soundUuid, soundData);
scene.AssetService.Store(soundAsset);
asset1FileName = ArchiveConstants.ASSETS_PATH + soundUuid + ".wav";
*/
}
}
}
/// <summary>
/// Test saving an OpenSim Region Archive.
/// </summary>
[Test]
public void TestSaveOar()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
SceneObjectGroup sog1;
SceneObjectGroup sog2;
UUID ncAssetUuid;
CreateTestObjects(m_scene, out sog1, out sog2, out ncAssetUuid);
MemoryStream archiveWriteStream = new MemoryStream();
m_scene.EventManager.OnOarFileSaved += SaveCompleted;
Guid requestId = new Guid("00000000-0000-0000-0000-808080808080");
lock (this)
{
m_archiverModule.ArchiveRegion(archiveWriteStream, requestId);
//AssetServerBase assetServer = (AssetServerBase)scene.CommsManager.AssetCache.AssetServer;
//while (assetServer.HasWaitingRequests())
// assetServer.ProcessNextRequest();
Monitor.Wait(this, 60000);
}
Assert.That(m_lastRequestId, Is.EqualTo(requestId));
byte[] archive = archiveWriteStream.ToArray();
MemoryStream archiveReadStream = new MemoryStream(archive);
TarArchiveReader tar = new TarArchiveReader(archiveReadStream);
bool gotNcAssetFile = false;
string expectedNcAssetFileName = string.Format("{0}_{1}", ncAssetUuid, "notecard.txt");
List<string> foundPaths = new List<string>();
List<string> expectedPaths = new List<string>();
expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1));
expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2));
string filePath;
TarArchiveReader.TarEntryType tarEntryType;
byte[] data = tar.ReadEntry(out filePath, out tarEntryType);
Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH));
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions);
arr.LoadControlFile(filePath, data, new DearchiveScenesInfo());
Assert.That(arr.ControlFileLoaded, Is.True);
while (tar.ReadEntry(out filePath, out tarEntryType) != null)
{
if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
{
string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
Assert.That(fileName, Is.EqualTo(expectedNcAssetFileName));
gotNcAssetFile = true;
}
else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
{
foundPaths.Add(filePath);
}
}
Assert.That(gotNcAssetFile, Is.True, "No notecard asset file in archive");
Assert.That(foundPaths, Is.EquivalentTo(expectedPaths));
// TODO: Test presence of more files and contents of files.
}
/// <summary>
/// Test saving an OpenSim Region Archive with the no assets option
/// </summary>
[Test]
public void TestSaveOarNoAssets()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
SceneObjectPart part1 = CreateSceneObjectPart1();
SceneObjectGroup sog1 = new SceneObjectGroup(part1);
m_scene.AddNewSceneObject(sog1, false);
SceneObjectPart part2 = CreateSceneObjectPart2();
AssetNotecard nc = new AssetNotecard();
nc.BodyText = "Hello World!";
nc.Encode();
UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000");
AssetBase ncAsset
= AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);
m_scene.AssetService.Store(ncAsset);
SceneObjectGroup sog2 = new SceneObjectGroup(part2);
TaskInventoryItem ncItem
= new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid };
part2.Inventory.AddInventoryItem(ncItem, true);
m_scene.AddNewSceneObject(sog2, false);
MemoryStream archiveWriteStream = new MemoryStream();
Guid requestId = new Guid("00000000-0000-0000-0000-808080808080");
Dictionary<string, Object> options = new Dictionary<string, Object>();
options.Add("noassets", true);
m_archiverModule.ArchiveRegion(archiveWriteStream, requestId, options);
// Don't wait for completion - with --noassets save oar happens synchronously
// Monitor.Wait(this, 60000);
Assert.That(m_lastRequestId, Is.EqualTo(requestId));
byte[] archive = archiveWriteStream.ToArray();
MemoryStream archiveReadStream = new MemoryStream(archive);
TarArchiveReader tar = new TarArchiveReader(archiveReadStream);
List<string> foundPaths = new List<string>();
List<string> expectedPaths = new List<string>();
expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1));
expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2));
string filePath;
TarArchiveReader.TarEntryType tarEntryType;
byte[] data = tar.ReadEntry(out filePath, out tarEntryType);
Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH));
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions);
arr.LoadControlFile(filePath, data, new DearchiveScenesInfo());
Assert.That(arr.ControlFileLoaded, Is.True);
while (tar.ReadEntry(out filePath, out tarEntryType) != null)
{
if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
{
Assert.Fail("Asset was found in saved oar of TestSaveOarNoAssets()");
}
else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
{
foundPaths.Add(filePath);
}
}
Assert.That(foundPaths, Is.EquivalentTo(expectedPaths));
// TODO: Test presence of more files and contents of files.
}
/// <summary>
/// Test loading an OpenSim Region Archive.
/// </summary>
[Test]
public void TestLoadOar()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
MemoryStream archiveWriteStream = new MemoryStream();
TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
// Put in a random blank directory to check that this doesn't upset the load process
tar.WriteDir("ignoreme");
// Also check that direct entries which will also have a file entry containing that directory doesn't
// upset load
tar.WriteDir(ArchiveConstants.TERRAINS_PATH);
tar.WriteFile(
ArchiveConstants.CONTROL_FILE_PATH,
new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup()));
SceneObjectPart part1 = CreateSceneObjectPart1();
part1.SitTargetOrientation = new Quaternion(0.2f, 0.3f, 0.4f, 0.5f);
part1.SitTargetPosition = new Vector3(1, 2, 3);
SceneObjectGroup object1 = new SceneObjectGroup(part1);
// Let's put some inventory items into our object
string soundItemName = "sound-item1";
UUID soundItemUuid = UUID.Parse("00000000-0000-0000-0000-000000000002");
Type type = GetType();
Assembly assembly = type.Assembly;
string soundDataResourceName = null;
string[] names = assembly.GetManifestResourceNames();
foreach (string name in names)
{
if (name.EndsWith(".Resources.test-sound.wav"))
soundDataResourceName = name;
}
Assert.That(soundDataResourceName, Is.Not.Null);
byte[] soundData;
UUID soundUuid;
CreateSoundAsset(tar, assembly, soundDataResourceName, out soundData, out soundUuid);
TaskInventoryItem item1
= new TaskInventoryItem { AssetID = soundUuid, ItemID = soundItemUuid, Name = soundItemName };
part1.Inventory.AddInventoryItem(item1, true);
m_scene.AddNewSceneObject(object1, false);
string object1FileName = string.Format(
"{0}_{1:000}-{2:000}-{3:000}__{4}.xml",
part1.Name,
Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z),
part1.UUID);
tar.WriteFile(ArchiveConstants.OBJECTS_PATH + object1FileName, SceneObjectSerializer.ToXml2Format(object1));
tar.Close();
MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
lock (this)
{
m_scene.EventManager.OnOarFileLoaded += LoadCompleted;
m_archiverModule.DearchiveRegion(archiveReadStream);
}
Assert.That(m_lastErrorMessage, Is.Null);
TestLoadedRegion(part1, soundItemName, soundData);
}
/// <summary>
/// Test loading an OpenSim Region Archive where the scene object parts are not ordered by link number (e.g.
/// 2 can come after 3).
/// </summary>
[Test]
public void TestLoadOarUnorderedParts()
{
TestHelpers.InMethod();
UUID ownerId = TestHelpers.ParseTail(0xaaaa);
MemoryStream archiveWriteStream = new MemoryStream();
TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
tar.WriteFile(
ArchiveConstants.CONTROL_FILE_PATH,
new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup()));
SceneObjectGroup sog1 = SceneHelpers.CreateSceneObject(1, ownerId, "obj1-", 0x11);
SceneObjectPart sop2
= SceneHelpers.CreateSceneObjectPart("obj1-Part2", TestHelpers.ParseTail(0x12), ownerId);
SceneObjectPart sop3
= SceneHelpers.CreateSceneObjectPart("obj1-Part3", TestHelpers.ParseTail(0x13), ownerId);
// Add the parts so they will be written out in reverse order to the oar
sog1.AddPart(sop3);
sop3.LinkNum = 3;
sog1.AddPart(sop2);
sop2.LinkNum = 2;
tar.WriteFile(
ArchiveConstants.CreateOarObjectPath(sog1.Name, sog1.UUID, sog1.AbsolutePosition),
SceneObjectSerializer.ToXml2Format(sog1));
tar.Close();
MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
lock (this)
{
m_scene.EventManager.OnOarFileLoaded += LoadCompleted;
m_archiverModule.DearchiveRegion(archiveReadStream);
}
Assert.That(m_lastErrorMessage, Is.Null);
SceneObjectPart part2 = m_scene.GetSceneObjectPart("obj1-Part2");
Assert.That(part2.LinkNum, Is.EqualTo(2));
SceneObjectPart part3 = m_scene.GetSceneObjectPart("obj1-Part3");
Assert.That(part3.LinkNum, Is.EqualTo(3));
}
/// <summary>
/// Test loading an OpenSim Region Archive saved with the --publish option.
/// </summary>
[Test]
public void TestLoadPublishedOar()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
SceneObjectPart part1 = CreateSceneObjectPart1();
SceneObjectGroup sog1 = new SceneObjectGroup(part1);
m_scene.AddNewSceneObject(sog1, false);
SceneObjectPart part2 = CreateSceneObjectPart2();
AssetNotecard nc = new AssetNotecard();
nc.BodyText = "Hello World!";
nc.Encode();
UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000");
AssetBase ncAsset
= AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);
m_scene.AssetService.Store(ncAsset);
SceneObjectGroup sog2 = new SceneObjectGroup(part2);
TaskInventoryItem ncItem
= new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid };
part2.Inventory.AddInventoryItem(ncItem, true);
m_scene.AddNewSceneObject(sog2, false);
MemoryStream archiveWriteStream = new MemoryStream();
m_scene.EventManager.OnOarFileSaved += SaveCompleted;
Guid requestId = new Guid("00000000-0000-0000-0000-808080808080");
lock (this)
{
m_archiverModule.ArchiveRegion(
archiveWriteStream, requestId, new Dictionary<string, Object>() { { "wipe-owners", Boolean.TrueString } });
Monitor.Wait(this, 60000);
}
Assert.That(m_lastRequestId, Is.EqualTo(requestId));
byte[] archive = archiveWriteStream.ToArray();
MemoryStream archiveReadStream = new MemoryStream(archive);
{
UUID estateOwner = TestHelpers.ParseTail(0x4747);
UUID objectOwner = TestHelpers.ParseTail(0x15);
// Reload to new scene
ArchiverModule archiverModule = new ArchiverModule();
SerialiserModule serialiserModule = new SerialiserModule();
TerrainModule terrainModule = new TerrainModule();
SceneHelpers m_sceneHelpers2 = new SceneHelpers();
TestScene scene2 = m_sceneHelpers2.SetupScene();
SceneHelpers.SetupSceneModules(scene2, archiverModule, serialiserModule, terrainModule);
// Make sure there's a valid owner for the owner we saved (this should have been wiped if the code is
// behaving correctly
UserAccountHelpers.CreateUserWithInventory(scene2, objectOwner);
scene2.RegionInfo.EstateSettings.EstateOwner = estateOwner;
lock (this)
{
scene2.EventManager.OnOarFileLoaded += LoadCompleted;
archiverModule.DearchiveRegion(archiveReadStream);
}
Assert.That(m_lastErrorMessage, Is.Null);
SceneObjectGroup loadedSog = scene2.GetSceneObjectGroup(part1.Name);
Assert.That(loadedSog.OwnerID, Is.EqualTo(estateOwner));
Assert.That(loadedSog.LastOwnerID, Is.EqualTo(estateOwner));
}
}
/// <summary>
/// Test OAR loading where the land parcel is group deeded.
/// </summary>
/// <remarks>
/// In this situation, the owner ID is set to the group ID.
/// </remarks>
[Test]
public void TestLoadOarDeededLand()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID landID = TestHelpers.ParseTail(0x10);
MockGroupsServicesConnector groupsService = new MockGroupsServicesConnector();
IConfigSource configSource = new IniConfigSource();
IConfig config = configSource.AddConfig("Groups");
config.Set("Enabled", true);
config.Set("Module", "GroupsModule");
config.Set("DebugEnabled", true);
SceneHelpers.SetupSceneModules(
m_scene, configSource, new object[] { new GroupsModule(), groupsService, new LandManagementModule() });
// Create group in scene for loading
// FIXME: For now we'll put up with the issue that we'll get a group ID that varies across tests.
UUID groupID
= groupsService.CreateGroup(UUID.Zero, "group1", "", true, UUID.Zero, 3, true, true, true, UUID.Zero);
// Construct OAR
MemoryStream oarStream = new MemoryStream();
TarArchiveWriter tar = new TarArchiveWriter(oarStream);
tar.WriteDir(ArchiveConstants.LANDDATA_PATH);
tar.WriteFile(
ArchiveConstants.CONTROL_FILE_PATH,
new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup()));
LandObject lo = new LandObject(groupID, true, m_scene);
lo.SetLandBitmap(lo.BasicFullRegionLandBitmap());
LandData ld = lo.LandData;
ld.GlobalID = landID;
string ldPath = ArchiveConstants.CreateOarLandDataPath(ld);
tar.WriteFile(ldPath, LandDataSerializer.Serialize(ld, null));
tar.Close();
oarStream = new MemoryStream(oarStream.ToArray());
// Load OAR
lock (this)
{
m_scene.EventManager.OnOarFileLoaded += LoadCompleted;
m_archiverModule.DearchiveRegion(oarStream);
}
ILandObject rLo = m_scene.LandChannel.GetLandObject(16, 16);
LandData rLd = rLo.LandData;
Assert.That(rLd.GlobalID, Is.EqualTo(landID));
Assert.That(rLd.OwnerID, Is.EqualTo(groupID));
Assert.That(rLd.GroupID, Is.EqualTo(groupID));
Assert.That(rLd.IsGroupOwned, Is.EqualTo(true));
}
/// <summary>
/// Test loading the region settings of an OpenSim Region Archive.
/// </summary>
[Test]
public void TestLoadOarRegionSettings()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
MemoryStream archiveWriteStream = new MemoryStream();
TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
tar.WriteDir(ArchiveConstants.TERRAINS_PATH);
tar.WriteFile(
ArchiveConstants.CONTROL_FILE_PATH,
new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup()));
RegionSettings rs = new RegionSettings();
rs.AgentLimit = 17;
rs.AllowDamage = true;
rs.AllowLandJoinDivide = true;
rs.AllowLandResell = true;
rs.BlockFly = true;
rs.BlockShowInSearch = true;
rs.BlockTerraform = true;
rs.DisableCollisions = true;
rs.DisablePhysics = true;
rs.DisableScripts = true;
rs.Elevation1NW = 15.9;
rs.Elevation1NE = 45.3;
rs.Elevation1SE = 49;
rs.Elevation1SW = 1.9;
rs.Elevation2NW = 4.5;
rs.Elevation2NE = 19.2;
rs.Elevation2SE = 9.2;
rs.Elevation2SW = 2.1;
rs.FixedSun = true;
rs.SunPosition = 12.0;
rs.ObjectBonus = 1.4;
rs.RestrictPushing = true;
rs.TerrainLowerLimit = 0.4;
rs.TerrainRaiseLimit = 17.9;
rs.TerrainTexture1 = UUID.Parse("00000000-0000-0000-0000-000000000020");
rs.TerrainTexture2 = UUID.Parse("00000000-0000-0000-0000-000000000040");
rs.TerrainTexture3 = UUID.Parse("00000000-0000-0000-0000-000000000060");
rs.TerrainTexture4 = UUID.Parse("00000000-0000-0000-0000-000000000080");
rs.UseEstateSun = true;
rs.WaterHeight = 23;
rs.TelehubObject = UUID.Parse("00000000-0000-0000-0000-111111111111");
rs.AddSpawnPoint(SpawnPoint.Parse("1,-2,0.33"));
tar.WriteFile(ArchiveConstants.SETTINGS_PATH + "region1.xml", RegionSettingsSerializer.Serialize(rs));
tar.Close();
MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
lock (this)
{
m_scene.EventManager.OnOarFileLoaded += LoadCompleted;
m_archiverModule.DearchiveRegion(archiveReadStream);
}
Assert.That(m_lastErrorMessage, Is.Null);
RegionSettings loadedRs = m_scene.RegionInfo.RegionSettings;
Assert.That(loadedRs.AgentLimit, Is.EqualTo(17));
Assert.That(loadedRs.AllowDamage, Is.True);
Assert.That(loadedRs.AllowLandJoinDivide, Is.True);
Assert.That(loadedRs.AllowLandResell, Is.True);
Assert.That(loadedRs.BlockFly, Is.True);
Assert.That(loadedRs.BlockShowInSearch, Is.True);
Assert.That(loadedRs.BlockTerraform, Is.True);
Assert.That(loadedRs.DisableCollisions, Is.True);
Assert.That(loadedRs.DisablePhysics, Is.True);
Assert.That(loadedRs.DisableScripts, Is.True);
Assert.That(loadedRs.Elevation1NW, Is.EqualTo(15.9));
Assert.That(loadedRs.Elevation1NE, Is.EqualTo(45.3));
Assert.That(loadedRs.Elevation1SE, Is.EqualTo(49));
Assert.That(loadedRs.Elevation1SW, Is.EqualTo(1.9));
Assert.That(loadedRs.Elevation2NW, Is.EqualTo(4.5));
Assert.That(loadedRs.Elevation2NE, Is.EqualTo(19.2));
Assert.That(loadedRs.Elevation2SE, Is.EqualTo(9.2));
Assert.That(loadedRs.Elevation2SW, Is.EqualTo(2.1));
Assert.That(loadedRs.FixedSun, Is.True);
Assert.AreEqual(12.0, loadedRs.SunPosition);
Assert.That(loadedRs.ObjectBonus, Is.EqualTo(1.4));
Assert.That(loadedRs.RestrictPushing, Is.True);
Assert.That(loadedRs.TerrainLowerLimit, Is.EqualTo(0.4));
Assert.That(loadedRs.TerrainRaiseLimit, Is.EqualTo(17.9));
Assert.That(loadedRs.TerrainTexture1, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000020")));
Assert.That(loadedRs.TerrainTexture2, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000040")));
Assert.That(loadedRs.TerrainTexture3, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000060")));
Assert.That(loadedRs.TerrainTexture4, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000080")));
Assert.That(loadedRs.UseEstateSun, Is.True);
Assert.That(loadedRs.WaterHeight, Is.EqualTo(23));
Assert.AreEqual(UUID.Zero, loadedRs.TelehubObject); // because no object was found with the original UUID
Assert.AreEqual(0, loadedRs.SpawnPoints().Count);
}
/// <summary>
/// Test merging an OpenSim Region Archive into an existing scene
/// </summary>
//[Test]
public void TestMergeOar()
{
TestHelpers.InMethod();
//XmlConfigurator.Configure();
MemoryStream archiveWriteStream = new MemoryStream();
// string part2Name = "objectMerge";
// PrimitiveBaseShape part2Shape = PrimitiveBaseShape.CreateCylinder();
// Vector3 part2GroupPosition = new Vector3(90, 80, 70);
// Quaternion part2RotationOffset = new Quaternion(60, 70, 80, 90);
// Vector3 part2OffsetPosition = new Vector3(20, 25, 30);
SceneObjectPart part2 = CreateSceneObjectPart2();
// Create an oar file that we can use for the merge
{
ArchiverModule archiverModule = new ArchiverModule();
SerialiserModule serialiserModule = new SerialiserModule();
TerrainModule terrainModule = new TerrainModule();
Scene scene = m_sceneHelpers.SetupScene();
SceneHelpers.SetupSceneModules(scene, archiverModule, serialiserModule, terrainModule);
m_scene.AddNewSceneObject(new SceneObjectGroup(part2), false);
// Write out this scene
scene.EventManager.OnOarFileSaved += SaveCompleted;
lock (this)
{
m_archiverModule.ArchiveRegion(archiveWriteStream);
Monitor.Wait(this, 60000);
}
}
{
SceneObjectPart part1 = CreateSceneObjectPart1();
m_scene.AddNewSceneObject(new SceneObjectGroup(part1), false);
// Merge in the archive we created earlier
byte[] archive = archiveWriteStream.ToArray();
MemoryStream archiveReadStream = new MemoryStream(archive);
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
archiveOptions.Add("merge", null);
m_archiverModule.DearchiveRegion(archiveReadStream, Guid.Empty, archiveOptions);
SceneObjectPart object1Existing = m_scene.GetSceneObjectPart(part1.Name);
Assert.That(object1Existing, Is.Not.Null, "object1 was not present after merge");
Assert.That(object1Existing.Name, Is.EqualTo(part1.Name), "object1 names not identical after merge");
Assert.That(object1Existing.GroupPosition, Is.EqualTo(part1.GroupPosition), "object1 group position not equal after merge");
SceneObjectPart object2PartMerged = m_scene.GetSceneObjectPart(part2.Name);
Assert.That(object2PartMerged, Is.Not.Null, "object2 was not present after merge");
Assert.That(object2PartMerged.Name, Is.EqualTo(part2.Name), "object2 names not identical after merge");
Assert.That(object2PartMerged.GroupPosition, Is.EqualTo(part2.GroupPosition), "object2 group position not equal after merge");
}
}
/// <summary>
/// Test saving a multi-region OAR.
/// </summary>
[Test]
public void TestSaveMultiRegionOar()
{
TestHelpers.InMethod();
// Create test regions
int WIDTH = 2;
int HEIGHT = 2;
List<Scene> scenes = new List<Scene>();
// Maps (Directory in OAR file -> scene)
Dictionary<string, Scene> regionPaths = new Dictionary<string, Scene>();
// Maps (Scene -> expected object paths)
Dictionary<UUID, List<string>> expectedPaths = new Dictionary<UUID, List<string>>();
// List of expected assets
List<UUID> expectedAssets = new List<UUID>();
for (uint y = 0; y < HEIGHT; y++)
{
for (uint x = 0; x < WIDTH; x++)
{
Scene scene;
if (x == 0 && y == 0)
{
scene = m_scene; // this scene was already created in SetUp()
}
else
{
scene = m_sceneHelpers.SetupScene(string.Format("Unit test region {0}", (y * WIDTH) + x + 1), UUID.Random(), 1000 + x, 1000 + y);
SceneHelpers.SetupSceneModules(scene, new ArchiverModule(), m_serialiserModule, new TerrainModule());
}
scenes.Add(scene);
string dir = String.Format("{0}_{1}_{2}", x + 1, y + 1, scene.RegionInfo.RegionName.Replace(" ", "_"));
regionPaths[dir] = scene;
SceneObjectGroup sog1;
SceneObjectGroup sog2;
UUID ncAssetUuid;
CreateTestObjects(scene, out sog1, out sog2, out ncAssetUuid);
expectedPaths[scene.RegionInfo.RegionID] = new List<string>();
expectedPaths[scene.RegionInfo.RegionID].Add(ArchiveHelpers.CreateObjectPath(sog1));
expectedPaths[scene.RegionInfo.RegionID].Add(ArchiveHelpers.CreateObjectPath(sog2));
expectedAssets.Add(ncAssetUuid);
}
}
// Save OAR
MemoryStream archiveWriteStream = new MemoryStream();
m_scene.EventManager.OnOarFileSaved += SaveCompleted;
Guid requestId = new Guid("00000000-0000-0000-0000-808080808080");
Dictionary<string, Object> options = new Dictionary<string, Object>();
options.Add("all", true);
lock (this)
{
m_archiverModule.ArchiveRegion(archiveWriteStream, requestId, options);
Monitor.Wait(this, 60000);
}
// Check that the OAR contains the expected data
Assert.That(m_lastRequestId, Is.EqualTo(requestId));
byte[] archive = archiveWriteStream.ToArray();
MemoryStream archiveReadStream = new MemoryStream(archive);
TarArchiveReader tar = new TarArchiveReader(archiveReadStream);
Dictionary<UUID, List<string>> foundPaths = new Dictionary<UUID, List<string>>();
List<UUID> foundAssets = new List<UUID>();
foreach (Scene scene in scenes)
{
foundPaths[scene.RegionInfo.RegionID] = new List<string>();
}
string filePath;
TarArchiveReader.TarEntryType tarEntryType;
byte[] data = tar.ReadEntry(out filePath, out tarEntryType);
Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH));
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions);
arr.LoadControlFile(filePath, data, new DearchiveScenesInfo());
Assert.That(arr.ControlFileLoaded, Is.True);
while (tar.ReadEntry(out filePath, out tarEntryType) != null)
{
if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
{
// Assets are shared, so this file doesn't belong to any specific region.
string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
if (fileName.EndsWith("_notecard.txt"))
foundAssets.Add(UUID.Parse(fileName.Substring(0, fileName.Length - "_notecard.txt".Length)));
}
else
{
// This file belongs to one of the regions. Find out which one.
Assert.IsTrue(filePath.StartsWith(ArchiveConstants.REGIONS_PATH));
string[] parts = filePath.Split(new Char[] { '/' }, 3);
Assert.AreEqual(3, parts.Length);
string regionDirectory = parts[1];
string relativePath = parts[2];
Scene scene = regionPaths[regionDirectory];
if (relativePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
{
foundPaths[scene.RegionInfo.RegionID].Add(relativePath);
}
}
}
Assert.AreEqual(scenes.Count, foundPaths.Count);
foreach (Scene scene in scenes)
{
Assert.That(foundPaths[scene.RegionInfo.RegionID], Is.EquivalentTo(expectedPaths[scene.RegionInfo.RegionID]));
}
Assert.That(foundAssets, Is.EquivalentTo(expectedAssets));
}
/// <summary>
/// Test loading a multi-region OAR.
/// </summary>
[Test]
public void TestLoadMultiRegionOar()
{
TestHelpers.InMethod();
// Create an ArchiveScenesGroup with the regions in the OAR. This is needed to generate the control file.
int WIDTH = 2;
int HEIGHT = 2;
for (uint y = 0; y < HEIGHT; y++)
{
for (uint x = 0; x < WIDTH; x++)
{
Scene scene;
if (x == 0 && y == 0)
{
scene = m_scene; // this scene was already created in SetUp()
}
else
{
scene = m_sceneHelpers.SetupScene(string.Format("Unit test region {0}", (y * WIDTH) + x + 1), UUID.Random(), 1000 + x, 1000 + y);
SceneHelpers.SetupSceneModules(scene, new ArchiverModule(), m_serialiserModule, new TerrainModule());
}
}
}
ArchiveScenesGroup scenesGroup = new ArchiveScenesGroup();
m_sceneHelpers.SceneManager.ForEachScene(delegate(Scene scene)
{
scenesGroup.AddScene(scene);
});
scenesGroup.CalcSceneLocations();
// Generate the OAR file
MemoryStream archiveWriteStream = new MemoryStream();
TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
ArchiveWriteRequest writeRequest = new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty);
writeRequest.MultiRegionFormat = true;
tar.WriteFile(
ArchiveConstants.CONTROL_FILE_PATH, writeRequest.CreateControlFile(scenesGroup));
SceneObjectPart part1 = CreateSceneObjectPart1();
part1.SitTargetOrientation = new Quaternion(0.2f, 0.3f, 0.4f, 0.5f);
part1.SitTargetPosition = new Vector3(1, 2, 3);
SceneObjectGroup object1 = new SceneObjectGroup(part1);
// Let's put some inventory items into our object
string soundItemName = "sound-item1";
UUID soundItemUuid = UUID.Parse("00000000-0000-0000-0000-000000000002");
Type type = GetType();
Assembly assembly = type.Assembly;
string soundDataResourceName = null;
string[] names = assembly.GetManifestResourceNames();
foreach (string name in names)
{
if (name.EndsWith(".Resources.test-sound.wav"))
soundDataResourceName = name;
}
Assert.That(soundDataResourceName, Is.Not.Null);
byte[] soundData;
UUID soundUuid;
CreateSoundAsset(tar, assembly, soundDataResourceName, out soundData, out soundUuid);
TaskInventoryItem item1
= new TaskInventoryItem { AssetID = soundUuid, ItemID = soundItemUuid, Name = soundItemName };
part1.Inventory.AddInventoryItem(item1, true);
m_scene.AddNewSceneObject(object1, false);
string object1FileName = string.Format(
"{0}_{1:000}-{2:000}-{3:000}__{4}.xml",
part1.Name,
Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z),
part1.UUID);
string path = "regions/1_1_Unit_test_region/" + ArchiveConstants.OBJECTS_PATH + object1FileName;
tar.WriteFile(path, SceneObjectSerializer.ToXml2Format(object1));
tar.Close();
// Delete the current objects, to test that they're loaded from the OAR and didn't
// just remain in the scene.
m_sceneHelpers.SceneManager.ForEachScene(delegate(Scene scene)
{
scene.DeleteAllSceneObjects();
});
// Create a "hole", to test that that the corresponding region isn't loaded from the OAR
m_sceneHelpers.SceneManager.CloseScene(SceneManager.Instance.Scenes[1]);
// Check thay the OAR file contains the expected data
MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
lock (this)
{
m_scene.EventManager.OnOarFileLoaded += LoadCompleted;
m_archiverModule.DearchiveRegion(archiveReadStream);
}
Assert.That(m_lastErrorMessage, Is.Null);
Assert.AreEqual(3, m_sceneHelpers.SceneManager.Scenes.Count);
TestLoadedRegion(part1, soundItemName, soundData);
}
private void TestLoadedRegion(SceneObjectPart part1, string soundItemName, byte[] soundData)
{
SceneObjectPart object1PartLoaded = m_scene.GetSceneObjectPart(part1.Name);
Assert.That(object1PartLoaded, Is.Not.Null, "object1 was not loaded");
Assert.That(object1PartLoaded.Name, Is.EqualTo(part1.Name), "object1 names not identical");
Assert.That(object1PartLoaded.GroupPosition, Is.EqualTo(part1.GroupPosition), "object1 group position not equal");
Assert.That(
object1PartLoaded.RotationOffset, Is.EqualTo(part1.RotationOffset), "object1 rotation offset not equal");
Assert.That(
object1PartLoaded.OffsetPosition, Is.EqualTo(part1.OffsetPosition), "object1 offset position not equal");
Assert.That(object1PartLoaded.SitTargetOrientation, Is.EqualTo(part1.SitTargetOrientation));
Assert.That(object1PartLoaded.SitTargetPosition, Is.EqualTo(part1.SitTargetPosition));
TaskInventoryItem loadedSoundItem = object1PartLoaded.Inventory.GetInventoryItems(soundItemName)[0];
Assert.That(loadedSoundItem, Is.Not.Null, "loaded sound item was null");
AssetBase loadedSoundAsset = m_scene.AssetService.Get(loadedSoundItem.AssetID.ToString());
Assert.That(loadedSoundAsset, Is.Not.Null, "loaded sound asset was null");
Assert.That(loadedSoundAsset.Data, Is.EqualTo(soundData), "saved and loaded sound data do not match");
Assert.Greater(m_scene.LandChannel.AllParcels().Count, 0, "incorrect number of parcels");
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.Iterator;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Iterator
{
public class AddYieldTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(null, new CSharpAddYieldCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldIEnumerableReturnNull()
{
var initial =
@"using System;
using System.Collections;
class Program
{
static IEnumerable M()
{
[|return null|];
}
}";
await TestMissingAsync(initial);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldIEnumerableReturnObject()
{
var initial =
@"using System;
using System.Collections;
class Program
{
static IEnumerable M()
{
[|return new object()|];
}
}";
var expected =
@"using System;
using System.Collections;
class Program
{
static IEnumerable M()
{
yield return new object();
}
}";
await TestAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldIEnumeratorReturnObject()
{
var initial =
@"using System;
using System.Collections;
class Program
{
static IEnumerator M()
{
[|return new object()|];
}
}";
var expected =
@"using System;
using System.Collections;
class Program
{
static IEnumerator M()
{
yield return new object();
}
}";
await TestAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldIEnumeratorReturnGenericList()
{
var initial =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator M<T>()
{
[|return new List<T>()|];
}
}";
var expected =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator M<T>()
{
yield return new List<T>();
}
}";
await TestAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldGenericIEnumeratorReturnObject()
{
var initial =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator<object> M()
{
[|return new object()|];
}
}";
var expected =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator<object> M()
{
yield return new object();
}
}";
await TestAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldGenericIEnumerableReturnObject()
{
var initial =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerable<object> M()
{
[|return new object()|];
}
}";
var expected =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerable<object> M()
{
yield return new object();
}
}";
await TestAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldIEnumerableReturnGenericList()
{
var initial =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerable M<T>()
{
[|return new List<T>()|];
}
}";
await TestMissingAsync(initial);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldGenericIEnumeratorReturnDefault()
{
var initial =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator<T> M<T>()
{
[|return default(T)|];
}
}";
var expected =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator<T> M<T>()
{
yield return default(T);
}
}";
await TestAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldGenericIEnumerableReturnConvertibleToObject()
{
var initial =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerable<object> M()
{
[|return 0|];
}
}";
var expected =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerable<object> M()
{
yield return 0;
}
}";
await TestAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldGenericIEnumerableReturnConvertibleToFloat()
{
var initial =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator<float> M()
{
[|return 0|];
}
}";
var expected =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator<float> M()
{
yield return 0;
}
}";
await TestAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldGenericIEnumeratorNonConvertableType()
{
var initial =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator<IList<DateTime>> M()
{
[|return new List<int>()|];
}
}";
await TestMissingAsync(initial);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldGenericIEnumeratorConvertableTypeDateTime()
{
var initial =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator<IList<DateTime>> M()
{
[|return new List<DateTime>()|];
}
}";
var expected =
@"using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static IEnumerator<IList<DateTime>> M()
{
yield return new List<DateTime>();
}
}";
await TestAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)]
public async Task TestAddYieldNoTypeArguments()
{
var initial =
@"using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
var d = new A<int>.B<StringBuilder>.C<char>.D<object>();
}
}
}
#pragma warning disable CS0108
public class A<Z> where Z : new()
{
public virtual Z P1 { get { return new Z(); } }
public class B<Y> : A<B<Y>> where Y : new()
{
public override A<Z>.B<Y> P1 { get; set; }
public virtual Y P2 { get { [|return new Z()|]; } }
public class C<X> : B<C<X>> where X : new()
{
public override A<A<Z>.B<Y>>.B<A<Z>.B<Y>.C<X>> P1 { get; set; }
public override A<Z>.B<Y>.C<X> P2 { get; set; }
public virtual X P3 { get; set; }
public class D<W> : C<D<W>> where W : new()
{
public override A<A<A<Z>.B<Y>>.B<A<Z>.B<Y>.C<X>>>.B<A<A<Z>.B<Y>>.B<A<Z>.B<Y>.C<X>>.C<A<Z>.B<Y>.C<X>.D<W>>> P1 { get; set; }
public override A<A<Z>.B<Y>>.B<A<Z>.B<Y>.C<X>>.C<A<Z>.B<Y>.C<X>.D<W>> P2 { get; set; }
public override A<Z>.B<Y>.C<X>.D<W> P3 { get; set; }
public virtual W P4 { get; set; }
}
}
}
}
";
await TestMissingAsync(initial);
}
}
}
| |
using System;
using System.Collections.Generic;
using ModestTree;
using Zenject.Internal;
using System.Linq;
#if !NOT_UNITY3D
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
#endif
namespace Zenject
{
internal static class BindingUtil
{
#if !NOT_UNITY3D
public static void AssertIsValidPrefab(UnityEngine.Object prefab)
{
Assert.That(!ZenUtilInternal.IsNull(prefab), "Received null prefab during bind command");
#if UNITY_EDITOR
// Unfortunately we can't do this check because asset bundles return PrefabType.None here
// as discussed here: https://github.com/modesttree/Zenject/issues/269#issuecomment-323419408
//Assert.That(PrefabUtility.GetPrefabType(prefab) == PrefabType.Prefab,
//"Expected prefab but found game object with name '{0}' during bind command", prefab.name);
#endif
}
public static void AssertIsValidGameObject(GameObject gameObject)
{
Assert.That(!ZenUtilInternal.IsNull(gameObject), "Received null game object during bind command");
#if UNITY_EDITOR
// Unfortunately we can't do this check because asset bundles return PrefabType.None here
// as discussed here: https://github.com/modesttree/Zenject/issues/269#issuecomment-323419408
//Assert.That(PrefabUtility.GetPrefabType(gameObject) != PrefabType.Prefab,
//"Expected game object but found prefab instead with name '{0}' during bind command", gameObject.name);
#endif
}
public static void AssertIsNotComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotComponent(type);
}
}
public static void AssertIsNotComponent<T>()
{
AssertIsNotComponent(typeof(T));
}
public static void AssertIsNotComponent(Type type)
{
Assert.That(!type.DerivesFrom(typeof(Component)),
"Invalid type given during bind command. Expected type '{0}' to NOT derive from UnityEngine.Component", type);
}
public static void AssertDerivesFromUnityObject(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertDerivesFromUnityObject(type);
}
}
public static void AssertDerivesFromUnityObject<T>()
{
AssertDerivesFromUnityObject(typeof(T));
}
public static void AssertDerivesFromUnityObject(Type type)
{
Assert.That(type.DerivesFrom<UnityEngine.Object>(),
"Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Object", type);
}
public static void AssertTypesAreNotComponents(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotComponent(type);
}
}
public static void AssertIsValidResourcePath(string resourcePath)
{
Assert.That(!string.IsNullOrEmpty(resourcePath), "Null or empty resource path provided");
// We'd like to validate the path here but unfortunately there doesn't appear to be
// a way to do this besides loading it
}
public static void AssertIsInterfaceOrScriptableObject(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsInterfaceOrScriptableObject(type);
}
}
public static void AssertIsInterfaceOrScriptableObject<T>()
{
AssertIsInterfaceOrScriptableObject(typeof(T));
}
public static void AssertIsInterfaceOrScriptableObject(Type type)
{
Assert.That(type.DerivesFrom(typeof(ScriptableObject)) || type.IsInterface(),
"Invalid type given during bind command. Expected type '{0}' to either derive from UnityEngine.ScriptableObject or be an interface", type);
}
public static void AssertIsInterfaceOrComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsInterfaceOrComponent(type);
}
}
public static void AssertIsInterfaceOrComponent<T>()
{
AssertIsInterfaceOrComponent(typeof(T));
}
public static void AssertIsInterfaceOrComponent(Type type)
{
Assert.That(type.DerivesFrom(typeof(Component)) || type.IsInterface(),
"Invalid type given during bind command. Expected type '{0}' to either derive from UnityEngine.Component or be an interface", type);
}
public static void AssertIsComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsComponent(type);
}
}
public static void AssertIsComponent<T>()
{
AssertIsComponent(typeof(T));
}
public static void AssertIsComponent(Type type)
{
Assert.That(type.DerivesFrom(typeof(Component)),
"Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Component", type);
}
#else
public static void AssertTypesAreNotComponents(IEnumerable<Type> types)
{
}
public static void AssertIsNotComponent(Type type)
{
}
public static void AssertIsNotComponent<T>()
{
}
public static void AssertIsNotComponent(IEnumerable<Type> types)
{
}
#endif
public static void AssertTypesAreNotAbstract(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotAbstract(type);
}
}
public static void AssertIsNotAbstract(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotAbstract(type);
}
}
public static void AssertIsNotAbstract<T>()
{
AssertIsNotAbstract(typeof(T));
}
public static void AssertIsNotAbstract(Type type)
{
Assert.That(!type.IsAbstract(),
"Invalid type given during bind command. Expected type '{0}' to not be abstract.", type);
}
public static void AssertIsDerivedFromType(Type concreteType, Type parentType)
{
#if !(UNITY_WSA && ENABLE_DOTNET)
// TODO: Is it possible to do this on WSA?
Assert.That(parentType.IsOpenGenericType() == concreteType.IsOpenGenericType(),
"Invalid type given during bind command. Expected type '{0}' and type '{1}' to both either be open generic types or not open generic types", parentType, concreteType);
if (parentType.IsOpenGenericType())
{
Assert.That(concreteType.IsOpenGenericType());
Assert.That(TypeExtensions.IsAssignableToGenericType(concreteType, parentType),
"Invalid type given during bind command. Expected open generic type '{0}' to derive from open generic type '{1}'", concreteType, parentType);
}
else
#endif
{
Assert.That(concreteType.DerivesFromOrEqual(parentType),
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'", concreteType, parentType.Name());
}
}
public static void AssertConcreteTypeListIsNotEmpty(IEnumerable<Type> concreteTypes)
{
Assert.That(concreteTypes.Count() >= 1,
"Must supply at least one concrete type to the current binding");
}
public static void AssertIsDerivedFromTypes(
IEnumerable<Type> concreteTypes, IEnumerable<Type> parentTypes, InvalidBindResponses invalidBindResponse)
{
if (invalidBindResponse == InvalidBindResponses.Assert)
{
AssertIsDerivedFromTypes(concreteTypes, parentTypes);
}
else
{
Assert.IsEqual(invalidBindResponse, InvalidBindResponses.Skip);
}
}
public static void AssertIsDerivedFromTypes(IEnumerable<Type> concreteTypes, IEnumerable<Type> parentTypes)
{
foreach (var concreteType in concreteTypes)
{
AssertIsDerivedFromTypes(concreteType, parentTypes);
}
}
public static void AssertIsDerivedFromTypes(Type concreteType, IEnumerable<Type> parentTypes)
{
foreach (var parentType in parentTypes)
{
AssertIsDerivedFromType(concreteType, parentType);
}
}
public static void AssertInstanceDerivesFromOrEqual(object instance, IEnumerable<Type> parentTypes)
{
if (!ZenUtilInternal.IsNull(instance))
{
foreach (var baseType in parentTypes)
{
AssertInstanceDerivesFromOrEqual(instance, baseType);
}
}
}
public static void AssertInstanceDerivesFromOrEqual(object instance, Type baseType)
{
if (!ZenUtilInternal.IsNull(instance))
{
Assert.That(instance.GetType().DerivesFromOrEqual(baseType),
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'", instance.GetType(), baseType.Name());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Threading;
using System.Runtime;
using Xunit;
namespace System.Tests
{
public static partial class GCTests
{
private static bool s_is32Bits = IntPtr.Size == 4; // Skip IntPtr tests on 32-bit platforms
[Fact]
public static void AddMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure(-1)); // Bytes allocated < 0
if (s_is32Bits)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("pressure", () => GC.AddMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms
}
}
[Fact]
public static void Collect_Int()
{
for (int i = 0; i < GC.MaxGeneration + 10; i++)
{
GC.Collect(i);
}
}
[Fact]
public static void Collect_Int_NegativeGeneration_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1)); // Generation < 0
}
[Theory]
[InlineData(GCCollectionMode.Default)]
[InlineData(GCCollectionMode.Forced)]
public static void Collect_Int_GCCollectionMode(GCCollectionMode mode)
{
for (int gen = 0; gen <= 2; gen++)
{
var b = new byte[1024 * 1024 * 10];
int oldCollectionCount = GC.CollectionCount(gen);
b = null;
GC.Collect(gen, mode);
Assert.True(GC.CollectionCount(gen) > oldCollectionCount);
}
}
[Fact]
public static void Collect_NegativeGenerationCount_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default));
AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default, false));
}
[Theory]
[InlineData(GCCollectionMode.Default - 1)]
[InlineData(GCCollectionMode.Optimized + 1)]
public static void Collection_InvalidCollectionMode_ThrowsArgumentOutOfRangeException(GCCollectionMode mode)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", "Enum value was out of legal range.", () => GC.Collect(2, mode));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", "Enum value was out of legal range.", () => GC.Collect(2, mode, false));
}
[Fact]
public static void Collect_CallsFinalizer()
{
FinalizerTest.Run();
}
private class FinalizerTest
{
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static void MakeAndDropTest()
{
new TestObject();
}
public static void Run()
{
MakeAndDropTest();
GC.Collect();
// Make sure Finalize() is called
GC.WaitForPendingFinalizers();
Assert.True(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void KeepAlive()
{
KeepAliveTest.Run();
}
private class KeepAliveTest
{
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static void MakeAndDropDNKA()
{
new DoNotKeepAliveObject();
}
public static void Run()
{
var keepAlive = new KeepAliveObject();
MakeAndDropDNKA();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(DoNotKeepAliveObject.Finalized);
Assert.False(KeepAliveObject.Finalized);
GC.KeepAlive(keepAlive);
}
private class KeepAliveObject
{
public static bool Finalized { get; private set; }
~KeepAliveObject()
{
Finalized = true;
}
}
private class DoNotKeepAliveObject
{
public static bool Finalized { get; private set; }
~DoNotKeepAliveObject()
{
Finalized = true;
}
}
}
[Fact]
public static void KeepAlive_Null()
{
KeepAliveNullTest.Run();
}
private class KeepAliveNullTest
{
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static void MakeAndNull()
{
var obj = new TestObject();
obj = null;
}
public static void Run()
{
MakeAndNull();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void KeepAlive_Recursive()
{
KeepAliveRecursiveTest.Run();
}
private class KeepAliveRecursiveTest
{
public static void Run()
{
int recursionCount = 0;
RunWorker(new TestObject(), ref recursionCount);
}
private static void RunWorker(object obj, ref int recursionCount)
{
if (recursionCount++ == 10)
return;
GC.Collect();
GC.WaitForPendingFinalizers();
RunWorker(obj, ref recursionCount);
Assert.False(TestObject.Finalized);
GC.KeepAlive(obj);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void SuppressFinalizer()
{
SuppressFinalizerTest.Run();
}
private class SuppressFinalizerTest
{
public static void Run()
{
var obj = new TestObject();
GC.SuppressFinalize(obj);
obj = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void SuppressFinalizer_NullObject_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("obj", () => GC.SuppressFinalize(null)); // Obj is null
}
[Fact]
public static void ReRegisterForFinalize()
{
ReRegisterForFinalizeTest.Run();
}
[Fact]
public static void ReRegisterFoFinalize_NullObject_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("obj", () => GC.ReRegisterForFinalize(null)); // Obj is null
}
private class ReRegisterForFinalizeTest
{
public static void Run()
{
TestObject.Finalized = false;
CreateObject();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(TestObject.Finalized);
}
private static void CreateObject()
{
using (var obj = new TestObject())
{
GC.SuppressFinalize(obj);
}
}
private class TestObject : IDisposable
{
public static bool Finalized { get; set; }
~TestObject()
{
Finalized = true;
}
public void Dispose()
{
GC.ReRegisterForFinalize(this);
}
}
}
[Fact]
public static void CollectionCount_NegativeGeneration_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.CollectionCount(-1)); // Generation < 0
}
[Fact]
public static void RemoveMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure(-1)); // Bytes allocated < 0
if (s_is32Bits)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms
}
}
[Fact]
public static void GetTotalMemoryTest_ForceCollection()
{
// We don't test GetTotalMemory(false) at all because a collection
// could still occur even if not due to the GetTotalMemory call,
// and as such there's no way to validate the behavior. We also
// don't verify a tighter bound for the result of GetTotalMemory
// because collections could cause significant fluctuations.
GC.Collect();
int gen0 = GC.CollectionCount(0);
int gen1 = GC.CollectionCount(1);
int gen2 = GC.CollectionCount(2);
Assert.InRange(GC.GetTotalMemory(true), 1, long.MaxValue);
Assert.InRange(GC.CollectionCount(0), gen0 + 1, int.MaxValue);
Assert.InRange(GC.CollectionCount(1), gen1 + 1, int.MaxValue);
Assert.InRange(GC.CollectionCount(2), gen2 + 1, int.MaxValue);
}
[Fact]
public static void GetGeneration()
{
// We don't test a tighter bound on GetGeneration as objects
// can actually get demoted or stay in the same generation
// across collections.
GC.Collect();
var obj = new object();
for (int i = 0; i <= GC.MaxGeneration + 1; i++)
{
Assert.InRange(GC.GetGeneration(obj), 0, GC.MaxGeneration);
GC.Collect();
}
}
[Theory]
[InlineData(GCLargeObjectHeapCompactionMode.CompactOnce)]
[InlineData(GCLargeObjectHeapCompactionMode.Default)]
public static void LargeObjectHeapCompactionModeRoundTrips(GCLargeObjectHeapCompactionMode value)
{
GCLargeObjectHeapCompactionMode orig = GCSettings.LargeObjectHeapCompactionMode;
try
{
GCSettings.LargeObjectHeapCompactionMode = value;
Assert.Equal(value, GCSettings.LargeObjectHeapCompactionMode);
}
finally
{
GCSettings.LargeObjectHeapCompactionMode = orig;
Assert.Equal(orig, GCSettings.LargeObjectHeapCompactionMode);
}
}
[Theory]
[InlineData(GCLatencyMode.Batch)]
[InlineData(GCLatencyMode.Interactive)]
public static void LatencyRoundtrips(GCLatencyMode value)
{
GCLatencyMode orig = GCSettings.LatencyMode;
try
{
GCSettings.LatencyMode = value;
Assert.Equal(value, GCSettings.LatencyMode);
}
finally
{
GCSettings.LatencyMode = orig;
Assert.Equal(orig, GCSettings.LatencyMode);
}
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)] //Concurrent GC is not enabled on Unix. Recombine to TestLatencyRoundTrips once addressed.
[InlineData(GCLatencyMode.LowLatency)]
[InlineData(GCLatencyMode.SustainedLowLatency)]
public static void LatencyRoundtrips_LowLatency(GCLatencyMode value) => LatencyRoundtrips(value);
}
public class GCExtendedTests : RemoteExecutorTestBase
{
private const int TimeoutMilliseconds = 10 * 30 * 1000; //if full GC is triggered it may take a while
/// <summary>
/// NoGC regions will be automatically exited if more than the requested budget
/// is allocated while still in the region. In order to avoid this, the budget is set
/// to be higher than what the test should be allocating. When running on CoreCLR/DesktopCLR,
/// these tests generally do not allocate because they are implemented as fcalls into the runtime
/// itself, but the CoreRT runtime is written in mostly managed code and tends to allocate more.
///
/// This budget should be high enough to avoid exiting no-gc regions when doing normal unit
/// tests, regardless of the runtime.
/// </summary>
private const int NoGCRequestedBudget = 8192;
[Fact]
[OuterLoop]
public static void GetGeneration_WeakReference()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Func<WeakReference> getweakref = delegate ()
{
Version myobj = new Version();
var wkref = new WeakReference(myobj);
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.True(GC.GetGeneration(wkref) >= 0);
Assert.Equal(GC.GetGeneration(wkref), GC.GetGeneration(myobj));
GC.EndNoGCRegion();
myobj = null;
return wkref;
};
WeakReference weakref = getweakref();
Assert.True(weakref != null);
#if !DEBUG
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
Assert.Throws<ArgumentNullException>(() => GC.GetGeneration(weakref));
#endif
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
public static void GCNotificationNegTests()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(100, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, 100));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(10, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, 10));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(100, 10));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(10, 100));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.WaitForFullGCApproach(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.WaitForFullGCComplete(-2));
}
[Theory]
[InlineData(true, -1)]
[InlineData(false, -1)]
[InlineData(true, 0)]
[InlineData(false, 0)]
[InlineData(true, 100)]
[InlineData(false, 100)]
[InlineData(true, int.MaxValue)]
[InlineData(false, int.MaxValue)]
[OuterLoop]
public static void GCNotificationTests(bool approach, int timeout)
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke((approachString, timeoutString) =>
{
TestWait(bool.Parse(approachString), int.Parse(timeoutString));
return SuccessExitCode;
}, approach.ToString(), timeout.ToString(), options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_EndNoGCRegion_ThrowsInvalidOperationException()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[MethodImpl(MethodImplOptions.NoOptimization)]
private static void AllocateALot()
{
for (int i = 0; i < 10000; i++)
{
var array = new long[NoGCRequestedBudget];
GC.KeepAlive(array);
}
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_ExitThroughAllocation()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024));
AllocateALot();
// at this point, the GC should have booted us out of the no GC region
// since we allocated too much.
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion_BlockingCollection()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion_LargeObjectHeapSize()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion_BlockingCollectionAndLOH()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_SettingLatencyMode_ThrowsInvalidOperationException()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
// The budget for this test is 4mb, because the act of throwing an exception with a message
// contained in a resource file has to potential to allocate a lot on CoreRT. In particular, when compiling
// in multi-file mode, this will trigger a resource lookup in System.Private.CoreLib.
//
// In addition to this, the Assert.Throws xunit combinator tends to also allocate a lot.
Assert.True(GC.TryStartNoGCRegion(4000 * 1024, true));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
Assert.Throws<InvalidOperationException>(() => GCSettings.LatencyMode = GCLatencyMode.LowLatency);
GC.EndNoGCRegion();
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize_BlockingCollection()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize_LOHSize()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
return SuccessExitCode;
}, options).Dispose();
}
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize_LOHSize_BlockingCollection()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
return SuccessExitCode;
}, options).Dispose();
}
[Theory]
[OuterLoop]
[InlineData(0)]
[InlineData(-1)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Difference in behavior, full framework doesn't throw, fixed in .NET Core")]
public static void TryStartNoGCRegion_TotalSizeOutOfRange(long size)
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(sizeString =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("totalSize", () => GC.TryStartNoGCRegion(long.Parse(sizeString)));
return SuccessExitCode;
}, size.ToString(), options).Dispose();
}
[Theory]
[OuterLoop]
[InlineData(0)] // invalid because lohSize ==
[InlineData(-1)] // invalid because lohSize < 0
[InlineData(1152921504606846976)] // invalid because lohSize > totalSize
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Difference in behavior, full framework doesn't throw, fixed in .NET Core")]
public static void TryStartNoGCRegion_LOHSizeInvalid(long size)
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(sizeString =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("lohSize", () => GC.TryStartNoGCRegion(1024, long.Parse(sizeString)));
return SuccessExitCode;
}, size.ToString(), options).Dispose();
}
public static void TestWait(bool approach, int timeout)
{
GCNotificationStatus result = GCNotificationStatus.Failed;
Thread cancelProc = null;
// Since we need to test an infinite (or very large) wait but the API won't return, spawn off a thread which
// will cancel the wait after a few seconds
//
bool cancelTimeout = (timeout == -1) || (timeout > 10000);
GC.RegisterForFullGCNotification(20, 20);
try
{
if (cancelTimeout)
{
cancelProc = new Thread(new ThreadStart(CancelProc));
cancelProc.Start();
}
if (approach)
result = GC.WaitForFullGCApproach(timeout);
else
result = GC.WaitForFullGCComplete(timeout);
}
catch (Exception e)
{
Assert.True(false, $"({approach}, {timeout}) Error - Unexpected exception received: {e.ToString()}");
}
finally
{
if (cancelProc != null)
cancelProc.Join();
}
if (cancelTimeout)
{
Assert.True(result == GCNotificationStatus.Canceled, $"({approach}, {timeout}) Error - WaitForFullGCApproach result not Cancelled");
}
else
{
Assert.True(result == GCNotificationStatus.Timeout, $"({approach}, {timeout}) Error - WaitForFullGCApproach result not Timeout");
}
}
public static void CancelProc()
{
Thread.Sleep(500);
GC.CancelFullGCNotification();
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Text;
internal partial class Interop
{
internal partial class WinHttp
{
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandle WinHttpOpen(
IntPtr userAgent,
uint accessType,
string proxyName,
string proxyBypass, int flags);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpCloseHandle(
IntPtr handle);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandle WinHttpConnect(
SafeWinHttpHandle sessionHandle,
string serverName,
ushort serverPort,
uint reserved);
// NOTE: except for the return type, this refers to the same function as WinHttpConnect.
[DllImport(Interop.Libraries.WinHttp, EntryPoint = "WinHttpConnect", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandleWithCallback WinHttpConnectWithCallback(
SafeWinHttpHandle sessionHandle,
string serverName,
ushort serverPort,
uint reserved);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandle WinHttpOpenRequest(
SafeWinHttpHandle connectHandle,
string verb,
string objectName,
string version,
string referrer,
string acceptTypes,
uint flags);
// NOTE: except for the return type, this refers to the same function as WinHttpOpenRequest.
[DllImport(Interop.Libraries.WinHttp, EntryPoint = "WinHttpOpenRequest", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandleWithCallback WinHttpOpenRequestWithCallback(
SafeWinHttpHandle connectHandle,
string verb,
string objectName,
string version,
string referrer,
string acceptTypes,
uint flags);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpAddRequestHeaders(
SafeWinHttpHandle requestHandle,
[In] StringBuilder headers,
uint headersLength,
uint modifiers);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpAddRequestHeaders(
SafeWinHttpHandle requestHandle,
string headers,
uint headersLength,
uint modifiers);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSendRequest(
SafeWinHttpHandle requestHandle,
[In] StringBuilder headers,
uint headersLength,
IntPtr optional,
uint optionalLength,
uint totalLength,
IntPtr context);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpReceiveResponse(
SafeWinHttpHandle requestHandle,
IntPtr reserved);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryDataAvailable(
SafeWinHttpHandle requestHandle,
out uint bytesAvailable);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryDataAvailable(
SafeWinHttpHandle requestHandle,
IntPtr parameterIgnoredAndShouldBeNullForAsync);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpReadData(
SafeWinHttpHandle requestHandle,
IntPtr buffer,
uint bufferSize,
out uint bytesRead);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpReadData(
SafeWinHttpHandle requestHandle,
IntPtr buffer,
uint bufferSize,
IntPtr parameterIgnoredAndShouldBeNullForAsync);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel,
string name,
[Out] StringBuilder buffer,
ref uint bufferLength,
IntPtr index);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel,
string name,
[Out] StringBuilder buffer,
ref uint bufferLength,
ref uint index);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel,
string name,
ref uint number,
ref uint bufferLength,
IntPtr index);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryOption(
SafeWinHttpHandle handle,
uint option,
[Out] StringBuilder buffer,
ref uint bufferSize);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryOption(
SafeWinHttpHandle handle,
uint option,
ref IntPtr buffer,
ref uint bufferSize);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryOption(
SafeWinHttpHandle handle,
uint option,
IntPtr buffer,
ref uint bufferSize);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpWriteData(
SafeWinHttpHandle requestHandle,
IntPtr buffer,
uint bufferSize,
out uint bytesWritten);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpWriteData(
SafeWinHttpHandle requestHandle,
IntPtr buffer,
uint bufferSize,
IntPtr parameterIgnoredAndShouldBeNullForAsync);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSetOption(
SafeWinHttpHandle handle,
uint option,
ref uint optionData,
uint optionLength = sizeof(uint));
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSetOption(
SafeWinHttpHandle handle,
uint option,
string optionData,
uint optionLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSetOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSetCredentials(
SafeWinHttpHandle requestHandle,
uint authTargets,
uint authScheme,
string userName,
string password,
IntPtr reserved);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryAuthSchemes(
SafeWinHttpHandle requestHandle,
out uint supportedSchemes,
out uint firstScheme,
out uint authTarget);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSetTimeouts(
SafeWinHttpHandle handle,
int resolveTimeout,
int connectTimeout,
int sendTimeout,
int receiveTimeout);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpGetIEProxyConfigForCurrentUser(
out WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpGetProxyForUrl(
SafeWinHttpHandle sessionHandle, string url,
ref WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions,
out WINHTTP_PROXY_INFO proxyInfo);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr WinHttpSetStatusCallback(
SafeWinHttpHandle handle,
WINHTTP_STATUS_CALLBACK callback,
uint notificationFlags,
IntPtr reserved);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandleWithCallback WinHttpWebSocketCompleteUpgrade(
SafeWinHttpHandle requestHandle,
IntPtr context);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketSend(
SafeWinHttpHandle webSocketHandle,
WINHTTP_WEB_SOCKET_BUFFER_TYPE bufferType,
IntPtr buffer,
uint bufferLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketReceive(
SafeWinHttpHandle webSocketHandle,
IntPtr buffer,
uint bufferLength,
out uint bytesRead,
out WINHTTP_WEB_SOCKET_BUFFER_TYPE bufferType);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketShutdown(
SafeWinHttpHandle webSocketHandle,
ushort status,
byte[] reason,
uint reasonLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketShutdown(
SafeWinHttpHandle webSocketHandle,
ushort status,
IntPtr reason,
uint reasonLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketClose(
SafeWinHttpHandle webSocketHandle,
ushort status,
byte[] reason,
uint reasonLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketClose(
SafeWinHttpHandle webSocketHandle,
ushort status,
IntPtr reason,
uint reasonLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketQueryCloseStatus(
SafeWinHttpHandle webSocketHandle,
out ushort status,
byte[] reason,
uint reasonLength,
out uint reasonLengthConsumed);
}
}
| |
//
// Profile.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2008-2010 Novell, Inc.
// Copyright (C) 2008, 2010 Stephane Delcroix
//
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace FSpot.Cms
{
public class Profile : IDisposable
{
static readonly Profile srgb = new Profile (NativeMethods.CmsCreateSRGBProfile ());
static Profile ()
{
//TODO
//SetErrorAction (ErrorAction.Show);
}
bool disposed;
public HandleRef Handle { get; private set; }
Profile () : this (NativeMethods.CmsCreateProfilePlaceholder ())
{
}
public static Profile CreateSRgb ()
{
return CreateStandardRgb ();
}
public static Profile CreateStandardRgb ()
{
return srgb;
}
public static Profile CreateAlternateRgb ()
{
// FIXME I'm basing this off the values set in the camera
// exif data when the adobe profile is selected. They could
// easily be off
var wp = new ColorCIExyY (.3127, .329, 1.0);
var primaries = new ColorCIExyYTriple (
new ColorCIExyY (.64, .33, 1.0),
new ColorCIExyY (.21, .71, 1.0),
new ColorCIExyY (.15, .06, 1.0));
var tc = new ToneCurve (2.2);
var tcs = new ToneCurve[] { tc, tc, tc, tc };
return new Profile (wp, primaries, tcs);
}
public static Profile CreateLab (ColorCIExyY wp)
{
return new Profile (NativeMethods.CmsCreateLabProfile (out wp));
}
public static Profile CreateLab ()
{
return new Profile (NativeMethods.CmsCreateLabProfile (IntPtr.Zero));
}
public static Profile CreateGray (ColorCIExyY whitePoint, ToneCurve transfer)
{
if (transfer == null)
return new Profile (NativeMethods.CmsCreateGrayProfile (ref whitePoint, new ToneCurve (2.2).Handle));
return new Profile (NativeMethods.CmsCreateGrayProfile (ref whitePoint, transfer.Handle));
}
public static Profile GetScreenProfile (Gdk.Screen screen)
{
if (screen == null)
throw new ArgumentNullException (nameof (screen));
IntPtr profile = NativeMethods.FScreenGetProfile (screen.Handle);
if (profile == IntPtr.Zero)
return null;
return new Profile (profile);
}
public static Profile CreateAbstract (int nLUTPoints,
double Exposure,
double Bright,
double Contrast,
double Hue,
double Saturation,
int TempSrc,
int TempDest)
{
#if true
var gamma = new ToneCurve (Math.Pow (10, -Bright / 100));
var line = new ToneCurve (1.0);
var tables = new ToneCurve[] { gamma, line, line };
return CreateAbstract (nLUTPoints, Exposure, 0.0, Contrast, Hue, Saturation, tables,
ColorCIExyY.WhitePointFromTemperature (TempSrc),
ColorCIExyY.WhitePointFromTemperature (TempDest));
#else
GammaTable [] tables = null;
return CreateAbstract (nLUTPoints, Exposure, Bright, Contrast, Hue, Saturation, tables,
ColorCIExyY.WhitePointFromTemperature (TempSrc),
ColorCIExyY.WhitePointFromTemperature (TempDest));
#endif
}
public static Profile CreateAbstract (int nLUTPoints,
double Exposure,
double Bright,
double Contrast,
double Hue,
double Saturation,
ToneCurve[] tables,
ColorCIExyY srcWp,
ColorCIExyY destWp)
{
if (tables == null) {
var gamma = new ToneCurve (Math.Pow (10, -Bright / 100));
var line = new ToneCurve (1.0);
tables = new ToneCurve[] { gamma, line, line };
}
/*
System.Console.WriteLine ("e {0}", Exposure);
System.Console.WriteLine ("b {0}", Bright);
System.Console.WriteLine ("c {0}", Contrast);
System.Console.WriteLine ("h {0}", Hue);
System.Console.WriteLine ("s {0} {1} {2}", Saturation, srcWp, destWp);
*/
return new Profile (NativeMethods.FCmsCreateBCHSWabstractProfile (nLUTPoints,
Exposure,
0.0, //Bright,
Contrast,
Hue,
Saturation,
ref srcWp,
ref destWp,
CopyHandles (tables)));
}
public Profile (IccColorSpace colorSpace, ToneCurve[] gamma)
{
Handle = new HandleRef (this, NativeMethods.CmsCreateLinearizationDeviceLink (colorSpace, CopyHandles (gamma)));
}
static HandleRef[] CopyHandles (ToneCurve[] gamma)
{
if (gamma == null)
return null;
var gamma_handles = new HandleRef[gamma.Length];
for (int i = 0; i < gamma_handles.Length; i++)
gamma_handles[i] = gamma[i].Handle;
return gamma_handles;
}
public Profile (ColorCIExyY whitepoint, ColorCIExyYTriple primaries, ToneCurve[] gamma)
{
Handle = new HandleRef (this, NativeMethods.CmsCreateRGBProfile (out whitepoint, out primaries, CopyHandles (gamma)));
}
public Profile (string path)
{
Handle = new HandleRef (this, NativeMethods.CmsOpenProfileFromFile (path, "r"));
if (Handle.Handle == IntPtr.Zero)
throw new CmsException ($"Error opening ICC profile in file {path}");
}
public byte[] Save ()
{
unsafe {
uint length = 0;
if (NativeMethods.CmsSaveProfileToMem (Handle, null, ref length)) {
byte[] data = new byte[length];
fixed (byte* data_p = &data[0]) {
if (NativeMethods.CmsSaveProfileToMem (Handle, data_p, ref length)) {
return data;
}
}
}
}
throw new SaveException ("Error Saving Profile");
}
public Profile (byte[] data) : this (data, 0, data.Length)
{
if (data == null)
throw new ArgumentNullException (nameof (data));
}
public Profile (byte[] data, int startOffset, int length)
{
if (startOffset < 0)
throw new ArgumentOutOfRangeException (nameof (startOffset), "startOffset < 0");
if (data == null)
throw new ArgumentNullException (nameof (data));
if (data.Length - startOffset < 0)
throw new ArgumentOutOfRangeException (nameof (startOffset), "startOffset > data.Length");
if (data.Length - length - startOffset < 0)
throw new ArgumentOutOfRangeException (nameof (length), "startOffset + length > data.Length");
IntPtr profileh;
unsafe {
fixed (byte* start = &data[startOffset]) {
profileh = NativeMethods.CmsOpenProfileFromMem (start, (uint)length);
}
}
if (profileh == IntPtr.Zero)
throw new CmsException ("Invalid Profile Data");
Handle = new HandleRef (this, profileh);
}
public ColorCIEXYZ MediaWhitePoint {
get {
IntPtr ptr = NativeMethods.CmsReadTag (Handle, NativeMethods.CmsTagSignature.MediaWhitePoint);
if (ptr == IntPtr.Zero)
throw new CmsException ("unable to retrieve white point from profile");
return ColorCIEXYZ.FromPtr (ptr);
}
}
public ColorCIEXYZ MediaBlackPoint {
get {
IntPtr ptr = NativeMethods.CmsReadTag (Handle, NativeMethods.CmsTagSignature.MediaBlackPoint);
if (ptr == IntPtr.Zero)
throw new CmsException ("unable to retrieve white point from profile");
return ColorCIEXYZ.FromPtr (ptr);
}
}
public ColorCIEXYZTriple Colorants {
get {
IntPtr rPtr = NativeMethods.CmsReadTag (Handle, NativeMethods.CmsTagSignature.RedColorant);
if (rPtr == IntPtr.Zero)
throw new CmsException ("Unable to retrieve red profile colorant");
IntPtr gPtr = NativeMethods.CmsReadTag (Handle, NativeMethods.CmsTagSignature.GreenColorant);
if (gPtr == IntPtr.Zero)
throw new CmsException ("Unable to retrieve green profile colorant");
IntPtr bPtr = NativeMethods.CmsReadTag (Handle, NativeMethods.CmsTagSignature.BlueColorant);
if (bPtr == IntPtr.Zero)
throw new CmsException ("Unable to retrieve blue profile colorant");
return new ColorCIEXYZTriple (
ColorCIEXYZ.FromPtr (rPtr),
ColorCIEXYZ.FromPtr (gPtr),
ColorCIEXYZ.FromPtr (bPtr)
);
}
}
public IccColorSpace ColorSpace {
get { return (IccColorSpace)NativeMethods.CmsGetColorSpace (Handle); }
}
public IccProfileClass DeviceClass {
get { return (IccProfileClass)NativeMethods.CmsGetDeviceClass (Handle); }
}
public string Model {
get {
lock (srgb) {
var ret = new StringBuilder (128);
_ = NativeMethods.CmsGetProfileInfo (
Handle,
NativeMethods.CmsProfileInfo.Model,
"en", "US",
ret,
ret.Capacity
);
return ret.ToString ();
}
}
}
public string ProductName {
get {
lock (srgb) {
var ret = new StringBuilder (128);
_ = NativeMethods.CmsGetProfileInfo (
Handle,
NativeMethods.CmsProfileInfo.Manufacturer,
"en", "US",
ret,
ret.Capacity
);
return ret.ToString ();
}
}
}
public string ProductDescription {
get {
lock (srgb) {
var ret = new StringBuilder (128);
_ = NativeMethods.CmsGetProfileInfo (
Handle,
NativeMethods.CmsProfileInfo.Description,
"en", "US",
ret,
ret.Capacity
);
return ret.ToString ();
}
}
}
enum ErrorAction
{
Abort,
Show,
Ignore
}
static void SetErrorAction (ErrorAction act)
{
NativeMethods.CmsErrorAction ((int)act);
}
public override string ToString ()
{
return ProductName;
}
protected Profile (IntPtr handle)
{
Handle = new HandleRef (this, handle);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (disposed)
return;
disposed = true;
if (disposing) {
// free managed resources
}
// free unmanaged resources
_ = NativeMethods.CmsCloseProfile (Handle);
}
~Profile ()
{
Dispose (false);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Flunity.Utils;
namespace Flunity
{
/// <summary>
/// Container for DisplayObjects.
/// All children inherit matrix and color transformation from parent container.
/// </summary>
public class DisplayContainer : DisplayObject, IEnumerable<DisplayObject>
{
#region static
public static DisplayContainer CreateFrom(params DisplayObject[] children)
{
var container = new DisplayContainer();
foreach (var displayObject in children)
{
container.AddChild(displayObject);
}
return container;
}
#endregion
public Rect? predefinedBounds = null;
private LinkedList<DisplayObject> _children = new LinkedList<DisplayObject>();
public DisplayContainer()
{
}
public DisplayContainer(DisplayContainer parent)
{
this.parent = parent;
}
internal override void InternalAddedToStage(FlashStage stage)
{
base.InternalAddedToStage(stage);
foreach (var child in _children)
{
child.stage = stage;
}
}
internal override void InternalRemovedFromStage(FlashStage stage)
{
base.InternalRemovedFromStage(stage);
foreach (var child in _children)
{
child.stage = null;
}
}
/// <summary>
/// Adds specified children to this <c>DisplayContainer</c>.
/// </summary>
/// <param name="children">Children to add</param>
public void AddChildren(IEnumerable<DisplayObject> children)
{
foreach (var child in children)
{
AddChild(child);
}
}
/// <summary>
/// Adds specified child to this <c>DisplayContainer</c>
/// </summary>
/// <param name="child">Child to add.</param>
public void AddChild(DisplayObject child)
{
AddChildAt(child, numChildren);
}
/// <summary>
/// Adds child at the specified position.
/// </summary>
/// <param name="child">DisplayObject to add</param>
/// <param name="position">Child position</param>
public void AddChildAt(DisplayObject child, Vector2 position)
{
child.position = position;
AddChild(child);
}
/// <summary>Adds child object before the target object.</summary>
/// <param name="before">DisplayObject before which to add child</param>
/// <param name="child">DisplayObject to add</param>
/// <exception cref="System.Exception">Thrown when source and target is the same object</exception>
public void AddChildBefore(DisplayObject before, DisplayObject child)
{
AssertNotDrawPhase();
if (before == child)
throw new Exception("Source and target is the same object");
if (before.parent != this)
{
AddChild(child);
return;
}
MoveFromParent(child);
_children.AddBefore(before.node, child.node);
ProcessAdding(child);
}
/// <summary>Adds child object after the target object.</summary>
/// <param name="after">DisplayObject after which to add child</param>
/// <param name="child">DisplayObject to add</param>
/// <exception cref="System.Exception">Thrown when source and target is the same object</exception>
public void AddChildAfter(DisplayObject after, DisplayObject child)
{
AssertNotDrawPhase();
if (after == child)
throw new Exception("Source and targets are same objects");
if (after.parent != this)
{
AddChild(child);
return;
}
MoveFromParent(child);
_children.AddAfter(after.node, child.node);
ProcessAdding(child);
}
/// <summary>
/// Adds specified <c>DisplayObject</c> at specified index
/// </summary>
/// <param name="child">Child to add</param>
/// <param name="childNum">Position Index</param>
public void AddChildAt(DisplayObject child, int childNum)
{
AssertNotDrawPhase();
if (child.parent == this)
{
SetChildIndex(child, childNum);
return;
}
childNum = childNum.ClampInt(0, _children.Count);
MoveFromParent(child);
if (childNum == 0)
_children.AddFirst(child.node);
else if (childNum == _children.Count)
_children.AddLast(child.node);
else
_children.AddBefore(GetChildAt(childNum).node, child.node);
ProcessAdding(child);
}
/// <summary>
/// Removes specified <c>DisplayObject</c> from its parent.
/// </summary>
/// <param name="child">Child to remove from its parent</param>
private void MoveFromParent(DisplayObject child)
{
if (child.parent != null)
child.parent.RemoveChild(child);
}
/// <summary>
/// Removes specified child DisplayObject
/// </summary>
/// <param name="child">Child to remove</param>
public void RemoveChild(DisplayObject child)
{
AssertNotDrawPhase();
_children.Remove(child.node);
child.stage = null;
child.InternalSetParent(null);
OnChildrenChanged();
}
private void ProcessAdding(DisplayObject child)
{
child.InternalSetParent(this);
child.stage = stage;
child.colorDirty = true;
child.transformDirty = true;
OnChildrenChanged();
}
protected internal virtual void OnChildrenChanged()
{
}
public override void Draw()
{}
/// <summary>
/// Returns index of the specified child.
/// </summary>
/// <param name="child">Child to get index of</param>
/// <returns>Index of the specified child.</returns>
public int GetChildIndex(DisplayObject child)
{
if (child.parent != this)
return -1;
var index = 0;
for (var t = _children.First; t.Value != child; t = t.Next)
{
index++;
}
return index;
}
public void SetChildIndex(DisplayObject child, int childIndex)
{
AssertNotDrawPhase();
ValidateExistingChild(child);
childIndex = childIndex.ClampInt(0, _children.Count - 1);
_children.Remove(child.node);
if (childIndex == 0)
_children.AddFirst(child.node);
else if (childIndex == _children.Count)
_children.AddLast(child.node);
else
_children.AddBefore(GetChildAt(childIndex).node, child.node);
}
/// <summary>
/// Returns child <c>DisplayObject</c> at the specified index.
/// </summary>
/// <param name="childIndex">Index of child to retrieve</param>
/// <returns>Child <c>DisplayObject</c> at the specified index</returns>
public DisplayObject GetChildAt(int childIndex)
{
if (childIndex < 0 || childIndex >= _children.Count)
throw new IndexOutOfRangeException("Cannot find child at: " + childIndex + " (numChildren = " + _children.Count);
var t = _children.First;
for (var i = 0; i < childIndex; i++)
{
t = t.Next;
}
return t.Value;
}
public void BringToTop(DisplayObject child)
{
SetChildIndex(child, _children.Count - 1);
}
public void SendToBack(DisplayObject child)
{
SetChildIndex(child, 0);
}
public override Rect GetInternalBounds()
{
return predefinedBounds != null
? predefinedBounds.Value
: GetChildrenBounds();
}
public Rect GetChildrenBounds()
{
var resultBounds = new Rect();
var firstChild = true;
foreach (var child in _children)
{
if (!child.visible)
continue;
var childBounds = child.GetLocalBounds();
if (firstChild)
{
firstChild = false;
resultBounds = childBounds;
}
else
{
GeomUtil.UnionRect(ref resultBounds, ref childBounds, out resultBounds);
}
}
return resultBounds;
}
public void RemoveChildren()
{
while (numChildren > 0)
{
RemoveChild(_children.First.Value);
}
}
private void AssertNotDrawPhase()
{
if (isOnStage && stage.isDrawPhase)
throw new Exception("Cannon modify display list in draw phase");
}
private void ValidateExistingChild(DisplayObject child)
{
if (child.parent != this)
throw new Exception("Container does not contain this child");
}
public int numChildren
{
get { return _children.Count; }
}
public DisplayObject this[string childName]
{
get { return GetChildByName(childName); }
}
public DisplayObject this[int childNum]
{
get { return GetChildAt(childNum); }
}
public DisplayObject GetChildByName(string elementName)
{
foreach (var child in _children)
{
if (child.name == elementName)
return child;
}
return null;
}
public List<DisplayObject> GetChildren(Predicate<DisplayObject> filter = null)
{
return GetChildren<DisplayObject>(filter);
}
public List<T> GetChildren<T>(Predicate<T> filter = null) where T : DisplayObject
{
var result = new List<T>();
foreach (var item in _children)
{
var child = item as T;
if (child == null)
continue;
if (filter == null || filter(child))
result.Add(child);
}
return result;
}
public List<DisplayObject> GetNestedChildren(Predicate<DisplayObject> filter = null)
{
return GetNestedChildren<DisplayObject>(filter);
}
public List<T> GetNestedChildren<T>(Predicate<T> filter = null) where T : DisplayObject
{
var result = new List<T>();
var iterator = GetTreeIterator();
while (iterator.MoveNext())
{
var child = iterator.Current as T;
if (child == null)
continue;
if (filter == null || filter(child))
result.Add(child);
}
return result;
}
public T GetChild<T>() where T : DisplayObject
{
var type = typeof(T);
foreach (var child in _children)
{
if (type.IsInstanceOfType(child))
return (T)child;
}
return null;
}
protected override void ResetDisplayObject()
{
RemoveChildren();
base.ResetDisplayObject();
}
public override void ValidateDisplayObject()
{
base.ValidateDisplayObject();
var iterator = GetTreeIterator();
while (iterator.MoveNext())
{
var child = iterator.Current;
child.UpdateTransform();
child.transformDirty = false;
}
}
public DisplayTreeIterator GetTreeIterator()
{
return new DisplayTreeIterator(this);
}
#region enumerable
public LinkedList<DisplayObject>.Enumerator GetEnumerator()
{
return _children.GetEnumerator();
}
IEnumerator<DisplayObject> IEnumerable<DisplayObject>.GetEnumerator()
{
return _children.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _children.GetEnumerator();
}
#endregion
public IEnumerable<DisplayObject> children
{
get { return _children; }
set
{
RemoveChildren();
foreach (var displayObject in value)
{
AddChild(displayObject);
}
}
}
public bool HasChild(DisplayObject child)
{
return child.parent == this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Newtonsoft.Json4.Tests.TestObjects;
using NUnit.Framework;
using Newtonsoft.Json4.Linq;
using Newtonsoft.Json4.Converters;
using System.IO;
using System.Collections;
namespace Newtonsoft.Json4.Tests.Linq
{
public class JPathTests : TestFixtureBase
{
[Test]
public void SingleProperty()
{
JPath path = new JPath("Blah");
Assert.AreEqual(1, path.Parts.Count);
Assert.AreEqual("Blah", path.Parts[0]);
}
[Test]
public void TwoProperties()
{
JPath path = new JPath("Blah.Two");
Assert.AreEqual(2, path.Parts.Count);
Assert.AreEqual("Blah", path.Parts[0]);
Assert.AreEqual("Two", path.Parts[1]);
}
[Test]
public void SinglePropertyAndIndexer()
{
JPath path = new JPath("Blah[0]");
Assert.AreEqual(2, path.Parts.Count);
Assert.AreEqual("Blah", path.Parts[0]);
Assert.AreEqual(0, path.Parts[1]);
}
[Test]
public void MultiplePropertiesAndIndexers()
{
JPath path = new JPath("Blah[0].Two.Three[1].Four");
Assert.AreEqual(6, path.Parts.Count);
Assert.AreEqual("Blah", path.Parts[0]);
Assert.AreEqual(0, path.Parts[1]);
Assert.AreEqual("Two", path.Parts[2]);
Assert.AreEqual("Three", path.Parts[3]);
Assert.AreEqual(1, path.Parts[4]);
Assert.AreEqual("Four", path.Parts[5]);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = @"Unexpected character while parsing path indexer: [")]
public void BadCharactersInIndexer()
{
new JPath("Blah[[0]].Two.Three[1].Four");
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = @"Path ended with open indexer. Expected ]")]
public void UnclosedIndexer()
{
new JPath("Blah[0");
}
[Test]
public void AdditionalDots()
{
JPath path = new JPath(".Blah..[0]..Two.Three....[1].Four.");
Assert.AreEqual(6, path.Parts.Count);
Assert.AreEqual("Blah", path.Parts[0]);
Assert.AreEqual(0, path.Parts[1]);
Assert.AreEqual("Two", path.Parts[2]);
Assert.AreEqual("Three", path.Parts[3]);
Assert.AreEqual(1, path.Parts[4]);
Assert.AreEqual("Four", path.Parts[5]);
}
[Test]
public void IndexerOnly()
{
JPath path = new JPath("[111119990]");
Assert.AreEqual(1, path.Parts.Count);
Assert.AreEqual(111119990, path.Parts[0]);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Empty path indexer.")]
public void EmptyIndexer()
{
new JPath("[]");
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected character while parsing path: ]")]
public void IndexerCloseInProperty()
{
new JPath("]");
}
[Test]
public void AdjacentIndexers()
{
JPath path = new JPath("[1][0][0][" + int.MaxValue + "]");
Assert.AreEqual(4, path.Parts.Count);
Assert.AreEqual(1, path.Parts[0]);
Assert.AreEqual(0, path.Parts[1]);
Assert.AreEqual(0, path.Parts[2]);
Assert.AreEqual(int.MaxValue, path.Parts[3]);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected character following indexer: B")]
public void MissingDotAfterIndexer()
{
new JPath("[1]Blah");
}
[Test]
public void EvaluateSingleProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateMissingProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Missing[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObject()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("[1]");
Assert.IsNull(t);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = @"Index 1 not valid on JObject.")]
public void EvaluateIndexerOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
o.SelectToken("[1]", true);
}
[Test]
public void EvaluatePropertyOnArray()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("BlahBlah");
Assert.IsNull(t);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = @"Property 'BlahBlah' not valid on JArray.")]
public void EvaluatePropertyOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
a.SelectToken("BlahBlah", true);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = @"Index 1 not valid on JConstructor.")]
public void EvaluateIndexerOnConstructorWithError()
{
JConstructor c = new JConstructor("Blah");
c.SelectToken("[1]", true);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Property 'Missing' does not exist on JObject.")]
public void EvaluateMissingPropertyWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
o.SelectToken("Missing", true);
}
[Test]
public void EvaluateOutOfBoundsIndxer()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("[1000].Ha");
Assert.IsNull(t);
}
[Test]
[ExpectedException(typeof(IndexOutOfRangeException), ExpectedMessage = "Index 1000 outside the bounds of JArray.")]
public void EvaluateOutOfBoundsIndxerWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
a.SelectToken("[1000].Ha", true);
}
[Test]
public void EvaluateArray()
{
JArray a = new JArray(1, 2, 3, 4);
JToken t = a.SelectToken("[1]");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(2, (int)t);
}
[Test]
public void EvaluateSinglePropertyReturningArray()
{
JObject o = new JObject(
new JProperty("Blah", new [] { 1, 2, 3 }));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Array, t.Type);
t = o.SelectToken("Blah[2]");
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(3, (int)t);
}
[Test]
public void EvaluateLastSingleCharacterProperty()
{
JObject o2 = JObject.Parse("{'People':[{'N':'Jeff'}]}");
string a2 = (string)o2.SelectToken("People[0].N");
Assert.AreEqual("Jeff", a2);
}
[Test]
public void Example()
{
JObject o = JObject.Parse(@"{
""Stores"": [
""Lambton Quay"",
""Willis Street""
],
""Manufacturers"": [
{
""Name"": ""Acme Co"",
""Products"": [
{
""Name"": ""Anvil"",
""Price"": 50
}
]
},
{
""Name"": ""Contoso"",
""Products"": [
{
""Name"": ""Elbow Grease"",
""Price"": 99.95
},
{
""Name"": ""Headlight Fluid"",
""Price"": 4
}
]
}
]
}");
string name = (string)o.SelectToken("Manufacturers[0].Name");
// Acme Co
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
// 50
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
// Elbow Grease
Assert.AreEqual("Acme Co", name);
Assert.AreEqual(50m, productPrice);
Assert.AreEqual("Elbow Grease", productName);
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
// Lambton Quay
// Willis Street
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
// null
// Headlight Fluid
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
// 149.95
Assert.AreEqual(2, storeNames.Count);
Assert.AreEqual("Lambton Quay", storeNames[0]);
Assert.AreEqual("Willis Street", storeNames[1]);
Assert.AreEqual(2, firstProductNames.Count);
Assert.AreEqual(null, firstProductNames[0]);
Assert.AreEqual("Headlight Fluid", firstProductNames[1]);
Assert.AreEqual(149.95m, totalPrice);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Android.Content;
using Xamarin.Auth;
namespace MvvX.Plugins.OAuthClient
{
public class PlatformOAuthClient : IOAuthClient
{
#region Fields
private Account account;
private CustomOAuth2Authenticator auth;
private Context context;
private string accountStoreKeyName;
public bool AllowCancel
{
get
{
return auth.AllowCancel;
}
set
{
auth.AllowCancel = value;
}
}
public string AccessTokenName
{
get
{
return auth.AccessTokenName;
}
set
{
auth.AccessTokenName = value;
}
}
public string ClientId
{
get
{
return auth.ClientId;
}
}
public string ClientSecret
{
get
{
return auth.ClientSecret;
}
}
public bool DoNotEscapeScope
{
get
{
return auth.DoNotEscapeScope;
}
set
{
auth.DoNotEscapeScope = value;
}
}
public Dictionary<string, string> RequestParameters
{
get
{
return auth.RequestParameters;
}
}
#endregion
#region Events
public event EventHandler<IAuthenticatorCompletedEventArgs> Completed;
private void OAuth2Authenticator_Completed(object sender, AuthenticatorCompletedEventArgs e)
{
account = e.Account;
if (e.IsAuthenticated)
AccountStore.Create(context).Save(e.Account, accountStoreKeyName);
if (Completed != null)
{
Completed(sender, new PlatformAuthenticatorCompletedEventArgs(e));
}
}
public event EventHandler<IAuthenticatorErrorEventArgs> Error;
private void OAuth2Authenticator_Error(object sender, AuthenticatorErrorEventArgs e)
{
if (Error != null)
{
Error(sender, new PlatformAuthenticatorErrorEventArgs(e));
}
}
#endregion
#region Methods
public void Start(string screenTitle)
{
var intent = auth.GetUI(context);
context.StartActivity(intent);
}
public void New(object parameter, string accountStoreKeyName, string clientId, string scope, Uri authorizeUrl, Uri redirectUrl)
{
if (auth != null)
{
auth.Completed -= OAuth2Authenticator_Completed;
auth.Error -= OAuth2Authenticator_Error;
}
this.accountStoreKeyName = accountStoreKeyName;
if (!(parameter is Context))
throw new ArgumentException("parameter must be a Context object");
context = parameter as Context;
LoadAccount();
auth = new CustomOAuth2Authenticator(
clientId: clientId,
scope: scope,
authorizeUrl: authorizeUrl,
redirectUrl: redirectUrl);
auth.Completed += OAuth2Authenticator_Completed;
auth.Error += OAuth2Authenticator_Error;
}
public void New(object parameter, string accountStoreKeyName, string clientId, string clientSecret, string scope, Uri authorizeUrl, Uri redirectUrl, Uri accessTokenUrl)
{
if (auth != null)
{
auth.Completed -= OAuth2Authenticator_Completed;
auth.Error -= OAuth2Authenticator_Error;
}
this.accountStoreKeyName = accountStoreKeyName;
if (!(parameter is Context))
throw new ArgumentException("parameter must be a Context object");
context = parameter as Context;
LoadAccount();
auth = new CustomOAuth2Authenticator(
clientId: clientId,
clientSecret: clientSecret,
scope: scope,
authorizeUrl: authorizeUrl,
redirectUrl: redirectUrl,
accessTokenUrl: accessTokenUrl);
auth.Completed += OAuth2Authenticator_Completed;
auth.Error += OAuth2Authenticator_Error;
}
private void LoadAccount()
{
IEnumerable<Account> accounts = AccountStore.Create(context).FindAccountsForService(accountStoreKeyName);
if (accounts != null && accounts.Any())
account = accounts.First();
else
account = null;
}
public IOAuth2Request CreateRequest(string method, Uri url, IDictionary<string, string> parameters, IAccount account)
{
var request = new CustomOAuth2Request(method, url, parameters, new Account(account.Username, account.Properties, account.Cookies));
return new PlatformOAuth2Request(request);
}
public IOAuth2Request CreateRequest(string method, string accessTokenParameterName, Uri url, IDictionary<string, string> parameters, IAccount account)
{
var request = new CustomOAuth2Request(method, url, parameters, new Account(account.Username, account.Properties, account.Cookies));
request.AccessTokenParameterName = accessTokenParameterName;
return new PlatformOAuth2Request(request);
}
public void New(object parameter, string accountStoreKeyName, string clientId, string scope, Uri authorizeUrl, string loginRelativeUri, string tokenRelativeUri, Uri redirectUrl)
{
throw new NotImplementedException("Authorization code with Pkce is not implemented for this device");
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prism.Modularity;
namespace Prism.Wpf.Tests.Modularity
{
[TestClass]
public class ModuleCatalogFixture
{
[TestMethod]
public void CanCreateCatalogFromList()
{
var moduleInfo = new ModuleInfo("MockModule", "type");
List<ModuleInfo> moduleInfos = new List<ModuleInfo> { moduleInfo };
var moduleCatalog = new ModuleCatalog(moduleInfos);
Assert.AreEqual(1, moduleCatalog.Modules.Count());
Assert.AreEqual(moduleInfo, moduleCatalog.Modules.ElementAt(0));
}
[TestMethod]
public void CanGetDependenciesForModule()
{
// A <- B
var moduleInfoA = CreateModuleInfo("A");
var moduleInfoB = CreateModuleInfo("B", "A");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
, moduleInfoB
};
var moduleCatalog = new ModuleCatalog(moduleInfos);
IEnumerable<ModuleInfo> dependentModules = moduleCatalog.GetDependentModules(moduleInfoB);
Assert.AreEqual(1, dependentModules.Count());
Assert.AreEqual(moduleInfoA, dependentModules.ElementAt(0));
}
[TestMethod]
public void CanCompleteListWithTheirDependencies()
{
// A <- B <- C
var moduleInfoA = CreateModuleInfo("A");
var moduleInfoB = CreateModuleInfo("B", "A");
var moduleInfoC = CreateModuleInfo("C", "B");
var moduleInfoOrphan = CreateModuleInfo("X", "B");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
, moduleInfoB
, moduleInfoC
, moduleInfoOrphan
};
var moduleCatalog = new ModuleCatalog(moduleInfos);
IEnumerable<ModuleInfo> dependantModules = moduleCatalog.CompleteListWithDependencies(new[] { moduleInfoC });
Assert.AreEqual(3, dependantModules.Count());
Assert.IsTrue(dependantModules.Contains(moduleInfoA));
Assert.IsTrue(dependantModules.Contains(moduleInfoB));
Assert.IsTrue(dependantModules.Contains(moduleInfoC));
}
[TestMethod]
[ExpectedException(typeof(CyclicDependencyFoundException))]
public void ShouldThrowOnCyclicDependency()
{
// A <- B <- C <- A
var moduleInfoA = CreateModuleInfo("A", "C");
var moduleInfoB = CreateModuleInfo("B", "A");
var moduleInfoC = CreateModuleInfo("C", "B");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
, moduleInfoB
, moduleInfoC
};
new ModuleCatalog(moduleInfos).Validate();
}
[TestMethod]
[ExpectedException(typeof(DuplicateModuleException))]
public void ShouldThrowOnDuplicateModule()
{
var moduleInfoA1 = CreateModuleInfo("A");
var moduleInfoA2 = CreateModuleInfo("A");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA1
, moduleInfoA2
};
new ModuleCatalog(moduleInfos).Validate();
}
[TestMethod]
[ExpectedException(typeof(ModularityException))]
public void ShouldThrowOnMissingDependency()
{
var moduleInfoA = CreateModuleInfo("A", "B");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
};
new ModuleCatalog(moduleInfos).Validate();
}
[TestMethod]
public void CanAddModules()
{
var catalog = new ModuleCatalog();
catalog.AddModule(typeof(MockModule));
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName);
}
[TestMethod]
public void CanAddGroups()
{
var catalog = new ModuleCatalog();
ModuleInfo moduleInfo = new ModuleInfo();
ModuleInfoGroup group = new ModuleInfoGroup { moduleInfo };
catalog.Items.Add(group);
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreSame(moduleInfo, catalog.Modules.ElementAt(0));
}
[TestMethod]
public void ShouldAggregateGroupsAndLooseModuleInfos()
{
var catalog = new ModuleCatalog();
ModuleInfo moduleInfo1 = new ModuleInfo();
ModuleInfo moduleInfo2 = new ModuleInfo();
ModuleInfo moduleInfo3 = new ModuleInfo();
catalog.Items.Add(new ModuleInfoGroup() { moduleInfo1 });
catalog.Items.Add(new ModuleInfoGroup() { moduleInfo2 });
catalog.AddModule(moduleInfo3);
Assert.AreEqual(3, catalog.Modules.Count());
Assert.IsTrue(catalog.Modules.Contains(moduleInfo1));
Assert.IsTrue(catalog.Modules.Contains(moduleInfo2));
Assert.IsTrue(catalog.Modules.Contains(moduleInfo3));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CompleteListWithDependenciesThrowsWithNull()
{
var catalog = new ModuleCatalog();
catalog.CompleteListWithDependencies(null);
}
[TestMethod]
public void LooseModuleIfDependentOnModuleInGroupThrows()
{
var catalog = new ModuleCatalog();
catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") });
catalog.AddModule(CreateModuleInfo("ModuleB", "ModuleA"));
try
{
catalog.Validate();
}
catch (Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(ModularityException));
Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName);
return;
}
Assert.Fail("Exception not thrown.");
}
[TestMethod]
public void ModuleInGroupDependsOnModuleInOtherGroupThrows()
{
var catalog = new ModuleCatalog();
catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") });
catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleB", "ModuleA") });
try
{
catalog.Validate();
}
catch (Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(ModularityException));
Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName);
return;
}
Assert.Fail("Exception not thrown.");
}
[TestMethod]
public void ShouldRevalidateWhenAddingNewModuleIfValidated()
{
var testableCatalog = new TestableModuleCatalog();
testableCatalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") });
testableCatalog.Validate();
testableCatalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleB") });
Assert.IsTrue(testableCatalog.ValidateCalled);
}
[TestMethod]
public void ModuleInGroupCanDependOnModuleInSameGroup()
{
var catalog = new ModuleCatalog();
var moduleA = CreateModuleInfo("ModuleA");
var moduleB = CreateModuleInfo("ModuleB", "ModuleA");
catalog.Items.Add(new ModuleInfoGroup()
{
moduleA,
moduleB
});
var moduleBDependencies = catalog.GetDependentModules(moduleB);
Assert.AreEqual(1, moduleBDependencies.Count());
Assert.AreEqual(moduleA, moduleBDependencies.First());
}
[TestMethod]
public void StartupModuleDependentOnAnOnDemandModuleThrows()
{
var catalog = new ModuleCatalog();
var moduleOnDemand = CreateModuleInfo("ModuleA");
moduleOnDemand.InitializationMode = InitializationMode.OnDemand;
catalog.AddModule(moduleOnDemand);
catalog.AddModule(CreateModuleInfo("ModuleB", "ModuleA"));
try
{
catalog.Validate();
}
catch (Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(ModularityException));
Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName);
return;
}
Assert.Fail("Exception not thrown.");
}
[TestMethod]
public void ShouldReturnInCorrectRetrieveOrderWhenCompletingListWithDependencies()
{
// A <- B <- C <- D, C <- X
var moduleA = CreateModuleInfo("A");
var moduleB = CreateModuleInfo("B", "A");
var moduleC = CreateModuleInfo("C", "B");
var moduleD = CreateModuleInfo("D", "C");
var moduleX = CreateModuleInfo("X", "C");
var moduleCatalog = new ModuleCatalog();
// Add the modules in random order
moduleCatalog.AddModule(moduleB);
moduleCatalog.AddModule(moduleA);
moduleCatalog.AddModule(moduleD);
moduleCatalog.AddModule(moduleX);
moduleCatalog.AddModule(moduleC);
var dependantModules = moduleCatalog.CompleteListWithDependencies(new[] { moduleD, moduleX }).ToList();
Assert.AreEqual(5, dependantModules.Count);
Assert.IsTrue(dependantModules.IndexOf(moduleA) < dependantModules.IndexOf(moduleB));
Assert.IsTrue(dependantModules.IndexOf(moduleB) < dependantModules.IndexOf(moduleC));
Assert.IsTrue(dependantModules.IndexOf(moduleC) < dependantModules.IndexOf(moduleD));
Assert.IsTrue(dependantModules.IndexOf(moduleC) < dependantModules.IndexOf(moduleX));
}
[TestMethod]
public void CanLoadCatalogFromXaml()
{
Stream stream =
Assembly.GetExecutingAssembly().GetManifestResourceStream(
"Prism.Wpf.Tests.Modularity.ModuleCatalogXaml.SimpleModuleCatalog.xaml");
var catalog = ModuleCatalog.CreateFromXaml(stream);
Assert.IsNotNull(catalog);
Assert.AreEqual(4, catalog.Modules.Count());
}
[TestMethod]
public void ShouldLoadAndValidateOnInitialize()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
Assert.IsFalse(testableCatalog.LoadCalled);
Assert.IsFalse(testableCatalog.ValidateCalled);
testableCatalog.Initialize();
Assert.IsTrue(testableCatalog.LoadCalled);
Assert.IsTrue(testableCatalog.ValidateCalled);
Assert.IsTrue(testableCatalog.LoadCalledFirst);
}
[TestMethod]
public void ShouldNotLoadAgainIfInitializedCalledMoreThanOnce()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
Assert.IsFalse(testableCatalog.LoadCalled);
Assert.IsFalse(testableCatalog.ValidateCalled);
testableCatalog.Initialize();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
testableCatalog.Initialize();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
}
[TestMethod]
public void ShouldNotLoadAgainDuringInitialize()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
Assert.IsFalse(testableCatalog.LoadCalled);
Assert.IsFalse(testableCatalog.ValidateCalled);
testableCatalog.Load();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
testableCatalog.Initialize();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
}
[TestMethod]
public void ShouldAllowLoadToBeInvokedTwice()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
testableCatalog.Load();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
testableCatalog.Load();
Assert.AreEqual<int>(2, testableCatalog.LoadCalledCount);
}
[TestMethod]
public void CanAddModule1()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule("Module", "ModuleType", InitializationMode.OnDemand, "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("Module", catalog.Modules.First().ModuleName);
Assert.AreEqual("ModuleType", catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.OnDemand, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddModule2()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule("Module", "ModuleType", "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("Module", catalog.Modules.First().ModuleName);
Assert.AreEqual("ModuleType", catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.WhenAvailable, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddModule3()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule(typeof(MockModule), InitializationMode.OnDemand, "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName);
Assert.AreEqual(typeof(MockModule).AssemblyQualifiedName, catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.OnDemand, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddModule4()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule(typeof(MockModule), "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName);
Assert.AreEqual(typeof(MockModule).AssemblyQualifiedName, catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.WhenAvailable, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddGroup()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.Items.Add(new ModuleInfoGroup());
catalog.AddGroup(InitializationMode.OnDemand, "Ref1",
new ModuleInfo("M1", "T1"),
new ModuleInfo("M2", "T2", "M1"));
Assert.AreEqual(2, catalog.Modules.Count());
var module1 = catalog.Modules.First();
var module2 = catalog.Modules.Skip(1).First();
Assert.AreEqual("M1", module1.ModuleName);
Assert.AreEqual("T1", module1.ModuleType);
Assert.AreEqual("Ref1", module1.Ref);
Assert.AreEqual(InitializationMode.OnDemand, module1.InitializationMode);
Assert.AreEqual("M2", module2.ModuleName);
Assert.AreEqual("T2", module2.ModuleType);
Assert.AreEqual("Ref1", module2.Ref);
Assert.AreEqual(InitializationMode.OnDemand, module2.InitializationMode);
}
private class TestableModuleCatalog : ModuleCatalog
{
public bool ValidateCalled { get; set; }
public bool LoadCalledFirst { get; set; }
public bool LoadCalled
{
get { return LoadCalledCount > 0; }
}
public int LoadCalledCount { get; set; }
public override void Validate()
{
ValidateCalled = true;
Validated = true;
}
protected override void InnerLoad()
{
if (ValidateCalled == false && !LoadCalled)
LoadCalledFirst = true;
LoadCalledCount++;
}
}
private static ModuleInfo CreateModuleInfo(string name, params string[] dependsOn)
{
ModuleInfo moduleInfo = new ModuleInfo(name, name);
moduleInfo.DependsOn.AddRange(dependsOn);
return moduleInfo;
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// 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 Event Store LLP 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.
//
using System;
using EventStore.Core.Data;
using EventStore.Core.Services.Storage.ReaderIndex;
using NUnit.Framework;
using ReadStreamResult = EventStore.Core.Services.Storage.ReaderIndex.ReadStreamResult;
namespace EventStore.Core.Tests.Services.Storage.MaxAgeMaxCount
{
[TestFixture]
public class when_having_one_stream_with_maxage_and_other_stream_with_maxcount_and_streams_have_same_hash : ReadIndexTestScenario
{
private EventRecord _r11;
private EventRecord _r12;
private EventRecord _r13;
private EventRecord _r14;
private EventRecord _r15;
private EventRecord _r16;
private EventRecord _r21;
private EventRecord _r22;
private EventRecord _r23;
private EventRecord _r24;
private EventRecord _r25;
private EventRecord _r26;
protected override void WriteTestScenario()
{
var now = DateTime.UtcNow;
var metadata1 = string.Format(@"{{""$maxAge"":{0}}}", (int)TimeSpan.FromMinutes(25).TotalSeconds);
const string metadata2 = @"{""$maxCount"":2}";
_r11 = WriteStreamMetadata("ES1", 0, metadata1);
_r21 = WriteStreamMetadata("ES2", 0, metadata2);
_r12 = WriteSingleEvent("ES1", 0, "bla1", now.AddMinutes(-100));
_r13 = WriteSingleEvent("ES1", 1, "bla1", now.AddMinutes(-20));
_r22 = WriteSingleEvent("ES2", 0, "bla1", now.AddMinutes(-100));
_r23 = WriteSingleEvent("ES2", 1, "bla1", now.AddMinutes(-20));
_r14 = WriteSingleEvent("ES1", 2, "bla1", now.AddMinutes(-11));
_r24 = WriteSingleEvent("ES2", 2, "bla1", now.AddMinutes(-10));
_r15 = WriteSingleEvent("ES1", 3, "bla1", now.AddMinutes(-5));
_r16 = WriteSingleEvent("ES1", 4, "bla1", now.AddMinutes(-2));
_r25 = WriteSingleEvent("ES2", 3, "bla1", now.AddMinutes(-1));
_r26 = WriteSingleEvent("ES2", 4, "bla1", now.AddMinutes(-1));
}
[Test]
public void single_event_read_doesnt_return_stream_created_event_for_both_streams()
{
var result = ReadIndex.ReadEvent("ES1", 0);
Assert.AreEqual(ReadEventResult.NotFound, result.Result);
Assert.IsNull(result.Record);
result = ReadIndex.ReadEvent("ES2", 0);
Assert.AreEqual(ReadEventResult.NotFound, result.Result);
Assert.IsNull(result.Record);
}
[Test]
public void single_event_read_doesnt_return_expired_events_and_returns_all_actual_ones_for_stream_1()
{
var result = ReadIndex.ReadEvent("ES1", 0);
Assert.AreEqual(ReadEventResult.NotFound, result.Result);
Assert.IsNull(result.Record);
result = ReadIndex.ReadEvent("ES1", 1);
Assert.AreEqual(ReadEventResult.Success, result.Result);
Assert.AreEqual(_r13, result.Record);
result = ReadIndex.ReadEvent("ES1", 2);
Assert.AreEqual(ReadEventResult.Success, result.Result);
Assert.AreEqual(_r14, result.Record);
result = ReadIndex.ReadEvent("ES1", 3);
Assert.AreEqual(ReadEventResult.Success, result.Result);
Assert.AreEqual(_r15, result.Record);
result = ReadIndex.ReadEvent("ES1", 4);
Assert.AreEqual(ReadEventResult.Success, result.Result);
Assert.AreEqual(_r16, result.Record);
}
[Test]
public void single_event_read_doesnt_return_expired_events_and_returns_all_actual_ones_for_stream_2()
{
var result = ReadIndex.ReadEvent("ES2", 0);
Assert.AreEqual(ReadEventResult.NotFound, result.Result);
Assert.IsNull(result.Record);
result = ReadIndex.ReadEvent("ES2", 1);
Assert.AreEqual(ReadEventResult.NotFound, result.Result);
Assert.IsNull(result.Record);
result = ReadIndex.ReadEvent("ES2", 2);
Assert.AreEqual(ReadEventResult.NotFound, result.Result);
Assert.IsNull(result.Record);
result = ReadIndex.ReadEvent("ES2", 3);
Assert.AreEqual(ReadEventResult.Success, result.Result);
Assert.AreEqual(_r25, result.Record);
result = ReadIndex.ReadEvent("ES2", 4);
Assert.AreEqual(ReadEventResult.Success, result.Result);
Assert.AreEqual(_r26, result.Record);
}
[Test]
public void forward_range_read_doesnt_return_expired_records_for_stream_1()
{
var result = ReadIndex.ReadStreamEventsForward("ES1", 0, 100);
Assert.AreEqual(ReadStreamResult.Success, result.Result);
Assert.AreEqual(4, result.Records.Length);
Assert.AreEqual(_r13, result.Records[0]);
Assert.AreEqual(_r14, result.Records[1]);
Assert.AreEqual(_r15, result.Records[2]);
Assert.AreEqual(_r16, result.Records[3]);
}
[Test]
public void forward_range_read_doesnt_return_expired_records_for_stream_2()
{
var result = ReadIndex.ReadStreamEventsForward("ES2", 0, 100);
Assert.AreEqual(ReadStreamResult.Success, result.Result);
Assert.AreEqual(2, result.Records.Length);
Assert.AreEqual(_r25, result.Records[0]);
Assert.AreEqual(_r26, result.Records[1]);
}
[Test]
public void backward_range_read_doesnt_return_expired_records_for_stream_1()
{
var result = ReadIndex.ReadStreamEventsBackward("ES1", -1, 100);
Assert.AreEqual(ReadStreamResult.Success, result.Result);
Assert.AreEqual(4, result.Records.Length);
Assert.AreEqual(_r16, result.Records[0]);
Assert.AreEqual(_r15, result.Records[1]);
Assert.AreEqual(_r14, result.Records[2]);
Assert.AreEqual(_r13, result.Records[3]);
}
[Test]
public void backward_range_read_doesnt_return_expired_records_for_stream_2()
{
var result = ReadIndex.ReadStreamEventsBackward("ES2", -1, 100);
Assert.AreEqual(ReadStreamResult.Success, result.Result);
Assert.AreEqual(2, result.Records.Length);
Assert.AreEqual(_r26, result.Records[0]);
Assert.AreEqual(_r25, result.Records[1]);
}
[Test]
public void read_all_forward_returns_all_records_including_expired_ones()
{
var records = ReadIndex.ReadAllEventsForward(new TFPos(0, 0), 100).Records;
Assert.AreEqual(12, records.Count);
Assert.AreEqual(_r11, records[0].Event);
Assert.AreEqual(_r21, records[1].Event);
Assert.AreEqual(_r12, records[2].Event);
Assert.AreEqual(_r13, records[3].Event);
Assert.AreEqual(_r22, records[4].Event);
Assert.AreEqual(_r23, records[5].Event);
Assert.AreEqual(_r14, records[6].Event);
Assert.AreEqual(_r24, records[7].Event);
Assert.AreEqual(_r15, records[8].Event);
Assert.AreEqual(_r16, records[9].Event);
Assert.AreEqual(_r25, records[10].Event);
Assert.AreEqual(_r26, records[11].Event);
}
[Test]
public void read_all_backward_returns_all_records_including_expired_ones()
{
var records = ReadIndex.ReadAllEventsBackward(GetBackwardReadPos(), 100).Records;
Assert.AreEqual(12, records.Count);
Assert.AreEqual(_r11, records[11].Event);
Assert.AreEqual(_r21, records[10].Event);
Assert.AreEqual(_r12, records[9].Event);
Assert.AreEqual(_r13, records[8].Event);
Assert.AreEqual(_r22, records[7].Event);
Assert.AreEqual(_r23, records[6].Event);
Assert.AreEqual(_r14, records[5].Event);
Assert.AreEqual(_r24, records[4].Event);
Assert.AreEqual(_r15, records[3].Event);
Assert.AreEqual(_r16, records[2].Event);
Assert.AreEqual(_r25, records[1].Event);
Assert.AreEqual(_r26, records[0].Event);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
namespace System.Net.Http.Headers
{
public class ViaHeaderValue : ICloneable
{
private string _protocolName;
private string _protocolVersion;
private string _receivedBy;
private string _comment;
public string ProtocolName
{
get { return _protocolName; }
}
public string ProtocolVersion
{
get { return _protocolVersion; }
}
public string ReceivedBy
{
get { return _receivedBy; }
}
public string Comment
{
get { return _comment; }
}
public ViaHeaderValue(string protocolVersion, string receivedBy)
: this(protocolVersion, receivedBy, null, null)
{
}
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName)
: this(protocolVersion, receivedBy, protocolName, null)
{
}
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName, string comment)
{
HeaderUtilities.CheckValidToken(protocolVersion, "protocolVersion");
CheckReceivedBy(receivedBy);
if (!string.IsNullOrEmpty(protocolName))
{
HeaderUtilities.CheckValidToken(protocolName, "protocolName");
_protocolName = protocolName;
}
if (!string.IsNullOrEmpty(comment))
{
HeaderUtilities.CheckValidComment(comment, "comment");
_comment = comment;
}
_protocolVersion = protocolVersion;
_receivedBy = receivedBy;
}
private ViaHeaderValue()
{
}
private ViaHeaderValue(ViaHeaderValue source)
{
Contract.Requires(source != null);
_protocolName = source._protocolName;
_protocolVersion = source._protocolVersion;
_receivedBy = source._receivedBy;
_comment = source._comment;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if (!string.IsNullOrEmpty(_protocolName))
{
sb.Append(_protocolName);
sb.Append('/');
}
sb.Append(_protocolVersion);
sb.Append(' ');
sb.Append(_receivedBy);
if (!string.IsNullOrEmpty(_comment))
{
sb.Append(' ');
sb.Append(_comment);
}
return sb.ToString();
}
public override bool Equals(object obj)
{
ViaHeaderValue other = obj as ViaHeaderValue;
if (other == null)
{
return false;
}
// Note that for token and host case-insensitive comparison is used. Comments are compared using case-
// sensitive comparison.
return string.Equals(_protocolVersion, other._protocolVersion, StringComparison.OrdinalIgnoreCase) &&
string.Equals(_receivedBy, other._receivedBy, StringComparison.OrdinalIgnoreCase) &&
string.Equals(_protocolName, other._protocolName, StringComparison.OrdinalIgnoreCase) &&
string.Equals(_comment, other._comment, StringComparison.Ordinal);
}
public override int GetHashCode()
{
int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_protocolVersion) ^
StringComparer.OrdinalIgnoreCase.GetHashCode(_receivedBy);
if (!string.IsNullOrEmpty(_protocolName))
{
result = result ^ StringComparer.OrdinalIgnoreCase.GetHashCode(_protocolName);
}
if (!string.IsNullOrEmpty(_comment))
{
result = result ^ _comment.GetHashCode();
}
return result;
}
public static ViaHeaderValue Parse(string input)
{
int index = 0;
return (ViaHeaderValue)GenericHeaderParser.SingleValueViaParser.ParseValue(input, null, ref index);
}
public static bool TryParse(string input, out ViaHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.SingleValueViaParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (ViaHeaderValue)output;
return true;
}
return false;
}
internal static int GetViaLength(string input, int startIndex, out object parsedValue)
{
Contract.Requires(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Read <protocolName> and <protocolVersion> in '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'
string protocolName = null;
string protocolVersion = null;
int current = GetProtocolEndIndex(input, startIndex, out protocolName, out protocolVersion);
// If we reached the end of the string after reading protocolName/Version we return (we expect at least
// <receivedBy> to follow). If reading protocolName/Version read 0 bytes, we return.
if ((current == startIndex) || (current == input.Length))
{
return 0;
}
Debug.Assert(protocolVersion != null);
// Read <receivedBy> in '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'
string receivedBy = null;
int receivedByLength = HttpRuleParser.GetHostLength(input, current, true, out receivedBy);
if (receivedByLength == 0)
{
return 0;
}
current = current + receivedByLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
string comment = null;
if ((current < input.Length) && (input[current] == '('))
{
// We have a <comment> in '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'
int commentLength = 0;
if (HttpRuleParser.GetCommentLength(input, current, out commentLength) != HttpParseResult.Parsed)
{
return 0; // We found a '(' character but it wasn't a valid comment. Abort.
}
comment = input.Substring(current, commentLength);
current = current + commentLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
ViaHeaderValue result = new ViaHeaderValue();
result._protocolVersion = protocolVersion;
result._protocolName = protocolName;
result._receivedBy = receivedBy;
result._comment = comment;
parsedValue = result;
return current - startIndex;
}
private static int GetProtocolEndIndex(string input, int startIndex, out string protocolName,
out string protocolVersion)
{
// We have a string of the form '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'. The first
// token may either be the protocol name or protocol version. We'll only find out after reading the token
// and by looking at the following character: If it is a '/' we just parsed the protocol name, otherwise
// the protocol version.
protocolName = null;
protocolVersion = null;
int current = startIndex;
int protocolVersionOrNameLength = HttpRuleParser.GetTokenLength(input, current);
if (protocolVersionOrNameLength == 0)
{
return 0;
}
current = startIndex + protocolVersionOrNameLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
if (current == input.Length)
{
return 0;
}
if (input[current] == '/')
{
// We parsed the protocol name
protocolName = input.Substring(startIndex, protocolVersionOrNameLength);
current++; // skip the '/' delimiter
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
protocolVersionOrNameLength = HttpRuleParser.GetTokenLength(input, current);
if (protocolVersionOrNameLength == 0)
{
return 0; // We have a string "<token>/" followed by non-token chars. This is invalid.
}
protocolVersion = input.Substring(current, protocolVersionOrNameLength);
current = current + protocolVersionOrNameLength;
whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
}
else
{
protocolVersion = input.Substring(startIndex, protocolVersionOrNameLength);
}
if (whitespaceLength == 0)
{
return 0; // We were able to parse [<protocolName>/]<protocolVersion> but it wasn't followed by a WS
}
return current;
}
object ICloneable.Clone()
{
return new ViaHeaderValue(this);
}
private static void CheckReceivedBy(string receivedBy)
{
if (string.IsNullOrEmpty(receivedBy))
{
throw new ArgumentException(SR.net_http_argument_empty_string, nameof(receivedBy));
}
// 'receivedBy' can either be a host or a token. Since a token is a valid host, we only verify if the value
// is a valid host.
string host = null;
if (HttpRuleParser.GetHostLength(receivedBy, 0, true, out host) != receivedBy.Length)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, receivedBy));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using NUnit.Framework;
using Palaso.WritingSystems;
namespace Palaso.Tests.WritingSystems
{
[TestFixture]
public class LdmlInXmlWritingSystemRepositoryInterfaceTests : IWritingSystemRepositoryTests
{
public override IWritingSystemRepository CreateNewStore()
{
return new LdmlInXmlWritingSystemRepository();
}
}
[TestFixture]
public class LdmlInXmlWritingSystemRepositoryTests
{
private string _testFilePath;
private LdmlInXmlWritingSystemRepository _writingSystemRepository;
private WritingSystemDefinition _writingSystem;
[SetUp]
public void Setup()
{
_writingSystem = new WritingSystemDefinition();
_testFilePath = Path.GetTempFileName();
_writingSystemRepository = new LdmlInXmlWritingSystemRepository();
}
[TearDown]
public void TearDown()
{
File.Delete(_testFilePath);
}
private void WriteLdmlFile(string filePath, IEnumerable<WritingSystemDefinition> writingSystems)
{
XmlWriter xmlWriter = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("someroot");
xmlWriter.WriteStartElement("writingsystems");
LdmlDataMapper adaptor = new LdmlDataMapper();
foreach (WritingSystemDefinition ws in writingSystems)
{
adaptor.Write(xmlWriter, ws, null);
}
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
private void WriteAllDefinitionsToFile(string filePath, LdmlInXmlWritingSystemRepository repository)
{
XmlWriter xmlWriter = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("someroot");
repository.SaveAllDefinitions(xmlWriter);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
[Test]
public void SaveAllToXmlReaderReadAsFile_ReadsBackCorrect()
{
WritingSystemDefinition ws1 = new WritingSystemDefinition();
ws1.Language = "en";
_writingSystemRepository.Set(ws1);
WritingSystemDefinition ws2 = new WritingSystemDefinition();
ws2.Language = "fr";
_writingSystemRepository.Set(ws2);
Assert.AreEqual(2, _writingSystemRepository.Count);
XmlWriter xmlWriter = new XmlTextWriter(_testFilePath, System.Text.Encoding.UTF8);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("someroot");
_writingSystemRepository.SaveAllDefinitions(xmlWriter);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
LdmlInXmlWritingSystemRepository testRepository = new LdmlInXmlWritingSystemRepository();
Assert.AreEqual(0, testRepository.Count);
testRepository.LoadAllDefinitions(_testFilePath);
Assert.AreEqual(2, testRepository.Count);
}
[Test]
public void SaveAllToXmlReaderReadAsXmlReader_ReadsBackCorrect()
{
WritingSystemDefinition ws1 = new WritingSystemDefinition();
ws1.Language = "en";
_writingSystemRepository.Set(ws1);
WritingSystemDefinition ws2 = new WritingSystemDefinition();
ws2.Language = "fr";
_writingSystemRepository.Set(ws2);
Assert.AreEqual(2, _writingSystemRepository.Count);
XmlWriter xmlWriter = new XmlTextWriter(_testFilePath, System.Text.Encoding.UTF8);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("someroot");
_writingSystemRepository.SaveAllDefinitions(xmlWriter);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
XmlReader xmlReader = new XmlTextReader(new StreamReader(_testFilePath));
xmlReader.ReadToFollowing("writingsystems");
LdmlInXmlWritingSystemRepository testRepository = new LdmlInXmlWritingSystemRepository();
Assert.AreEqual(0, testRepository.Count);
testRepository.LoadAllDefinitions(xmlReader);
Assert.AreEqual(2, testRepository.Count);
xmlReader.Close();
}
#if false
[Test]
public void SavesWhenNotPreexisting()
{
_writingSystemRepository.StoreDefinition(_writingSystem);
AssertWritingSystemFileExists(_writingSystem);
}
private void AssertWritingSystemFileExists(WritingSystemDefinition writingSystem)
{
AssertWritingSystemFileExists(writingSystem, _writingSystemRepository);
}
private void AssertWritingSystemFileExists(WritingSystemDefinition writingSystem, LdmlInXmlWritingSystemRepository repository)
{
string path = repository.PathToWritingSystem(writingSystem);
Assert.IsTrue(File.Exists(path));
}
[Test]
public void FileNameWhenNothingKnown()
{
Assert.AreEqual("unknown.ldml", _writingSystemRepository.GetFileName(_writingSystem));
}
[Test]
public void FileNameWhenOnlyHaveIso()
{
_writingSystem.ISO = "en";
Assert.AreEqual("en.ldml", _writingSystemRepository.GetFileName(_writingSystem));
}
[Test]
public void FileNameWhenHaveIsoAndRegion()
{
_writingSystem.ISO = "en";
_writingSystem.Region = "us";
Assert.AreEqual("en-us.ldml", _writingSystemRepository.GetFileName(_writingSystem));
}
[Test]
public void SavesWhenPreexisting()
{
_writingSystem.ISO = "en";
_writingSystemRepository.StoreDefinition(_writingSystem);
_writingSystemRepository.StoreDefinition(_writingSystem);
WritingSystemDefinition ws2 = new WritingSystemDefinition();
_writingSystem.ISO = "en";
_writingSystemRepository.StoreDefinition(ws2);
}
[Test]
public void RegressionWhereUnchangedDefDeleted()
{
_writingSystem.ISO = "blah";
_writingSystemRepository.StoreDefinition(_writingSystem);
WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("blah");
_writingSystemRepository.StoreDefinition(ws2);
AssertWritingSystemFileExists(_writingSystem);
}
[Test]
public void SavesWhenDirectoryNotFound()
{
var newRepository = new LdmlInXmlWritingSystemRepository();
newRepository.StoreDefinition(_writingSystem);
AssertWritingSystemFileExists(_writingSystem, newRepository);
}
[Test]
public void UpdatesFileNameWhenISOChanges()
{
_writingSystem.ISO = "1";
_writingSystemRepository.StoreDefinition(_writingSystem);
string path = Path.Combine(_writingSystemRepository.PathToWritingSystems, "1.ldml");
Assert.IsTrue(File.Exists(path));
WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("1");
ws2.ISO = "2";
_writingSystemRepository.StoreDefinition(ws2);
Assert.IsFalse(File.Exists(path));
path = Path.Combine(_writingSystemRepository.PathToWritingSystems, "2.ldml");
Assert.IsTrue(File.Exists(path));
}
[Test]
public void MakesNewFileIfNeeded()
{
_writingSystem.ISO = "blah";
_writingSystemRepository.StoreDefinition(_writingSystem);
AssertXmlFile.AtLeastOneMatch(PathToWS, "ldml/identity/language[@type='blah']");
}
[Test]
public void CanSetVariantToLDMLUsingSameWS()
{
_writingSystemRepository.StoreDefinition(_writingSystem);
_writingSystem.Variant = "piglatin";
_writingSystemRepository.StoreDefinition(_writingSystem);
AssertXmlFile.AtLeastOneMatch(PathToWS, "ldml/identity/variant[@type='piglatin']");
}
[Test]
public void CanSetVariantToExistingLDML()
{
_writingSystem.ISO = "blah";
_writingSystem.Abbreviation = "bl";//crucially, abbreviation isn't part of the name of the file
_writingSystemRepository.StoreDefinition(_writingSystem);
//here, the task is not to overwrite what was in ther already
WritingSystemDefinition ws2 = new WritingSystemDefinition();
ws2 = _writingSystemRepository.LoadDefinition("blah");
ws2.Variant = "piglatin";
_writingSystemRepository.StoreDefinition(ws2);
string path = Path.Combine(_writingSystemRepository.PathToWritingSystems, _writingSystemRepository.GetFileName(ws2));
AssertXmlFile.AtLeastOneMatch(path, "ldml/identity/variant[@type='piglatin']");
AssertXmlFile.AtLeastOneMatch(path, "ldml/special/palaso:abbreviation[@value='bl']", LdmlAdaptor.MakeNameSpaceManager());
}
[Test]
public void CanReadVariant()
{
_writingSystem.ISO = "en";
_writingSystem.Variant = "piglatin";
_writingSystemRepository.StoreDefinition(_writingSystem);
//here, the task is not to overwrite what was in ther already
WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("en-piglatin");
Assert.AreEqual("piglatin", ws2.Variant);
}
[Test]
public void CanSaveAndReadDefaultFont()
{
_writingSystem.ISO = "en";
_writingSystem.DefaultFontName = "Courier";
_writingSystemRepository.StoreDefinition(_writingSystem);
//here, the task is not to overwrite what was in ther already
WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("en");
Assert.AreEqual("Courier", ws2.DefaultFontName);
}
[Test]
public void CanSaveAndReadKeyboardName()
{
_writingSystem.ISO = "en";
_writingSystem.Keyboard = "Thai";
_writingSystemRepository.StoreDefinition(_writingSystem);
//here, the task is not to overwrite what was in ther already
WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("en");
Assert.AreEqual("Thai", ws2.Keyboard);
}
[Test]
public void CanSaveAndReadRightToLeft()
{
_writingSystem.ISO = "en";
Assert.IsFalse(_writingSystem.RightToLeftScript);
_writingSystem.RightToLeftScript = true;
Assert.IsTrue(_writingSystem.RightToLeftScript);
_writingSystemRepository.StoreDefinition(_writingSystem);
//here, the task is not to overwrite what was in ther already
WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("en");
Assert.IsTrue(ws2.RightToLeftScript);
}
[Test]
public void CanRemoveVariant()
{
_writingSystem.ISO = "en";
_writingSystem.Variant = "piglatin";
_writingSystemRepository.StoreDefinition(_writingSystem);
string path = _writingSystemRepository.PathToWritingSystem(_writingSystem);
AssertXmlFile.AtLeastOneMatch(path, "ldml/identity/variant");
_writingSystem.Variant = string.Empty;
_writingSystemRepository.StoreDefinition(_writingSystem);
TestUtilities.AssertXPathIsNull(PathToWS, "ldml/identity/variant");
}
[Test]
public void CanRemoveAbbreviation()
{
_writingSystem.ISO = "en";
_writingSystem.Abbreviation = "abbrev";
_writingSystemRepository.StoreDefinition(_writingSystem);
string path = _writingSystemRepository.PathToWritingSystem(_writingSystem);
AssertXmlFile.AtLeastOneMatch(path, "ldml/special/palaso:abbreviation", LdmlAdaptor.MakeNameSpaceManager());
_writingSystem.Abbreviation = string.Empty;
_writingSystemRepository.StoreDefinition(_writingSystem);
TestUtilities.AssertXPathIsNull(PathToWS, "ldml/special/palaso:abbreviation", LdmlAdaptor.MakeNameSpaceManager());
}
[Test]
public void WritesAbbreviationToLDML()
{
_writingSystem.ISO = "blah";
_writingSystem.Abbreviation = "bl";
_writingSystemRepository.StoreDefinition(_writingSystem);
AssertXmlFile.AtLeastOneMatch(PathToWS, "ldml/special/palaso:abbreviation[@value='bl']", LdmlAdaptor.MakeNameSpaceManager());
}
private string PathToWS
{
get
{
return _writingSystemRepository.PathToWritingSystem(_writingSystem);
}
}
[Test]
public void CanDeleteFileThatIsNotInTrash()
{
_writingSystem.ISO = "blah";
_writingSystemRepository.StoreDefinition(_writingSystem);
string path = Path.Combine(_writingSystemRepository.PathToWritingSystems, _writingSystemRepository.GetFileName(_writingSystem));
Assert.IsTrue(File.Exists(path));
_writingSystemRepository.DeleteDefinition(_writingSystem);
Assert.IsFalse(File.Exists(path));
AssertFileIsInTrash(_writingSystem);
}
private void AssertFileIsInTrash(WritingSystemDefinition definition)
{
string path = Path.Combine(_writingSystemRepository.PathToWritingSystems, "trash");
path = Path.Combine(path, _writingSystemRepository.GetFileName(definition));
Assert.IsTrue(File.Exists(path));
}
[Test]
public void CanDeleteFileMatchingOneThatWasPreviouslyTrashed()
{
_writingSystem.ISO = "blah";
_writingSystemRepository.StoreDefinition(_writingSystem);
_writingSystemRepository.DeleteDefinition(_writingSystem);
AssertFileIsInTrash(_writingSystem);
WritingSystemDefinition ws2 = new WritingSystemDefinition();
ws2.ISO = "blah";
_writingSystemRepository.StoreDefinition(ws2);
_writingSystemRepository.DeleteDefinition(ws2);
string path = Path.Combine(_writingSystemRepository.PathToWritingSystems, _writingSystemRepository.GetFileName(_writingSystem));
Assert.IsFalse(File.Exists(path));
AssertFileIsInTrash(_writingSystem);
}
[Test]
public void MarkedNotModifiedWhenNew()
{
//not worth saving until has some data
Assert.IsFalse(_writingSystem.Modified);
}
[Test]
public void MarkedAsModifiedWhenISOChanges()
{
_writingSystem.ISO = "foo";
Assert.IsTrue(_writingSystem.Modified);
}
[Test]
public void MarkedAsNotModifiedWhenLoaded()
{
_writingSystem.ISO = "blah";
_writingSystemRepository.StoreDefinition(_writingSystem);
WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("blah");
Assert.IsFalse(ws2.Modified);
}
[Test]
public void MarkedAsNotModifiedWhenSaved()
{
_writingSystem.ISO = "bla";
Assert.IsTrue(_writingSystem.Modified);
_writingSystemRepository.StoreDefinition(_writingSystem);
Assert.IsFalse(_writingSystem.Modified);
_writingSystem.ISO = "foo";
Assert.IsTrue(_writingSystem.Modified);
}
[Test]
public void LoadDefinitionCanFabricateEnglish()
{
_writingSystemRepository.DontSetDefaultDefinitions = false;
Assert.AreEqual("English", _writingSystemRepository.LoadDefinition("en-Latn").LanguageName);
}
[Test]
public void DefaultDefinitionListIncludesActiveOSLanguages()
{
_writingSystemRepository.DontSetDefaultDefinitions = false;
_writingSystemRepository.SystemWritingSystemProvider = new DummyWritingSystemProvider();
IList<WritingSystemDefinition> list = _writingSystemRepository.WritingSystemDefinitions;
Assert.IsTrue(ContainsLanguageWithName(list, "test"));
}
[Test]
public void DefaultLanguageNotSetedIfInTrash()
{
_writingSystemRepository.DontSetDefaultDefinitions = false;
_writingSystemRepository.SystemWritingSystemProvider = new DummyWritingSystemProvider();
IList<WritingSystemDefinition> list = _writingSystemRepository.WritingSystemDefinitions;
Assert.IsTrue(ContainsLanguageWithName(list, "test"));
WritingSystemDefinition ws2 = _writingSystemRepository.WritingSystemDefinitions[0];
Assert.IsNotNull(ws2);
_writingSystemRepository.DeleteDefinition(ws2);
var repository = new LdmlInXmlWritingSystemRepository(_testDir);
repository.DontSetDefaultDefinitions = false;
repository.SystemWritingSystemProvider = new DummyWritingSystemProvider();
Assert.IsFalse(ContainsLanguageWithName(repository.WritingSystemDefinitions, "test"));
}
private bool ContainsLanguageWithName(IList<WritingSystemDefinition> list, string name)
{
foreach (WritingSystemDefinition definition in list)
{
if (definition.LanguageName == name)
return true;
}
return false;
}
class DummyWritingSystemProvider : IEnumerable<WritingSystemDefinition>
{
#region IEnumerable<WritingSystemDefinition> Members
public IEnumerable<WritingSystemDefinition> ActiveOSLanguages
{
get
{
yield return new WritingSystemDefinition("tst", "", "", "", "test", "", false);
}
}
#endregion
}
#endif
}
}
| |
#if (NET20)
using System.Collections;
using System.Collections.Generic;
namespace System.Linq
{
/// <summary>Provides a set of static (Shared in Visual Basic) methods for querying objects that implement <see cref="IEnumerable{T}"/>.</summary>
internal static class Enumerable
{
/// <summary>Determines whether any element of a sequence satisfies a condition.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> whose elements to apply the predicate to.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns><c>true</c> if any elements in the source sequence pass the test in the specified predicate; otherwise, <c>false</c>.</returns>
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
foreach (TSource element in source)
if (predicate(element)) return true;
return false;
}
/// <summary>Casts the elements of an <see cref="IEnumerable"/> to the specified type.</summary>
/// <typeparam name="TResult">The type to cast the elements of source to.</typeparam>
/// <param name="source">The <see cref="IEnumerable{T}"/> that contains the elements to be cast to type <typeparamref name="TResult"/>.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains each element of the source sequence cast to the specified type.</returns>
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
{
foreach (var i in source)
yield return (TResult)i;
}
/// <summary>Determines whether a sequence contains a specified element by using the default equality comparer.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">A sequence in which to locate a value.</param>
/// <param name="value">The value to locate in the sequence.</param>
/// <returns><c>true</c> if the source sequence contains an element that has the specified value; otherwise, <c>false</c>.</returns>
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value)
{
foreach (var i in source)
if (i.Equals(value)) return true;
return false;
}
/// <summary>Returns the number of elements in a sequence.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">A sequence that contains elements to be counted.</param>
/// <returns>The number of elements in the input sequence.</returns>
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (source is ICollection<TSource> c) return c.Count;
if (source is ICollection ngc) return ngc.Count;
var i = 0;
foreach (var e in source) i++;
return i;
}
/// <summary>Returns distinct elements from a sequence by using the default equality comparer to compare values.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">The sequence to remove duplicate elements from.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains distinct elements from the source sequence.</returns>
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source)
{
var set = new Hashtable();
foreach (var element in source)
if (!set.ContainsKey(element))
{
set.Add(element, null);
yield return element;
}
}
/// <summary>Returns the first element of a sequence.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">The <see cref="IEnumerable{T}"/> to return the first element of.</param>
/// <returns>The first element in the specified sequence.</returns>
public static TSource First<TSource>(this IEnumerable<TSource> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (source is IList<TSource> list)
{
if (list.Count > 0) return list[0];
}
else
{
using (var e = source.GetEnumerator())
{
if (e.MoveNext()) return e.Current;
}
}
throw new InvalidOperationException(@"No elements");
}
/// <summary>Returns the first element of a sequence that satisfies a specified condition.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">The <see cref="IEnumerable{T}"/> to return the first element of.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>The first element in the sequence that passes the test in the specified predicate function.</returns>
public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
foreach (var element in source)
if (predicate(element)) return element;
throw new InvalidOperationException(@"No match");
}
/// <summary>Returns the first element of a sequence, or a default value if the sequence contains no elements.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">The <see cref="IEnumerable{T}"/> to return the first element of.</param>
/// <returns><c>default( <typeparamref name="TSource"/>)</c> if <paramref name="source"/> is empty; otherwise, the first element in <paramref name="source"/>.</returns>
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (source is IList<TSource> list)
{
if (list.Count > 0) return list[0];
}
else
{
using (var e = source.GetEnumerator())
{
if (e.MoveNext()) return e.Current;
}
}
return default(TSource);
}
/// <summary>Returns the first element of the sequence that satisfies a condition or a default value if no such element is found.</summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> to return an element from.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns><c>default(<typeparamref name="TSource"/>)</c> if <paramref name="source"/> is empty or if no element passes the test specified by <paramref name="predicate"/>; otherwise, the first element in <paramref name="source"/> that passes the test specified by <paramref name="predicate"/>.</returns>
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
foreach (var element in source)
if (predicate(element)) return element;
return default(TSource);
}
/// <summary>Returns the minimum value in a generic sequence.</summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">A sequence of values to determine the minimum value of.</param>
/// <returns>The minimum value in the sequence.</returns>
public static TSource Min<TSource>(this IEnumerable<TSource> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
var comparer = Comparer<TSource>.Default;
var value = default(TSource);
if (value == null)
{
foreach (var x in source)
{
if (x != null && (value == null || comparer.Compare(x, value) < 0))
value = x;
}
return value;
}
var hasValue = false;
foreach (var x in source)
{
if (hasValue)
{
if (comparer.Compare(x, value) < 0)
value = x;
}
else
{
value = x;
hasValue = true;
}
}
if (hasValue) return value;
throw new InvalidOperationException("No elements");
}
/// <summary>Returns the maximum value in a generic sequence.</summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <returns>The maximum value in the sequence.</returns>
public static TSource Max<TSource>(this IEnumerable<TSource> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
var comparer = Comparer<TSource>.Default;
var value = default(TSource);
if (value == null) {
foreach (var x in source) {
if (x != null && (value == null || comparer.Compare(x, value) > 0))
value = x;
}
return value;
}
var hasValue = false;
foreach (var x in source) {
if (hasValue) {
if (comparer.Compare(x, value) > 0)
value = x;
}
else {
value = x;
hasValue = true;
}
}
if (hasValue) return value;
throw new InvalidOperationException("No elements");
}
/// <summary>Sorts the elements of a sequence in ascending order according to a key.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="source">A sequence of values to order.</param>
/// <param name="keySelector">A function to extract a key from an element.</param>
/// <returns>An <see cref="IEnumerable{T}"/> whose elements are sorted according to a key.</returns>
public static IEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
var d = new SortedDictionary<TKey, TSource>();
foreach (var item in source)
d.Add(keySelector(item), item);
return d.Values;
}
/// <summary>Projects each element of a sequence into a new form.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <typeparam name="TResult">The type of the value returned by <paramref name="selector"/>.</typeparam>
/// <param name="source">A sequence of values to invoke a transform function on.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>An <see cref="IEnumerable{T}"/> whose elements are the result of invoking the transform function on each element of <paramref name="source"/>.</returns>
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
if (selector == null) throw new ArgumentNullException(nameof(selector));
foreach (var i in source)
yield return selector(i);
}
/// <summary>Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> to return a single element from.</param>
/// <param name="predicate">A function to test an element for a condition.</param>
/// <returns>The single element of the input sequence that satisfies a condition.</returns>
public static TSource Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
var result = default(TSource);
long count = 0;
foreach (var element in source)
{
if (!predicate(element)) continue;
result = element;
checked { count++; }
}
if (count == 0) throw new InvalidOperationException(@"No matches");
if (count != 1) throw new InvalidOperationException(@"More than one match.");
return result;
}
/// <summary>Computes the sum of a sequence of nullable <see cref="Int32"/> values.</summary>
/// <param name="source">A sequence of nullable <see cref="Int32"/> values to calculate the sum of.</param>
/// <returns>The sum of the values in the sequence.</returns>
public static int Sum(this IEnumerable<int> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
int sum = 0;
checked
{
foreach (int v in source) sum += v;
}
return sum;
}
/// <summary>
/// Computes the sum of the sequence of nullable <see cref="Int32"/> values that are obtained by invoking a transform function on each element of the input sequence.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">A sequence of values that are used to calculate a sum.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The sum of the projected values.</returns>
public static int Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) => Sum(Select(source, selector));
/// <summary>Creates an array from a <see cref="IEnumerable"/>.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> to create an array from.</param>
/// <returns>An array that contains the elements from the input sequence.</returns>
public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source) => ToList(source).ToArray();
/// <summary>
/// Creates a <see cref="Dictionary{TKey,TValue}"/> from an <see cref="IEnumerable{T}"/> according to a specified key selector function, a comparer, and
/// an element selector function.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <typeparam name="TElement">The type of the value returned by <paramref name="elementSelector"/>.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> to create a <see cref="Dictionary{TKey,TValue}"/> from.</param>
/// <param name="keySelector">A function to extract a key from each element.</param>
/// <param name="elementSelector">A transform function to produce a result element value from each element.</param>
/// <param name="comparer">An <see cref="IEqualityComparer{T}"/> to compare keys.</param>
/// <returns>A <see cref="Dictionary{TKey,TValue}"/> that contains values of type TElement selected from the input sequence.</returns>
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
if (elementSelector == null) throw new ArgumentNullException(nameof(elementSelector));
var d = new Dictionary<TKey, TElement>(comparer);
foreach (var element in source) d.Add(keySelector(element), elementSelector(element));
return d;
}
/// <summary>Creates a <see cref="List{T}"/> from an <see cref="IEnumerable{T}"/>.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> to create a <see cref="List{T}"/> from.</param>
/// <returns>A <see cref="List{T}"/> that contains elements from the input sequence.</returns>
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
var l = new List<TSource>();
foreach (var i in source)
l.Add(i);
return l;
}
/// <summary>Filters a sequence of values based on a predicate.</summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> to filter.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains elements from the input sequence that satisfy the condition.</returns>
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
foreach (var i in source)
if (predicate(i)) yield return i;
}
}
}
#endif
| |
// 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 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// SkipUrlEncodingOperations operations.
/// </summary>
internal partial class SkipUrlEncodingOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISkipUrlEncodingOperations
{
/// <summary>
/// Initializes a new instance of the SkipUrlEncodingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SkipUrlEncodingOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> GetMethodPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (unencodedPathParam == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "unencodedPathParam");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("unencodedPathParam", unencodedPathParam);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetMethodPathValid", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/method/path/valid/{unencodedPathParam}").ToString();
url = url.Replace("{unencodedPathParam}", unencodedPathParam);
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> GetPathPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (unencodedPathParam == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "unencodedPathParam");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("unencodedPathParam", unencodedPathParam);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetPathPathValid", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/path/path/valid/{unencodedPathParam}").ToString();
url = url.Replace("{unencodedPathParam}", unencodedPathParam);
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='unencodedPathParam'>
/// An unencoded path parameter with value 'path1/path2/path3'. Possible
/// values for this parameter include: 'path1/path2/path3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> GetSwaggerPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (unencodedPathParam == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "unencodedPathParam");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("unencodedPathParam", unencodedPathParam);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetSwaggerPathValid", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/swagger/path/valid/{unencodedPathParam}").ToString();
url = url.Replace("{unencodedPathParam}", unencodedPathParam);
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> GetMethodQueryValidWithHttpMessagesAsync(string q1, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (q1 == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "q1");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetMethodQueryValid", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/method/query/valid").ToString();
List<string> queryParameters = new List<string>();
if (q1 != null)
{
queryParameters.Add(string.Format("q1={0}", q1));
}
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> GetMethodQueryNullWithHttpMessagesAsync(string q1 = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetMethodQueryNull", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/method/query/null").ToString();
List<string> queryParameters = new List<string>();
if (q1 != null)
{
queryParameters.Add(string.Format("q1={0}", q1));
}
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> GetPathQueryValidWithHttpMessagesAsync(string q1, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (q1 == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "q1");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetPathQueryValid", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/path/query/valid").ToString();
List<string> queryParameters = new List<string>();
if (q1 != null)
{
queryParameters.Add(string.Format("q1={0}", q1));
}
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='q1'>
/// An unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'. Possible values for this parameter
/// include: 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> GetSwaggerQueryValidWithHttpMessagesAsync(string q1 = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetSwaggerQueryValid", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/swagger/query/valid").ToString();
List<string> queryParameters = new List<string>();
if (q1 != null)
{
queryParameters.Add(string.Format("q1={0}", q1));
}
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
#region Copyright
/*
* The original .NET implementation of the SimMetrics library is taken from the Java
* source and converted to NET using the Microsoft Java converter.
* It is notclear who made the initial convertion to .NET.
*
* This updated version has started with the 1.0 .NET release of SimMetrics and used
* FxCop (http://www.gotdotnet.com/team/fxcop/) to highlight areas where changes needed
* to be made to the converted code.
*
* this version with updates Copyright (c) 2006 Chris Parkinson.
*
* For any queries on the .NET version please contact me through the
* sourceforge web address.
*
* SimMetrics - SimMetrics is a java library of Similarity or Distance
* Metrics, e.g. Levenshtein Distance, that provide float based similarity
* measures between string Data. All metrics return consistant measures
* rather than unbounded similarity scores.
*
* Copyright (C) 2005 Sam Chapman - Open Source Release v1.1
*
* Please Feel free to contact me about this library, I would appreciate
* knowing quickly what you wish to use it for and any criticisms/comments
* upon the SimMetric library.
*
* email: s.chapman@dcs.shef.ac.uk
* www: http://www.dcs.shef.ac.uk/~sam/
* www: http://www.dcs.shef.ac.uk/~sam/stringmetrics.html
*
* address: Sam Chapman,
* Department of Computer Science,
* University of Sheffield,
* Sheffield,
* S. Yorks,
* S1 4DP
* United Kingdom,
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
namespace npongo.wpf.simMetrics.SimMetricsMetricUtilities
{
using System;
using npongo.wpf.simMetrics.SimMetricsApi;
using npongo.wpf.simMetrics.SimMetricsUtilities;
/// <summary>
/// implements the Smith-Waterman edit distance function
/// </summary>
sealed public class SmithWaterman : AbstractStringMetric {
const double defaultGapCost = 0.5;
const double defaultMismatchScore = 0.0;
const double defaultPerfectMatchScore = 1.0;
/// <summary>
/// a constant for calculating the estimated timing cost.
/// </summary>
const double estimatedTimingConstant = 0.000161F;
/// <summary>
/// constructor - default (empty).
/// </summary>
public SmithWaterman() : this(defaultGapCost, new SubCostRange1ToMinus2()) {}
/// <summary>
/// constructor
/// </summary>
/// <param name="costG">the cost of a gap</param>
public SmithWaterman(double costG) : this(costG, new SubCostRange1ToMinus2()) {}
/// <summary>
/// constructor
/// </summary>
/// <param name="costG">the cost of a gap</param>
/// <param name="costFunction">the cost function to use</param>
public SmithWaterman(double costG, AbstractSubstitutionCost costFunction) {
gapCost = costG;
dCostFunction = costFunction;
}
/// <summary>
/// constructor
/// </summary>
/// <param name="costFunction">the cost function to use</param>
public SmithWaterman(AbstractSubstitutionCost costFunction) : this(defaultGapCost, costFunction) {}
/// <summary>
/// the private cost function used in the levenstein distance.
/// </summary>
AbstractSubstitutionCost dCostFunction;
/// <summary>
/// the cost of a gap.
/// </summary>
double gapCost;
/// <summary>
/// gets the similarity of the two strings using Smith Waterman distance.
/// </summary>
/// <param name="firstWord"></param>
/// <param name="secondWord"></param>
/// <returns>a value between 0-1 of the similarity</returns>
public override double GetSimilarity(string firstWord, string secondWord) {
if ((firstWord != null) && (secondWord != null)) {
double smithWaterman = GetUnnormalisedSimilarity(firstWord, secondWord);
double maxValue = Math.Min(firstWord.Length, secondWord.Length);
if (dCostFunction.MaxCost > -gapCost) {
maxValue *= dCostFunction.MaxCost;
}
else {
maxValue *= (-gapCost);
}
if (maxValue == defaultMismatchScore) {
return defaultPerfectMatchScore;
}
else {
return smithWaterman / maxValue;
}
}
return defaultMismatchScore;
}
/// <summary> gets a div class xhtml similarity explaining the operation of the metric.</summary>
/// <param name="firstWord">string 1</param>
/// <param name="secondWord">string 2</param>
/// <returns> a div class html section detailing the metric operation.</returns>
public override string GetSimilarityExplained(string firstWord, string secondWord) {
throw new NotImplementedException();
}
/// <summary>
/// gets the estimated time in milliseconds it takes to perform a similarity timing.
/// </summary>
/// <param name="firstWord"></param>
/// <param name="secondWord"></param>
/// <returns>the estimated time in milliseconds taken to perform the similarity measure</returns>
public override double GetSimilarityTimingEstimated(string firstWord, string secondWord) {
if ((firstWord != null) && (secondWord != null)) {
double firstLength = firstWord.Length;
double secondLength = secondWord.Length;
return (firstLength * secondLength + firstLength + secondLength) * estimatedTimingConstant;
}
return 0.0;
}
/// <summary>
/// gets the un-normalised similarity measure of the metric for the given strings.</summary>
/// <param name="firstWord"></param>
/// <param name="secondWord"></param>
/// <returns> returns the score of the similarity measure (un-normalised)</returns>
public override double GetUnnormalisedSimilarity(string firstWord, string secondWord) {
if ((firstWord != null) && (secondWord != null)) {
int n = firstWord.Length;
int m = secondWord.Length;
if (n == 0) {
return m;
}
if (m == 0) {
return n;
}
double[][] d = new double[n][];
for (int i = 0; i < n; i++) {
d[i] = new double[m];
}
double maxSoFar = defaultMismatchScore;
for (int i = 0; i < n; i++) {
double cost = dCostFunction.GetCost(firstWord, i, secondWord, 0);
if (i == 0) {
d[0][0] = MathFunctions.MaxOf3(defaultMismatchScore, -gapCost, cost);
}
else {
d[i][0] = MathFunctions.MaxOf3(defaultMismatchScore, d[i - 1][0] - gapCost, cost);
}
if (d[i][0] > maxSoFar) {
maxSoFar = d[i][0];
}
}
for (int j = 0; j < m; j++) {
double cost = dCostFunction.GetCost(firstWord, 0, secondWord, j);
if (j == 0) {
d[0][0] = MathFunctions.MaxOf3(defaultMismatchScore, -gapCost, cost);
}
else {
d[0][j] = MathFunctions.MaxOf3(defaultMismatchScore, d[0][j - 1] - gapCost, cost);
}
if (d[0][j] > maxSoFar) {
maxSoFar = d[0][j];
}
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
double cost = dCostFunction.GetCost(firstWord, i, secondWord, j);
d[i][j] =
MathFunctions.MaxOf4(defaultMismatchScore, d[i - 1][j] - gapCost, d[i][j - 1] - gapCost,
d[i - 1][j - 1] + cost);
if (d[i][j] > maxSoFar) {
maxSoFar = d[i][j];
}
}
}
return maxSoFar;
}
return 0.0;
}
/// <summary>
/// get the d(i,j) cost function.
/// </summary>
public AbstractSubstitutionCost DCostFunction { get { return dCostFunction; } set { DCostFunction = value; } }
/// <summary>
/// the gap cost for the distance function.
/// </summary>
public double GapCost { get { return gapCost; } set { gapCost = value; } }
/// <summary>
/// returns the long string identifier for the metric.
/// </summary>
public override string LongDescriptionString { get { return "Implements the Smith-Waterman algorithm providing a similarity measure between two string"; } }
/// <summary>
/// returns the string identifier for the metric .
/// </summary>
public override string ShortDescriptionString { get { return "SmithWaterman"; } }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNetCore.Components.Routing;
namespace Microsoft.AspNetCore.Components
{
/// <summary>
/// Resolves components for an application.
/// </summary>
internal static class RouteTableFactory
{
private static readonly ConcurrentDictionary<RouteKey, RouteTable> Cache = new();
public static readonly IComparer<RouteEntry> RoutePrecedence = Comparer<RouteEntry>.Create(RouteComparison);
public static RouteTable Create(RouteKey routeKey)
{
if (Cache.TryGetValue(routeKey, out var resolvedComponents))
{
return resolvedComponents;
}
var componentTypes = GetRouteableComponents(routeKey);
var routeTable = Create(componentTypes);
Cache.TryAdd(routeKey, routeTable);
return routeTable;
}
public static void ClearCaches() => Cache.Clear();
private static List<Type> GetRouteableComponents(RouteKey routeKey)
{
var routeableComponents = new List<Type>();
if (routeKey.AppAssembly is not null)
{
GetRouteableComponents(routeableComponents, routeKey.AppAssembly);
}
if (routeKey.AdditionalAssemblies is not null)
{
foreach (var assembly in routeKey.AdditionalAssemblies)
{
GetRouteableComponents(routeableComponents, assembly);
}
}
return routeableComponents;
static void GetRouteableComponents(List<Type> routeableComponents, Assembly assembly)
{
foreach (var type in assembly.ExportedTypes)
{
if (typeof(IComponent).IsAssignableFrom(type) && type.IsDefined(typeof(RouteAttribute)))
{
routeableComponents.Add(type);
}
}
}
}
internal static RouteTable Create(List<Type> componentTypes)
{
var templatesByHandler = new Dictionary<Type, string[]>();
foreach (var componentType in componentTypes)
{
// We're deliberately using inherit = false here.
//
// RouteAttribute is defined as non-inherited, because inheriting a route attribute always causes an
// ambiguity. You end up with two components (base class and derived class) with the same route.
var routeAttributes = componentType.GetCustomAttributes(typeof(RouteAttribute), inherit: false);
var templates = new string[routeAttributes.Length];
for (var i = 0; i < routeAttributes.Length; i++)
{
var attribute = (RouteAttribute)routeAttributes[i];
templates[i] = attribute.Template;
}
templatesByHandler.Add(componentType, templates);
}
return Create(templatesByHandler);
}
internal static RouteTable Create(Dictionary<Type, string[]> templatesByHandler)
{
var routes = new List<RouteEntry>();
foreach (var (type, templates) in templatesByHandler)
{
var allRouteParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var parsedTemplates = new (RouteTemplate, HashSet<string>)[templates.Length];
for (var i = 0; i < templates.Length; i++)
{
var parsedTemplate = TemplateParser.ParseTemplate(templates[i]);
var parameterNames = GetParameterNames(parsedTemplate);
parsedTemplates[i] = (parsedTemplate, parameterNames);
foreach (var parameterName in parameterNames)
{
allRouteParameterNames.Add(parameterName);
}
}
foreach (var (parsedTemplate, routeParameterNames) in parsedTemplates)
{
var unusedRouteParameterNames = GetUnusedParameterNames(allRouteParameterNames, routeParameterNames);
var entry = new RouteEntry(parsedTemplate, type, unusedRouteParameterNames);
routes.Add(entry);
}
}
routes.Sort(RoutePrecedence);
return new RouteTable(routes.ToArray());
}
private static HashSet<string> GetParameterNames(RouteTemplate routeTemplate)
{
var parameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var segment in routeTemplate.Segments)
{
if (segment.IsParameter)
{
parameterNames.Add(segment.Value);
}
}
return parameterNames;
}
private static List<string>? GetUnusedParameterNames(HashSet<string> allRouteParameterNames, HashSet<string> routeParameterNames)
{
List<string>? unusedParameters = null;
foreach (var item in allRouteParameterNames)
{
if (!routeParameterNames.Contains(item))
{
unusedParameters ??= new();
unusedParameters.Add(item);
}
}
return unusedParameters;
}
/// <summary>
/// Route precedence algorithm.
/// We collect all the routes and sort them from most specific to
/// less specific. The specificity of a route is given by the specificity
/// of its segments and the position of those segments in the route.
/// * A literal segment is more specific than a parameter segment.
/// * A parameter segment with more constraints is more specific than one with fewer constraints
/// * Segment earlier in the route are evaluated before segments later in the route.
/// For example:
/// /Literal is more specific than /Parameter
/// /Route/With/{parameter} is more specific than /{multiple}/With/{parameters}
/// /Product/{id:int} is more specific than /Product/{id}
///
/// Routes can be ambiguous if:
/// They are composed of literals and those literals have the same values (case insensitive)
/// They are composed of a mix of literals and parameters, in the same relative order and the
/// literals have the same values.
/// For example:
/// * /literal and /Literal
/// /{parameter}/literal and /{something}/literal
/// /{parameter:constraint}/literal and /{something:constraint}/literal
///
/// To calculate the precedence we sort the list of routes as follows:
/// * Shorter routes go first.
/// * A literal wins over a parameter in precedence.
/// * For literals with different values (case insensitive) we choose the lexical order
/// * For parameters with different numbers of constraints, the one with more wins
/// If we get to the end of the comparison routing we've detected an ambiguous pair of routes.
/// </summary>
internal static int RouteComparison(RouteEntry x, RouteEntry y)
{
if (ReferenceEquals(x, y))
{
return 0;
}
var xTemplate = x.Template;
var yTemplate = y.Template;
var minSegments = Math.Min(xTemplate.Segments.Length, yTemplate.Segments.Length);
var currentResult = 0;
for (var i = 0; i < minSegments; i++)
{
var xSegment = xTemplate.Segments[i];
var ySegment = yTemplate.Segments[i];
var xRank = GetRank(xSegment);
var yRank = GetRank(ySegment);
currentResult = xRank.CompareTo(yRank);
// If they are both literals we can disambiguate
if ((xRank, yRank) == (0, 0))
{
currentResult = StringComparer.OrdinalIgnoreCase.Compare(xSegment.Value, ySegment.Value);
}
if (currentResult != 0)
{
break;
}
}
if (currentResult == 0)
{
currentResult = xTemplate.Segments.Length.CompareTo(yTemplate.Segments.Length);
}
if (currentResult == 0)
{
throw new InvalidOperationException($@"The following routes are ambiguous:
'{x.Template.TemplateText}' in '{x.Handler.FullName}'
'{y.Template.TemplateText}' in '{y.Handler.FullName}'
");
}
return currentResult;
}
private static int GetRank(TemplateSegment xSegment)
{
return xSegment switch
{
// Literal
{ IsParameter: false } => 0,
// Parameter with constraints
{ IsParameter: true, IsCatchAll: false, Constraints: { Length: > 0 } } => 1,
// Parameter without constraints
{ IsParameter: true, IsCatchAll: false, Constraints: { Length: 0 } } => 2,
// Catch all parameter with constraints
{ IsParameter: true, IsCatchAll: true, Constraints: { Length: > 0 } } => 3,
// Catch all parameter without constraints
{ IsParameter: true, IsCatchAll: true, Constraints: { Length: 0 } } => 4,
// The segment is not correct
_ => throw new InvalidOperationException($"Unknown segment definition '{xSegment}.")
};
}
}
}
| |
/*
* 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.Data;
using System.Data.SqlClient;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.MSSQL
{
public class MSSQLEstateStore : IEstateDataStore
{
private const string _migrationStore = "EstateStore";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private MSSQLManager _Database;
private string m_connectionString;
private FieldInfo[] _Fields;
private Dictionary<string, FieldInfo> _FieldMap = new Dictionary<string, FieldInfo>();
#region Public methods
public MSSQLEstateStore()
{
}
public MSSQLEstateStore(string connectionString)
{
Initialise(connectionString);
}
/// <summary>
/// Initialises the estatedata class.
/// </summary>
/// <param name="connectionString">connectionString.</param>
public void Initialise(string connectionString)
{
if (!string.IsNullOrEmpty(connectionString))
{
m_connectionString = connectionString;
_Database = new MSSQLManager(connectionString);
}
//Migration settings
using (SqlConnection conn = new SqlConnection(m_connectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, "EstateStore");
m.Update();
}
//Interesting way to get parameters! Maybe implement that also with other types
Type t = typeof(EstateSettings);
_Fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo f in _Fields)
{
if (f.Name.Substring(0, 2) == "m_")
_FieldMap[f.Name.Substring(2)] = f;
}
}
/// <summary>
/// Loads the estate settings.
/// </summary>
/// <param name="regionID">region ID.</param>
/// <returns></returns>
public EstateSettings LoadEstateSettings(UUID regionID, bool create)
{
EstateSettings es = new EstateSettings();
string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = @RegionID";
bool insertEstate = false;
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@RegionID", regionID));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
foreach (string name in FieldList)
{
FieldInfo f = _FieldMap[name];
object v = reader[name];
if (f.FieldType == typeof(bool))
{
f.SetValue(es, Convert.ToInt32(v) != 0);
}
else if (f.FieldType == typeof(UUID))
{
f.SetValue(es, new UUID((Guid)v)); // uuid);
}
else if (f.FieldType == typeof(string))
{
f.SetValue(es, v.ToString());
}
else if (f.FieldType == typeof(UInt32))
{
f.SetValue(es, Convert.ToUInt32(v));
}
else if (f.FieldType == typeof(Single))
{
f.SetValue(es, Convert.ToSingle(v));
}
else
f.SetValue(es, v);
}
}
else
{
insertEstate = true;
}
}
}
if (insertEstate && create)
{
DoCreate(es);
LinkRegion(regionID, (int)es.EstateID);
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
//Set event
es.OnSave += StoreEstateSettings;
return es;
}
public EstateSettings CreateNewEstate()
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
DoCreate(es);
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
private void DoCreate(EstateSettings es)
{
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
string sql = string.Format("insert into estate_settings ({0}) values ( @{1})", String.Join(",", names.ToArray()), String.Join(", @", names.ToArray()));
//_Log.Debug("[DB ESTATE]: SQL: " + sql);
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand insertCommand = new SqlCommand(sql, conn))
{
insertCommand.CommandText = sql + " SET @ID = SCOPE_IDENTITY()";
foreach (string name in names)
{
insertCommand.Parameters.Add(_Database.CreateParameter("@" + name, _FieldMap[name].GetValue(es)));
}
SqlParameter idParameter = new SqlParameter("@ID", SqlDbType.Int);
idParameter.Direction = ParameterDirection.Output;
insertCommand.Parameters.Add(idParameter);
conn.Open();
insertCommand.ExecuteNonQuery();
es.EstateID = Convert.ToUInt32(idParameter.Value);
}
//TODO check if this is needed??
es.Save();
}
/// <summary>
/// Stores the estate settings.
/// </summary>
/// <param name="es">estate settings</param>
public void StoreEstateSettings(EstateSettings es)
{
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
string sql = string.Format("UPDATE estate_settings SET ");
foreach (string name in names)
{
sql += name + " = @" + name + ", ";
}
sql = sql.Remove(sql.LastIndexOf(","));
sql += " WHERE EstateID = @EstateID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
foreach (string name in names)
{
cmd.Parameters.Add(_Database.CreateParameter("@" + name, _FieldMap[name].GetValue(es)));
}
cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID));
conn.Open();
cmd.ExecuteNonQuery();
}
SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups);
}
#endregion
#region Private methods
private string[] FieldList
{
get { return new List<string>(_FieldMap.Keys).ToArray(); }
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
string sql = "select bannedUUID from estateban where EstateID = @EstateID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlParameter idParameter = new SqlParameter("@EstateID", SqlDbType.Int);
idParameter.Value = es.EstateID;
cmd.Parameters.Add(idParameter);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
EstateBan eb = new EstateBan();
eb.BannedUserID = new UUID((Guid)reader["bannedUUID"]); //uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
}
}
}
private UUID[] LoadUUIDList(uint estateID, string table)
{
List<UUID> uuids = new List<UUID>();
string sql = string.Format("select uuid from {0} where EstateID = @EstateID", table);
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
uuids.Add(new UUID((Guid)reader["uuid"])); //uuid);
}
}
}
return uuids.ToArray();
}
private void SaveBanList(EstateSettings es)
{
//Delete first
using (SqlConnection conn = new SqlConnection(m_connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "delete from estateban where EstateID = @EstateID";
cmd.Parameters.AddWithValue("@EstateID", (int)es.EstateID);
cmd.ExecuteNonQuery();
//Insert after
cmd.CommandText = "insert into estateban (EstateID, bannedUUID,bannedIp, bannedIpHostMask, bannedNameMask) values ( @EstateID, @bannedUUID, '','','' )";
cmd.Parameters.AddWithValue("@bannedUUID", Guid.Empty);
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters["@bannedUUID"].Value = b.BannedUserID.Guid;
cmd.ExecuteNonQuery();
}
}
}
}
private void SaveUUIDList(uint estateID, string table, UUID[] data)
{
using (SqlConnection conn = new SqlConnection(m_connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.Parameters.AddWithValue("@EstateID", (int)estateID);
cmd.CommandText = string.Format("delete from {0} where EstateID = @EstateID", table);
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format("insert into {0} (EstateID, uuid) values ( @EstateID, @uuid )", table);
cmd.Parameters.AddWithValue("@uuid", Guid.Empty);
foreach (UUID uuid in data)
{
cmd.Parameters["@uuid"].Value = uuid.Guid; //.ToString(); //TODO check if this works
cmd.ExecuteNonQuery();
}
}
}
}
public EstateSettings LoadEstateSettings(int estateID)
{
EstateSettings es = new EstateSettings();
string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_settings where EstateID = @EstateID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@EstateID", (int)estateID);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
foreach (string name in FieldList)
{
FieldInfo f = _FieldMap[name];
object v = reader[name];
if (f.FieldType == typeof(bool))
{
f.SetValue(es, Convert.ToInt32(v) != 0);
}
else if (f.FieldType == typeof(UUID))
{
f.SetValue(es, new UUID((Guid)v)); // uuid);
}
else if (f.FieldType == typeof(string))
{
f.SetValue(es, v.ToString());
}
else if (f.FieldType == typeof(UInt32))
{
f.SetValue(es, Convert.ToUInt32(v));
}
else if (f.FieldType == typeof(Single))
{
f.SetValue(es, Convert.ToSingle(v));
}
else
f.SetValue(es, v);
}
}
}
}
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
//Set event
es.OnSave += StoreEstateSettings;
return es;
}
public List<EstateSettings> LoadEstateSettingsAll()
{
List<EstateSettings> allEstateSettings = new List<EstateSettings>();
List<int> allEstateIds = GetEstatesAll();
foreach (int estateId in allEstateIds)
allEstateSettings.Add(LoadEstateSettings(estateId));
return allEstateSettings;
}
public List<int> GetEstates(string search)
{
List<int> result = new List<int>();
string sql = "select estateID from estate_settings where EstateName = @EstateName";
using (SqlConnection conn = new SqlConnection(m_connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@EstateName", search);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
}
return result;
}
public List<int> GetEstatesAll()
{
List<int> result = new List<int>();
string sql = "select estateID from estate_settings";
using (SqlConnection conn = new SqlConnection(m_connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
}
return result;
}
public List<int> GetEstatesByOwner(UUID ownerID)
{
List<int> result = new List<int>();
string sql = "select estateID from estate_settings where EstateOwner = @EstateOwner";
using (SqlConnection conn = new SqlConnection(m_connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@EstateOwner", ownerID);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
}
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
string deleteSQL = "delete from estate_map where RegionID = @RegionID";
string insertSQL = "insert into estate_map values (@RegionID, @EstateID)";
using (SqlConnection conn = new SqlConnection(m_connectionString))
{
conn.Open();
SqlTransaction transaction = conn.BeginTransaction();
try
{
using (SqlCommand cmd = new SqlCommand(deleteSQL, conn))
{
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("@RegionID", regionID.Guid);
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd = new SqlCommand(insertSQL, conn))
{
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("@RegionID", regionID.Guid);
cmd.Parameters.AddWithValue("@EstateID", estateID);
int ret = cmd.ExecuteNonQuery();
if (ret != 0)
transaction.Commit();
else
transaction.Rollback();
return (ret != 0);
}
}
catch (Exception ex)
{
m_log.Error("[REGION DB]: LinkRegion failed: " + ex.Message);
transaction.Rollback();
}
}
return false;
}
public List<UUID> GetRegions(int estateID)
{
List<UUID> result = new List<UUID>();
string sql = "select RegionID from estate_map where EstateID = @EstateID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@EstateID", estateID);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(DBGuid.FromDB(reader["RegionID"]));
}
reader.Close();
}
}
}
return result;
}
public bool DeleteEstate(int estateID)
{
// TODO: Implementation!
return false;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.XPath;
namespace System.Xml.Xsl.Xslt
{
using XPathParser = XPathParser<QilNode>;
using XPathNodeType = System.Xml.XPath.XPathNodeType;
internal class XPathPatternParser
{
public interface IPatternBuilder : IXPathBuilder<QilNode>
{
IXPathBuilder<QilNode> GetPredicateBuilder(QilNode context);
}
private XPathScanner _scanner;
private IPatternBuilder _ptrnBuilder;
private readonly XPathParser _predicateParser = new XPathParser();
public QilNode Parse(XPathScanner scanner, IPatternBuilder ptrnBuilder)
{
Debug.Assert(_scanner == null && _ptrnBuilder == null);
Debug.Assert(scanner != null && ptrnBuilder != null);
QilNode result = null;
ptrnBuilder.StartBuild();
try
{
_scanner = scanner;
_ptrnBuilder = ptrnBuilder;
result = this.ParsePattern();
_scanner.CheckToken(LexKind.Eof);
}
finally
{
result = ptrnBuilder.EndBuild(result);
#if DEBUG
_ptrnBuilder = null;
_scanner = null;
#endif
}
return result;
}
/*
* Pattern ::= LocationPathPattern ('|' LocationPathPattern)*
*/
private QilNode ParsePattern()
{
QilNode opnd = ParseLocationPathPattern();
while (_scanner.Kind == LexKind.Union)
{
_scanner.NextLex();
opnd = _ptrnBuilder.Operator(XPathOperator.Union, opnd, ParseLocationPathPattern());
}
return opnd;
}
/*
* LocationPathPattern ::= '/' RelativePathPattern? | '//'? RelativePathPattern | IdKeyPattern (('/' | '//') RelativePathPattern)?
*/
private QilNode ParseLocationPathPattern()
{
QilNode opnd;
switch (_scanner.Kind)
{
case LexKind.Slash:
_scanner.NextLex();
opnd = _ptrnBuilder.Axis(XPathAxis.Root, XPathNodeType.All, null, null);
if (XPathParser.IsStep(_scanner.Kind))
{
opnd = _ptrnBuilder.JoinStep(opnd, ParseRelativePathPattern());
}
return opnd;
case LexKind.SlashSlash:
_scanner.NextLex();
return _ptrnBuilder.JoinStep(
_ptrnBuilder.Axis(XPathAxis.Root, XPathNodeType.All, null, null),
_ptrnBuilder.JoinStep(
_ptrnBuilder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativePathPattern()
)
);
case LexKind.Name:
if (_scanner.CanBeFunction && _scanner.Prefix.Length == 0 && (_scanner.Name == "id" || _scanner.Name == "key"))
{
opnd = ParseIdKeyPattern();
switch (_scanner.Kind)
{
case LexKind.Slash:
_scanner.NextLex();
opnd = _ptrnBuilder.JoinStep(opnd, ParseRelativePathPattern());
break;
case LexKind.SlashSlash:
_scanner.NextLex();
opnd = _ptrnBuilder.JoinStep(opnd,
_ptrnBuilder.JoinStep(
_ptrnBuilder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativePathPattern()
)
);
break;
}
return opnd;
}
break;
}
opnd = ParseRelativePathPattern();
return opnd;
}
/*
* IdKeyPattern ::= 'id' '(' Literal ')' | 'key' '(' Literal ',' Literal ')'
*/
private QilNode ParseIdKeyPattern()
{
Debug.Assert(_scanner.CanBeFunction);
Debug.Assert(_scanner.Prefix.Length == 0);
Debug.Assert(_scanner.Name == "id" || _scanner.Name == "key");
List<QilNode> args = new List<QilNode>(2);
if (_scanner.Name == "id")
{
_scanner.NextLex();
_scanner.PassToken(LexKind.LParens);
_scanner.CheckToken(LexKind.String);
args.Add(_ptrnBuilder.String(_scanner.StringValue));
_scanner.NextLex();
_scanner.PassToken(LexKind.RParens);
return _ptrnBuilder.Function("", "id", args);
}
else
{
_scanner.NextLex();
_scanner.PassToken(LexKind.LParens);
_scanner.CheckToken(LexKind.String);
args.Add(_ptrnBuilder.String(_scanner.StringValue));
_scanner.NextLex();
_scanner.PassToken(LexKind.Comma);
_scanner.CheckToken(LexKind.String);
args.Add(_ptrnBuilder.String(_scanner.StringValue));
_scanner.NextLex();
_scanner.PassToken(LexKind.RParens);
return _ptrnBuilder.Function("", "key", args);
}
}
/*
* RelativePathPattern ::= StepPattern (('/' | '//') StepPattern)*
*/
//Max depth to avoid StackOverflow
private const int MaxParseRelativePathDepth = 1024;
private int _parseRelativePath = 0;
private QilNode ParseRelativePathPattern()
{
if (++_parseRelativePath > MaxParseRelativePathDepth)
{
if (LocalAppContextSwitches.LimitXPathComplexity)
{
throw _scanner.CreateException(SR.Xslt_InputTooComplex);
}
}
QilNode opnd = ParseStepPattern();
if (_scanner.Kind == LexKind.Slash)
{
_scanner.NextLex();
opnd = _ptrnBuilder.JoinStep(opnd, ParseRelativePathPattern());
}
else if (_scanner.Kind == LexKind.SlashSlash)
{
_scanner.NextLex();
opnd = _ptrnBuilder.JoinStep(opnd,
_ptrnBuilder.JoinStep(
_ptrnBuilder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativePathPattern()
)
);
}
--_parseRelativePath;
return opnd;
}
/*
* StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate*
* ChildOrAttributeAxisSpecifier ::= @ ? | ('child' | 'attribute') '::'
*/
private QilNode ParseStepPattern()
{
QilNode opnd;
XPathAxis axis;
switch (_scanner.Kind)
{
case LexKind.Dot:
case LexKind.DotDot:
throw _scanner.CreateException(SR.XPath_InvalidAxisInPattern);
case LexKind.At:
axis = XPathAxis.Attribute;
_scanner.NextLex();
break;
case LexKind.Axis:
axis = _scanner.Axis;
if (axis != XPathAxis.Child && axis != XPathAxis.Attribute)
{
throw _scanner.CreateException(SR.XPath_InvalidAxisInPattern);
}
_scanner.NextLex(); // Skip '::'
_scanner.NextLex();
break;
case LexKind.Name:
case LexKind.Star:
// NodeTest must start with Name or '*'
axis = XPathAxis.Child;
break;
default:
throw _scanner.CreateException(SR.XPath_UnexpectedToken, _scanner.RawValue);
}
XPathNodeType nodeType;
string nodePrefix, nodeName;
XPathParser.InternalParseNodeTest(_scanner, axis, out nodeType, out nodePrefix, out nodeName);
opnd = _ptrnBuilder.Axis(axis, nodeType, nodePrefix, nodeName);
XPathPatternBuilder xpathPatternBuilder = _ptrnBuilder as XPathPatternBuilder;
if (xpathPatternBuilder != null)
{
//for XPathPatternBuilder, get all predicates and then build them
List<QilNode> predicates = new List<QilNode>();
while (_scanner.Kind == LexKind.LBracket)
{
predicates.Add(ParsePredicate(opnd));
}
if (predicates.Count > 0)
opnd = xpathPatternBuilder.BuildPredicates(opnd, predicates);
}
else
{
while (_scanner.Kind == LexKind.LBracket)
{
opnd = _ptrnBuilder.Predicate(opnd, ParsePredicate(opnd), /*reverseStep:*/false);
}
}
return opnd;
}
/*
* Predicate ::= '[' Expr ']'
*/
private QilNode ParsePredicate(QilNode context)
{
Debug.Assert(_scanner.Kind == LexKind.LBracket);
_scanner.NextLex();
QilNode result = _predicateParser.Parse(_scanner, _ptrnBuilder.GetPredicateBuilder(context), LexKind.RBracket);
Debug.Assert(_scanner.Kind == LexKind.RBracket);
_scanner.NextLex();
return result;
}
}
}
| |
namespace AutoMapper
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Impl;
using Internal;
/// <summary>
/// Main configuration object holding all mapping configuration for a source and destination type
/// </summary>
[DebuggerDisplay("{_sourceType.Type.Name} -> {_destinationType.Type.Name}")]
public class TypeMap
{
private readonly IList<Action<object, object>> _afterMapActions = new List<Action<object, object>>();
private readonly IList<Action<object, object>> _beforeMapActions = new List<Action<object, object>>();
private readonly TypeInfo _destinationType;
private readonly ISet<TypePair> _includedDerivedTypes = new HashSet<TypePair>();
private readonly ThreadSafeList<PropertyMap> _propertyMaps = new ThreadSafeList<PropertyMap>();
private readonly ThreadSafeList<SourceMemberConfig> _sourceMemberConfigs =
new ThreadSafeList<SourceMemberConfig>();
private readonly IList<PropertyMap> _inheritedMaps = new List<PropertyMap>();
private PropertyMap[] _orderedPropertyMaps;
private readonly TypeInfo _sourceType;
private bool _sealed;
private Func<ResolutionContext, bool> _condition;
private int _maxDepth = Int32.MaxValue;
private IList<TypeMap> _inheritedTypeMaps = new List<TypeMap>();
public TypeMap(TypeInfo sourceType, TypeInfo destinationType, MemberList memberList)
{
_sourceType = sourceType;
_destinationType = destinationType;
Profile = ConfigurationStore.DefaultProfileName;
ConfiguredMemberList = memberList;
}
public ConstructorMap ConstructorMap { get; private set; }
public Type SourceType => _sourceType.Type;
public Type DestinationType => _destinationType.Type;
public string Profile { get; set; }
public Func<ResolutionContext, object> CustomMapper { get; private set; }
public LambdaExpression CustomProjection { get; private set; }
public Action<object, object> BeforeMap
{
get
{
return (src, dest) =>
{
foreach (var action in _beforeMapActions)
action(src, dest);
};
}
}
public Action<object, object> AfterMap
{
get
{
return (src, dest) =>
{
foreach (var action in _afterMapActions)
action(src, dest);
};
}
}
public Func<ResolutionContext, object> DestinationCtor { get; set; }
public List<string> IgnorePropertiesStartingWith { get; set; }
public Type DestinationTypeOverride { get; set; }
public bool ConstructDestinationUsingServiceLocator { get; set; }
public MemberList ConfiguredMemberList { get; }
public IEnumerable<TypePair> IncludedDerivedTypes => _includedDerivedTypes;
public int MaxDepth
{
get { return _maxDepth; }
set
{
_maxDepth = value;
SetCondition(o => PassesDepthCheck(o, value));
}
}
public Func<object, object> Substitution { get; set; }
public LambdaExpression ConstructExpression { get; set; }
public IEnumerable<PropertyMap> GetPropertyMaps()
{
return _sealed ? _orderedPropertyMaps : _propertyMaps.Concat(_inheritedMaps);
}
public void AddPropertyMap(PropertyMap propertyMap)
{
_propertyMaps.Add(propertyMap);
}
protected void AddInheritedMap(PropertyMap propertyMap)
{
_inheritedMaps.Add(propertyMap);
}
public void AddPropertyMap(IMemberAccessor destProperty, IEnumerable<IValueResolver> resolvers)
{
var propertyMap = new PropertyMap(destProperty);
resolvers.Each(propertyMap.ChainResolver);
AddPropertyMap(propertyMap);
}
public string[] GetUnmappedPropertyNames()
{
var autoMappedProperties = _propertyMaps.Where(pm => pm.IsMapped())
.Select(pm => pm.DestinationProperty.Name);
var inheritedProperties = _inheritedMaps.Where(pm => pm.IsMapped())
.Select(pm => pm.DestinationProperty.Name);
IEnumerable<string> properties;
if(ConfiguredMemberList == MemberList.Destination)
{
properties = _destinationType.PublicWriteAccessors
.Select(p => p.Name)
.Except(autoMappedProperties)
.Except(inheritedProperties);
}
else
{
var redirectedSourceMembers = _propertyMaps
.Where(pm => pm.IsMapped() && pm.SourceMember != null && pm.SourceMember.Name != pm.DestinationProperty.Name)
.Select(pm => pm.SourceMember.Name);
var ignoredSourceMembers = _sourceMemberConfigs
.Where(smc => smc.IsIgnored())
.Select(pm => pm.SourceMember.Name);
properties = _sourceType.PublicReadAccessors
.Select(p => p.Name)
.Except(autoMappedProperties)
.Except(inheritedProperties)
.Except(redirectedSourceMembers)
.Except(ignoredSourceMembers);
}
return properties.Where(memberName => !IgnorePropertiesStartingWith.Any(memberName.StartsWith)).ToArray();
}
public PropertyMap FindOrCreatePropertyMapFor(IMemberAccessor destinationProperty)
{
var propertyMap = GetExistingPropertyMapFor(destinationProperty);
if (propertyMap != null) return propertyMap;
propertyMap = new PropertyMap(destinationProperty);
AddPropertyMap(propertyMap);
return propertyMap;
}
public void IncludeDerivedTypes(Type derivedSourceType, Type derivedDestinationType)
{
_includedDerivedTypes.Add(new TypePair(derivedSourceType, derivedDestinationType));
}
public Type GetDerivedTypeFor(Type derivedSourceType)
{
// This might need to be fixed for multiple derived source types to different dest types
var match = _includedDerivedTypes.FirstOrDefault(tp => tp.SourceType == derivedSourceType);
return DestinationTypeOverride ?? match?.DestinationType ?? DestinationType;
}
public bool TypeHasBeenIncluded(Type derivedSourceType, Type derivedDestinationType)
{
return _includedDerivedTypes.Contains(new TypePair(derivedSourceType, derivedDestinationType));
}
public bool HasDerivedTypesToInclude()
{
return _includedDerivedTypes.Any() || DestinationTypeOverride != null;
}
public void UseCustomMapper(Func<ResolutionContext, object> customMapper)
{
CustomMapper = customMapper;
_propertyMaps.Clear();
}
public void AddBeforeMapAction(Action<object, object> beforeMap)
{
_beforeMapActions.Add(beforeMap);
}
public void AddAfterMapAction(Action<object, object> afterMap)
{
_afterMapActions.Add(afterMap);
}
public void Seal()
{
if (_sealed)
return;
foreach (var inheritedTypeMap in _inheritedTypeMaps)
{
inheritedTypeMap.Seal();
ApplyInheritedTypeMap(inheritedTypeMap);
}
_orderedPropertyMaps =
_propertyMaps
.Union(_inheritedMaps)
.OrderBy(map => map.GetMappingOrder()).ToArray();
_orderedPropertyMaps.Each(pm => pm.Seal());
foreach (var inheritedMap in _inheritedMaps)
inheritedMap.Seal();
_sealed = true;
}
public bool Equals(TypeMap other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other._sourceType, _sourceType) && Equals(other._destinationType, _destinationType);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (TypeMap)) return false;
return Equals((TypeMap) obj);
}
public override int GetHashCode()
{
unchecked
{
return (_sourceType.GetHashCode()*397) ^ _destinationType.GetHashCode();
}
}
public PropertyMap GetExistingPropertyMapFor(IMemberAccessor destinationProperty)
{
var propertyMap =
_propertyMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name));
if (propertyMap != null)
return propertyMap;
propertyMap =
_inheritedMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name));
if (propertyMap == null)
return null;
var propertyInfo = propertyMap.DestinationProperty.MemberInfo as PropertyInfo;
if (propertyInfo == null)
return propertyMap;
var baseAccessor = propertyInfo.GetAccessors()[0];
if (baseAccessor.IsAbstract || baseAccessor.IsVirtual)
return propertyMap;
var accessor = ((PropertyInfo) destinationProperty.MemberInfo).GetAccessors()[0];
if (baseAccessor.DeclaringType == accessor.DeclaringType)
return propertyMap;
return null;
}
public void AddInheritedPropertyMap(PropertyMap mappedProperty)
{
_inheritedMaps.Add(mappedProperty);
}
public void InheritTypes(TypeMap inheritedTypeMap)
{
foreach (var includedDerivedType in inheritedTypeMap._includedDerivedTypes
.Where(includedDerivedType => !_includedDerivedTypes.Contains(includedDerivedType)))
{
_includedDerivedTypes.Add(includedDerivedType);
}
}
public void SetCondition(Func<ResolutionContext, bool> condition)
{
_condition = condition;
}
public bool ShouldAssignValue(ResolutionContext resolutionContext)
{
return _condition == null || _condition(resolutionContext);
}
public void AddConstructorMap(ConstructorInfo constructorInfo, IEnumerable<ConstructorParameterMap> parameters)
{
var ctorMap = new ConstructorMap(constructorInfo, parameters);
ConstructorMap = ctorMap;
}
public SourceMemberConfig FindOrCreateSourceMemberConfigFor(MemberInfo sourceMember)
{
var config = _sourceMemberConfigs.FirstOrDefault(smc => smc.SourceMember == sourceMember);
if (config == null)
{
config = new SourceMemberConfig(sourceMember);
_sourceMemberConfigs.Add(config);
}
return config;
}
private static bool PassesDepthCheck(ResolutionContext context, int maxDepth)
{
if (context.InstanceCache.ContainsKey(context))
{
// return true if we already mapped this value and it's in the cache
return true;
}
ResolutionContext contextCopy = context;
int currentDepth = 1;
// walk parents to determine current depth
while (contextCopy.Parent != null)
{
if (contextCopy.SourceType == context.TypeMap.SourceType &&
contextCopy.DestinationType == context.TypeMap.DestinationType)
{
// same source and destination types appear higher up in the hierarchy
currentDepth++;
}
contextCopy = contextCopy.Parent;
}
return currentDepth <= maxDepth;
}
public void UseCustomProjection(LambdaExpression projectionExpression)
{
CustomProjection = projectionExpression;
_propertyMaps.Clear();
}
public void ApplyInheritedMap(TypeMap inheritedTypeMap)
{
_inheritedTypeMaps.Add(inheritedTypeMap);
}
private void ApplyInheritedTypeMap(TypeMap inheritedTypeMap)
{
foreach (var inheritedMappedProperty in inheritedTypeMap.GetPropertyMaps().Where(m => m.IsMapped()))
{
var conventionPropertyMap = GetPropertyMaps()
.SingleOrDefault(m =>
m.DestinationProperty.Name == inheritedMappedProperty.DestinationProperty.Name);
if (conventionPropertyMap != null && inheritedMappedProperty.HasCustomValueResolver && !conventionPropertyMap.HasCustomValueResolver)
{
conventionPropertyMap.AssignCustomValueResolver(
inheritedMappedProperty.GetSourceValueResolvers().First());
conventionPropertyMap.AssignCustomExpression(inheritedMappedProperty.CustomExpression);
}
else if (conventionPropertyMap == null)
{
var propertyMap = new PropertyMap(inheritedMappedProperty);
AddInheritedPropertyMap(propertyMap);
}
}
//Include BeforeMap
if (inheritedTypeMap.BeforeMap != null)
AddBeforeMapAction(inheritedTypeMap.BeforeMap);
//Include AfterMap
if (inheritedTypeMap.AfterMap != null)
AddAfterMapAction(inheritedTypeMap.AfterMap);
}
internal LambdaExpression DestinationConstructorExpression(Expression instanceParameter)
{
var ctorExpr = ConstructExpression;
if(ctorExpr != null)
{
return ctorExpr;
}
Expression newExpression;
if(ConstructorMap != null && ConstructorMap.CtorParams.All(p => p.CanResolve))
{
newExpression = ConstructorMap.NewExpression(instanceParameter);
}
else
{
newExpression = Expression.New(DestinationTypeOverride ?? DestinationType);
}
return Expression.Lambda(newExpression);
}
}
}
| |
using System;
/// <summary>
/// Char.IsSurrogatePair(string, index)
/// Note: This method is new in the .NET Framework version 2.0.
/// Indicates whether two adjacent Char objects at a specified position in a string form a surrogate pair.
/// </summary>
public class CharIsSurrogatePair
{
private const int c_MIN_STR_LEN = 2;
private const int c_MAX_STR_LEN = 256;
private const char c_HIGH_SURROGATE_START = '\ud800';
private const char c_HIGH_SURROGATE_END = '\udbff';
private const char c_LOW_SURROGATE_START = '\udc00';
private const char c_LOW_SURROGATE_END = '\udfff';
public static int Main()
{
CharIsSurrogatePair testObj = new CharIsSurrogatePair();
TestLibrary.TestFramework.BeginTestCase("for method: Char.IsSurrogatePair(string, index)");
if (testObj.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("[Negaitive]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
char chA;
char chB;
//Generate a high surrogate character for validate
int count = (int)c_HIGH_SURROGATE_END - (int)c_HIGH_SURROGATE_START + 1;
int offset = TestLibrary.Generator.GetInt32(-55) % count;
chA = (char)((int)c_HIGH_SURROGATE_START + offset);
//Generate a character not low surrogate for validate
count = (int)c_LOW_SURROGATE_END - (int)c_LOW_SURROGATE_START + 1;
offset = TestLibrary.Generator.GetInt32(-55) % count;
chB = (char)((int)c_LOW_SURROGATE_START + offset);
return this.DoTest("PosTest1: First character is high surrogate, and the second is low surrogate",
"P001", "001", "002", chA, chB, true);
}
public bool PosTest2()
{
char chA;
char chB;
//Generate a high surrogate character for validate
int count = (int)c_HIGH_SURROGATE_END - (int)c_HIGH_SURROGATE_START + 1;
int offset = TestLibrary.Generator.GetInt32(-55) % count;
chA = (char)((int)c_HIGH_SURROGATE_START + offset);
//Generate a character not low surrogate for validate
int i = TestLibrary.Generator.GetInt32(-55) & 0x00000001;
if (0 == i)
{
chB = (char)(TestLibrary.Generator.GetInt32(-55) % ((int)c_LOW_SURROGATE_START));
}
else
{
chB = (char)((int)c_LOW_SURROGATE_END + 1 +
TestLibrary.Generator.GetInt32(-55) % ((int)char.MaxValue - (int)c_LOW_SURROGATE_END));
}
return this.DoTest("PosTest2: First character is high surrogate, but the second is not low surrogate",
"P002", "003", "004", chA, chB, false);
}
public bool PosTest3()
{
char chA;
char chB;
//Generate a character not high surrogate for validate
int i = TestLibrary.Generator.GetInt32(-55) & 0x00000001;
if (0 == i)
{
chA = (char)(TestLibrary.Generator.GetInt32(-55) % ((int)c_HIGH_SURROGATE_START));
}
else
{
chA = (char)((int)c_HIGH_SURROGATE_END + 1 +
TestLibrary.Generator.GetInt32(-55) % ((int)char.MaxValue - (int)c_HIGH_SURROGATE_END));
}
//Generate a low surrogate character for validate
int count = (int)c_LOW_SURROGATE_END - (int)c_LOW_SURROGATE_START + 1;
int offset = TestLibrary.Generator.GetInt32(-55) % count;
chB = (char)((int)c_LOW_SURROGATE_START + offset);
return this.DoTest("PosTest2: Second character is low surrogate, but the first is not high surrogate",
"P003", "005", "006", chA, chB, false);
}
public bool PosTest4()
{
char chA;
char chB;
//Generate a character not high surrogate for validate
int i = TestLibrary.Generator.GetInt32(-55) & 0x00000001;
if (0 == i)
{
chA = (char)(TestLibrary.Generator.GetInt32(-55) % ((int)c_HIGH_SURROGATE_START));
}
else
{
chA = (char)((int)c_HIGH_SURROGATE_END + 1 +
TestLibrary.Generator.GetInt32(-55) % ((int)char.MaxValue - (int)c_HIGH_SURROGATE_END));
}
//Generate a character not low surrogate for validate
i = TestLibrary.Generator.GetInt32(-55) & 0x00000001;
if (0 == i)
{
chB = (char)(TestLibrary.Generator.GetInt32(-55) % ((int)c_LOW_SURROGATE_START));
}
else
{
chB = (char)((int)c_LOW_SURROGATE_END + 1 +
TestLibrary.Generator.GetInt32(-55) % ((int)char.MaxValue - (int)c_LOW_SURROGATE_END));
}
return this.DoTest("PosTest2: Both the first character and the second are invalid",
"P004", "007", "008", chA, chB, false);
}
#endregion
#region Helper method for positive tests
private bool DoTest(string testDesc,
string testId,
string errorNum1,
string errorNum2,
char chA,
char chB,
bool expectedResult)
{
bool retVal = true;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
string str = string.Empty + chA + chB;
bool actualResult = char.IsSurrogatePair(str, 0);
if (expectedResult != actualResult)
{
if (expectedResult)
{
errorDesc = string.Format("Character \\u{0:x} and \\u{1:x} should belong to surrogate pair.", (int)chA, (int)chB);
}
else
{
errorDesc = string.Format("Character \\u{0:x} and \\u{1:x} does not belong to surrogate pair.", (int)chA, (int)chB);
}
TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nCharacter is \\u{0:x} and \\u{1:x}", chA, chB);
TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentNullException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: String is a null reference (Nothing in Visual Basic).";
string errorDesc;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
index = TestLibrary.Generator.GetInt32(-55);
char.IsPunctuation(null, index);
errorDesc = "ArgumentNullException is not thrown as expected, index is " + index;
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e + "\n Index is " + index;
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//ArgumentOutOfRangeException
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: Index is too great.";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = str.Length + TestLibrary.Generator.GetInt16(-55);
index = str.Length;
char.IsPunctuation(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: Index is a negative value";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = -1 * (TestLibrary.Generator.GetInt16(-55));
char.IsPunctuation(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index);
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
namespace _02.Salaries
{
using System;
using System.Collections.Generic;
using System.Text;
public class Graph<T>
{
internal IDictionary<T, Node<T>> Nodes { get; private set; }
private readonly HashSet<Node<T>> visited;
public Graph()
{
Nodes = new Dictionary<T, Node<T>>();
visited = new HashSet<Node<T>>();
}
public void AddNode(T name)
{
var node = new Node<T>(name);
if (Nodes.ContainsKey(name))
{
throw new ArgumentException(string.Format("Node with name {0} is existing in the graph.", name));
}
Nodes.Add(name, node);
}
public void AddConnection(T fromNode, T toNode, int distance, bool twoWay)
{
if (!Nodes.ContainsKey(fromNode))
{
this.AddNode(fromNode);
}
if (!Nodes.ContainsKey(toNode))
{
this.AddNode(toNode);
}
Nodes[fromNode].AddConnection(Nodes[toNode], distance, twoWay);
}
public List<Node<T>> FindShortestDistanceToAllNodes(T startNodeName)
{
if (!Nodes.ContainsKey(startNodeName))
{
throw new ArgumentOutOfRangeException(string.Format("{0} is not containing in the graph.", startNodeName));
}
SetShortestDistances(Nodes[startNodeName]);
var nodes = new List<Node<T>>();
foreach (var item in Nodes)
{
if (!item.Key.Equals(startNodeName))
{
nodes.Add(item.Value);
}
}
return nodes;
}
private void SetShortestDistances(Node<T> startNode)
{
var queue = new PriorityQueue<Node<T>>();
// set to all nodes DijkstraDistance to PositiveInfinity
foreach (var node in Nodes)
{
if (!startNode.Name.Equals(node.Key))
{
node.Value.DijkstraDistance = double.PositiveInfinity;
//queue.Enqueue(node.Value);
}
}
startNode.DijkstraDistance = 0.0d;
queue.Enqueue(startNode);
while (queue.Count != 0)
{
Node<T> currentNode = queue.Dequeue();
if (double.IsPositiveInfinity(currentNode.DijkstraDistance))
{
break;
}
foreach (var neighbour in Nodes[currentNode.Name].Connections)
{
double subDistance = currentNode.DijkstraDistance + neighbour.Distance;
if (subDistance < neighbour.Target.DijkstraDistance)
{
neighbour.Target.DijkstraDistance = subDistance;
queue.Enqueue(neighbour.Target);
}
}
}
}
public void SetAllDijkstraDistanceValue(double value)
{
foreach (var node in Nodes)
{
node.Value.DijkstraDistance = value;
}
}
public double GetSumOfAllDijkstraDistance()
{
foreach (var item in Nodes)
{
if (!visited.Contains(item.Value))
{
EmployDfs(item.Value);
}
}
double sum = 0;
foreach (var node in Nodes)
{
sum += node.Value.DijkstraDistance;
}
return sum;
}
public void EmployDfs(Node<T> node)
{
visited.Add(node);
foreach (var item in node.Connections)
{
if (!visited.Contains(item.Target))
{
EmployDfs(item.Target);
}
node.DijkstraDistance += item.Target.DijkstraDistance;
}
if (node.DijkstraDistance == 0)
{
node.DijkstraDistance++;
}
}
public void EmployBfs(T nodeName)
{
var nodes = new Queue<Node<T>>();
Node<T> node = Nodes[nodeName];
nodes.Enqueue(node);
while (nodes.Count != 0)
{
Node<T> currentNode = nodes.Dequeue();
currentNode.DijkstraDistance++;
foreach (var connection in Nodes[currentNode.Name].Connections)
{
nodes.Enqueue(connection.Target);
}
}
}
public List<Edge<T>> PrimeMinimumSpanningTree(T startNodeName)
{
if (!Nodes.ContainsKey(startNodeName))
{
throw new ArgumentOutOfRangeException(string.Format("{0} is not containing in the graph.", startNodeName));
}
var mpdTree = new List<Edge<T>>();
var queue = new PriorityQueue<Edge<T>>();
Node<T> node = Nodes[startNodeName];
foreach (var edge in node.Connections)
{
queue.Enqueue(edge);
}
visited.Add(node);
while (queue.Count > 0)
{
Edge<T> edge = queue.Dequeue();
if (!visited.Contains(edge.Target))
{
node = edge.Target;
visited.Add(node); //we "visit" this node
mpdTree.Add(edge);
foreach (var item in node.Connections)
{
if (!mpdTree.Contains(item))
{
if (!visited.Contains(item.Target))
{
queue.Enqueue(item);
}
}
}
}
}
visited.Clear();
return mpdTree;
}
public override string ToString()
{
var result = new StringBuilder();
foreach (var node in this.Nodes)
{
result.Append("(" + node.Key + ") -> ");
foreach (var conection in node.Value.Connections)
{
result.Append("(" + conection.Target + ") with:" + conection.Distance + " ");
}
result.AppendLine();
}
return result.ToString();
}
}
}
| |
/*
* 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.
*/
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable NonReadonlyMemberInGetHashCode
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity.Rendezvous;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Eviction;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Ssl;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Communication.Tcp;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.DataStructures.Configuration;
using Apache.Ignite.Core.Deployment;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Multicast;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Failure;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.PersistentStore;
using Apache.Ignite.Core.Plugin.Cache;
using Apache.Ignite.Core.Tests.Binary;
using Apache.Ignite.Core.Tests.Plugin;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
using CheckpointWriteOrder = Apache.Ignite.Core.PersistentStore.CheckpointWriteOrder;
using DataPageEvictionMode = Apache.Ignite.Core.Cache.Configuration.DataPageEvictionMode;
using WalMode = Apache.Ignite.Core.PersistentStore.WalMode;
/// <summary>
/// Tests <see cref="IgniteConfiguration"/> serialization.
/// </summary>
public class IgniteConfigurationSerializerTest
{
/// <summary>
/// Tests the predefined XML.
/// </summary>
[Test]
public void TestPredefinedXml()
{
var xml = File.ReadAllText(Path.Combine("Config", "full-config.xml"));
var cfg = IgniteConfiguration.FromXml(xml);
Assert.AreEqual("c:", cfg.WorkDirectory);
Assert.AreEqual("127.1.1.1", cfg.Localhost);
Assert.IsTrue(cfg.IsDaemon);
Assert.AreEqual(1024, cfg.JvmMaxMemoryMb);
Assert.AreEqual(TimeSpan.FromSeconds(10), cfg.MetricsLogFrequency);
Assert.AreEqual(TimeSpan.FromMinutes(1), ((TcpDiscoverySpi)cfg.DiscoverySpi).JoinTimeout);
Assert.AreEqual("192.168.1.1", ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalAddress);
Assert.AreEqual(6655, ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalPort);
Assert.AreEqual(7,
((TcpDiscoveryMulticastIpFinder) ((TcpDiscoverySpi) cfg.DiscoverySpi).IpFinder).AddressRequestAttempts);
Assert.AreEqual(new[] { "-Xms1g", "-Xmx4g" }, cfg.JvmOptions);
Assert.AreEqual(15, ((LifecycleBean) cfg.LifecycleHandlers.Single()).Foo);
Assert.AreEqual("testBar", ((NameMapper) cfg.BinaryConfiguration.NameMapper).Bar);
Assert.AreEqual(
"Apache.Ignite.Core.Tests.IgniteConfigurationSerializerTest+FooClass, Apache.Ignite.Core.Tests",
cfg.BinaryConfiguration.Types.Single());
Assert.IsFalse(cfg.BinaryConfiguration.CompactFooter);
Assert.AreEqual(new[] {42, EventType.TaskFailed, EventType.JobFinished}, cfg.IncludedEventTypes);
Assert.AreEqual(@"c:\myconfig.xml", cfg.SpringConfigUrl);
Assert.IsTrue(cfg.AutoGenerateIgniteInstanceName);
Assert.AreEqual(new TimeSpan(1, 2, 3), cfg.LongQueryWarningTimeout);
Assert.IsFalse(cfg.IsActiveOnStart);
Assert.IsTrue(cfg.AuthenticationEnabled);
Assert.AreEqual(10000, cfg.MvccVacuumFrequency);
Assert.AreEqual(4, cfg.MvccVacuumThreadCount);
Assert.AreEqual(123, cfg.SqlQueryHistorySize);
Assert.AreEqual(true, cfg.JavaPeerClassLoadingEnabled);
Assert.IsNotNull(cfg.SqlSchemas);
Assert.AreEqual(2, cfg.SqlSchemas.Count);
Assert.IsTrue(cfg.SqlSchemas.Contains("SCHEMA_1"));
Assert.IsTrue(cfg.SqlSchemas.Contains("schema_2"));
Assert.AreEqual("someId012", cfg.ConsistentId);
Assert.IsFalse(cfg.RedirectJavaConsoleOutput);
Assert.AreEqual("secondCache", cfg.CacheConfiguration.Last().Name);
var cacheCfg = cfg.CacheConfiguration.First();
Assert.AreEqual(CacheMode.Replicated, cacheCfg.CacheMode);
Assert.IsTrue(cacheCfg.ReadThrough);
Assert.IsTrue(cacheCfg.WriteThrough);
Assert.IsInstanceOf<MyPolicyFactory>(cacheCfg.ExpiryPolicyFactory);
Assert.IsTrue(cacheCfg.EnableStatistics);
Assert.IsFalse(cacheCfg.WriteBehindCoalescing);
Assert.AreEqual(PartitionLossPolicy.ReadWriteAll, cacheCfg.PartitionLossPolicy);
Assert.AreEqual("fooGroup", cacheCfg.GroupName);
Assert.AreEqual("bar", cacheCfg.KeyConfiguration.Single().AffinityKeyFieldName);
Assert.AreEqual("foo", cacheCfg.KeyConfiguration.Single().TypeName);
Assert.IsTrue(cacheCfg.OnheapCacheEnabled);
Assert.AreEqual(8, cacheCfg.StoreConcurrentLoadAllThreshold);
Assert.AreEqual(9, cacheCfg.RebalanceOrder);
Assert.AreEqual(10, cacheCfg.RebalanceBatchesPrefetchCount);
Assert.AreEqual(11, cacheCfg.MaxQueryIteratorsCount);
Assert.AreEqual(12, cacheCfg.QueryDetailMetricsSize);
Assert.AreEqual(13, cacheCfg.QueryParallelism);
Assert.AreEqual("mySchema", cacheCfg.SqlSchema);
var queryEntity = cacheCfg.QueryEntities.Single();
Assert.AreEqual(typeof(int), queryEntity.KeyType);
Assert.AreEqual(typeof(string), queryEntity.ValueType);
Assert.AreEqual("myTable", queryEntity.TableName);
Assert.AreEqual("length", queryEntity.Fields.Single().Name);
Assert.AreEqual(typeof(int), queryEntity.Fields.Single().FieldType);
Assert.IsTrue(queryEntity.Fields.Single().IsKeyField);
Assert.IsTrue(queryEntity.Fields.Single().NotNull);
Assert.AreEqual(3.456d, (double)queryEntity.Fields.Single().DefaultValue);
Assert.AreEqual("somefield.field", queryEntity.Aliases.Single().FullName);
Assert.AreEqual("shortField", queryEntity.Aliases.Single().Alias);
var queryIndex = queryEntity.Indexes.Single();
Assert.AreEqual(QueryIndexType.Geospatial, queryIndex.IndexType);
Assert.AreEqual("indexFld", queryIndex.Fields.Single().Name);
Assert.AreEqual(true, queryIndex.Fields.Single().IsDescending);
Assert.AreEqual(123, queryIndex.InlineSize);
var nearCfg = cacheCfg.NearConfiguration;
Assert.IsNotNull(nearCfg);
Assert.AreEqual(7, nearCfg.NearStartSize);
var nodeFilter = (AttributeNodeFilter)cacheCfg.NodeFilter;
Assert.IsNotNull(nodeFilter);
var attributes = nodeFilter.Attributes.ToList();
Assert.AreEqual(3, nodeFilter.Attributes.Count);
Assert.AreEqual(new KeyValuePair<string, object>("myNode", "true"), attributes[0]);
Assert.AreEqual(new KeyValuePair<string, object>("foo", null), attributes[1]);
Assert.AreEqual(new KeyValuePair<string, object>("baz", null), attributes[2]);
var plc = nearCfg.EvictionPolicy as FifoEvictionPolicy;
Assert.IsNotNull(plc);
Assert.AreEqual(10, plc.BatchSize);
Assert.AreEqual(20, plc.MaxSize);
Assert.AreEqual(30, plc.MaxMemorySize);
var plc2 = cacheCfg.EvictionPolicy as LruEvictionPolicy;
Assert.IsNotNull(plc2);
Assert.AreEqual(1, plc2.BatchSize);
Assert.AreEqual(2, plc2.MaxSize);
Assert.AreEqual(3, plc2.MaxMemorySize);
var af = cacheCfg.AffinityFunction as RendezvousAffinityFunction;
Assert.IsNotNull(af);
Assert.AreEqual(99, af.Partitions);
Assert.IsTrue(af.ExcludeNeighbors);
var afBf = af.AffinityBackupFilter as ClusterNodeAttributeAffinityBackupFilter;
Assert.IsNotNull(afBf);
Assert.AreEqual(new[] {"foo1", "bar2"}, afBf.AttributeNames);
var platformCacheConfiguration = cacheCfg.PlatformCacheConfiguration;
Assert.AreEqual("int", platformCacheConfiguration.KeyTypeName);
Assert.AreEqual("string", platformCacheConfiguration.ValueTypeName);
Assert.IsTrue(platformCacheConfiguration.KeepBinary);
Assert.AreEqual(new Dictionary<string, object>
{
{"myNode", "true"},
{"foo", new FooClass {Bar = "Baz"}}
}, cfg.UserAttributes);
var atomicCfg = cfg.AtomicConfiguration;
Assert.AreEqual(2, atomicCfg.Backups);
Assert.AreEqual(CacheMode.Local, atomicCfg.CacheMode);
Assert.AreEqual(250, atomicCfg.AtomicSequenceReserveSize);
var tx = cfg.TransactionConfiguration;
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.DefaultTransactionConcurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.DefaultTransactionIsolation);
Assert.AreEqual(new TimeSpan(0,1,2), tx.DefaultTimeout);
Assert.AreEqual(15, tx.PessimisticTransactionLogSize);
Assert.AreEqual(TimeSpan.FromSeconds(33), tx.PessimisticTransactionLogLinger);
var comm = cfg.CommunicationSpi as TcpCommunicationSpi;
Assert.IsNotNull(comm);
Assert.AreEqual(33, comm.AckSendThreshold);
Assert.AreEqual(new TimeSpan(0, 1, 2), comm.IdleConnectionTimeout);
Assert.IsInstanceOf<TestLogger>(cfg.Logger);
var binType = cfg.BinaryConfiguration.TypeConfigurations.Single();
Assert.AreEqual("typeName", binType.TypeName);
Assert.AreEqual("affKeyFieldName", binType.AffinityKeyFieldName);
Assert.IsTrue(binType.IsEnum);
Assert.AreEqual(true, binType.KeepDeserialized);
Assert.IsInstanceOf<IdMapper>(binType.IdMapper);
Assert.IsInstanceOf<NameMapper>(binType.NameMapper);
Assert.IsInstanceOf<TestSerializer>(binType.Serializer);
var plugins = cfg.PluginConfigurations;
Assert.IsNotNull(plugins);
Assert.IsNotNull(plugins.Cast<TestIgnitePluginConfiguration>().SingleOrDefault());
Assert.IsNotNull(cacheCfg.PluginConfigurations.Cast<MyPluginConfiguration>().SingleOrDefault());
var eventStorage = cfg.EventStorageSpi as MemoryEventStorageSpi;
Assert.IsNotNull(eventStorage);
Assert.AreEqual(23.45, eventStorage.ExpirationTimeout.TotalSeconds);
Assert.AreEqual(129, eventStorage.MaxEventCount);
var memCfg = cfg.MemoryConfiguration;
Assert.IsNotNull(memCfg);
Assert.AreEqual(3, memCfg.ConcurrencyLevel);
Assert.AreEqual("dfPlc", memCfg.DefaultMemoryPolicyName);
Assert.AreEqual(45, memCfg.PageSize);
Assert.AreEqual(67, memCfg.SystemCacheInitialSize);
Assert.AreEqual(68, memCfg.SystemCacheMaxSize);
var memPlc = memCfg.MemoryPolicies.Single();
Assert.AreEqual(1, memPlc.EmptyPagesPoolSize);
Assert.AreEqual(0.2, memPlc.EvictionThreshold);
Assert.AreEqual("dfPlc", memPlc.Name);
Assert.AreEqual(DataPageEvictionMode.RandomLru, memPlc.PageEvictionMode);
Assert.AreEqual("abc", memPlc.SwapFilePath);
Assert.AreEqual(89, memPlc.InitialSize);
Assert.AreEqual(98, memPlc.MaxSize);
Assert.IsTrue(memPlc.MetricsEnabled);
Assert.AreEqual(9, memPlc.SubIntervals);
Assert.AreEqual(TimeSpan.FromSeconds(62), memPlc.RateTimeInterval);
Assert.AreEqual(PeerAssemblyLoadingMode.CurrentAppDomain, cfg.PeerAssemblyLoadingMode);
var sql = cfg.SqlConnectorConfiguration;
Assert.IsNotNull(sql);
Assert.AreEqual("bar", sql.Host);
Assert.AreEqual(10, sql.Port);
Assert.AreEqual(11, sql.PortRange);
Assert.AreEqual(12, sql.SocketSendBufferSize);
Assert.AreEqual(13, sql.SocketReceiveBufferSize);
Assert.IsTrue(sql.TcpNoDelay);
Assert.AreEqual(14, sql.MaxOpenCursorsPerConnection);
Assert.AreEqual(15, sql.ThreadPoolSize);
var client = cfg.ClientConnectorConfiguration;
Assert.IsNotNull(client);
Assert.AreEqual("bar", client.Host);
Assert.AreEqual(10, client.Port);
Assert.AreEqual(11, client.PortRange);
Assert.AreEqual(12, client.SocketSendBufferSize);
Assert.AreEqual(13, client.SocketReceiveBufferSize);
Assert.IsTrue(client.TcpNoDelay);
Assert.AreEqual(14, client.MaxOpenCursorsPerConnection);
Assert.AreEqual(15, client.ThreadPoolSize);
Assert.AreEqual(19, client.IdleTimeout.TotalSeconds);
Assert.AreEqual(20, client.ThinClientConfiguration.MaxActiveTxPerConnection);
Assert.AreEqual(21, client.ThinClientConfiguration.MaxActiveComputeTasksPerConnection);
var pers = cfg.PersistentStoreConfiguration;
Assert.AreEqual(true, pers.AlwaysWriteFullPages);
Assert.AreEqual(TimeSpan.FromSeconds(1), pers.CheckpointingFrequency);
Assert.AreEqual(2, pers.CheckpointingPageBufferSize);
Assert.AreEqual(3, pers.CheckpointingThreads);
Assert.AreEqual(TimeSpan.FromSeconds(4), pers.LockWaitTime);
Assert.AreEqual("foo", pers.PersistentStorePath);
Assert.AreEqual(5, pers.TlbSize);
Assert.AreEqual("bar", pers.WalArchivePath);
Assert.AreEqual(TimeSpan.FromSeconds(6), pers.WalFlushFrequency);
Assert.AreEqual(7, pers.WalFsyncDelayNanos);
Assert.AreEqual(8, pers.WalHistorySize);
Assert.AreEqual(WalMode.None, pers.WalMode);
Assert.AreEqual(9, pers.WalRecordIteratorBufferSize);
Assert.AreEqual(10, pers.WalSegments);
Assert.AreEqual(11, pers.WalSegmentSize);
Assert.AreEqual("baz", pers.WalStorePath);
Assert.IsTrue(pers.MetricsEnabled);
Assert.AreEqual(3, pers.SubIntervals);
Assert.AreEqual(TimeSpan.FromSeconds(6), pers.RateTimeInterval);
Assert.AreEqual(CheckpointWriteOrder.Random, pers.CheckpointWriteOrder);
Assert.IsTrue(pers.WriteThrottlingEnabled);
var listeners = cfg.LocalEventListeners;
Assert.AreEqual(2, listeners.Count);
var rebalListener = (LocalEventListener<CacheRebalancingEvent>) listeners.First();
Assert.AreEqual(new[] {EventType.CacheObjectPut, 81}, rebalListener.EventTypes);
Assert.AreEqual("Apache.Ignite.Core.Tests.EventsTestLocalListeners+Listener`1" +
"[Apache.Ignite.Core.Events.CacheRebalancingEvent]",
rebalListener.Listener.GetType().ToString());
var ds = cfg.DataStorageConfiguration;
Assert.IsFalse(ds.AlwaysWriteFullPages);
Assert.AreEqual(TimeSpan.FromSeconds(1), ds.CheckpointFrequency);
Assert.AreEqual(3, ds.CheckpointThreads);
Assert.AreEqual(4, ds.ConcurrencyLevel);
Assert.AreEqual(TimeSpan.FromSeconds(5), ds.LockWaitTime);
Assert.IsTrue(ds.MetricsEnabled);
Assert.AreEqual(6, ds.PageSize);
Assert.AreEqual("cde", ds.StoragePath);
Assert.AreEqual(TimeSpan.FromSeconds(7), ds.MetricsRateTimeInterval);
Assert.AreEqual(8, ds.MetricsSubIntervalCount);
Assert.AreEqual(11, ds.WalThreadLocalBufferSize);
Assert.AreEqual("abc", ds.WalArchivePath);
Assert.AreEqual(TimeSpan.FromSeconds(12), ds.WalFlushFrequency);
Assert.AreEqual(13, ds.WalFsyncDelayNanos);
Assert.AreEqual(14, ds.WalHistorySize);
Assert.AreEqual(Core.Configuration.WalMode.Background, ds.WalMode);
Assert.AreEqual(15, ds.WalRecordIteratorBufferSize);
Assert.AreEqual(16, ds.WalSegments);
Assert.AreEqual(17, ds.WalSegmentSize);
Assert.AreEqual("wal-store", ds.WalPath);
Assert.AreEqual(TimeSpan.FromSeconds(18), ds.WalAutoArchiveAfterInactivity);
Assert.AreEqual(TimeSpan.FromSeconds(19), ds.WalForceArchiveTimeout);
Assert.IsTrue(ds.WriteThrottlingEnabled);
Assert.AreEqual(DiskPageCompression.Zstd, ds.WalPageCompression);
var dr = ds.DataRegionConfigurations.Single();
Assert.AreEqual(1, dr.EmptyPagesPoolSize);
Assert.AreEqual(2, dr.EvictionThreshold);
Assert.AreEqual(3, dr.InitialSize);
Assert.AreEqual(4, dr.MaxSize);
Assert.AreEqual("reg2", dr.Name);
Assert.AreEqual(Core.Configuration.DataPageEvictionMode.RandomLru, dr.PageEvictionMode);
Assert.AreEqual(TimeSpan.FromSeconds(1), dr.MetricsRateTimeInterval);
Assert.AreEqual(5, dr.MetricsSubIntervalCount);
Assert.AreEqual("swap", dr.SwapPath);
Assert.IsTrue(dr.MetricsEnabled);
Assert.AreEqual(7, dr.CheckpointPageBufferSize);
dr = ds.DefaultDataRegionConfiguration;
Assert.AreEqual(2, dr.EmptyPagesPoolSize);
Assert.AreEqual(3, dr.EvictionThreshold);
Assert.AreEqual(4, dr.InitialSize);
Assert.AreEqual(5, dr.MaxSize);
Assert.AreEqual("reg1", dr.Name);
Assert.AreEqual(Core.Configuration.DataPageEvictionMode.Disabled, dr.PageEvictionMode);
Assert.AreEqual(TimeSpan.FromSeconds(3), dr.MetricsRateTimeInterval);
Assert.AreEqual(6, dr.MetricsSubIntervalCount);
Assert.AreEqual("swap2", dr.SwapPath);
Assert.IsFalse(dr.MetricsEnabled);
var sysDr = ds.SystemDataRegionConfiguration;
Assert.AreEqual(9, sysDr.InitialSize);
Assert.AreEqual(10, sysDr.MaxSize);
Assert.IsInstanceOf<SslContextFactory>(cfg.SslContextFactory);
Assert.IsInstanceOf<StopNodeOrHaltFailureHandler>(cfg.FailureHandler);
var failureHandler = (StopNodeOrHaltFailureHandler)cfg.FailureHandler;
Assert.IsTrue(failureHandler.TryStop);
Assert.AreEqual(TimeSpan.Parse("0:1:0"), failureHandler.Timeout);
var ec = cfg.ExecutorConfiguration;
Assert.NotNull(ec);
Assert.AreEqual(2, ec.Count);
Assert.AreEqual(new[] {"exec1", "exec2"}, ec.Select(e => e.Name));
Assert.AreEqual(new[] {1, 2}, ec.Select(e => e.Size));
Assert.AreEqual(AsyncContinuationExecutor.UnsafeSynchronous, cfg.AsyncContinuationExecutor);
}
/// <summary>
/// Tests the serialize deserialize.
/// </summary>
[Test]
public void TestSerializeDeserialize()
{
// Test custom
CheckSerializeDeserialize(GetTestConfig());
// Test custom with different culture to make sure numbers are serialized properly
RunWithCustomCulture(() => CheckSerializeDeserialize(GetTestConfig()));
// Test default
CheckSerializeDeserialize(new IgniteConfiguration());
}
/// <summary>
/// Tests that all properties are present in the schema.
/// </summary>
[Test]
public void TestAllPropertiesArePresentInSchema()
{
CheckAllPropertiesArePresentInSchema("IgniteConfigurationSection.xsd", "igniteConfiguration",
typeof(IgniteConfiguration));
}
/// <summary>
/// Checks that all properties are present in schema.
/// </summary>
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
public static void CheckAllPropertiesArePresentInSchema(string xsd, string sectionName, Type type)
{
var schema = XDocument.Load(xsd)
.Root.Elements()
.Single(x => x.Attribute("name").Value == sectionName);
CheckPropertyIsPresentInSchema(type, schema);
}
/// <summary>
/// Checks the property is present in schema.
/// </summary>
// ReSharper disable once UnusedParameter.Local
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
private static void CheckPropertyIsPresentInSchema(Type type, XElement schema)
{
Func<string, string> toLowerCamel = x => char.ToLowerInvariant(x[0]) + x.Substring(1);
foreach (var prop in type.GetProperties())
{
if (!prop.CanWrite)
continue; // Read-only properties are not configured in XML.
if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any())
continue; // Skip deprecated.
var propType = prop.PropertyType;
var isCollection = propType.IsGenericType &&
propType.GetGenericTypeDefinition() == typeof(ICollection<>);
if (isCollection)
propType = propType.GetGenericArguments().First();
var propName = toLowerCamel(prop.Name);
Assert.IsTrue(schema.Descendants().Select(x => x.Attribute("name"))
.Any(x => x != null && x.Value == propName),
"Property is missing in XML schema: " + propName);
var isComplexProp = propType.Namespace != null && propType.Namespace.StartsWith("Apache.Ignite.Core");
if (isComplexProp)
CheckPropertyIsPresentInSchema(propType, schema);
}
}
/// <summary>
/// Tests the schema validation.
/// </summary>
[Test]
public void TestSchemaValidation()
{
CheckSchemaValidation();
RunWithCustomCulture(CheckSchemaValidation);
// Check invalid xml
const string invalidXml =
@"<igniteConfiguration xmlns='http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection'>
<binaryConfiguration /><binaryConfiguration />
</igniteConfiguration>";
Assert.Throws<XmlSchemaValidationException>(() => CheckSchemaValidation(invalidXml));
}
/// <summary>
/// Tests the XML conversion.
/// </summary>
[Test]
public void TestToXml()
{
// Empty config
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine +
"<igniteConfiguration xmlns=\"http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection\" />",
new IgniteConfiguration().ToXml());
// Some properties
var cfg = new IgniteConfiguration
{
IgniteInstanceName = "myGrid",
ClientMode = true,
CacheConfiguration = new[]
{
new CacheConfiguration("myCache")
{
CacheMode = CacheMode.Replicated,
QueryEntities = new[]
{
new QueryEntity(typeof(int)),
new QueryEntity(typeof(int), typeof(string))
}
}
},
IncludedEventTypes = new[]
{
EventType.CacheEntryCreated,
EventType.CacheNodesLeft
}
};
Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?>
<igniteConfiguration clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection"">
<cacheConfiguration>
<cacheConfiguration cacheMode=""Replicated"" name=""myCache"">
<queryEntities>
<queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" />
<queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" />
</queryEntities>
</cacheConfiguration>
</cacheConfiguration>
<includedEventTypes>
<int>CacheEntryCreated</int>
<int>CacheNodesLeft</int>
</includedEventTypes>
</igniteConfiguration>"), cfg.ToXml());
// Custom section name and indent
var sb = new StringBuilder();
var settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " "
};
using (var xmlWriter = XmlWriter.Create(sb, settings))
{
cfg.ToXml(xmlWriter, "igCfg");
}
Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?>
<igCfg clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection"">
<cacheConfiguration>
<cacheConfiguration cacheMode=""Replicated"" name=""myCache"">
<queryEntities>
<queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" />
<queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" />
</queryEntities>
</cacheConfiguration>
</cacheConfiguration>
<includedEventTypes>
<int>CacheEntryCreated</int>
<int>CacheNodesLeft</int>
</includedEventTypes>
</igCfg>"), sb.ToString());
}
/// <summary>
/// Tests the deserialization.
/// </summary>
[Test]
public void TestFromXml()
{
// Empty section.
var cfg = IgniteConfiguration.FromXml("<x />");
AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg);
// Empty section with XML header.
cfg = IgniteConfiguration.FromXml("<?xml version=\"1.0\" encoding=\"utf-16\"?><x />");
AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg);
// Simple test.
cfg = IgniteConfiguration.FromXml(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />");
AssertExtensions.ReflectionEqual(new IgniteConfiguration {IgniteInstanceName = "myGrid", ClientMode = true}, cfg);
// Invalid xml.
var ex = Assert.Throws<ConfigurationErrorsException>(() =>
IgniteConfiguration.FromXml(@"<igCfg foo=""bar"" />"));
Assert.AreEqual("Invalid IgniteConfiguration attribute 'foo=bar', there is no such property " +
"on 'Apache.Ignite.Core.IgniteConfiguration'", ex.Message);
// Xml reader.
using (var xmlReader = XmlReader.Create(
new StringReader(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />")))
{
cfg = IgniteConfiguration.FromXml(xmlReader);
}
AssertExtensions.ReflectionEqual(new IgniteConfiguration { IgniteInstanceName = "myGrid", ClientMode = true }, cfg);
}
/// <summary>
/// Ensures windows-style \r\n line endings in a string literal.
/// Git settings may cause string literals in both styles.
/// </summary>
private static string FixLineEndings(string s)
{
return s.Split('\n').Select(x => x.TrimEnd('\r'))
.Aggregate((acc, x) => string.Format("{0}{1}{2}", acc, Environment.NewLine, x));
}
/// <summary>
/// Checks the schema validation.
/// </summary>
private static void CheckSchemaValidation()
{
CheckSchemaValidation(GetTestConfig().ToXml());
}
/// <summary>
/// Checks the schema validation.
/// </summary>
private static void CheckSchemaValidation(string xml)
{
var xmlns = "http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection";
var schemaFile = "IgniteConfigurationSection.xsd";
CheckSchemaValidation(xml, xmlns, schemaFile);
}
/// <summary>
/// Checks the schema validation.
/// </summary>
public static void CheckSchemaValidation(string xml, string xmlns, string schemaFile)
{
var document = new XmlDocument();
document.Schemas.Add(xmlns, XmlReader.Create(schemaFile));
document.Load(new StringReader(xml));
document.Validate(null);
}
/// <summary>
/// Checks the serialize deserialize.
/// </summary>
/// <param name="cfg">The config.</param>
private static void CheckSerializeDeserialize(IgniteConfiguration cfg)
{
var resCfg = SerializeDeserialize(cfg);
AssertExtensions.ReflectionEqual(cfg, resCfg);
}
/// <summary>
/// Serializes and deserializes a config.
/// </summary>
private static IgniteConfiguration SerializeDeserialize(IgniteConfiguration cfg)
{
var xml = cfg.ToXml();
return IgniteConfiguration.FromXml(xml);
}
/// <summary>
/// Gets the test configuration.
/// </summary>
private static IgniteConfiguration GetTestConfig()
{
return new IgniteConfiguration
{
IgniteInstanceName = "gridName",
JvmOptions = new[] {"1", "2"},
Localhost = "localhost11",
JvmClasspath = "classpath",
Assemblies = new[] {"asm1", "asm2", "asm3"},
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new[]
{
new BinaryTypeConfiguration
{
IsEnum = true,
KeepDeserialized = true,
AffinityKeyFieldName = "affKeyFieldName",
TypeName = "typeName",
IdMapper = new IdMapper(),
NameMapper = new NameMapper(),
Serializer = new TestSerializer()
},
new BinaryTypeConfiguration
{
IsEnum = false,
KeepDeserialized = false,
AffinityKeyFieldName = "affKeyFieldName",
TypeName = "typeName2",
Serializer = new BinaryReflectiveSerializer()
}
},
Types = new[] {typeof(string).FullName},
IdMapper = new IdMapper(),
KeepDeserialized = true,
NameMapper = new NameMapper(),
Serializer = new TestSerializer()
},
CacheConfiguration = new[]
{
new CacheConfiguration("cacheName")
{
AtomicityMode = CacheAtomicityMode.Transactional,
Backups = 15,
CacheMode = CacheMode.Replicated,
CacheStoreFactory = new TestCacheStoreFactory(),
CopyOnRead = false,
EagerTtl = false,
Invalidate = true,
KeepBinaryInStore = true,
LoadPreviousValue = true,
LockTimeout = TimeSpan.FromSeconds(56),
MaxConcurrentAsyncOperations = 24,
QueryEntities = new[]
{
new QueryEntity
{
Fields = new[]
{
new QueryField("field", typeof(int))
{
IsKeyField = true,
NotNull = true,
DefaultValue = "foo"
}
},
Indexes = new[]
{
new QueryIndex("field")
{
IndexType = QueryIndexType.FullText,
InlineSize = 32
}
},
Aliases = new[]
{
new QueryAlias("field.field", "fld")
},
KeyType = typeof(string),
ValueType = typeof(long),
TableName = "table-1",
KeyFieldName = "k",
ValueFieldName = "v"
},
},
ReadFromBackup = false,
RebalanceBatchSize = 33,
RebalanceDelay = TimeSpan.MaxValue,
RebalanceMode = CacheRebalanceMode.Sync,
RebalanceThrottle = TimeSpan.FromHours(44),
RebalanceTimeout = TimeSpan.FromMinutes(8),
SqlEscapeAll = true,
WriteBehindBatchSize = 45,
WriteBehindEnabled = true,
WriteBehindFlushFrequency = TimeSpan.FromSeconds(55),
WriteBehindFlushSize = 66,
WriteBehindFlushThreadCount = 2,
WriteBehindCoalescing = false,
WriteSynchronizationMode = CacheWriteSynchronizationMode.FullAsync,
NearConfiguration = new NearCacheConfiguration
{
NearStartSize = 5,
EvictionPolicy = new FifoEvictionPolicy
{
BatchSize = 19,
MaxMemorySize = 1024,
MaxSize = 555
}
},
PlatformCacheConfiguration = new PlatformCacheConfiguration
{
KeyTypeName = typeof(int).FullName,
ValueTypeName = typeof(string).FullName,
KeepBinary = true
},
EvictionPolicy = new LruEvictionPolicy
{
BatchSize = 18,
MaxMemorySize = 1023,
MaxSize = 554
},
AffinityFunction = new RendezvousAffinityFunction
{
ExcludeNeighbors = true,
Partitions = 48,
AffinityBackupFilter = new ClusterNodeAttributeAffinityBackupFilter
{
AttributeNames = new[] {"foo", "baz", "bar"}
}
},
ExpiryPolicyFactory = new MyPolicyFactory(),
EnableStatistics = true,
PluginConfigurations = new[]
{
new MyPluginConfiguration()
},
MemoryPolicyName = "somePolicy",
PartitionLossPolicy = PartitionLossPolicy.ReadOnlyAll,
GroupName = "abc",
SqlIndexMaxInlineSize = 24,
KeyConfiguration = new[]
{
new CacheKeyConfiguration
{
AffinityKeyFieldName = "abc",
TypeName = "def"
},
},
OnheapCacheEnabled = true,
StoreConcurrentLoadAllThreshold = 7,
RebalanceOrder = 3,
RebalanceBatchesPrefetchCount = 4,
MaxQueryIteratorsCount = 512,
QueryDetailMetricsSize = 100,
QueryParallelism = 16,
SqlSchema = "foo"
}
},
ClientMode = true,
DiscoverySpi = new TcpDiscoverySpi
{
NetworkTimeout = TimeSpan.FromSeconds(1),
SocketTimeout = TimeSpan.FromSeconds(2),
AckTimeout = TimeSpan.FromSeconds(3),
JoinTimeout = TimeSpan.FromSeconds(4),
MaxAckTimeout = TimeSpan.FromSeconds(5),
IpFinder = new TcpDiscoveryMulticastIpFinder
{
TimeToLive = 110,
MulticastGroup = "multicastGroup",
AddressRequestAttempts = 10,
MulticastPort = 987,
ResponseTimeout = TimeSpan.FromDays(1),
LocalAddress = "127.0.0.2",
Endpoints = new[] {"", "abc"}
},
ClientReconnectDisabled = true,
ForceServerMode = true,
IpFinderCleanFrequency = TimeSpan.FromMinutes(7),
LocalAddress = "127.0.0.1",
LocalPort = 49900,
LocalPortRange = 13,
ReconnectCount = 11,
StatisticsPrintFrequency = TimeSpan.FromSeconds(20),
ThreadPriority = 6,
TopologyHistorySize = 1234567
},
IgniteHome = "igniteHome",
IncludedEventTypes = EventType.CacheQueryAll,
JvmDllPath = @"c:\jvm",
JvmInitialMemoryMb = 1024,
JvmMaxMemoryMb = 2048,
LifecycleHandlers = new[] {new LifecycleBean(), new LifecycleBean()},
MetricsExpireTime = TimeSpan.FromSeconds(15),
MetricsHistorySize = 45,
MetricsLogFrequency = TimeSpan.FromDays(2),
MetricsUpdateFrequency = TimeSpan.MinValue,
NetworkSendRetryCount = 7,
NetworkSendRetryDelay = TimeSpan.FromSeconds(98),
NetworkTimeout = TimeSpan.FromMinutes(4),
SuppressWarnings = true,
WorkDirectory = @"c:\work",
IsDaemon = true,
UserAttributes = Enumerable.Range(1, 10).ToDictionary(x => x.ToString(),
x => x % 2 == 0 ? (object) x : new FooClass {Bar = x.ToString()}),
AtomicConfiguration = new AtomicConfiguration
{
CacheMode = CacheMode.Replicated,
AtomicSequenceReserveSize = 200,
Backups = 2
},
TransactionConfiguration = new TransactionConfiguration
{
PessimisticTransactionLogSize = 23,
DefaultTransactionIsolation = TransactionIsolation.ReadCommitted,
DefaultTimeout = TimeSpan.FromDays(2),
DefaultTransactionConcurrency = TransactionConcurrency.Optimistic,
PessimisticTransactionLogLinger = TimeSpan.FromHours(3)
},
CommunicationSpi = new TcpCommunicationSpi
{
LocalPort = 47501,
MaxConnectTimeout = TimeSpan.FromSeconds(34),
MessageQueueLimit = 15,
ConnectTimeout = TimeSpan.FromSeconds(17),
IdleConnectionTimeout = TimeSpan.FromSeconds(19),
SelectorsCount = 8,
ReconnectCount = 33,
SocketReceiveBufferSize = 512,
AckSendThreshold = 99,
DirectBuffer = false,
DirectSendBuffer = true,
LocalPortRange = 45,
LocalAddress = "127.0.0.1",
TcpNoDelay = false,
SlowClientQueueLimit = 98,
SocketSendBufferSize = 2045,
UnacknowledgedMessagesBufferSize = 3450
},
SpringConfigUrl = "test",
Logger = new ConsoleLogger(),
FailureDetectionTimeout = TimeSpan.FromMinutes(2),
ClientFailureDetectionTimeout = TimeSpan.FromMinutes(3),
LongQueryWarningTimeout = TimeSpan.FromDays(4),
PluginConfigurations = new[] {new TestIgnitePluginConfiguration()},
EventStorageSpi = new MemoryEventStorageSpi
{
ExpirationTimeout = TimeSpan.FromMilliseconds(12345),
MaxEventCount = 257
},
MemoryConfiguration = new MemoryConfiguration
{
ConcurrencyLevel = 3,
DefaultMemoryPolicyName = "somePolicy",
PageSize = 4,
SystemCacheInitialSize = 5,
SystemCacheMaxSize = 6,
MemoryPolicies = new[]
{
new MemoryPolicyConfiguration
{
Name = "myDefaultPlc",
PageEvictionMode = DataPageEvictionMode.Random2Lru,
InitialSize = 245 * 1024 * 1024,
MaxSize = 345 * 1024 * 1024,
EvictionThreshold = 0.88,
EmptyPagesPoolSize = 77,
SwapFilePath = "myPath1",
RateTimeInterval = TimeSpan.FromSeconds(22),
SubIntervals = 99
},
new MemoryPolicyConfiguration
{
Name = "customPlc",
PageEvictionMode = DataPageEvictionMode.RandomLru,
EvictionThreshold = 0.77,
EmptyPagesPoolSize = 66,
SwapFilePath = "somePath2",
MetricsEnabled = true
}
}
},
PeerAssemblyLoadingMode = PeerAssemblyLoadingMode.CurrentAppDomain,
ClientConnectorConfiguration = new ClientConnectorConfiguration
{
Host = "foo",
Port = 2,
PortRange = 3,
MaxOpenCursorsPerConnection = 4,
SocketReceiveBufferSize = 5,
SocketSendBufferSize = 6,
TcpNoDelay = false,
ThinClientEnabled = false,
OdbcEnabled = false,
JdbcEnabled = false,
ThreadPoolSize = 7,
IdleTimeout = TimeSpan.FromMinutes(5),
ThinClientConfiguration = new ThinClientConfiguration
{
MaxActiveTxPerConnection = 8,
MaxActiveComputeTasksPerConnection = 9
}
},
PersistentStoreConfiguration = new PersistentStoreConfiguration
{
AlwaysWriteFullPages = true,
CheckpointingFrequency = TimeSpan.FromSeconds(25),
CheckpointingPageBufferSize = 28 * 1024 * 1024,
CheckpointingThreads = 2,
LockWaitTime = TimeSpan.FromSeconds(5),
PersistentStorePath = Path.GetTempPath(),
TlbSize = 64 * 1024,
WalArchivePath = Path.GetTempPath(),
WalFlushFrequency = TimeSpan.FromSeconds(3),
WalFsyncDelayNanos = 3,
WalHistorySize = 10,
WalMode = WalMode.Background,
WalRecordIteratorBufferSize = 32 * 1024 * 1024,
WalSegments = 6,
WalSegmentSize = 5 * 1024 * 1024,
WalStorePath = Path.GetTempPath(),
SubIntervals = 25,
MetricsEnabled = true,
RateTimeInterval = TimeSpan.FromDays(1),
CheckpointWriteOrder = CheckpointWriteOrder.Random,
WriteThrottlingEnabled = true
},
IsActiveOnStart = false,
ConsistentId = "myId123",
LocalEventListeners = new[]
{
new LocalEventListener<IEvent>
{
EventTypes = new[] {1, 2},
Listener = new MyEventListener()
}
},
DataStorageConfiguration = new DataStorageConfiguration
{
AlwaysWriteFullPages = true,
CheckpointFrequency = TimeSpan.FromSeconds(25),
CheckpointThreads = 2,
LockWaitTime = TimeSpan.FromSeconds(5),
StoragePath = Path.GetTempPath(),
WalThreadLocalBufferSize = 64 * 1024,
WalArchivePath = Path.GetTempPath(),
WalFlushFrequency = TimeSpan.FromSeconds(3),
WalFsyncDelayNanos = 3,
WalHistorySize = 10,
WalMode = Core.Configuration.WalMode.None,
WalRecordIteratorBufferSize = 32 * 1024 * 1024,
WalSegments = 6,
WalSegmentSize = 5 * 1024 * 1024,
WalPath = Path.GetTempPath(),
MetricsEnabled = true,
MetricsSubIntervalCount = 7,
MetricsRateTimeInterval = TimeSpan.FromSeconds(9),
CheckpointWriteOrder = Core.Configuration.CheckpointWriteOrder.Sequential,
WriteThrottlingEnabled = true,
ConcurrencyLevel = 1,
PageSize = 5 * 1024,
WalAutoArchiveAfterInactivity = TimeSpan.FromSeconds(19),
WalForceArchiveTimeout = TimeSpan.FromSeconds(20),
WalPageCompression = DiskPageCompression.Lz4,
WalPageCompressionLevel = 10,
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
Name = "reg1",
EmptyPagesPoolSize = 50,
EvictionThreshold = 0.8,
InitialSize = 100 * 1024 * 1024,
MaxSize = 150 * 1024 * 1024,
MetricsEnabled = true,
PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru,
PersistenceEnabled = false,
MetricsRateTimeInterval = TimeSpan.FromMinutes(2),
MetricsSubIntervalCount = 6,
SwapPath = Path.GetTempPath(),
CheckpointPageBufferSize = 7
},
DataRegionConfigurations = new[]
{
new DataRegionConfiguration
{
Name = "reg2",
EmptyPagesPoolSize = 51,
EvictionThreshold = 0.7,
InitialSize = 101 * 1024 * 1024,
MaxSize = 151 * 1024 * 1024,
MetricsEnabled = false,
PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru,
PersistenceEnabled = false,
MetricsRateTimeInterval = TimeSpan.FromMinutes(3),
MetricsSubIntervalCount = 7,
SwapPath = Path.GetTempPath()
}
},
SystemDataRegionConfiguration = new SystemDataRegionConfiguration
{
InitialSize = 64 * 1024 * 1024,
MaxSize = 128 * 1024 * 1024,
}
},
SslContextFactory = new SslContextFactory(),
FailureHandler = new StopNodeOrHaltFailureHandler
{
TryStop = false,
Timeout = TimeSpan.FromSeconds(10)
},
SqlQueryHistorySize = 345,
JavaPeerClassLoadingEnabled = true,
ExecutorConfiguration = new[]
{
new ExecutorConfiguration
{
Name = "exec-1",
Size = 11
}
},
AsyncContinuationExecutor = AsyncContinuationExecutor.ThreadPool
};
}
/// <summary>
/// Runs the with custom culture.
/// </summary>
/// <param name="action">The action.</param>
private static void RunWithCustomCulture(Action action)
{
RunWithCulture(action, CultureInfo.InvariantCulture);
RunWithCulture(action, CultureInfo.GetCultureInfo("ru-RU"));
}
/// <summary>
/// Runs the with culture.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="cultureInfo">The culture information.</param>
private static void RunWithCulture(Action action, CultureInfo cultureInfo)
{
var oldCulture = Thread.CurrentThread.CurrentCulture;
try
{
Thread.CurrentThread.CurrentCulture = cultureInfo;
action();
}
finally
{
Thread.CurrentThread.CurrentCulture = oldCulture;
}
}
/// <summary>
/// Test bean.
/// </summary>
public class LifecycleBean : ILifecycleHandler
{
/// <summary>
/// Gets or sets the foo.
/// </summary>
/// <value>
/// The foo.
/// </value>
public int Foo { get; set; }
/// <summary>
/// This method is called when lifecycle event occurs.
/// </summary>
/// <param name="evt">Lifecycle event.</param>
public void OnLifecycleEvent(LifecycleEventType evt)
{
// No-op.
}
}
/// <summary>
/// Test mapper.
/// </summary>
public class NameMapper : IBinaryNameMapper
{
/// <summary>
/// Gets or sets the bar.
/// </summary>
/// <value>
/// The bar.
/// </value>
public string Bar { get; set; }
/// <summary>
/// Gets the type name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>
/// Type name.
/// </returns>
public string GetTypeName(string name)
{
return name;
}
/// <summary>
/// Gets the field name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>
/// Field name.
/// </returns>
public string GetFieldName(string name)
{
return name;
}
}
/// <summary>
/// Serializer.
/// </summary>
public class TestSerializer : IBinarySerializer
{
/** <inheritdoc /> */
public void WriteBinary(object obj, IBinaryWriter writer)
{
// No-op.
}
/** <inheritdoc /> */
public void ReadBinary(object obj, IBinaryReader reader)
{
// No-op.
}
}
/// <summary>
/// Test class.
/// </summary>
public class FooClass
{
public string Bar { get; set; }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return string.Equals(Bar, ((FooClass) obj).Bar);
}
public override int GetHashCode()
{
return Bar != null ? Bar.GetHashCode() : 0;
}
public static bool operator ==(FooClass left, FooClass right)
{
return Equals(left, right);
}
public static bool operator !=(FooClass left, FooClass right)
{
return !Equals(left, right);
}
}
/// <summary>
/// Test factory.
/// </summary>
public class TestCacheStoreFactory : IFactory<ICacheStore>
{
/// <summary>
/// Creates an instance of the cache store.
/// </summary>
/// <returns>
/// New instance of the cache store.
/// </returns>
public ICacheStore CreateInstance()
{
return null;
}
}
/// <summary>
/// Test logger.
/// </summary>
public class TestLogger : ILogger
{
/** <inheritdoc /> */
public void Log(LogLevel level, string message, object[] args, IFormatProvider formatProvider, string category,
string nativeErrorInfo, Exception ex)
{
throw new NotImplementedException();
}
/** <inheritdoc /> */
public bool IsEnabled(LogLevel level)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Test factory.
/// </summary>
public class MyPolicyFactory : IFactory<IExpiryPolicy>
{
/** <inheritdoc /> */
public IExpiryPolicy CreateInstance()
{
throw new NotImplementedException();
}
}
public class MyPluginConfiguration : ICachePluginConfiguration
{
int? ICachePluginConfiguration.CachePluginConfigurationClosureFactoryId
{
get { return 0; }
}
void ICachePluginConfiguration.WriteBinary(IBinaryRawWriter writer)
{
throw new NotImplementedException();
}
}
public class MyEventListener : IEventListener<IEvent>
{
public bool Invoke(IEvent evt)
{
throw new NotImplementedException();
}
}
}
}
| |
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
using Microsoft.WindowsAPICodePack.Shell.Interop;
using Microsoft.WindowsAPICodePack.Shell;
namespace Microsoft.WindowsAPICodePack.Taskbar
{
internal static class TabbedThumbnailNativeMethods
{
internal const int DisplayFrame = 0x00000001;
internal const int ForceIconicRepresentation = 7;
internal const int HasIconicBitmap = 10;
internal const uint WmDwmSendIconicThumbnail = 0x0323;
internal const uint WmDwmSendIconicLivePreviewBitmap = 0x0326;
internal const uint WaActive = 1;
internal const uint WaClickActive = 2;
internal const int ScClose = 0xF060;
internal const int ScMaximize = 0xF030;
internal const int ScMinimize = 0xF020;
internal const uint MsgfltAdd = 1;
internal const uint MsgfltRemove = 2;
[DllImport("dwmapi.dll")]
internal static extern int DwmSetIconicThumbnail(
IntPtr hwnd, IntPtr hbitmap, uint flags);
[DllImport("dwmapi.dll")]
internal static extern int DwmInvalidateIconicBitmaps(IntPtr hwnd);
[DllImport("dwmapi.dll")]
internal static extern int DwmSetIconicLivePreviewBitmap(
IntPtr hwnd,
IntPtr hbitmap,
ref NativePoint ptClient,
uint flags);
[DllImport("dwmapi.dll")]
internal static extern int DwmSetIconicLivePreviewBitmap(
IntPtr hwnd, IntPtr hbitmap, IntPtr ptClient, uint flags);
[DllImport("dwmapi.dll", PreserveSig = true)]
internal static extern int DwmSetWindowAttribute(
IntPtr hwnd,
//DWMWA_* values.
uint dwAttributeToSet,
IntPtr pvAttributeValue,
uint cbAttribute);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetWindowRect(IntPtr hwnd, ref NativeRect rect);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetClientRect(IntPtr hwnd, ref NativeRect rect);
internal static bool GetClientSize(IntPtr hwnd, out System.Drawing.Size size)
{
NativeRect rect = new NativeRect();
if (!GetClientRect(hwnd, ref rect))
{
size = new System.Drawing.Size(-1, -1);
return false;
}
size = new System.Drawing.Size(rect.Right, rect.Bottom);
return true;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ClientToScreen(
IntPtr hwnd,
ref NativePoint point);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool StretchBlt(
IntPtr hDestDC, int destX, int destY, int destWidth, int destHeight,
IntPtr hSrcDC, int srcX, int srcY, int srcWidth, int srcHeight,
uint operation);
[DllImport("user32.dll")]
internal static extern IntPtr GetWindowDC(IntPtr hwnd);
[DllImport("user32.dll")]
internal static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr ChangeWindowMessageFilter(uint message, uint dwFlag);
/// <summary>
/// Sets the specified iconic thumbnail for the specified window.
/// This is typically done in response to a DWM message.
/// </summary>
/// <param name="hwnd">The window handle.</param>
/// <param name="hBitmap">The thumbnail bitmap.</param>
internal static void SetIconicThumbnail(IntPtr hwnd, IntPtr hBitmap)
{
int rc = DwmSetIconicThumbnail(
hwnd,
hBitmap,
DisplayFrame);
if (rc != 0)
{
throw Marshal.GetExceptionForHR(rc);
}
}
/// <summary>
/// Sets the specified peek (live preview) bitmap for the specified
/// window. This is typically done in response to a DWM message.
/// </summary>
/// <param name="hwnd">The window handle.</param>
/// <param name="bitmap">The thumbnail bitmap.</param>
/// <param name="displayFrame">Whether to display a standard window
/// frame around the bitmap.</param>
internal static void SetPeekBitmap(IntPtr hwnd, IntPtr bitmap, bool displayFrame)
{
int rc = DwmSetIconicLivePreviewBitmap(
hwnd,
bitmap,
IntPtr.Zero,
displayFrame ? DisplayFrame : (uint)0);
if (rc != 0)
{
throw Marshal.GetExceptionForHR(rc);
}
}
/// <summary>
/// Sets the specified peek (live preview) bitmap for the specified
/// window. This is typically done in response to a DWM message.
/// </summary>
/// <param name="hwnd">The window handle.</param>
/// <param name="bitmap">The thumbnail bitmap.</param>
/// <param name="offset">The client area offset at which to display
/// the specified bitmap. The rest of the parent window will be
/// displayed as "remembered" by the DWM.</param>
/// <param name="displayFrame">Whether to display a standard window
/// frame around the bitmap.</param>
internal static void SetPeekBitmap(IntPtr hwnd, IntPtr bitmap, System.Drawing.Point offset, bool displayFrame)
{
var nativePoint = new NativePoint(offset.X, offset.Y);
int rc = DwmSetIconicLivePreviewBitmap(
hwnd,
bitmap,
ref nativePoint,
displayFrame ? DisplayFrame : (uint)0);
if (rc != 0)
{
Exception e = Marshal.GetExceptionForHR(rc);
if (e is ArgumentException)
{
// Ignore argument exception as it's not really recommended to be throwing
// exception when rendering the peek bitmap. If it's some other kind of exception,
// then throw it.
}
else
{
throw e;
}
}
}
/// <summary>
/// Call this method to either enable custom previews on the taskbar (second argument as true)
/// or to disable (second argument as false). If called with True, the method will call DwmSetWindowAttribute
/// for the specific window handle and let DWM know that we will be providing a custom bitmap for the thumbnail
/// as well as Aero peek.
/// </summary>
/// <param name="hwnd"></param>
/// <param name="enable"></param>
internal static void EnableCustomWindowPreview(IntPtr hwnd, bool enable)
{
IntPtr t = Marshal.AllocHGlobal(4);
Marshal.WriteInt32(t, enable ? 1 : 0);
try
{
int rc = DwmSetWindowAttribute(hwnd, HasIconicBitmap, t, 4);
if (rc != 0)
{
throw Marshal.GetExceptionForHR(rc);
}
rc = DwmSetWindowAttribute(hwnd, ForceIconicRepresentation, t, 4);
if (rc != 0)
{
throw Marshal.GetExceptionForHR(rc);
}
}
finally
{
Marshal.FreeHGlobal(t);
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Options;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Repl;
namespace Microsoft.PythonTools {
/// <summary>
/// Exposes language specific options for Python via automation. This object
/// can be fetched using Dte.GetObject("VsPython").
/// </summary>
[ComVisible(true)]
public sealed class PythonAutomation : IVsPython, IPythonOptions3, IPythonIntellisenseOptions {
private readonly IServiceProvider _serviceProvider;
private readonly PythonToolsService _pyService;
private AutomationInteractiveOptions _interactiveOptions;
internal PythonAutomation(IServiceProvider serviceProvider) {
_serviceProvider = serviceProvider;
_pyService = serviceProvider.GetPythonToolsService();
Debug.Assert(_pyService != null, "Did not find PythonToolsService");
}
#region IPythonOptions Members
IPythonIntellisenseOptions IPythonOptions.Intellisense {
get { return this; }
}
IPythonInteractiveOptions IPythonOptions.Interactive {
get {
if (_interactiveOptions == null) {
_interactiveOptions = new AutomationInteractiveOptions(_serviceProvider);
}
return _interactiveOptions;
}
}
bool IPythonOptions.PromptBeforeRunningWithBuildErrorSetting {
get {
return _pyService.DebuggerOptions.PromptBeforeRunningWithBuildError;
}
set {
_pyService.DebuggerOptions.PromptBeforeRunningWithBuildError = value;
_pyService.DebuggerOptions.Save();
}
}
Severity IPythonOptions.IndentationInconsistencySeverity {
get {
return _pyService.GeneralOptions.IndentationInconsistencySeverity;
}
set {
_pyService.GeneralOptions.IndentationInconsistencySeverity = value;
_pyService.GeneralOptions.Save();
}
}
bool IPythonOptions.AutoAnalyzeStandardLibrary {
get {
return _pyService.GeneralOptions.AutoAnalyzeStandardLibrary;
}
set {
_pyService.GeneralOptions.AutoAnalyzeStandardLibrary = value;
_pyService.GeneralOptions.Save();
}
}
bool IPythonOptions.TeeStandardOutput {
get {
return _pyService.DebuggerOptions.TeeStandardOutput;
}
set {
_pyService.DebuggerOptions.TeeStandardOutput = value;
_pyService.DebuggerOptions.Save();
}
}
bool IPythonOptions.WaitOnAbnormalExit {
get {
return _pyService.DebuggerOptions.WaitOnAbnormalExit;
}
set {
_pyService.DebuggerOptions.WaitOnAbnormalExit = value;
_pyService.DebuggerOptions.Save();
}
}
bool IPythonOptions.WaitOnNormalExit {
get {
return _pyService.DebuggerOptions.WaitOnNormalExit;
}
set {
_pyService.DebuggerOptions.WaitOnNormalExit = value;
_pyService.DebuggerOptions.Save();
}
}
bool IPythonOptions2.UseLegacyDebugger {
get {
return _pyService.DebuggerOptions.UseLegacyDebugger;
}
set {
_pyService.DebuggerOptions.UseLegacyDebugger = value;
_pyService.DebuggerOptions.Save();
}
}
bool IPythonOptions3.PromptForEnvCreate {
get {
return _pyService.GeneralOptions.PromptForEnvCreate;
}
set {
_pyService.GeneralOptions.PromptForEnvCreate = value;
_pyService.GeneralOptions.Save();
}
}
bool IPythonOptions3.PromptForPackageInstallation {
get {
return _pyService.GeneralOptions.PromptForPackageInstallation;
}
set {
_pyService.GeneralOptions.PromptForPackageInstallation = value;
_pyService.GeneralOptions.Save();
}
}
#endregion
#region IPythonIntellisenseOptions Members
bool IPythonIntellisenseOptions.AddNewLineAtEndOfFullyTypedWord {
get {
return _pyService.AdvancedOptions.AddNewLineAtEndOfFullyTypedWord;
}
set {
_pyService.AdvancedOptions.AddNewLineAtEndOfFullyTypedWord = value;
_pyService.AdvancedOptions.Save();
}
}
bool IPythonIntellisenseOptions.EnterCommitsCompletion {
get {
return _pyService.AdvancedOptions.EnterCommitsIntellisense;
}
set {
_pyService.AdvancedOptions.EnterCommitsIntellisense = value;
_pyService.AdvancedOptions.Save();
}
}
bool IPythonIntellisenseOptions.UseMemberIntersection {
get {
return _pyService.AdvancedOptions.IntersectMembers;
}
set {
_pyService.AdvancedOptions.IntersectMembers = value;
_pyService.AdvancedOptions.Save();
}
}
string IPythonIntellisenseOptions.CompletionCommittedBy {
get {
return _pyService.AdvancedOptions.CompletionCommittedBy;
}
set {
_pyService.AdvancedOptions.CompletionCommittedBy = value;
_pyService.AdvancedOptions.Save();
}
}
bool IPythonIntellisenseOptions.AutoListIdentifiers {
get {
return _pyService.AdvancedOptions.AutoListIdentifiers;
}
set {
_pyService.AdvancedOptions.AutoListIdentifiers = value;
_pyService.AdvancedOptions.Save();
}
}
#endregion
void IVsPython.OpenInteractive(string description) {
var compModel = _pyService.ComponentModel;
if (compModel == null) {
throw new InvalidOperationException("Could not activate component model");
}
var provider = compModel.GetService<InteractiveWindowProvider>();
var interpreters = compModel.GetService<IInterpreterRegistryService>();
var factory = interpreters.Configurations
.Where(PythonInterpreterFactoryExtensions.IsRunnable)
.FirstOrDefault(f => f.Description.Equals(description, StringComparison.CurrentCultureIgnoreCase));
if (factory == null) {
throw new KeyNotFoundException("Could not create interactive window with name: " + description);
}
var window = provider.OpenOrCreate(
PythonReplEvaluatorProvider.GetEvaluatorId(factory)
);
if (window == null) {
throw new InvalidOperationException("Could not create interactive window");
}
window.Show(true);
}
}
[ComVisible(true)]
public sealed class AutomationInteractiveOptions : IPythonInteractiveOptions {
private readonly IServiceProvider _serviceProvider;
public AutomationInteractiveOptions(IServiceProvider serviceProvider) {
_serviceProvider = serviceProvider;
}
internal PythonInteractiveOptions CurrentOptions {
get {
return _serviceProvider.GetPythonToolsService().InteractiveOptions;
}
}
private void SaveSettingsToStorage() {
CurrentOptions.Save();
}
bool IPythonInteractiveOptions.UseSmartHistory {
get {
return CurrentOptions.UseSmartHistory;
}
set {
CurrentOptions.UseSmartHistory = value;
SaveSettingsToStorage();
}
}
string IPythonInteractiveOptions.CompletionMode {
get {
return CurrentOptions.CompletionMode.ToString();
}
set {
ReplIntellisenseMode mode;
if (Enum.TryParse(value, out mode)) {
CurrentOptions.CompletionMode = mode;
SaveSettingsToStorage();
} else {
throw new InvalidOperationException(
String.Format(
"Bad intellisense mode, must be one of: {0}",
String.Join(", ", Enum.GetNames(typeof(ReplIntellisenseMode)))
)
);
}
}
}
string IPythonInteractiveOptions.StartupScripts {
get {
return CurrentOptions.Scripts;
}
set {
CurrentOptions.Scripts = value;
SaveSettingsToStorage();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: This class will encapsulate a byte and provide an
** Object representation of it.
**
**
===========================================================*/
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Byte : IComparable, IConvertible, IFormattable, IComparable<Byte>, IEquatable<Byte>
{
private byte m_value; // Do not rename (binary serialization)
// The maximum value that a Byte may represent: 255.
public const byte MaxValue = (byte)0xFF;
// The minimum value that a Byte may represent: 0.
public const byte MinValue = 0;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type byte, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (!(value is Byte))
{
throw new ArgumentException(SR.Arg_MustBeByte);
}
return m_value - (((Byte)value).m_value);
}
public int CompareTo(Byte value)
{
return m_value - value;
}
// Determines whether two Byte objects are equal.
public override bool Equals(Object obj)
{
if (!(obj is Byte))
{
return false;
}
return m_value == ((Byte)obj).m_value;
}
[NonVersionable]
public bool Equals(Byte obj)
{
return m_value == obj;
}
// Gets a hash code for this instance.
public override int GetHashCode()
{
return m_value;
}
[Pure]
public static byte Parse(String s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[Pure]
public static byte Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
[Pure]
public static byte Parse(String s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses an unsigned byte from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
[Pure]
public static byte Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
}
public static byte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
private static byte Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info)
{
int i = 0;
try
{
i = Number.ParseInt32(s, style, info);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Byte, e);
}
if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Byte);
return (byte)i;
}
public static bool TryParse(String s, out Byte result)
{
if (s == null)
{
result = 0;
return false;
}
return TryParse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null)
{
result = 0;
return false;
}
return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
}
public static bool TryParse(ReadOnlySpan<char> s, out byte result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Byte result)
{
result = 0;
int i;
if (!Number.TryParseInt32(s, style, info, out i))
{
return false;
}
if (i < MinValue || i > MaxValue)
{
return false;
}
result = (byte)i;
return true;
}
[Pure]
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
//
// IConvertible implementation
//
[Pure]
public TypeCode GetTypeCode()
{
return TypeCode.Byte;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return m_value;
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Configuration.ConfigurationManagerTest.cs - Unit tests
// for System.Configuration.ConfigurationManager.
//
// Author:
// Chris Toshok <toshok@ximian.com>
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2005-2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using Xunit;
using SysConfig = System.Configuration.Configuration;
namespace MonoTests.System.Configuration
{
using Util;
public class ConfigurationManagerTest
{
[Fact] // OpenExeConfiguration (ConfigurationUserLevel)
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19384")]
public void OpenExeConfiguration1_UserLevel_None()
{
SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
FileInfo fi = new FileInfo(config.FilePath);
Assert.Equal(TestUtil.ThisConfigFileName, fi.Name);
}
[Fact]
public void OpenExeConfiguration1_UserLevel_PerUserRoaming()
{
string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// If there is not ApplicationData folder PerUserRoaming won't work
if (string.IsNullOrEmpty(applicationData)) return;
SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
Assert.False(string.IsNullOrEmpty(config.FilePath), "should have some file path");
FileInfo fi = new FileInfo(config.FilePath);
Assert.Equal("user.config", fi.Name);
}
[Fact]
[ActiveIssue(15065, TestPlatforms.AnyUnix)]
public void OpenExeConfiguration1_UserLevel_PerUserRoamingAndLocal()
{
SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
FileInfo fi = new FileInfo(config.FilePath);
Assert.Equal("user.config", fi.Name);
}
[Fact] // OpenExeConfiguration (String)
public void OpenExeConfiguration2()
{
using (var temp = new TempDirectory())
{
string exePath;
SysConfig config;
exePath = Path.Combine(temp.Path, "DoesNotExist.whatever");
File.Create(exePath).Close();
config = ConfigurationManager.OpenExeConfiguration(exePath);
Assert.Equal(exePath + ".config", config.FilePath);
exePath = Path.Combine(temp.Path, "SomeExecutable.exe");
File.Create(exePath).Close();
config = ConfigurationManager.OpenExeConfiguration(exePath);
Assert.Equal(exePath + ".config", config.FilePath);
exePath = Path.Combine(temp.Path, "Foo.exe.config");
File.Create(exePath).Close();
config = ConfigurationManager.OpenExeConfiguration(exePath);
Assert.Equal(exePath + ".config", config.FilePath);
}
}
[Fact] // OpenExeConfiguration (String)
public void OpenExeConfiguration2_ExePath_DoesNotExist()
{
using (var temp = new TempDirectory())
{
string exePath = Path.Combine(temp.Path, "DoesNotExist.exe");
ConfigurationErrorsException ex = Assert.Throws<ConfigurationErrorsException>(
() => ConfigurationManager.OpenExeConfiguration(exePath));
// An error occurred loading a configuration file:
// The parameter 'exePath' is invalid
Assert.Equal(typeof(ConfigurationErrorsException), ex.GetType());
Assert.Null(ex.Filename);
Assert.NotNull(ex.InnerException);
Assert.Equal(0, ex.Line);
Assert.NotNull(ex.Message);
// The parameter 'exePath' is invalid
ArgumentException inner = ex.InnerException as ArgumentException;
Assert.NotNull(inner);
Assert.Equal(typeof(ArgumentException), inner.GetType());
Assert.Null(inner.InnerException);
Assert.NotNull(inner.Message);
Assert.Equal("exePath", inner.ParamName);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #18831")]
public void exePath_UserLevelNone()
{
string name = TestUtil.ThisApplicationPath;
SysConfig config = ConfigurationManager.OpenExeConfiguration(name);
Assert.Equal(TestUtil.ThisApplicationPath + ".config", config.FilePath);
}
[Fact]
public void exePath_UserLevelPerRoaming()
{
string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// If there is not ApplicationData folder PerUserRoaming won't work
if (string.IsNullOrEmpty(applicationData)) return;
Assert.True(Directory.Exists(applicationData), "application data should exist");
SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
string filePath = config.FilePath;
Assert.False(string.IsNullOrEmpty(filePath), "should have some file path");
Assert.True(filePath.StartsWith(applicationData), "#1:" + filePath);
Assert.Equal("user.config", Path.GetFileName(filePath));
}
[Fact]
[ActiveIssue(15066, TestPlatforms.AnyUnix)]
public void exePath_UserLevelPerRoamingAndLocal()
{
SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
string filePath = config.FilePath;
string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
Assert.True(filePath.StartsWith(applicationData), "#1:" + filePath);
Assert.Equal("user.config", Path.GetFileName(filePath));
}
[Fact]
public void mapped_UserLevelNone()
{
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "execonfig";
SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
FileInfo fi = new FileInfo(config.FilePath);
Assert.Equal("execonfig", fi.Name);
}
[Fact]
public void mapped_UserLevelPerRoaming()
{
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "execonfig";
map.RoamingUserConfigFilename = "roaminguser";
SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoaming);
FileInfo fi = new FileInfo(config.FilePath);
Assert.Equal("roaminguser", fi.Name);
}
[Fact]
// Doesn't pass on Mono
// [Category("NotWorking")]
public void mapped_UserLevelPerRoaming_no_execonfig()
{
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.RoamingUserConfigFilename = "roaminguser";
Assert.Throws<ArgumentException>(() => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoaming));
}
[Fact]
public void mapped_UserLevelPerRoamingAndLocal()
{
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "execonfig";
map.RoamingUserConfigFilename = "roaminguser";
map.LocalUserConfigFilename = "localuser";
SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal);
FileInfo fi = new FileInfo(config.FilePath);
Assert.Equal("localuser", fi.Name);
}
[Fact]
// Doesn't pass on Mono
// [Category("NotWorking")]
public void mapped_UserLevelPerRoamingAndLocal_no_execonfig()
{
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.RoamingUserConfigFilename = "roaminguser";
map.LocalUserConfigFilename = "localuser";
Assert.Throws<ArgumentException>(() => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal));
}
[Fact]
// Doesn't pass on Mono
// [Category("NotWorking")]
public void mapped_UserLevelPerRoamingAndLocal_no_roaminguser()
{
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "execonfig";
map.LocalUserConfigFilename = "localuser";
Assert.Throws<ArgumentException>(() => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal));
}
[Fact]
public void MachineConfig()
{
SysConfig config = ConfigurationManager.OpenMachineConfiguration();
FileInfo fi = new FileInfo(config.FilePath);
Assert.Equal("machine.config", fi.Name);
}
[Fact]
public void mapped_MachineConfig()
{
ConfigurationFileMap map = new ConfigurationFileMap();
map.MachineConfigFilename = "machineconfig";
SysConfig config = ConfigurationManager.OpenMappedMachineConfiguration(map);
FileInfo fi = new FileInfo(config.FilePath);
Assert.Equal("machineconfig", fi.Name);
}
[Fact]
// Doesn't pass on Mono
// [Category("NotWorking")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19384")]
public void mapped_ExeConfiguration_null()
{
SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(null, ConfigurationUserLevel.None);
FileInfo fi = new FileInfo(config.FilePath);
Assert.Equal(TestUtil.ThisConfigFileName, fi.Name);
}
[Fact]
// Doesn't pass on Mono
// [Category("NotWorking")]
public void mapped_MachineConfig_null()
{
SysConfig config = ConfigurationManager.OpenMappedMachineConfiguration(null);
FileInfo fi = new FileInfo(config.FilePath);
Assert.Equal("machine.config", fi.Name);
}
[Fact]
public void GetSectionReturnsNativeObject()
{
Assert.True(ConfigurationManager.GetSection("appSettings") is NameValueCollection);
}
[Fact] // Test for bug #3412
// Doesn't pass on Mono
// [Category("NotWorking")]
public void TestAddRemoveSection()
{
const string name = "testsection";
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// ensure not present
if (config.Sections.Get(name) != null)
{
config.Sections.Remove(name);
}
// add
config.Sections.Add(name, new TestSection());
// remove
var section = config.Sections.Get(name);
Assert.NotNull(section);
Assert.NotNull(section as TestSection);
config.Sections.Remove(name);
// add
config.Sections.Add(name, new TestSection());
// remove
section = config.Sections.Get(name);
Assert.NotNull(section);
Assert.NotNull(section as TestSection);
config.Sections.Remove(name);
}
[Fact]
public void TestFileMap()
{
using (var temp = new TempDirectory())
{
string configPath = Path.Combine(temp.Path, Path.GetRandomFileName() + ".config");
Assert.False(File.Exists(configPath));
var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = configPath;
var config = ConfigurationManager.OpenMappedExeConfiguration(
map, ConfigurationUserLevel.None);
config.Sections.Add("testsection", new TestSection());
config.Save();
Assert.True(File.Exists(configPath), "#1");
Assert.True(File.Exists(Path.GetFullPath(configPath)), "#2");
}
}
[Fact]
public void TestContext()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
const string name = "testsection";
// ensure not present
if (config.GetSection(name) != null)
config.Sections.Remove(name);
var section = new TestContextSection();
// Can't access EvaluationContext ....
Assert.Throws<ConfigurationErrorsException>(() => section.TestContext(null));
// ... until it's been added to a section.
config.Sections.Add(name, section);
section.TestContext("#2");
// Remove ...
config.Sections.Remove(name);
// ... and it doesn't lose its context
section.TestContext(null);
}
[Fact]
public void TestContext2()
{
using (var temp = new TempDirectory())
{
string configPath = Path.Combine(temp.Path, Path.GetRandomFileName() + ".config");
Assert.False(File.Exists(configPath));
var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = configPath;
var config = ConfigurationManager.OpenMappedExeConfiguration(
map, ConfigurationUserLevel.None);
config.Sections.Add("testsection", new TestSection());
config.Sections.Add("testcontext", new TestContextSection());
config.Save();
Assert.True(File.Exists(configPath), "#1");
}
}
class TestSection : ConfigurationSection { }
class TestContextSection : ConfigurationSection
{
public void TestContext(string label)
{
Assert.NotNull(EvaluationContext);
}
}
[Fact]
public void BadConfig()
{
using (var temp = new TempDirectory())
{
string xml = @" badXml";
var file = Path.Combine(temp.Path, "badConfig.config");
File.WriteAllText(file, xml);
var fileMap = new ConfigurationFileMap(file);
Assert.Equal(file,
Assert.Throws<ConfigurationErrorsException>(() => ConfigurationManager.OpenMappedMachineConfiguration(fileMap)).Filename);
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Xml;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using Xunit;
public class Log4JXmlTests : NLogTestBase
{
[Fact]
public void Log4JXmlTest()
{
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog throwExceptions='true'>
<targets>
<target name='debug' type='Debug' layout='${log4jxmlevent:includeCallSite=true:includeSourceInfo=true:includeNdlc=true:includeMdc=true:IncludeNdc=true:includeMdlc=true:IncludeAllProperties=true:ndcItemSeparator=\:\::includenlogdata=true:loggerName=${logger}}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>").LogFactory;
ScopeContext.Clear();
ScopeContext.PushProperty("foo1", "bar1");
ScopeContext.PushProperty("foo2", "bar2");
ScopeContext.PushProperty("foo3", "bar3");
ScopeContext.PushNestedState("baz1");
ScopeContext.PushNestedState("baz2");
ScopeContext.PushNestedState("baz3");
var logger = logFactory.GetLogger("A");
var logEventInfo = LogEventInfo.Create(LogLevel.Debug, "A", new Exception("Hello Exception", new Exception("Goodbye Exception")), null, "some message");
logEventInfo.Properties["nlogPropertyKey"] = "nlogPropertyValue";
logger.Log(logEventInfo);
string result = GetDebugLastMessage("debug", logFactory);
string wrappedResult = "<log4j:dummyRoot xmlns:log4j='http://log4j' xmlns:nlog='http://nlog'>" + result + "</log4j:dummyRoot>";
Assert.NotEqual("", result);
// make sure the XML can be read back and verify some fields
StringReader stringReader = new StringReader(wrappedResult);
var foundsChilds = new Dictionary<string, int>();
var requiredChilds = new List<string>
{
"log4j.event",
"log4j.message",
"log4j.NDC",
"log4j.locationInfo",
"nlog.locationInfo",
"log4j.properties",
"nlog.properties",
"log4j.throwable",
"log4j.data",
"nlog.data",
};
using (XmlReader reader = XmlReader.Create(stringReader))
{
while (reader.Read())
{
var key = reader.LocalName;
var fullKey = reader.Prefix + "." + key;
if (!foundsChilds.ContainsKey(fullKey))
{
foundsChilds[fullKey] = 0;
}
foundsChilds[fullKey]++;
if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "log4j")
{
switch (reader.LocalName)
{
case "dummyRoot":
break;
case "event":
Assert.Equal("DEBUG", reader.GetAttribute("level"));
Assert.Equal("A", reader.GetAttribute("logger"));
var epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long timestamp = Convert.ToInt64(reader.GetAttribute("timestamp"));
var time = epochStart.AddMilliseconds(timestamp);
var now = DateTime.UtcNow;
Assert.True(now.Ticks - time.Ticks < TimeSpan.FromSeconds(3).Ticks);
Assert.Equal(Thread.CurrentThread.ManagedThreadId.ToString(), reader.GetAttribute("thread"));
break;
case "message":
reader.Read();
Assert.Equal("some message", reader.Value);
break;
case "NDC":
reader.Read();
Assert.Equal("baz1::baz2::baz3", reader.Value);
break;
case "locationInfo":
Assert.Equal(MethodBase.GetCurrentMethod().DeclaringType.FullName, reader.GetAttribute("class"));
Assert.Equal(MethodBase.GetCurrentMethod().ToString(), reader.GetAttribute("method"));
break;
case "properties":
break;
case "throwable":
reader.Read();
Assert.Contains("Hello Exception", reader.Value);
Assert.Contains("Goodbye Exception", reader.Value);
break;
case "data":
string name = reader.GetAttribute("name");
string value = reader.GetAttribute("value");
switch (name)
{
case "log4japp":
Assert.Equal(AppDomain.CurrentDomain.FriendlyName + "(" + Process.GetCurrentProcess().Id + ")", value);
break;
case "log4jmachinename":
Assert.Equal(Environment.MachineName, value);
break;
case "foo1":
Assert.Equal("bar1", value);
break;
case "foo2":
Assert.Equal("bar2", value);
break;
case "foo3":
Assert.Equal("bar3", value);
break;
case "nlogPropertyKey":
Assert.Equal("nlogPropertyValue", value);
break;
default:
Assert.True(false, "Unknown <log4j:data>: " + name);
break;
}
break;
default:
throw new NotSupportedException("Unknown element: " + key);
}
continue;
}
if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "nlog")
{
switch (key)
{
case "eventSequenceNumber":
break;
case "locationInfo":
Assert.Equal(GetType().Assembly.FullName, reader.GetAttribute("assembly"));
break;
case "properties":
break;
case "data":
var name = reader.GetAttribute("name");
var value = reader.GetAttribute("value");
Assert.Equal("nlogPropertyKey", name);
Assert.Equal("nlogPropertyValue", value);
break;
default:
throw new NotSupportedException("Unknown element: " + key);
}
}
}
}
foreach (var required in requiredChilds)
{
Assert.True(foundsChilds.ContainsKey(required), $"{required} not found!");
}
}
[Fact]
public void Log4JXmlEventLayoutParameterTest()
{
var log4jLayout = new Log4JXmlEventLayout()
{
Parameters =
{
new NLogViewerParameterInfo
{
Name = "mt",
Layout = "${message:raw=true}",
}
},
};
log4jLayout.Renderer.AppInfo = "MyApp";
var logEventInfo = new LogEventInfo
{
LoggerName = "MyLOgger",
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56, DateTimeKind.Utc),
Level = LogLevel.Info,
Message = "hello, <{0}>",
Parameters = new[] { "world" },
};
var threadid = Environment.CurrentManagedThreadId;
var machinename = Environment.MachineName;
Assert.Equal($"<log4j:event logger=\"MyLOgger\" level=\"INFO\" timestamp=\"1262349296000\" thread=\"{threadid}\"><log4j:message>hello, <world></log4j:message><log4j:properties><log4j:data name=\"mt\" value=\"hello, <{{0}}>\" /><log4j:data name=\"log4japp\" value=\"MyApp\" /><log4j:data name=\"log4jmachinename\" value=\"{machinename}\" /></log4j:properties></log4j:event>", log4jLayout.Render(logEventInfo));
}
[Fact]
public void BadXmlValueTest()
{
var sb = new System.Text.StringBuilder();
var forbidden = new HashSet<int>();
int start = 64976; int end = 65007;
for (int i = start; i <= end; i++)
{
forbidden.Add(i);
}
forbidden.Add(0xFFFE);
forbidden.Add(0xFFFF);
for (int i = char.MinValue; i <= char.MaxValue; i++)
{
char c = Convert.ToChar(i);
if (char.IsSurrogate(c))
{
continue; // skip surrogates
}
if (forbidden.Contains(c))
{
continue;
}
sb.Append(c);
}
var badString = sb.ToString();
var settings = new XmlWriterSettings
{
Indent = true,
ConformanceLevel = ConformanceLevel.Fragment,
IndentChars = " ",
};
sb.Length = 0;
using (XmlWriter xtw = XmlWriter.Create(sb, settings))
{
xtw.WriteStartElement("log4j", "event", "http:://hello/");
xtw.WriteElementSafeString("log4j", "message", "http:://hello/", badString);
xtw.WriteEndElement();
xtw.Flush();
}
string goodString = null;
using (XmlReader reader = XmlReader.Create(new StringReader(sb.ToString())))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Text)
{
if (reader.Value.Contains("abc"))
goodString = reader.Value;
}
}
}
Assert.NotNull(goodString);
Assert.NotEqual(badString.Length, goodString.Length);
Assert.Contains("abc", badString);
Assert.Contains("abc", goodString);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Xunit;
namespace CoreXml.Test.XLinq.FunctionalTests.EventsTests
{
public class EventsAddBeforeSelf
{
public static object[][] ExecuteXDocumentVariationParams = new object[][] {
new object[] { new XNode[] { new XElement("element") }, new XComment("Comment") },
new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, new XProcessingInstruction("PI", "Data") },
new object[] { new XNode[] { new XDocumentType("root", "", "", "") }, new XElement("root") },
new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, new XText(" ") },
new object[] { new XNode[] { new XComment("Comment") }, new XDocumentType("root", "", "", "") },
new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, new XText(" ") }
};
[Theory, MemberData(nameof(ExecuteXDocumentVariationParams))]
public void ExecuteXDocumentVariation(XNode[] toAdd, XNode contextNode)
{
IEnumerable<XNode> toAddList = toAdd.OfType<XNode>();
XDocument xDoc = new XDocument(contextNode);
XDocument xDocOriginal = new XDocument(xDoc);
using (UndoManager undo = new UndoManager(xDoc))
{
undo.Group();
using (EventsHelper docHelper = new EventsHelper(xDoc))
{
using (EventsHelper nodeHelper = new EventsHelper(contextNode))
{
contextNode.AddBeforeSelf(toAdd);
Assert.True(toAddList.SequenceEqual(contextNode.NodesBeforeSelf(), XNode.EqualityComparer), "Nodes not added correctly!");
nodeHelper.Verify(0);
}
docHelper.Verify(XObjectChange.Add, toAdd);
}
undo.Undo();
Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!");
}
}
public static object[][] ExecuteXElementVariationParams = new object[][] {
new object[] { new XNode[] { new XElement("element") }, new XText("some text") },
new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, new XProcessingInstruction("PI", "Data") },
new object[] { new XNode[] { new XCData("x+y >= z-m") }, new XElement("child") },
new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, new XText(" ") },
new object[] { new XNode[] { new XComment("Comment") }, new XCData("x+y >= z-m") },
new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, new XText(" ") },
new object[] { InputSpace.GetElement(100, 10).DescendantNodes().ToArray(), new XText("..") }
};
[Theory, MemberData(nameof(ExecuteXElementVariationParams))]
public void ExecuteXElementVariation(XNode[] toAdd, XNode contextNode)
{
IEnumerable<XNode> toAddList = toAdd.OfType<XNode>();
XElement xElem = new XElement("root", contextNode);
XElement xElemOriginal = new XElement(xElem);
using (UndoManager undo = new UndoManager(xElem))
{
undo.Group();
using (EventsHelper elemHelper = new EventsHelper(xElem))
{
using (EventsHelper nodeHelper = new EventsHelper(contextNode))
{
contextNode.AddBeforeSelf(toAdd);
Assert.True(toAddList.SequenceEqual(contextNode.NodesBeforeSelf(), XNode.EqualityComparer), "Nodes not added correctly!");
nodeHelper.Verify(0);
}
elemHelper.Verify(XObjectChange.Add, toAdd);
}
undo.Undo();
Assert.True(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!");
Assert.True(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!");
}
}
[Fact]
public void XDocumentAddNull()
{
XElement xElem = new XElement("root", "text");
EventsHelper elemHelper = new EventsHelper(xElem);
xElem.FirstNode.AddBeforeSelf(null);
elemHelper.Verify(0);
}
[Fact]
public void XElementWorkOnTextNodes1()
{
XElement elem = new XElement("A", "text2");
XNode n = elem.FirstNode;
using (UndoManager undo = new UndoManager(elem))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(elem))
{
n.AddBeforeSelf("text0");
Assert.Equal("text0text2", elem.Value);
n.AddBeforeSelf("text1");
Assert.Equal("text0text1text2", elem.Value);
eHelper.Verify(new XObjectChange[] { XObjectChange.Add, XObjectChange.Value });
}
undo.Undo();
Assert.Equal("text2", elem.Value);
}
}
[Fact]
public void XElementWorkOnTextNodes2()
{
XElement elem = new XElement("A", "text2");
XNode n = elem.FirstNode;
using (UndoManager undo = new UndoManager(elem))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(elem))
{
n.AddBeforeSelf("text0", "text1");
Assert.Equal("text0text1text2", elem.Value);
eHelper.Verify(XObjectChange.Add);
}
undo.Undo();
Assert.Equal("text2", elem.Value);
}
}
}
public class EventsAddAfterSelf
{
public static object[][] ExecuteXDocumentVariationParams = new object[][] {
new object [] { new XNode[] { new XElement("element") }, new XComment("Comment") },
new object [] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, new XProcessingInstruction("PI", "Data") },
new object [] { new XNode[] { new XDocumentType("root", "", "", "") }, new XText(" ") },
new object [] { new XNode[] { new XProcessingInstruction("PI", "Data") }, new XText(" ") },
new object [] { new XNode[] { new XComment("Comment") }, new XElement("root") },
new object [] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, new XText(" ") }
};
[Theory, MemberData(nameof(ExecuteXDocumentVariationParams))]
public void ExecuteXDocumentVariation(XNode[] toAdd, XNode contextNode)
{
IEnumerable<XNode> toAddList = toAdd.OfType<XNode>();
XDocument xDoc = new XDocument(contextNode);
XDocument xDocOriginal = new XDocument(xDoc);
using (UndoManager undo = new UndoManager(xDoc))
{
undo.Group();
using (EventsHelper docHelper = new EventsHelper(xDoc))
{
using (EventsHelper nodeHelper = new EventsHelper(contextNode))
{
contextNode.AddAfterSelf(toAdd);
Assert.True(toAddList.SequenceEqual(contextNode.NodesAfterSelf(), XNode.EqualityComparer), "Nodes not added correctly!");
nodeHelper.Verify(0);
}
docHelper.Verify(XObjectChange.Add, toAdd);
}
undo.Undo();
Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!");
}
}
public static object[][] ExecuteXElementVariationParams = new object[][] {
new object[] { new XNode[] { new XElement("element") }, new XText("some text") },
new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, new XProcessingInstruction("PI", "Data") },
new object[] { new XNode[] { new XCData("x+y >= z-m") }, new XElement("child") },
new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, new XText(" ") },
new object[] { new XNode[] { new XComment("Comment") }, new XCData("x+y >= z-m") },
new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, new XText(" ") },
new object[] { InputSpace.GetElement(100, 10).DescendantNodes().ToArray(), new XText("..") }
};
[Theory, MemberData(nameof(ExecuteXElementVariationParams))]
public void ExecuteXElementVariation(XNode[] toAdd, XNode contextNode)
{
IEnumerable<XNode> toAddList = toAdd.OfType<XNode>();
XElement xElem = new XElement("root", contextNode);
XElement xElemOriginal = new XElement(xElem);
using (UndoManager undo = new UndoManager(xElem))
{
undo.Group();
using (EventsHelper elemHelper = new EventsHelper(xElem))
{
using (EventsHelper nodeHelper = new EventsHelper(contextNode))
{
contextNode.AddAfterSelf(toAdd);
Assert.True(toAddList.SequenceEqual(contextNode.NodesAfterSelf(), XNode.EqualityComparer), "Nodes not added correctly!");
nodeHelper.Verify(0);
}
elemHelper.Verify(XObjectChange.Add, toAdd);
}
undo.Undo();
Assert.True(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!");
Assert.True(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!");
}
}
[Fact]
public void XElementAddNull()
{
XElement xElem = new XElement("root", "text");
EventsHelper elemHelper = new EventsHelper(xElem);
xElem.LastNode.AddAfterSelf(null);
elemHelper.Verify(0);
}
[Fact]
public void XElementWorkOnTextNodes1()
{
XElement elem = new XElement("A", "text2");
XNode n = elem.FirstNode;
using (UndoManager undo = new UndoManager(elem))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(elem))
{
n.AddAfterSelf("text0");
Assert.Equal("text2text0", elem.Value);
n.AddAfterSelf("text1");
Assert.Equal("text2text0text1", elem.Value);
eHelper.Verify(new XObjectChange[] { XObjectChange.Value, XObjectChange.Value });
}
undo.Undo();
Assert.Equal("text2", elem.Value);
}
}
[Fact]
public void XElementWorkOnTextNodes2()
{
XElement elem = new XElement("A", "text2");
XNode n = elem.FirstNode;
using (UndoManager undo = new UndoManager(elem))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(elem))
{
n.AddAfterSelf("text0", "text1");
Assert.Equal("text2text0text1", elem.Value);
eHelper.Verify(XObjectChange.Value);
}
undo.Undo();
Assert.Equal("text2", elem.Value);
}
}
}
public class EventsAddFirst
{
public static object[][] ExecuteXDocumentVariationParams = new object[][] {
new object [] { new XNode[] { new XElement("element") }, null },
new object [] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, null },
new object [] { new XNode[] { new XDocumentType("root", "", "", "") }, null },
new object [] { new XNode[] { new XProcessingInstruction("PI", "Data") }, null },
new object [] { new XNode[] { new XComment("Comment") }, null },
new object [] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, null },
new object [] { new XNode[] { new XElement("element") }, new XComment("Comment") },
new object [] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, new XProcessingInstruction("PI", "Data") },
new object [] { new XNode[] { new XDocumentType("root", "", "", "") }, new XText(" ") },
new object [] { new XNode[] { new XProcessingInstruction("PI", "Data") }, new XText(" ") },
new object [] { new XNode[] { new XComment("Comment") }, new XElement("root") },
new object [] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, new XText(" ") }
};
[Theory, MemberData(nameof(ExecuteXDocumentVariationParams))]
public void ExecuteXDocumentVariation(XNode[] toAdd, XNode contextNode)
{
IEnumerable<XNode> allNodes, toAddList = toAdd.OfType<XNode>();
XDocument xDoc = contextNode == null ? new XDocument() : new XDocument(contextNode);
XDocument xDocOriginal = new XDocument(xDoc);
using (UndoManager undo = new UndoManager(xDoc))
{
undo.Group();
using (EventsHelper docHelper = new EventsHelper(xDoc))
{
xDoc.AddFirst(toAdd);
allNodes = contextNode == null ? xDoc.Nodes() : contextNode.NodesBeforeSelf();
Assert.True(toAddList.SequenceEqual(allNodes, XNode.EqualityComparer), "Nodes not added correctly!");
docHelper.Verify(XObjectChange.Add, toAdd);
}
undo.Undo();
Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!");
}
}
public static object[][] ExecuteXElementVariationParams = new object[][] {
new object[] { new XNode[] { new XElement("element") }, null },
new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, null },
new object[] { new XNode[] { new XCData("x+y >= z-m") }, null },
new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, null },
new object[] { new XNode[] { new XComment("Comment") }, null },
new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, null },
new object[] { InputSpace.GetElement(100, 10).DescendantNodes().ToArray(), null },
new object[] { new XNode[] { new XElement("element") }, new XText("some text") },
new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, new XProcessingInstruction("PI", "Data") },
new object[] { new XNode[] { new XCData("x+y >= z-m") }, new XElement("child") },
new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, new XText(" ") },
new object[] { new XNode[] { new XComment("Comment") }, new XCData("x+y >= z-m") },
new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, new XText(" ") },
new object[] { InputSpace.GetElement(100, 10).DescendantNodes().ToArray(), new XText("..") }
};
[Theory, MemberData(nameof(ExecuteXElementVariationParams))]
public void ExecuteXElementVariation(XNode[] toAdd, XNode contextNode)
{
IEnumerable<XNode> allNodes, toAddList = toAdd.OfType<XNode>();
XElement xElem = contextNode == null ? new XElement("root") : new XElement("root", contextNode);
XElement xElemOriginal = new XElement(xElem);
using (UndoManager undo = new UndoManager(xElem))
{
undo.Group();
using (EventsHelper elemHelper = new EventsHelper(xElem))
{
xElem.AddFirst(toAdd);
allNodes = contextNode == null ? xElem.Nodes() : contextNode.NodesBeforeSelf();
Assert.True(toAddList.SequenceEqual(allNodes, XNode.EqualityComparer), "Nodes not added correctly!");
elemHelper.Verify(XObjectChange.Add, toAdd);
}
undo.Undo();
Assert.True(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!");
Assert.True(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!");
}
}
[Fact]
public void XElementAddNull()
{
XElement xElem = new XElement("root", "text");
EventsHelper elemHelper = new EventsHelper(xElem);
xElem.AddFirst(null);
elemHelper.Verify(0);
}
[Fact]
public void XElementWorkOnTextNodes1()
{
XElement elem = new XElement("A", "text2");
using (UndoManager undo = new UndoManager(elem))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(elem))
{
elem.AddFirst("text0");
Assert.Equal("text0text2", elem.Value);
elem.AddFirst("text1");
Assert.Equal("text1text0text2", elem.Value);
eHelper.Verify(new XObjectChange[] { XObjectChange.Add, XObjectChange.Add });
}
undo.Undo();
Assert.Equal("text2", elem.Value);
}
}
[Fact]
public void XElementWorkOnTextNodes2()
{
XElement elem = new XElement("A", "text2");
using (UndoManager undo = new UndoManager(elem))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(elem))
{
elem.AddFirst("text0", "text1");
Assert.Equal("text0text1text2", elem.Value);
eHelper.Verify(XObjectChange.Add);
}
undo.Undo();
Assert.Equal("text2", elem.Value);
}
}
[Fact]
public void XElementStringContent()
{
bool firstTime = true;
XElement element = XElement.Parse("<root/>");
element.Changing += new EventHandler<XObjectChangeEventArgs>(
delegate (object sender, XObjectChangeEventArgs e)
{
if (firstTime)
{
firstTime = false;
element.AddFirst("Value");
}
});
Assert.Throws<InvalidOperationException>(() => { element.AddFirst(""); });
element.Verify();
}
[Fact]
public void XElementParentedXNode()
{
bool firstTime = true;
XElement element = XElement.Parse("<root></root>");
XElement child = new XElement("Add", "Me");
XElement newElement = new XElement("new", "element");
element.Changing += new EventHandler<XObjectChangeEventArgs>(
delegate (object sender, XObjectChangeEventArgs e)
{
if (firstTime)
{
firstTime = false;
newElement.Add(child);
}
});
Assert.Throws<InvalidOperationException>(() => { element.AddFirst(child); });
element.Verify();
Assert.Null(element.Element("Add"));
}
}
public class EventsAdd
{
public static object[][] ExecuteXDocumentVariationParams = new object[][] {
new object[] { new XNode[] { new XElement("element") }, null },
new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, null },
new object[] { new XNode[] { new XDocumentType("root", "", "", "") }, null },
new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, null },
new object[] { new XNode[] { new XComment("Comment") }, null },
new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, null },
new object[] { new XNode[] { new XElement("element") }, new XComment("Comment") },
new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, new XProcessingInstruction("PI", "Data") },
new object[] { new XNode[] { new XDocumentType("root", "", "", "") }, new XText(" ") },
new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, new XText(" ") },
new object[] { new XNode[] { new XComment("Comment") }, new XElement("root") },
new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, new XText(" ") }
};
[Theory, MemberData(nameof(ExecuteXDocumentVariationParams))]
public void ExecuteXDocumentVariation(XNode[] toAdd, XNode contextNode)
{
IEnumerable<XNode> allNodes, toAddList = toAdd.OfType<XNode>();
XDocument xDoc = contextNode == null ? new XDocument() : new XDocument(contextNode);
XDocument xDocOriginal = new XDocument(xDoc);
using (UndoManager undo = new UndoManager(xDoc))
{
undo.Group();
using (EventsHelper docHelper = new EventsHelper(xDoc))
{
xDoc.Add(toAdd);
allNodes = contextNode == null ? xDoc.Nodes() : contextNode.NodesAfterSelf();
Assert.True(toAddList.SequenceEqual(allNodes, XNode.EqualityComparer), "Nodes not added correctly!");
docHelper.Verify(XObjectChange.Add, toAdd);
}
undo.Undo();
Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!");
}
}
public static object[][] VariationsForXElementParams = new object[][] {
new object[] { new XNode[] { new XElement("element") }, null },
new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, null },
new object[] { new XNode[] { new XCData("x+y >= z-m") }, null },
new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, null },
new object[] { new XNode[] { new XComment("Comment") }, null },
new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, null },
new object[] { InputSpace.GetElement(100, 10).DescendantNodes().ToArray(), null },
new object[] { new XNode[] { new XElement("element") }, new XText("some text") },
new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, new XProcessingInstruction("PI", "Data") },
new object[] { new XNode[] { new XCData("x+y >= z-m") }, new XElement("child") },
new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, new XText(" ") },
new object[] { new XNode[] { new XComment("Comment") }, new XCData("x+y >= z-m") },
new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, new XText(" ") },
new object[] { InputSpace.GetElement(100, 10).DescendantNodes().ToArray(), new XText("..") }
};
[Theory, MemberData(nameof(VariationsForXElementParams))]
public void ExecuteXElementVariation(XNode[] toAdd, XNode contextNode)
{
IEnumerable<XNode> allNodes, toAddList = toAdd.OfType<XNode>();
XElement xElem = contextNode == null ? new XElement("root") : new XElement("root", contextNode);
XElement xElemOriginal = new XElement(xElem);
using (UndoManager undo = new UndoManager(xElem))
{
undo.Group();
using (EventsHelper elemHelper = new EventsHelper(xElem))
{
xElem.Add(toAdd);
allNodes = contextNode == null ? xElem.Nodes() : contextNode.NodesAfterSelf();
Assert.True(toAddList.SequenceEqual(allNodes, XNode.EqualityComparer), "Nodes not added correctly!");
elemHelper.Verify(XObjectChange.Add, toAdd);
}
undo.Undo();
Assert.True(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!");
Assert.True(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!");
}
}
public static object[][] ExecuteXAttributeVariationParams = new object[][] {
new object[] { new XAttribute[] { new XAttribute("xxx", "yyy") }, null },
new object[] { new XAttribute[] { new XAttribute("{a}xxx", "a_yyy") }, null },
new object[] { InputSpace.GetElement(100, 10).Attributes().ToArray(), null },
new object[] { new XAttribute[] { new XAttribute("xxx", "yyy") }, new XAttribute("a", "aa") },
new object[] { new XAttribute[] { new XAttribute("{b}xxx", "b_yyy") }, new XAttribute("a", "aa") },
new object[] { InputSpace.GetElement(100, 10).Attributes().ToArray(), new XAttribute("a", "aa") }
};
[Theory, MemberData(nameof(ExecuteXAttributeVariationParams))]
public void ExecuteXAttributeVariation(XAttribute[] toAdd, XAttribute contextNode)
{
IEnumerable<XAttribute> allNodes, toAddList = toAdd.OfType<XAttribute>();
XElement xElem = contextNode == null ? new XElement("root") : new XElement("root", contextNode);
XElement xElemOriginal = new XElement(xElem);
using (UndoManager undo = new UndoManager(xElem))
{
undo.Group();
using (EventsHelper elemHelper = new EventsHelper(xElem))
{
xElem.Add(toAdd);
allNodes = contextNode == null ? xElem.Attributes() : xElem.Attributes().Skip(1);
Assert.True(toAddList.SequenceEqual(allNodes, Helpers.MyAttributeComparer), "Attributes not added correctly!");
elemHelper.Verify(XObjectChange.Add, toAdd);
}
undo.Undo();
Assert.True(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!");
Assert.True(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!");
}
}
[Fact]
public void XAttributeXAttributeAddAtDeepLevel()
{
XDocument xDoc = new XDocument(InputSpace.GetAttributeElement(100, 10));
XDocument xDocOriginal = new XDocument(xDoc);
using (UndoManager undo = new UndoManager(xDoc))
{
undo.Group();
using (EventsHelper docHelper = new EventsHelper(xDoc))
{
using (EventsHelper eHelper = new EventsHelper(xDoc.Root))
{
foreach (XElement x in xDoc.Root.Descendants())
{
x.Add(new XAttribute("at", "value"));
eHelper.Verify(XObjectChange.Add);
}
docHelper.Verify(XObjectChange.Add, xDoc.Root.Descendants().Count());
}
}
undo.Undo();
Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!");
}
}
[Fact]
public void XElementXElementAddAtDeepLevel()
{
XDocument xDoc = new XDocument(InputSpace.GetElement(100, 10));
XDocument xDocOriginal = new XDocument(xDoc);
using (UndoManager undo = new UndoManager(xDoc))
{
undo.Group();
using (EventsHelper docHelper = new EventsHelper(xDoc))
{
using (EventsHelper eHelper = new EventsHelper(xDoc.Root))
{
foreach (XElement x in xDoc.Root.Descendants())
{
x.Add(new XText("Add Me"));
eHelper.Verify(XObjectChange.Add);
}
docHelper.Verify(XObjectChange.Add, xDoc.Root.Descendants().Count());
}
}
undo.Undo();
Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!");
}
}
[Fact]
public void XElementWorkTextNodes()
{
XElement elem = new XElement("A", "text2");
XElement xElemOriginal = new XElement(elem);
using (UndoManager undo = new UndoManager(elem))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(elem))
{
XNode x = elem.LastNode;
eHelper.Verify(0);
}
undo.Undo();
Assert.True(XNode.DeepEquals(elem, xElemOriginal), "Undo did not work!");
}
}
[Fact]
public void XElementWorkOnTextNodes1()
{
XElement elem = new XElement("A", "text2");
using (UndoManager undo = new UndoManager(elem))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(elem))
{
elem.Add("text0");
Assert.Equal("text2text0", elem.Value);
elem.Add("text1");
Assert.Equal("text2text0text1", elem.Value);
eHelper.Verify(new XObjectChange[] { XObjectChange.Value, XObjectChange.Value });
}
undo.Undo();
Assert.Equal("text2", elem.Value);
}
}
[Fact]
public void XElementWorkOnTextNodes2()
{
XElement elem = new XElement("A", "text2");
XElement xElemOriginal = new XElement(elem);
using (UndoManager undo = new UndoManager(elem))
{
undo.Group();
using (EventsHelper eHelper = new EventsHelper(elem))
{
elem.Add("text0", "text1");
Assert.Equal("text2text0text1", elem.Value);
eHelper.Verify(new XObjectChange[] { XObjectChange.Value, XObjectChange.Value });
}
undo.Undo();
Assert.Equal("text2", elem.Value);
}
}
[Fact]
public void XElementStringContent()
{
bool firstTime = true;
XElement element = XElement.Parse("<root/>");
element.Changing += new EventHandler<XObjectChangeEventArgs>(
delegate (object sender, XObjectChangeEventArgs e)
{
if (firstTime)
{
firstTime = false;
element.Add("Value");
}
});
Assert.Throws<InvalidOperationException>(() => { element.Add(""); });
element.Verify();
}
[Fact]
public void XElementParentedXNode()
{
bool firstTime = true;
XElement element = XElement.Parse("<root></root>");
XElement child = new XElement("Add", "Me");
XElement newElement = new XElement("new", "element");
element.Changing += new EventHandler<XObjectChangeEventArgs>(
delegate (object sender, XObjectChangeEventArgs e)
{
if (firstTime)
{
firstTime = false;
newElement.Add(child);
}
});
Assert.Throws<InvalidOperationException>(() => { element.Add(child); });
element.Verify();
Assert.Null(element.Element("Add"));
}
[Fact]
public void XElementParentedAttribute()
{
bool firstTime = true;
XElement element = XElement.Parse("<root></root>");
XElement newElement = new XElement("new", "element");
XAttribute child = new XAttribute("Add", "Me");
element.Changing += new EventHandler<XObjectChangeEventArgs>(
delegate (object sender, XObjectChangeEventArgs e)
{
if (firstTime)
{
firstTime = false;
newElement.Add(child);
}
});
Assert.Throws<InvalidOperationException>(() => { element.Add(child); });
element.Verify();
Assert.Null(element.Attribute("Add"));
}
}
}
| |
/*
* 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 OpenMetaverse;
using log4net;
using Nini.Config;
using System.Reflection;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Data;
using OpenSim.Framework;
namespace OpenSim.Services.InventoryService
{
public class XInventoryService : ServiceBase, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected IXInventoryData m_Database;
public XInventoryService(IConfigSource config) : base(config)
{
string dllName = String.Empty;
string connString = String.Empty;
//string realm = "Inventory"; // OSG version doesn't use this
//
// Try reading the [InventoryService] section first, if it exists
//
IConfig authConfig = config.Configs["InventoryService"];
if (authConfig != null)
{
dllName = authConfig.GetString("StorageProvider", dllName);
connString = authConfig.GetString("ConnectionString", connString);
// realm = authConfig.GetString("Realm", realm);
}
//
// Try reading the [DatabaseService] section, if it exists
//
IConfig dbConfig = config.Configs["DatabaseService"];
if (dbConfig != null)
{
if (dllName == String.Empty)
dllName = dbConfig.GetString("StorageProvider", String.Empty);
if (connString == String.Empty)
connString = dbConfig.GetString("ConnectionString", String.Empty);
}
//
// We tried, but this doesn't exist. We can't proceed.
//
if (dllName == String.Empty)
throw new Exception("No StorageProvider configured");
m_Database = LoadPlugin<IXInventoryData>(dllName,
new Object[] {connString, String.Empty});
if (m_Database == null)
throw new Exception("Could not find a storage interface in the given module");
}
public virtual bool CreateUserInventory(UUID principalID)
{
// This is braindeaad. We can't ever communicate that we fixed
// an existing inventory. Well, just return root folder status,
// but check sanity anyway.
//
bool result = false;
InventoryFolderBase rootFolder = GetRootFolder(principalID);
if (rootFolder == null)
{
rootFolder = ConvertToOpenSim(CreateFolder(principalID, UUID.Zero, (int)AssetType.RootFolder, "My Inventory"));
result = true;
}
XInventoryFolder[] sysFolders = GetSystemFolders(principalID);
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Animation) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Animation, "Animations");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Bodypart) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Bodypart, "Body Parts");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.CallingCard) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.CallingCard, "Calling Cards");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Clothing) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Clothing, "Clothing");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Gesture) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Gesture, "Gestures");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Landmark) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Landmark, "Landmarks");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.LostAndFoundFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.LostAndFoundFolder, "Lost And Found");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Notecard) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Notecard, "Notecards");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Object) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Object, "Objects");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.SnapshotFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.SnapshotFolder, "Photo Album");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.LSLText) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.LSLText, "Scripts");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Sound) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Sound, "Sounds");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Texture) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Texture, "Textures");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.TrashFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.TrashFolder, "Trash");
return result;
}
protected XInventoryFolder CreateFolder(UUID principalID, UUID parentID, int type, string name)
{
XInventoryFolder newFolder = new XInventoryFolder();
newFolder.folderName = name;
newFolder.type = type;
newFolder.version = 1;
newFolder.folderID = UUID.Random();
newFolder.agentID = principalID;
newFolder.parentFolderID = parentID;
m_Database.StoreFolder(newFolder);
return newFolder;
}
protected virtual XInventoryFolder[] GetSystemFolders(UUID principalID)
{
XInventoryFolder[] allFolders = m_Database.GetFolders(
new string[] { "agentID" },
new string[] { principalID.ToString() });
XInventoryFolder[] sysFolders = Array.FindAll(
allFolders,
delegate (XInventoryFolder f)
{
if (f.type > 0)
return true;
return false;
});
return sysFolders;
}
public virtual List<InventoryFolderBase> GetInventorySkeleton(UUID principalID)
{
XInventoryFolder[] allFolders = m_Database.GetFolders(
new string[] { "agentID" },
new string[] { principalID.ToString() });
if (allFolders.Length == 0)
return null;
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
foreach (XInventoryFolder x in allFolders)
{
//m_log.DebugFormat("[XINVENTORY]: Adding folder {0} to skeleton", x.folderName);
folders.Add(ConvertToOpenSim(x));
}
return folders;
}
public virtual InventoryFolderBase GetRootFolder(UUID principalID)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "parentFolderID"},
new string[] { principalID.ToString(), UUID.Zero.ToString() });
if (folders.Length == 0)
return null;
return ConvertToOpenSim(folders[0]);
}
public virtual InventoryFolderBase GetFolderForType(UUID principalID, AssetType type)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "type"},
new string[] { principalID.ToString(), ((int)type).ToString() });
if (folders.Length == 0)
return null;
return ConvertToOpenSim(folders[0]);
}
public virtual InventoryCollection GetFolderContent(UUID principalID, UUID folderID)
{
// This method doesn't receive a valud principal id from the
// connector. So we disregard the principal and look
// by ID.
//
m_log.DebugFormat("[XINVENTORY]: Fetch contents for folder {0}", folderID.ToString());
InventoryCollection inventory = new InventoryCollection();
inventory.UserID = principalID;
inventory.Folders = new List<InventoryFolderBase>();
inventory.Items = new List<InventoryItemBase>();
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "parentFolderID"},
new string[] { folderID.ToString() });
foreach (XInventoryFolder x in folders)
{
//m_log.DebugFormat("[XINVENTORY]: Adding folder {0} to response", x.folderName);
inventory.Folders.Add(ConvertToOpenSim(x));
}
XInventoryItem[] items = m_Database.GetItems(
new string[] { "parentFolderID"},
new string[] { folderID.ToString() });
foreach (XInventoryItem i in items)
{
//m_log.DebugFormat("[XINVENTORY]: Adding item {0} to response", i.inventoryName);
inventory.Items.Add(ConvertToOpenSim(i));
}
return inventory;
}
public virtual List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID)
{
// Since we probably don't get a valid principal here, either ...
//
List<InventoryItemBase> invItems = new List<InventoryItemBase>();
XInventoryItem[] items = m_Database.GetItems(
new string[] { "parentFolderID"},
new string[] { UUID.Zero.ToString() });
foreach (XInventoryItem i in items)
invItems.Add(ConvertToOpenSim(i));
return invItems;
}
public virtual bool AddFolder(InventoryFolderBase folder)
{
XInventoryFolder xFolder = ConvertFromOpenSim(folder);
return m_Database.StoreFolder(xFolder);
}
public virtual bool UpdateFolder(InventoryFolderBase folder)
{
return AddFolder(folder);
}
public virtual bool MoveFolder(InventoryFolderBase folder)
{
XInventoryFolder[] x = m_Database.GetFolders(
new string[] { "folderID" },
new string[] { folder.ID.ToString() });
if (x.Length == 0)
return false;
x[0].parentFolderID = folder.ParentID;
return m_Database.StoreFolder(x[0]);
}
// We don't check the principal's ID here
//
public virtual bool DeleteFolders(UUID principalID, List<UUID> folderIDs)
{
// Ignore principal ID, it's bogus at connector level
//
foreach (UUID id in folderIDs)
{
InventoryFolderBase f = new InventoryFolderBase();
f.ID = id;
PurgeFolder(f);
m_Database.DeleteFolders("folderID", id.ToString());
}
return true;
}
public virtual bool PurgeFolder(InventoryFolderBase folder)
{
XInventoryFolder[] subFolders = m_Database.GetFolders(
new string[] { "parentFolderID" },
new string[] { folder.ID.ToString() });
foreach (XInventoryFolder x in subFolders)
{
PurgeFolder(ConvertToOpenSim(x));
m_Database.DeleteFolders("folderID", x.folderID.ToString());
}
m_Database.DeleteItems("parentFolderID", folder.ID.ToString());
return true;
}
public virtual bool AddItem(InventoryItemBase item)
{
return m_Database.StoreItem(ConvertFromOpenSim(item));
}
public virtual bool UpdateItem(InventoryItemBase item)
{
return m_Database.StoreItem(ConvertFromOpenSim(item));
}
public virtual bool MoveItems(UUID principalID, List<InventoryItemBase> items)
{
// Principal is b0rked. *sigh*
//
foreach (InventoryItemBase i in items)
{
m_Database.MoveItem(i.ID.ToString(), i.Folder.ToString());
}
return true;
}
public virtual bool DeleteItems(UUID principalID, List<UUID> itemIDs)
{
// Just use the ID... *facepalms*
//
foreach (UUID id in itemIDs)
m_Database.DeleteItems("inventoryID", id.ToString());
return true;
}
public virtual InventoryItemBase GetItem(InventoryItemBase item)
{
XInventoryItem[] items = m_Database.GetItems(
new string[] { "inventoryID" },
new string[] { item.ID.ToString() });
if (items.Length == 0)
return null;
return ConvertToOpenSim(items[0]);
}
public virtual InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "folderID"},
new string[] { folder.ID.ToString() });
if (folders.Length == 0)
return null;
return ConvertToOpenSim(folders[0]);
}
public virtual List<InventoryItemBase> GetActiveGestures(UUID principalID)
{
XInventoryItem[] items = m_Database.GetActiveGestures(principalID);
if (items.Length == 0)
return new List<InventoryItemBase>();
List<InventoryItemBase> ret = new List<InventoryItemBase>();
foreach (XInventoryItem x in items)
ret.Add(ConvertToOpenSim(x));
return ret;
}
public virtual int GetAssetPermissions(UUID principalID, UUID assetID)
{
return m_Database.GetAssetPermissions(principalID, assetID);
}
// CM never needed those. Left unimplemented.
// Obsolete in core
//
public InventoryCollection GetUserInventory(UUID userID)
{
return null;
}
public void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
{
}
// Unused.
//
public bool HasInventoryForUser(UUID userID)
{
return false;
}
// CM Helpers
//
protected InventoryFolderBase ConvertToOpenSim(XInventoryFolder folder)
{
InventoryFolderBase newFolder = new InventoryFolderBase();
newFolder.ParentID = folder.parentFolderID;
newFolder.Type = (short)folder.type;
newFolder.Version = (ushort)folder.version;
newFolder.Name = folder.folderName;
newFolder.Owner = folder.agentID;
newFolder.ID = folder.folderID;
return newFolder;
}
protected XInventoryFolder ConvertFromOpenSim(InventoryFolderBase folder)
{
XInventoryFolder newFolder = new XInventoryFolder();
newFolder.parentFolderID = folder.ParentID;
newFolder.type = (int)folder.Type;
newFolder.version = (int)folder.Version;
newFolder.folderName = folder.Name;
newFolder.agentID = folder.Owner;
newFolder.folderID = folder.ID;
return newFolder;
}
protected InventoryItemBase ConvertToOpenSim(XInventoryItem item)
{
InventoryItemBase newItem = new InventoryItemBase();
newItem.AssetID = item.assetID;
newItem.AssetType = item.assetType;
newItem.Name = item.inventoryName;
newItem.Owner = item.avatarID;
newItem.ID = item.inventoryID;
newItem.InvType = item.invType;
newItem.Folder = item.parentFolderID;
newItem.CreatorId = item.creatorID.ToString();
newItem.Description = item.inventoryDescription;
newItem.NextPermissions = (uint)item.inventoryNextPermissions;
newItem.CurrentPermissions = (uint)item.inventoryCurrentPermissions;
newItem.BasePermissions = (uint)item.inventoryBasePermissions;
newItem.EveryOnePermissions = (uint)item.inventoryEveryOnePermissions;
newItem.GroupPermissions = (uint)item.inventoryGroupPermissions;
newItem.GroupID = item.groupID;
if (item.groupOwned == 0)
newItem.GroupOwned = false;
else
newItem.GroupOwned = true;
newItem.SalePrice = item.salePrice;
newItem.SaleType = (byte)item.saleType;
newItem.Flags = (uint)item.flags;
newItem.CreationDate = item.creationDate;
return newItem;
}
protected XInventoryItem ConvertFromOpenSim(InventoryItemBase item)
{
XInventoryItem newItem = new XInventoryItem();
newItem.assetID = item.AssetID;
newItem.assetType = item.AssetType;
newItem.inventoryName = item.Name;
newItem.avatarID = item.Owner;
newItem.inventoryID = item.ID;
newItem.invType = item.InvType;
newItem.parentFolderID = item.Folder;
newItem.creatorID = item.CreatorIdAsUuid;
newItem.inventoryDescription = item.Description;
newItem.inventoryNextPermissions = (int)item.NextPermissions;
newItem.inventoryCurrentPermissions = (int)item.CurrentPermissions;
newItem.inventoryBasePermissions = (int)item.BasePermissions;
newItem.inventoryEveryOnePermissions = (int)item.EveryOnePermissions;
newItem.inventoryGroupPermissions = (int)item.GroupPermissions;
newItem.groupID = item.GroupID;
if (item.GroupOwned)
newItem.groupOwned = 1;
else
newItem.groupOwned = 0;
newItem.salePrice = item.SalePrice;
newItem.saleType = (int)item.SaleType;
newItem.flags = (int)item.Flags;
newItem.creationDate = item.CreationDate;
return newItem;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using OpenLiveWriter.Interop.Com;
using OpenLiveWriter.Interop.Com.StructuredStorage;
using STGMEDIUM = OpenLiveWriter.Interop.Com.STGMEDIUM;
using TYMED = OpenLiveWriter.Interop.Com.TYMED;
namespace OpenLiveWriter.CoreServices
{
/// <summary>
/// Abstract base class for OleStgMedium sub-types. Implements IDisposable
/// so callers can release the underlying storage medium when they are
/// finished with it. Callers MUST call either Release or Dispose when
/// finished with the object because timely release of STGMEDIUM objects
/// is critical --- this requirement is validated via an assertion in
/// the destructor.
/// </summary>
public abstract class OleStgMedium : IDisposable
{
/// <summary>
/// Create an OleStgMedium that encapsulates the passed STGMEDIUM
/// </summary>
/// <param name="stg">Underlying STGMEDIUM</param>
public OleStgMedium(STGMEDIUM stg)
{
m_stg = stg;
}
/// <summary>
/// Destructor uses an assertion to verify that the user called
/// Release() or Dispose() when they are finished using the object
/// </summary>
~OleStgMedium()
{
Debug.Assert(m_stg.tymed == TYMED.NULL,
"You must call Release() or Dispose() on OleStgMedium when " +
"finished using it!");
}
/// <summary>
/// Release the underlying STGMEDIUM
/// </summary>
public virtual void Release()
{
if (m_stg.tymed != TYMED.NULL)
{
Ole32.ReleaseStgMedium(ref m_stg);
m_stg.tymed = TYMED.NULL;
}
}
/// <summary>
/// Release the underlying STGMEDIUM
/// </summary>
public void Dispose()
{
Release();
}
/// <summary>
/// Helper function used by subclasses to validate that the type
/// of the storage medium passed to them matches their type
/// </summary>
/// <param name="type">type of STGMEDIUM</param>
protected void ValidateType(TYMED type)
{
if (m_stg.tymed != type)
{
const string msg = "Invalid TYMED passed to OleStgMedium";
Debug.Assert(false, msg);
throw new InvalidOperationException(msg);
}
}
/// <summary>
/// Underlying STGMEDIUM
/// </summary>
private STGMEDIUM m_stg;
}
/// <summary>
/// Abstract base class for OleStgMedium types that are represented
/// by a Win32 handle.
/// </summary>
public abstract class OleStgMediumHandle : OleStgMedium
{
/// <summary>
/// Create an OleStgMediumHandle that encapsulates the passed STGMEDIUM
/// </summary>
/// <param name="stg">Underlying STGMEDIUM</param>
public OleStgMediumHandle(STGMEDIUM stg)
: base(stg)
{
m_handle = stg.contents;
}
/// <summary>
/// Underlying Win32 handle
/// </summary>
public IntPtr Handle
{
get { return m_handle; }
}
private IntPtr m_handle;
}
/// <summary>
/// OleStgMedium that contains an HGLOBAL
/// </summary>
public class OleStgMediumHGLOBAL : OleStgMediumHandle
{
/// <summary>
/// Create an OleStgMediumHandle that encapsulates the passed STGMEDIUM
/// </summary>
/// <param name="stg">Underlying STGMEDIUM</param>
public OleStgMediumHGLOBAL(STGMEDIUM stg)
: base(stg)
{
ValidateType(TYMED.HGLOBAL);
}
}
/// <summary>
/// OleStgMedium that contains an HBITMAP
/// </summary>
public class OleStgMediumGDI : OleStgMediumHandle
{
/// <summary>
/// Create an OleStgMediumHandle that encapsulates the passed STGMEDIUM
/// </summary>
/// <param name="stg">Underlying STGMEDIUM</param>
public OleStgMediumGDI(STGMEDIUM stg)
: base(stg)
{
ValidateType(TYMED.GDI);
}
}
/// <summary>
/// OleStgMedium that contains an standard metafile (HMETAFILE)
/// </summary>
public class OleStgMediumMFPICT : OleStgMediumHandle
{
/// <summary>
/// Create an OleStgMediumHandle that encapsulates the passed STGMEDIUM
/// </summary>
/// <param name="stg">Underlying STGMEDIUM</param>
public OleStgMediumMFPICT(STGMEDIUM stg)
: base(stg)
{
ValidateType(TYMED.MFPICT);
}
}
/// <summary>
/// OleStgMedium that contains an enhanced metafile (HMETAFILE)
/// </summary>
public class OleStgMediumENHMF : OleStgMediumHandle
{
/// <summary>
/// Create an OleStgMediumHandle that encapsulates the passed STGMEDIUM
/// </summary>
/// <param name="stg">Underlying STGMEDIUM</param>
public OleStgMediumENHMF(STGMEDIUM stg)
: base(stg)
{
ValidateType(TYMED.ENHMF);
}
}
/// <summary>
/// OleStgMedium that contains a file path
/// </summary>
public class OleStgMediumFILE : OleStgMedium
{
/// <summary>
/// Create an OleStgMediumHandle that encapsulates the passed STGMEDIUM
/// </summary>
/// <param name="stg">Underlying STGMEDIUM</param>
public OleStgMediumFILE(STGMEDIUM stg)
: base(stg)
{
// validate that the correct type has been passed in
ValidateType(TYMED.FILE);
// marshall the file path into a .NET string
m_path = Marshal.PtrToStringAuto(stg.contents);
}
/// <summary>
/// Path to the file
/// </summary>
public string Path
{
get { return m_path; }
}
private string m_path;
}
/// <summary>
/// Base class for OleStgMedium instances that are com objects
/// </summary>
public class OleStgMediumCOMOBJECT : OleStgMedium
{
/// <summary>
/// Create an OleStgMediumCOMOBJECT that encapsulates the passed STGMEDIUM
/// </summary>
/// <param name="stg">Underlying STGMEDIUM</param>
public OleStgMediumCOMOBJECT(STGMEDIUM stg)
: base(stg)
{
// store the com object
m_comObject = Marshal.GetObjectForIUnknown(stg.contents);
Debug.Assert(m_comObject != null);
}
/// <summary>
/// Underlying com object
/// </summary>
protected object m_comObject;
}
/// <summary>
/// OleStgMedium that contains a stream
/// </summary>
public class OleStgMediumISTREAM : OleStgMediumCOMOBJECT
{
/// <summary>
/// Create an OleStgMediumSTREAM that encapsulates the passed STGMEDIUM
/// </summary>
/// <param name="stg">Underlying STGMEDIUM</param>
public OleStgMediumISTREAM(STGMEDIUM stg)
: base(stg)
{
// validate that the correct type has been passed in
ValidateType(TYMED.ISTREAM);
// initialize the .NET stream
m_stream = new ComStream((IStream)m_comObject);
}
/// <summary>
/// Release the underlying STGMEDIUM (override)
/// </summary>
public override void Release()
{
// close the stream
m_stream.Close();
// release underlying storage
base.Release();
}
/// <summary>
/// Get the underlying stream as a .NET stream. The lifetime of the stream
/// is tied to the lifetime of the OleStgMediumISTORAGE (it will be automatically
/// disposed when the stg medium is disposed)
/// </summary>
public Stream Stream
{
get { return m_stream; }
}
private Stream m_stream = null;
}
/// <summary>
/// OleStgMedium that contains a storage
/// </summary>
public class OleStgMediumISTORAGE : OleStgMediumCOMOBJECT
{
/// <summary>
/// Create an OleStgMediumSTORAGE that encapsulates the passed STGMEDIUM
/// </summary>
/// <param name="stg">Underlying STGMEDIUM</param>
public OleStgMediumISTORAGE(STGMEDIUM stg)
: base(stg)
{
// validate that the correct type has been passed in
ValidateType(TYMED.ISTORAGE);
// initialize the storage
m_storage = new Storage((IStorage)m_comObject, false);
}
/// <summary>
/// Release the underlying STGMEDIUM (override)
/// </summary>
public override void Release()
{
// close the structured storage
m_storage.Close();
// release underlying storage
base.Release();
}
/// <summary>
/// Get the underlying storage as a .NET storage. The lifetime of the storage
/// is tied to the lifetime of the OleStgMediumISTORAGE (it will be
/// automatically disposed when the stg medium is disposed)
/// </summary>
public Storage Storage
{
get { return m_storage; }
}
private Storage m_storage = null;
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace Aurora.Modules.SampleCurrencyModule
{
/// <summary>
/// This is a demo for you to use when making one that works for you.
/// // To use the following you need to add:
/// -helperuri <ADDRESS TO HERE OR grid MONEY SERVER>
/// to the command line parameters you use to start up your client
/// This commonly looks like -helperuri http://127.0.0.1:9000/
/// </summary>
public class CurrencyModule : IMoneyModule, ISharedRegionModule
{
private bool m_enabled;
#region IMoneyModule Members
public int UploadCharge
{
get { return 0; }
}
public int GroupCreationCharge
{
get { return 0; }
}
public int ClientPort
{
get
{
return (int)MainServer.Instance.Port;
}
}
#pragma warning disable 67
public event ObjectPaid OnObjectPaid;
public event PostObjectPaid OnPostObjectPaid;
public bool Transfer(UUID toID, UUID fromID, int amount, string description)
{
return true;
}
public bool Transfer(UUID toID, UUID fromID, int amount, string description, TransactionType type)
{
return true;
}
public bool Transfer(UUID toID, UUID fromID, UUID toObjectID, UUID fromObjectID, int amount, string description,
TransactionType type)
{
if ((type == TransactionType.PayIntoObject) && (OnObjectPaid != null))
OnObjectPaid((fromObjectID == UUID.Zero) ? toObjectID : fromObjectID, fromID, amount);
return true;
}
public void Transfer(UUID objectID, UUID agentID, int amount)
{
}
#pragma warning restore 67
#region IRegionModuleBase Members
/// <summary>
/// Startup
/// </summary>
/// <param name = "scene"></param>
/// <param name = "config"></param>
public void Initialise(IConfigSource config)
{
IConfig currencyConfig = config.Configs["Currency"];
if (currencyConfig != null)
{
m_enabled = currencyConfig.GetString("Module", "") == Name;
}
}
public void AddRegion(IScene scene)
{
if (!m_enabled)
return;
// Send ObjectCapacity to Scene.. Which sends it to the SimStatsReporter.
scene.RegisterModuleInterface<IMoneyModule>(this);
// XMLRPCHandler = scene;
// To use the following you need to add:
// -helperuri <ADDRESS TO HERE OR grid MONEY SERVER>
// to the command line parameters you use to start up your client
// This commonly looks like -helperuri http://127.0.0.1:9000/
MainServer.Instance.AddXmlRPCHandler("getCurrencyQuote", quote_func);
MainServer.Instance.AddXmlRPCHandler("buyCurrency", buy_func);
MainServer.Instance.AddXmlRPCHandler("preflightBuyLandPrep", preflightBuyLandPrep_func);
MainServer.Instance.AddXmlRPCHandler("buyLandPrep", landBuy_func);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClosingClient += OnClosingClient;
}
public void RemoveRegion(IScene scene)
{
}
public void RegionLoaded(IScene scene)
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "BaseCurrency"; }
}
#endregion
public int Balance(UUID agentID)
{
return 0;
}
public bool Charge(UUID agentID, int amount, string text)
{
return true;
}
public bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID toID, int amount)
{
return true;
}
public void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount,
int transactiontype, string description)
{
}
#endregion
/// <summary>
/// New Client Event Handler
/// </summary>
/// <param name = "client"></param>
protected void OnNewClient(IClientAPI client)
{
// Subscribe to Money messages
client.OnEconomyDataRequest += EconomyDataRequestHandler;
client.OnMoneyBalanceRequest += SendMoneyBalance;
client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
}
protected void OnClosingClient(IClientAPI client)
{
// Subscribe to Money messages
client.OnEconomyDataRequest -= EconomyDataRequestHandler;
client.OnMoneyBalanceRequest -= SendMoneyBalance;
client.OnMoneyTransferRequest -= ProcessMoneyTransferRequest;
}
/// <summary>
/// Sends the the stored money balance to the client
/// </summary>
/// <param name = "client"></param>
/// <param name = "agentID"></param>
/// <param name = "SessionID"></param>
/// <param name = "TransactionID"></param>
protected void SendMoneyBalance(IClientAPI client, UUID agentID, UUID SessionID, UUID TransactionID)
{
client.SendMoneyBalance(TransactionID, true, new byte[0], 0);
}
#region Buy Currency and Land
protected XmlRpcResponse quote_func(XmlRpcRequest request, IPEndPoint ep)
{
Hashtable requestData = (Hashtable) request.Params[0];
UUID agentId = UUID.Zero;
int amount = 0;
Hashtable quoteResponse = new Hashtable();
XmlRpcResponse returnval = new XmlRpcResponse();
if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy"))
{
UUID.TryParse((string) requestData["agentId"], out agentId);
try
{
amount = (Int32) requestData["currencyBuy"];
}
catch (InvalidCastException)
{
}
Hashtable currencyResponse = new Hashtable {{"estimatedCost", 0}, {"currencyBuy", amount}};
quoteResponse.Add("success", true);
quoteResponse.Add("currency", currencyResponse);
quoteResponse.Add("confirm", "asdfad9fj39ma9fj");
returnval.Value = quoteResponse;
return returnval;
}
quoteResponse.Add("success", false);
quoteResponse.Add("errorMessage", "Invalid parameters passed to the quote box");
quoteResponse.Add("errorURI", "http://www.opensimulator.org/wiki");
returnval.Value = quoteResponse;
return returnval;
}
protected XmlRpcResponse buy_func(XmlRpcRequest request, IPEndPoint ep)
{
/*Hashtable requestData = (Hashtable)request.Params[0];
UUID agentId = UUID.Zero;
int amount = 0;
if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy"))
{
UUID.TryParse((string)requestData["agentId"], out agentId);
try
{
amount = (Int32)requestData["currencyBuy"];
}
catch (InvalidCastException)
{
}
if (agentId != UUID.Zero)
{
uint buyer = CheckExistAndRefreshFunds(agentId);
buyer += (uint)amount;
UpdateBalance(agentId,buyer);
IClientAPI client = LocateClientObject(agentId);
if (client != null)
{
SendMoneyBalance(client, agentId, client.SessionId, UUID.Zero);
}
}
}*/
XmlRpcResponse returnval = new XmlRpcResponse();
Hashtable returnresp = new Hashtable {{"success", true}};
returnval.Value = returnresp;
return returnval;
}
protected XmlRpcResponse preflightBuyLandPrep_func(XmlRpcRequest request, IPEndPoint ep)
{
XmlRpcResponse ret = new XmlRpcResponse();
Hashtable retparam = new Hashtable();
Hashtable membershiplevels = new Hashtable();
membershiplevels.Add("levels", membershiplevels);
Hashtable landuse = new Hashtable();
Hashtable level = new Hashtable {{"id", "00000000-0000-0000-0000-000000000000"}, {"", "Premium Membership"}};
Hashtable currencytable = new Hashtable {{"estimatedCost", 0}};
retparam.Add("success", true);
retparam.Add("currency", currencytable);
retparam.Add("membership", level);
retparam.Add("landuse", landuse);
retparam.Add("confirm", "asdfajsdkfjasdkfjalsdfjasdf");
ret.Value = retparam;
return ret;
}
protected XmlRpcResponse landBuy_func(XmlRpcRequest request, IPEndPoint ep)
{
XmlRpcResponse ret = new XmlRpcResponse();
Hashtable retparam = new Hashtable {{"success", true}};
ret.Value = retparam;
return ret;
}
#endregion
#region event Handlers
/// <summary>
/// Event called Economy Data Request handler.
/// </summary>
/// <param name = "agentId"></param>
public void EconomyDataRequestHandler(IClientAPI remoteClient)
{
remoteClient.SendEconomyData(0, remoteClient.Scene.RegionInfo.ObjectCapacity, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0);
}
public bool Charge(IClientAPI client, int amount)
{
return true;
}
#endregion
public List<GroupAccountHistory> GetTransactions(UUID groupID, UUID agentID, int currentInterval, int intervalDays)
{
return new List<GroupAccountHistory>();
}
public GroupBalance GetGroupBalance(UUID groupID)
{
return new GroupBalance() { StartingDate = DateTime.Now.AddDays(-4) };
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// GM is shortcut for GameObject Managements (for getting tag, script singleton, spawn and despawn)
/// </summary>
public static class GM {
/// <summary>
/// Get the component, or add it instead in case if it null
/// </summary>
public static T GetOrAddComponent<T>(this GameObject game) where T : Component
{
// Somebody said this is much faster 40% than usual <T>
var t = (T)game.GetComponent(typeof(T));
return t ?? (T)game.AddComponent(typeof(T));
}
/// <summary>
/// Extension short-hand for GetOrAddComponent (Always Returns ExMono)
/// </summary>
public static MonoBehaviourEX GC(this GameObject game) {
return GetOrAddComponent<MonoBehaviourEX>(game);
}
/// <summary>
/// Extension short-hand for GetComponent
/// </summary>
public static T GC<T>(this GameObject game) where T : Component {
return (T)game.GetComponent(typeof(T));
}
/// <summary>
/// Extension short-hand for GetOrAddComponent (Always Returns ExMono)
/// </summary>
public static MonoBehaviourEX GC(this Component game) {
return GetOrAddComponent<MonoBehaviourEX>(game.gameObject);
}
/// <summary>
/// Extension short-hand for GetComponent
/// </summary>
public static T GC<T>(this Component game) where T : Component {
return (T)game.GetComponent(typeof(T));
}
static Dictionary<string, GameObject> tagCatalog = new Dictionary<string, GameObject>();
static Dictionary<Type, Component> mainCatalog = new Dictionary<Type, Component>();
static Dictionary<string, Dictionary<Type, Component>> monoTaggedCatalog = new Dictionary<string, Dictionary<Type, Component>>();
/// <summary>
/// Get GameObject with Specific tag
/// </summary>
public static GameObject Get (string tag) {
if (tagCatalog.ContainsKey(tag)) {
var v = tagCatalog[tag];
if (v)
return v;
}
return tagCatalog[tag] = GameObject.FindWithTag(tag);
}
public static T Get<T>(string tag) where T : Component
{
return Get(tag).GetComponent<T>();
}
/// <summary>
/// Get Main component (one script for whole game)
/// </summary>
public static T Main<T> () where T : Component
{
var t = typeof(T);
return (T)(mainCatalog.GetValueOrDefault(t) ?? (mainCatalog[t] = (Component)GameObject.FindObjectOfType(t)));
}
public static T Main<T> (string gameTag) where T : Component
{
var t = typeof(T);
var dic = monoTaggedCatalog.GetValueOrDefault(gameTag);
if (dic == null)
dic = monoTaggedCatalog[gameTag] = new Dictionary<Type, Component>();
var obj = dic.GetValueOrDefault(t);
if (!obj) {
var gS = GameObject.FindGameObjectsWithTag(gameTag);
Component c = null;
for (int i = 0; i < gS.Length; i++)
{
if (c = gS[i].GetComponent(t)) {
obj = dic[t] = c;
break;
}
}
}
return (T)obj;
}
public static GameObject player {
get {
return Get("Player");
}
}
public static GameObject gameController {
get {
return Get("GameController");
}
}
static Dictionary<GameObject, Stack<GameObject>> prefabCatalog = new Dictionary<GameObject, Stack<GameObject>>();
static Dictionary<int, GameObject> prefabReleased = new Dictionary<int, GameObject>();
public static GameObject Spawn (GameObject prefab) {
#if UNITY_EDITOR
if (!prefab || prefab.activeInHierarchy)
throw new NotSupportedException("GM.Spawn() only accepts Prefab to be Instantianted");
#endif
var stk = prefabCatalog.GetValueOrDefault(prefab);
if (stk == null)
stk = prefabCatalog[prefab] = new Stack<GameObject>();
if (stk.Count == 0) {
var obj = GameObject.Instantiate(prefab);
prefabReleased[(obj.GetInstanceID())] = prefab;
return obj;
}
else {
var obj = stk.Pop();
obj.SetActive(true);
obj.SendMessage("Start", null, SendMessageOptions.DontRequireReceiver);
obj.hideFlags = HideFlags.None;
return obj;
}
}
public static GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation) {
var obj = Spawn(prefab);
var t = obj.transform;
t.position = position;
t.rotation = rotation;
return obj;
}
public static GameObject Spawn(GameObject prefab, Transform parent, bool keepWorldSpace = false) {
var obj = Spawn(prefab);
if (parent) {
var t = obj.transform;
t.SetParent(parent, keepWorldSpace);
}
return obj;
}
public static T Spawn<T>(GameObject prefab, Transform parent, bool keepWorldSpace = false) where T : Component
{
return (T)Spawn(prefab, parent, keepWorldSpace).GetComponent(typeof(T));
}
public static void BulkSpawn(List<GameObject> lists, GameObject prefab, Transform parent = null, int count = 1, bool keepWorldSpace = false)
{
for (int i = 0; i < count; i++)
{
lists.Add(Spawn(prefab, parent, keepWorldSpace));
}
}
public static void BulkSpawn<T>(List<T> lists, GameObject prefab, Transform parent = null, int count = 1, bool keepWorldSpace = false) where T : Component
{
for (int i = 0; i < count; i++)
{
lists.Add(Spawn<T>(prefab, parent, keepWorldSpace));
}
}
public static void Despawn(GameObject gameObj) {
var id = gameObj.GetInstanceID();
var prefab = prefabReleased.GetValueOrDefault(id);
if (!prefab) {
// Prefab not found. This is happen only in editor... where script goes recompiled in middle of game.
GameObject.Destroy(gameObj);
} else {
gameObj.SetActive(false);
gameObj.hideFlags = HideFlags.DontSave | HideFlags.HideInHierarchy;
var t = gameObj.transform;
t.SetParent(null, false);
t.position = Vector3.zero;
t.rotation = Quaternion.identity;
var stk = prefabCatalog.GetValueOrDefault(prefab);
if (stk == null)
stk = prefabCatalog[prefab] = new Stack<GameObject>();
stk.Push(gameObj);
}
}
public static void DespawnAllChildren(Transform parent, bool alsoDestroyNonSpawnedObjects = true) {
for (int i = parent.childCount; i-- > 0;)
{
var g = parent.GetChild(i).gameObject;
if (alsoDestroyNonSpawnedObjects || prefabReleased.ContainsKey(g.GetInstanceID()))
Despawn(g);
}
}
public static void DespawnAllChildren(List<GameObject> lists, bool alsoDestroyNonSpawnedObjects = true, bool alsoRemoveFromTheList = true) {
var flag = alsoRemoveFromTheList && !alsoRemoveFromTheList;
for (int i = lists.Count; i-- > 0;)
{
var g = lists[i];
if (alsoDestroyNonSpawnedObjects || prefabReleased.ContainsKey(g.GetInstanceID())) {
Despawn(g);
if (flag)
lists.RemoveAt(i);
}
}
if (alsoRemoveFromTheList & alsoRemoveFromTheList)
lists.Clear();
}
public static void DespawnAllChildren<T>(List<T> lists, bool alsoDestroyNonSpawnedObjects = true, bool alsoRemoveFromTheList = true) where T : Component
{
var flag = alsoRemoveFromTheList && !alsoRemoveFromTheList;
for (int i = lists.Count; i-- > 0;)
{
var g = lists[i].gameObject;
if (alsoDestroyNonSpawnedObjects || prefabReleased.ContainsKey(g.GetInstanceID())) {
Despawn(g);
if (flag)
lists.RemoveAt(i);
}
}
if (alsoRemoveFromTheList & alsoRemoveFromTheList)
lists.Clear();
}
}
| |
namespace YAF.Pages.Admin
{
#region Using
using System;
using System.Data;
using VZF.Data.Common;
using YAF.Core;
using YAF.Core.BBCode;
using YAF.Core.Services;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.Interfaces;
using VZF.Utils;
using VZF.Utils.Helpers;
#endregion
/// <summary>
/// The bbcode_edit.
/// </summary>
public partial class bbcode_edit : AdminPage
{
#region Constants and Fields
/// <summary>
/// The _bbcode id.
/// </summary>
private int? _bbcodeId;
#endregion
#region Properties
/// <summary>
/// Gets BBCodeID.
/// </summary>
protected int? BBCodeID
{
get
{
if (this._bbcodeId != null)
{
return this._bbcodeId;
}
if (this.Request.QueryString.GetFirstOrDefault("b") == null)
return null;
int id;
if (int.TryParse(this.Request.QueryString.GetFirstOrDefault("b"), out id))
{
this._bbcodeId = id;
return id;
}
return null;
}
}
#endregion
#region Methods
/// <summary>
/// The add_ click.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Add_Click([NotNull] object sender, [NotNull] EventArgs e)
{
short sortOrder;
if (!ValidationHelper.IsValidPosShort(this.txtExecOrder.Text.Trim()))
{
this.PageContext.AddLoadMessage(this.GetText("ADMIN_BBCODE_EDIT", "MSG_POSITIVE_VALUE"));
return;
}
if (!short.TryParse(this.txtExecOrder.Text.Trim(), out sortOrder))
{
this.PageContext.AddLoadMessage(this.GetText("ADMIN_BBCODE_EDIT", "MSG_NUMBER"));
return;
}
CommonDb.bbcode_save(PageContext.PageModuleID, this.BBCodeID,
this.PageContext.PageBoardID,
this.txtName.Text.Trim(),
this.txtDescription.Text,
this.txtOnClickJS.Text,
this.txtDisplayJS.Text,
this.txtEditJS.Text,
this.txtDisplayCSS.Text,
this.txtSearchRegEx.Text,
this.txtReplaceRegEx.Text,
this.txtVariables.Text,
this.chkUseModule.Checked,
this.txtModuleClass.Text,
sortOrder);
this.Get<IDataCache>().Remove(Constants.Cache.CustomBBCode);
this.Get<IObjectStore>().RemoveOf<IProcessReplaceRules>();
YafBuildLink.Redirect(ForumPages.admin_bbcode);
}
/// <summary>
/// The bind data.
/// </summary>
protected void BindData()
{
if (this.BBCodeID == null)
{
return;
}
DataRow row =
CommonDb.bbcode_list(PageContext.PageModuleID, this.PageContext.PageBoardID, this.BBCodeID.Value).Rows[0
];
// fill the control values...
this.txtName.Text = row["Name"].ToString();
this.txtExecOrder.Text = row["ExecOrder"].ToString();
this.txtDescription.Text = row["Description"].ToString();
this.txtOnClickJS.Text = row["OnClickJS"].ToString();
this.txtDisplayJS.Text = row["DisplayJS"].ToString();
this.txtEditJS.Text = row["EditJS"].ToString();
this.txtDisplayCSS.Text = row["DisplayCSS"].ToString();
this.txtSearchRegEx.Text = row["SearchRegex"].ToString();
this.txtReplaceRegEx.Text = row["ReplaceRegex"].ToString();
this.txtVariables.Text = row["Variables"].ToString();
this.txtModuleClass.Text = row["ModuleClass"].ToString();
this.chkUseModule.Checked = Convert.ToBoolean((row["UseModule"] == DBNull.Value) ? false : row["UseModule"]);
}
/// <summary>
/// The cancel_ click.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Cancel_Click([NotNull] object sender, [NotNull] EventArgs e)
{
YafBuildLink.Redirect(ForumPages.admin_bbcode);
}
/// <summary>
/// The page_ load.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
string strAddEdit = (this.BBCodeID == null) ? this.GetText("COMMON", "ADD") : this.GetText("COMMON", "EDIT");
if (!this.IsPostBack)
{
this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, YafBuildLink.GetLink(ForumPages.forum));
this.PageLinks.AddLink(this.GetText("ADMIN_ADMIN", "Administration"),
YafBuildLink.GetLink(ForumPages.admin_admin));
this.PageLinks.AddLink(this.GetText("ADMIN_BBCODE", "TITLE"),
YafBuildLink.GetLink(ForumPages.admin_bbcode));
this.PageLinks.AddLink(this.GetText("ADMIN_BBCODE_EDIT", "TITLE").FormatWith(strAddEdit), string.Empty);
this.Page.Header.Title = "{0} - {1} - {2}".FormatWith(
this.GetText("ADMIN_ADMIN", "Administration"),
this.GetText("ADMIN_BBCODE", "TITLE"),
this.GetText("ADMIN_BBCODE_EDIT", "TITLE").FormatWith(strAddEdit));
this.save.Text = this.GetText("ADMIN_COMMON", "SAVE");
this.cancel.Text = this.GetText("ADMIN_COMMON", "CANCEL");
this.BindData();
}
this.txtName.Attributes.Add("style", "width:99%");
this.txtDescription.Attributes.Add("style", "width:99%;height:75px;");
this.txtOnClickJS.Attributes.Add("style", "width:99%;height:75px;");
this.txtDisplayJS.Attributes.Add("style", "width:99%;height:75px;");
this.txtEditJS.Attributes.Add("style", "width:99%;height:75px;");
this.txtDisplayCSS.Attributes.Add("style", "width:99%;height:75px;");
this.txtSearchRegEx.Attributes.Add("style", "width:99%;height:75px;");
this.txtReplaceRegEx.Attributes.Add("style", "width:99%;height:75px;");
this.txtVariables.Attributes.Add("style", "width:99%;height:75px;");
this.txtModuleClass.Attributes.Add("style", "width:99%");
}
#endregion
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Text;
namespace Oranikle.Report.Engine
{
///<summary>
/// Represents all the pages of a report. Needed when you need
/// render based on pages. e.g. PDF
///</summary>
public class Pages : IEnumerable
{
Bitmap _bm; // bitmap to build graphics object
Graphics _g; // graphics object
Report _report; // owner report
List<Page> _pages; // array of pages
Page _currentPage; // the current page; 1st page if null
float _BottomOfPage; // the bottom of the page
float _PageHeight; // default height for all pages
float _PageWidth; // default width for all pages
public Pages(Report r)
{
_report = r;
_pages = new List<Page>(); // array of Page objects
_bm = new Bitmap(10, 10); // create a small bitmap to base our graphics
_g = Graphics.FromImage(_bm);
}
public Report Report
{
get { return _report;}
}
public Page this[int index]
{
get {return _pages[index];}
}
public int Count
{
get {return _pages.Count;}
}
public void AddPage(Page p)
{
_pages.Add(p);
_currentPage = p;
}
public void NextOrNew()
{
if (_currentPage == this.LastPage)
AddPage(new Page(PageCount+1));
else
{
_currentPage = _pages[_currentPage.PageNumber];
_currentPage.SetEmpty();
}
}
/// <summary>
/// CleanUp should be called after every render to reduce resource utilization.
/// </summary>
public void CleanUp()
{
if (_g != null)
{
_g.Dispose();
_g = null;
}
if (_bm != null)
{
_bm.Dispose();
_bm = null;
}
}
public void SortPageItems()
{
foreach (Page p in this)
{
p.SortPageItems();
}
}
public float BottomOfPage
{
get { return _BottomOfPage; }
set { _BottomOfPage = value; }
}
public Page CurrentPage
{
get
{
if (_currentPage != null)
return _currentPage;
if (_pages.Count >= 1)
{
_currentPage = _pages[0];
return _currentPage;
}
return null;
}
set
{
_currentPage = value;
#if DEBUG
if (value == null)
return;
foreach (Page p in _pages)
{
if (p == value)
return;
}
throw new Exception("CurrentPage must be in the list of pages");
#endif
}
}
public Page FirstPage
{
get
{
if (_pages.Count <= 0)
return null;
else
return _pages[0];
}
}
public Page LastPage
{
get
{
if (_pages.Count <= 0)
return null;
else
return _pages[_pages.Count-1];
}
}
public float PageHeight
{
get {return _PageHeight;}
set {_PageHeight = value;}
}
public float PageWidth
{
get {return _PageWidth;}
set {_PageWidth = value;}
}
public void RemoveLastPage()
{
Page lp = LastPage;
if (lp == null) // if no last page nothing to do
return;
_pages.RemoveAt(_pages.Count-1); // remove the page
if (this.CurrentPage == lp) // reset the current if necessary
{
if (_pages.Count <= 0)
CurrentPage = null;
else
CurrentPage = _pages[_pages.Count-1];
}
return;
}
public Graphics G
{
get
{
if (_g == null)
{
_bm = new Bitmap(10, 10); // create a small bitmap to base our graphics
_g = Graphics.FromImage(_bm);
}
return _g;
}
}
public int PageCount
{
get { return _pages.Count; }
}
#region IEnumerable Members
public IEnumerator GetEnumerator() // just loop thru the pages
{
return _pages.GetEnumerator();
}
#endregion
}
public class Page : IEnumerable
{
// note: all sizes are in points
int _pageno;
List<PageItem> _items; // array of items on the page
float _yOffset; // current y offset; top margin, page header, other details, ...
float _xOffset; // current x offset; margin, body taken into account?
int _emptyItems; // # of items which constitute empty
bool _needSort; // need sort
int _lastZIndex; // last ZIndex
System.Collections.Generic.Dictionary<string, Rows> _PageExprReferences; // needed to save page header/footer expressions
public Page(int page)
{
_pageno = page;
_items = new List<PageItem>();
_emptyItems = 0;
_needSort = false;
}
public PageItem this[int index]
{
get { return _items[index]; }
}
public int Count
{
get { return _items.Count; }
}
public void InsertObject(PageItem pi)
{
AddObjectInternal(pi);
_items.Insert(0, pi);
}
public void AddObject(PageItem pi)
{
AddObjectInternal(pi);
_items.Add(pi);
}
private void AddObjectInternal(PageItem pi)
{
pi.Page = this;
pi.ItemNumber = _items.Count;
if (_items.Count == 0)
_lastZIndex = pi.ZIndex;
else if (_lastZIndex != pi.ZIndex)
_needSort = true;
// adjust the page item locations
pi.X += _xOffset;
pi.Y += _yOffset;
if (pi is PageLine)
{
PageLine pl = pi as PageLine;
pl.X2 += _xOffset;
pl.Y2 += _yOffset;
}
else if (pi is PagePolygon)
{
PagePolygon pp = pi as PagePolygon;
for (int i = 0; i < pp.Points.Length; i++ )
{
pp.Points[i].X += _xOffset;
pp.Points[i].Y += _yOffset;
}
}
else if (pi is PageCurve)
{
PageCurve pc = pi as PageCurve;
for (int i = 0; i < pc.Points.Length; i++)
{
pc.Points[i].X += _xOffset;
pc.Points[i].Y += _yOffset;
}
}
}
public bool IsEmpty()
{
return _items.Count > _emptyItems? false: true;
}
public void SortPageItems()
{
if (!_needSort)
return;
_items.Sort();
}
public void ResetEmpty()
{
_emptyItems = 0;
}
public void SetEmpty()
{
_emptyItems = _items.Count;
}
public int PageNumber
{
get { return _pageno;}
}
public float XOffset
{
get { return _xOffset; }
set { _xOffset = value; }
}
public float YOffset
{
get { return _yOffset; }
set { _yOffset = value; }
}
public void AddPageExpressionRow(Report rpt, string exprname, Row r)
{
if (exprname == null || r == null)
return;
if (_PageExprReferences == null)
_PageExprReferences = new Dictionary<string, Rows>();
Rows rows=null;
_PageExprReferences.TryGetValue(exprname, out rows);
if (rows == null)
{
rows = new Rows(rpt);
rows.Data = new List<Row>();
_PageExprReferences.Add(exprname, rows);
}
Row row = new Row(rows, r); // have to make a new copy
row.RowNumber = rows.Data.Count;
rows.Data.Add(row); // add row to rows
return;
}
public Rows GetPageExpressionRows(string exprname)
{
if (_PageExprReferences == null)
return null;
Rows rows=null;
_PageExprReferences.TryGetValue(exprname, out rows);
return rows;
}
public void ResetPageExpressions()
{
_PageExprReferences = null; // clear it out; not needed once page header/footer are processed
}
#region IEnumerable Members
public IEnumerator GetEnumerator() // just loop thru the pages
{
return _items.GetEnumerator();
}
#endregion
}
public class PageItem : ICloneable, IComparable
{
Page parent; // parent page
float x; // x coordinate
float y; // y coordinate
float h; // height --- line redefines as Y2
float w; // width --- line redefines as X2
string hyperlink; // a hyperlink the object should link to
string bookmarklink; // a hyperlink within the report object should link to
string bookmark; // bookmark text for this pageItem
string tooltip; // a message to display when user hovers with mouse
int zindex; // zindex; items will be sorted by this
int itemNumber; // original number of item
StyleInfo si; // all the style information evaluated
bool allowselect = true; // allow selection of this item
public Page Page
{
get { return parent; }
set { parent = value; }
}
public bool AllowSelect
{
get { return allowselect; }
set { allowselect = value; }
}
public float X
{
get { return x;}
set { x = value;}
}
public float Y
{
get { return y;}
set { y = value;}
}
public int ZIndex
{
get { return zindex; }
set { zindex = value; }
}
public int ItemNumber
{
get { return itemNumber; }
set { itemNumber = value; }
}
public float H
{
get { return h;}
set { h = value;}
}
public float W
{
get { return w;}
set { w = value;}
}
public string HyperLink
{
get { return hyperlink;}
set { hyperlink = value;}
}
public string BookmarkLink
{
get { return bookmarklink;}
set { bookmarklink = value;}
}
public string Bookmark
{
get { return bookmark; }
set { bookmark = value; }
}
public string Tooltip
{
get { return tooltip;}
set { tooltip = value;}
}
public StyleInfo SI
{
get { return si;}
set { si = value;}
}
#region ICloneable Members
public object Clone()
{
return this.MemberwiseClone();
}
#endregion
#region IComparable Members
// Sort items based on zindex, then on order items were added to array
public int CompareTo(object obj)
{
PageItem pi = obj as PageItem;
int rc = this.zindex - pi.zindex;
if (rc == 0)
rc = this.itemNumber - pi.itemNumber;
return rc;
}
#endregion
}
public class PageImage : PageItem, ICloneable
{
string name; // name of object if constant image
ImageFormat imf; // type of image; png, jpeg are supported
byte[] imageData;
int samplesW;
int samplesH;
ImageRepeat repeat;
ImageSizingEnum sizing;
public PageImage(ImageFormat im, byte[] image, int w, int h)
{
Debug.Assert(im == ImageFormat.Jpeg || im == ImageFormat.Png || im == ImageFormat.Gif || im == ImageFormat.Wmf,
"PageImage only supports Jpeg, Gif and Png and WMF image formats (Thanks HYNE!).");
imf = im;
imageData = image;
samplesW = w;
samplesH = h;
repeat = ImageRepeat.NoRepeat;
sizing = ImageSizingEnum.AutoSize;
}
public byte[] ImageData
{
get {return imageData;}
}
public ImageFormat ImgFormat
{
get {return imf;}
}
public string Name
{
get {return name;}
set {name = value;}
}
public ImageRepeat Repeat
{
get {return repeat;}
set {repeat = value;}
}
public ImageSizingEnum Sizing
{
get {return sizing;}
set {sizing = value;}
}
public int SamplesW
{
get {return samplesW;}
}
public int SamplesH
{
get {return samplesH;}
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public enum ImageRepeat
{
Repeat, // repeat image in both x and y directions
NoRepeat, // don't repeat
RepeatX, // repeat image in x direction
RepeatY // repeat image in y direction
}
public class PageEllipse : PageItem, ICloneable
{
public PageEllipse()
{
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public class PageLine : PageItem, ICloneable
{
public PageLine()
{
}
public float X2
{
get {return W;}
set {W = value;}
}
public float Y2
{
get {return H;}
set {H = value;}
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public class PageCurve : PageItem, ICloneable
{
PointF[] _pointsF;
int _offset;
float _Tension;
public PageCurve()
{
}
public PointF[] Points
{
get { return _pointsF; }
set { _pointsF = value; }
}
public int Offset
{
get { return _offset; }
set { _offset = value; }
}
public float Tension
{
get { return _Tension; }
set { _Tension = value; }
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public class PagePolygon : PageItem, ICloneable
{
PointF[] Ps;
public PagePolygon()
{
}
public PointF[] Points
{
get {return Ps;}
set {Ps = value;}
}
}
public class PagePie : PageItem, ICloneable
{
Single SA;
Single SW;
public PagePie()
{
}
public Single StartAngle
{
get { return SA; }
set { SA = value; }
}
public Single SweepAngle
{
get { return SW; }
set { SW = value; }
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public class PageRectangle : PageItem, ICloneable
{
public PageRectangle()
{
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public class PageText : PageItem, ICloneable
{
string text; // the text
float descent; // in some cases the Font descent will be recorded; 0 otherwise
bool bGrow;
bool _NoClip=false; // on drawing disallow clipping
PageTextHtml _HtmlParent=null;
public PageText(string t)
{
text = t;
descent=0;
bGrow=false;
}
public PageTextHtml HtmlParent
{
get { return _HtmlParent; }
set { _HtmlParent = value; }
}
public string Text
{
get {return text;}
set {text = value;}
}
public float Descent
{
get {return descent;}
set {descent = value;}
}
public bool NoClip
{
get {return _NoClip;}
set {_NoClip = value;}
}
public bool CanGrow
{
get {return bGrow;}
set {bGrow = value;}
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
private IntPtr _acceptedFileDescriptor;
private int _socketAddressSize;
private SocketFlags _receivedFlags;
private Action<int, byte[], int, SocketFlags, SocketError> _transferCompletionCallback;
private void InitializeInternals()
{
// No-op for *nix.
}
private void FreeInternals()
{
// No-op for *nix.
}
private void SetupSingleBuffer()
{
// No-op for *nix.
}
private void SetupMultipleBuffers()
{
// No-op for *nix.
}
private void CompleteCore() { }
private void FinishOperationSync(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
Debug.Assert(socketError != SocketError.IOPending);
if (socketError == SocketError.Success)
{
FinishOperationSyncSuccess(bytesTransferred, flags);
}
else
{
FinishOperationSyncFailure(socketError, bytesTransferred, flags);
}
}
private void AcceptCompletionCallback(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError)
{
CompleteAcceptOperation(acceptedFileDescriptor, socketAddress, socketAddressSize, socketError);
CompletionCallback(0, SocketFlags.None, socketError);
}
private void CompleteAcceptOperation(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError)
{
_acceptedFileDescriptor = acceptedFileDescriptor;
Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer, $"Unexpected socketAddress: {socketAddress}");
_acceptAddressBufferCount = socketAddressSize;
}
internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle)
{
if (!_buffer.Equals(default))
{
throw new PlatformNotSupportedException(SR.net_sockets_accept_receive_notsupported);
}
_acceptedFileDescriptor = (IntPtr)(-1);
Debug.Assert(acceptHandle == null, $"Unexpected acceptHandle: {acceptHandle}");
IntPtr acceptedFd;
int socketAddressLen = _acceptAddressBufferCount / 2;
SocketError socketError = handle.AsyncContext.AcceptAsync(_acceptBuffer, ref socketAddressLen, out acceptedFd, AcceptCompletionCallback);
if (socketError != SocketError.IOPending)
{
CompleteAcceptOperation(acceptedFd, _acceptBuffer, socketAddressLen, socketError);
FinishOperationSync(socketError, 0, SocketFlags.None);
}
return socketError;
}
private void ConnectCompletionCallback(SocketError socketError)
{
CompletionCallback(0, SocketFlags.None, socketError);
}
internal unsafe SocketError DoOperationConnect(Socket socket, SafeSocketHandle handle)
{
SocketError socketError = handle.AsyncContext.ConnectAsync(_socketAddress.Buffer, _socketAddress.Size, ConnectCompletionCallback);
if (socketError != SocketError.IOPending)
{
FinishOperationSync(socketError, 0, SocketFlags.None);
}
return socketError;
}
internal SocketError DoOperationDisconnect(Socket socket, SafeSocketHandle handle)
{
SocketError socketError = SocketPal.Disconnect(socket, handle, _disconnectReuseSocket);
FinishOperationSync(socketError, 0, SocketFlags.None);
return socketError;
}
private Action<int, byte[], int, SocketFlags, SocketError> TransferCompletionCallback =>
_transferCompletionCallback ?? (_transferCompletionCallback = TransferCompletionCallbackCore);
private void TransferCompletionCallbackCore(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
{
CompleteTransferOperation(bytesTransferred, socketAddress, socketAddressSize, receivedFlags, socketError);
CompletionCallback(bytesTransferred, receivedFlags, socketError);
}
private void CompleteTransferOperation(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
{
Debug.Assert(socketAddress == null || socketAddress == _socketAddress.Buffer, $"Unexpected socketAddress: {socketAddress}");
_socketAddressSize = socketAddressSize;
_receivedFlags = receivedFlags;
}
internal unsafe SocketError DoOperationReceive(SafeSocketHandle handle, CancellationToken cancellationToken)
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
SocketFlags flags;
int bytesReceived;
SocketError errorCode;
if (_bufferList == null)
{
errorCode = handle.AsyncContext.ReceiveAsync(_buffer.Slice(_offset, _count), _socketFlags, out bytesReceived, out flags, TransferCompletionCallback, cancellationToken);
}
else
{
errorCode = handle.AsyncContext.ReceiveAsync(_bufferListInternal, _socketFlags, out bytesReceived, out flags, TransferCompletionCallback);
}
if (errorCode != SocketError.IOPending)
{
CompleteTransferOperation(bytesReceived, null, 0, flags, errorCode);
FinishOperationSync(errorCode, bytesReceived, flags);
}
return errorCode;
}
internal unsafe SocketError DoOperationReceiveFrom(SafeSocketHandle handle)
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
SocketFlags flags;
SocketError errorCode;
int bytesReceived = 0;
int socketAddressLen = _socketAddress.Size;
if (_bufferList == null)
{
errorCode = handle.AsyncContext.ReceiveFromAsync(_buffer.Slice(_offset, _count), _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback);
}
if (errorCode != SocketError.IOPending)
{
CompleteTransferOperation(bytesReceived, _socketAddress.Buffer, socketAddressLen, flags, errorCode);
FinishOperationSync(errorCode, bytesReceived, flags);
}
return errorCode;
}
private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
{
CompleteReceiveMessageFromOperation(bytesTransferred, socketAddress, socketAddressSize, receivedFlags, ipPacketInformation, errorCode);
CompletionCallback(bytesTransferred, receivedFlags, errorCode);
}
private void CompleteReceiveMessageFromOperation(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
{
Debug.Assert(_socketAddress != null, "Expected non-null _socketAddress");
Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress, $"Unexpected socketAddress: {socketAddress}");
_socketAddressSize = socketAddressSize;
_receivedFlags = receivedFlags;
_receiveMessageFromPacketInfo = ipPacketInformation;
}
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeSocketHandle handle)
{
_receiveMessageFromPacketInfo = default(IPPacketInformation);
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
bool isIPv4, isIPv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress, out isIPv4, out isIPv6);
int socketAddressSize = _socketAddress.Size;
int bytesReceived;
SocketFlags receivedFlags;
IPPacketInformation ipPacketInformation;
SocketError socketError = handle.AsyncContext.ReceiveMessageFromAsync(_buffer.Slice(_offset, _count), _bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressSize, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, ReceiveMessageFromCompletionCallback);
if (socketError != SocketError.IOPending)
{
CompleteReceiveMessageFromOperation(bytesReceived, _socketAddress.Buffer, socketAddressSize, receivedFlags, ipPacketInformation, socketError);
FinishOperationSync(socketError, bytesReceived, receivedFlags);
}
return socketError;
}
internal unsafe SocketError DoOperationSend(SafeSocketHandle handle, CancellationToken cancellationToken)
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
int bytesSent;
SocketError errorCode;
if (_bufferList == null)
{
errorCode = handle.AsyncContext.SendAsync(_buffer, _offset, _count, _socketFlags, out bytesSent, TransferCompletionCallback, cancellationToken);
}
else
{
errorCode = handle.AsyncContext.SendAsync(_bufferListInternal, _socketFlags, out bytesSent, TransferCompletionCallback);
}
if (errorCode != SocketError.IOPending)
{
CompleteTransferOperation(bytesSent, null, 0, SocketFlags.None, errorCode);
FinishOperationSync(errorCode, bytesSent, SocketFlags.None);
}
return errorCode;
}
internal SocketError DoOperationSendPackets(Socket socket, SafeSocketHandle handle)
{
Debug.Assert(_sendPacketsElements != null);
SendPacketsElement[] elements = (SendPacketsElement[])_sendPacketsElements.Clone();
FileStream[] files = new FileStream[elements.Length];
// Open all files synchronously ahead of time so that any exceptions are propagated
// to the caller, to match Windows behavior.
try
{
for (int i = 0; i < elements.Length; i++)
{
string path = elements[i]?.FilePath;
if (path != null)
{
files[i] = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, useAsync: true);
}
}
}
catch (Exception exc)
{
// Clean up any files that were already opened.
foreach (FileStream s in files)
{
s?.Dispose();
}
// Windows differentiates the directory not being found from the file not being found.
// Approximate this by checking to see if the directory exists; this is only best-effort,
// as there are various things that could affect this, e.g. directory creation racing with
// this check, but it's good enough for most situations.
if (exc is FileNotFoundException fnfe)
{
string dirname = Path.GetDirectoryName(fnfe.FileName);
if (!string.IsNullOrEmpty(dirname) && !Directory.Exists(dirname))
{
throw new DirectoryNotFoundException(fnfe.Message);
}
}
// Otherwise propagate the original error.
throw;
}
SocketPal.SendPacketsAsync(socket, SendPacketsFlags, elements, files, (bytesTransferred, error) =>
{
if (error == SocketError.Success)
{
FinishOperationAsyncSuccess((int)bytesTransferred, SocketFlags.None);
}
else
{
FinishOperationAsyncFailure(error, (int)bytesTransferred, SocketFlags.None);
}
});
return SocketError.IOPending;
}
internal SocketError DoOperationSendTo(SafeSocketHandle handle)
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
int bytesSent;
int socketAddressLen = _socketAddress.Size;
SocketError errorCode;
if (_bufferList == null)
{
errorCode = handle.AsyncContext.SendToAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesSent, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.SendToAsync(_bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesSent, TransferCompletionCallback);
}
if (errorCode != SocketError.IOPending)
{
CompleteTransferOperation(bytesSent, _socketAddress.Buffer, socketAddressLen, SocketFlags.None, errorCode);
FinishOperationSync(errorCode, bytesSent, SocketFlags.None);
}
return errorCode;
}
internal void LogBuffer(int size)
{
// This should only be called if tracing is enabled. However, there is the potential for a race
// condition where tracing is disabled between a calling check and here, in which case the assert
// may fire erroneously.
Debug.Assert(NetEventSource.IsEnabled);
if (_bufferList == null)
{
NetEventSource.DumpBuffer(this, _buffer, _offset, size);
}
else if (_acceptBuffer != null)
{
NetEventSource.DumpBuffer(this, _acceptBuffer, 0, size);
}
}
internal void LogSendPacketsBuffers(int size)
{
foreach (SendPacketsElement spe in _sendPacketsElements)
{
if (spe != null)
{
if (spe.Buffer != null && spe.Count > 0)
{
NetEventSource.DumpBuffer(this, spe.Buffer, spe.Offset, Math.Min(spe.Count, size));
}
else if (spe.FilePath != null)
{
NetEventSource.NotLoggedFile(spe.FilePath, _currentSocket, _completedOperation);
}
else if (spe.FileStream != null)
{
NetEventSource.NotLoggedFile(spe.FileStream.Name, _currentSocket, _completedOperation);
}
}
}
}
private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress)
{
System.Buffer.BlockCopy(_acceptBuffer, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount);
_acceptSocket = _currentSocket.CreateAcceptSocket(
SocketPal.CreateSocket(_acceptedFileDescriptor),
_currentSocket._rightEndPoint.Create(remoteSocketAddress));
return SocketError.Success;
}
private SocketError FinishOperationConnect()
{
// No-op for *nix.
return SocketError.Success;
}
private unsafe int GetSocketAddressSize()
{
return _socketAddressSize;
}
private unsafe void FinishOperationReceiveMessageFrom()
{
// No-op for *nix.
}
private void FinishOperationSendPackets()
{
// No-op for *nix.
}
private void CompletionCallback(int bytesTransferred, SocketFlags flags, SocketError socketError)
{
if (socketError == SocketError.Success)
{
FinishOperationAsyncSuccess(bytesTransferred, flags);
}
else
{
if (_currentSocket.Disposed)
{
socketError = SocketError.OperationAborted;
}
FinishOperationAsyncFailure(socketError, bytesTransferred, flags);
}
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// Section 5.2.25. Identifies the type of radio
/// </summary>
[Serializable]
[XmlRoot]
public partial class RadioEntityType
{
/// <summary>
/// Kind of entity
/// </summary>
private byte _entityKind;
/// <summary>
/// Domain of entity (air, surface, subsurface, space, etc)
/// </summary>
private byte _domain;
/// <summary>
/// country to which the design of the entity is attributed
/// </summary>
private ushort _country;
/// <summary>
/// category of entity
/// </summary>
private byte _category;
/// <summary>
/// subcategory of entity
/// </summary>
private byte _subcategory;
/// <summary>
/// specific info based on subcategory field
/// </summary>
private byte _nomenclatureVersion;
private ushort _nomenclature;
/// <summary>
/// Initializes a new instance of the <see cref="RadioEntityType"/> class.
/// </summary>
public RadioEntityType()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(RadioEntityType left, RadioEntityType right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(RadioEntityType left, RadioEntityType right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += 1; // this._entityKind
marshalSize += 1; // this._domain
marshalSize += 2; // this._country
marshalSize += 1; // this._category
marshalSize += 1; // this._subcategory
marshalSize += 1; // this._nomenclatureVersion
marshalSize += 2; // this._nomenclature
return marshalSize;
}
/// <summary>
/// Gets or sets the Kind of entity
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "entityKind")]
public byte EntityKind
{
get
{
return this._entityKind;
}
set
{
this._entityKind = value;
}
}
/// <summary>
/// Gets or sets the Domain of entity (air, surface, subsurface, space, etc)
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "domain")]
public byte Domain
{
get
{
return this._domain;
}
set
{
this._domain = value;
}
}
/// <summary>
/// Gets or sets the country to which the design of the entity is attributed
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "country")]
public ushort Country
{
get
{
return this._country;
}
set
{
this._country = value;
}
}
/// <summary>
/// Gets or sets the category of entity
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "category")]
public byte Category
{
get
{
return this._category;
}
set
{
this._category = value;
}
}
/// <summary>
/// Gets or sets the subcategory of entity
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "subcategory")]
public byte Subcategory
{
get
{
return this._subcategory;
}
set
{
this._subcategory = value;
}
}
/// <summary>
/// Gets or sets the specific info based on subcategory field
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "nomenclatureVersion")]
public byte NomenclatureVersion
{
get
{
return this._nomenclatureVersion;
}
set
{
this._nomenclatureVersion = value;
}
}
/// <summary>
/// Gets or sets the nomenclature
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "nomenclature")]
public ushort Nomenclature
{
get
{
return this._nomenclature;
}
set
{
this._nomenclature = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
dos.WriteUnsignedByte((byte)this._entityKind);
dos.WriteUnsignedByte((byte)this._domain);
dos.WriteUnsignedShort((ushort)this._country);
dos.WriteUnsignedByte((byte)this._category);
dos.WriteUnsignedByte((byte)this._subcategory);
dos.WriteUnsignedByte((byte)this._nomenclatureVersion);
dos.WriteUnsignedShort((ushort)this._nomenclature);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._entityKind = dis.ReadUnsignedByte();
this._domain = dis.ReadUnsignedByte();
this._country = dis.ReadUnsignedShort();
this._category = dis.ReadUnsignedByte();
this._subcategory = dis.ReadUnsignedByte();
this._nomenclatureVersion = dis.ReadUnsignedByte();
this._nomenclature = dis.ReadUnsignedShort();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<RadioEntityType>");
try
{
sb.AppendLine("<entityKind type=\"byte\">" + this._entityKind.ToString(CultureInfo.InvariantCulture) + "</entityKind>");
sb.AppendLine("<domain type=\"byte\">" + this._domain.ToString(CultureInfo.InvariantCulture) + "</domain>");
sb.AppendLine("<country type=\"ushort\">" + this._country.ToString(CultureInfo.InvariantCulture) + "</country>");
sb.AppendLine("<category type=\"byte\">" + this._category.ToString(CultureInfo.InvariantCulture) + "</category>");
sb.AppendLine("<subcategory type=\"byte\">" + this._subcategory.ToString(CultureInfo.InvariantCulture) + "</subcategory>");
sb.AppendLine("<nomenclatureVersion type=\"byte\">" + this._nomenclatureVersion.ToString(CultureInfo.InvariantCulture) + "</nomenclatureVersion>");
sb.AppendLine("<nomenclature type=\"ushort\">" + this._nomenclature.ToString(CultureInfo.InvariantCulture) + "</nomenclature>");
sb.AppendLine("</RadioEntityType>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as RadioEntityType;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(RadioEntityType obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (this._entityKind != obj._entityKind)
{
ivarsEqual = false;
}
if (this._domain != obj._domain)
{
ivarsEqual = false;
}
if (this._country != obj._country)
{
ivarsEqual = false;
}
if (this._category != obj._category)
{
ivarsEqual = false;
}
if (this._subcategory != obj._subcategory)
{
ivarsEqual = false;
}
if (this._nomenclatureVersion != obj._nomenclatureVersion)
{
ivarsEqual = false;
}
if (this._nomenclature != obj._nomenclature)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._entityKind.GetHashCode();
result = GenerateHash(result) ^ this._domain.GetHashCode();
result = GenerateHash(result) ^ this._country.GetHashCode();
result = GenerateHash(result) ^ this._category.GetHashCode();
result = GenerateHash(result) ^ this._subcategory.GetHashCode();
result = GenerateHash(result) ^ this._nomenclatureVersion.GetHashCode();
result = GenerateHash(result) ^ this._nomenclature.GetHashCode();
return result;
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERCLevel;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H09_Region_Child (editable child object).<br/>
/// This is a generated base class of <see cref="H09_Region_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="H08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class H09_Region_Child : BusinessBase<H09_Region_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name");
/// <summary>
/// Gets or sets the Cities Child Name.
/// </summary>
/// <value>The Cities Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H09_Region_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H09_Region_Child"/> object.</returns>
internal static H09_Region_Child NewH09_Region_Child()
{
return DataPortal.CreateChild<H09_Region_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="H09_Region_Child"/> object, based on given parameters.
/// </summary>
/// <param name="region_ID1">The Region_ID1 parameter of the H09_Region_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="H09_Region_Child"/> object.</returns>
internal static H09_Region_Child GetH09_Region_Child(int region_ID1)
{
return DataPortal.FetchChild<H09_Region_Child>(region_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H09_Region_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H09_Region_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="H09_Region_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H09_Region_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="region_ID1">The Region ID1.</param>
protected void Child_Fetch(int region_ID1)
{
var args = new DataPortalHookArgs(region_ID1);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IH09_Region_ChildDal>();
var data = dal.Fetch(region_ID1);
Fetch(data);
}
OnFetchPost(args);
}
private void Fetch(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="H09_Region_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Region_Child_NameProperty, dr.GetString("Region_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="H09_Region_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H08_Region parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IH09_Region_ChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Region_ID,
Region_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H09_Region_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(H08_Region parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IH09_Region_ChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Region_ID,
Region_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="H09_Region_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(H08_Region parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IH09_Region_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Region_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// File: HtmlParser.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Parser for Html-to-Xaml converter
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
// StringBuilder
// important TODOS:
// TODO 1. Start tags: The ParseXmlElement function has been modified to be called after both the
// angle bracket < and element name have been read, instead of just the < bracket and some valid name character,
// previously the case. This change was made so that elements with optional closing tags could read a new
// element's start tag and decide whether they were required to close. However, there is a question of whether to
// handle this in the parser or lexical analyzer. It is currently handled in the parser - the lexical analyzer still
// recognizes a start tag opener as a '<' + valid name start char; it is the parser that reads the actual name.
// this is correct behavior assuming that the name is a valid html name, because the lexical analyzer should not know anything
// about optional closing tags, etc. UPDATED: 10/13/2004: I am updating this to read the whole start tag of something
// that is not an HTML, treat it as empty, and add it to the tree. That way the converter will know it's there, but
// it will hvae no content. We could also partially recover by trying to look up and match names if they are similar
// TODO 2. Invalid element names: However, it might make sense to give the lexical analyzer the ability to identify
// a valid html element name and not return something as a start tag otherwise. For example, if we type <good>, should
// the lexical analyzer return that it has found the start of an element when this is not the case in HTML? But this will
// require implementing a lookahead token in the lexical analyzer so that it can treat an invalid element name as text. One
// character of lookahead will not be enough.
// TODO 3. Attributes: The attribute recovery is poor when reading attribute values in quotes - if no closing quotes are found,
// the lexical analyzer just keeps reading and if it eventually reaches the end of file, it would have just skipped everything.
// There are a couple of ways to deal with this: 1) stop reading attributes when we encounter a '>' character - this doesn't allow
// the '>' character to be used in attribute values, but it can still be used as an entity. 2) Maintain a HTML-specific list
// of attributes and their values that each html element can take, and if we find correct attribute namesand values for an
// element we use them regardless of the quotes, this way we could just ignore something invalid. One more option: 3) Read ahead
// in the quoted value and if we find an end of file, we can return to where we were and process as text. However this requires
// a lot of lookahead and a resettable reader.
// TODO 4: elements with optional closing tags: For elements with optional closing tags, we always close the element if we find
// that one of it's ancestors has closed. This condition may be too broad and we should develop a better heuristic. We should also
// improve the heuristics for closing certain elements when the next element starts
// TODO 5. Nesting: Support for unbalanced nesting, e.g. <b> <i> </b> </i>: this is not presently supported. To support it we may need
// to maintain two xml elements, one the element that represents what has already been read and another represents what we are presently reading.
// Then if we encounter an unbalanced nesting tag we could close the element that was supposed to close, save the current element
// and store it in the list of already-read content, and then open a new element to which all tags that are currently open
// can be applied. Is there a better way to do this? Should we do it at all?
// TODO 6. Elements with optional starting tags: there are 4 such elements in the HTML 4 specification - html, tbody, body and head.
// The current recovery doesn;t do anything for any of these elements except the html element, because it's not critical - head
// and body elementscan be contained within html element, and tbody is contained within table. To extend this for XHTML
// extensions, and to recover in case other elements are missing start tags, we would need to insert an extra recursive call
// to ParseXmlElement for the missing start tag. It is suggested to do this by giving ParseXmlElement an argument that specifies
// a name to use. If this argument is null, it assumes its name is the next token from the lexical analyzer and continues
// exactly as it does now. However, if the argument contains a valid html element name then it takes that value as its name
// and continues as before. This way, if the next token is the element that should actually be its child, it will see
// the name in the next step and initiate a recursive call. We would also need to add some logic in the loop for when a start tag
// is found - if the start tag is not compatible with current context and indicates that a start tag has been missed, then we
// can initiate the extra recursive call and give it the name of the missed start tag. The issues are when to insert this logic,
// and if we want to support it over multiple missing start tags. If we insert it at the time a start tag is read in element
// text, then we can support only one missing start tag, since the extra call will read the next start tag and make a recursive
// call without checking the context. This is a conceptual problem, and the check should be made just before a recursive call,
// with the choice being whether we should supply an element name as argument, or leave it as NULL and read from the input
// TODO 7: Context: Is it appropriate to keep track of context here? For example, should we only expect td, tr elements when
// reading a table and ignore them otherwise? This may be too much of a load on the parser, I think it's better if the converter
// deals with it
/// <summary>
/// HtmlParser class accepts a string of possibly badly formed Html, parses it and returns a string
/// of well-formed Html that is as close to the original string in content as possible
/// </summary>
internal class HtmlParser
{
// ---------------------------------------------------------------------
//
// Constructors
//
// ---------------------------------------------------------------------
#region Constructors
/// <summary>
/// Constructor. Initializes the _htmlLexicalAnalayzer element with the given input string
/// </summary>
/// <param name="inputString">
/// string to parsed into well-formed Html
/// </param>
private HtmlParser(string inputString)
{
// Create an output xml document
_document = new XmlDocument();
// initialize open tag stack
_openedElements = new Stack<XmlElement>();
_pendingInlineElements = new Stack<XmlElement>();
// initialize lexical analyzer
_htmlLexicalAnalyzer = new HtmlLexicalAnalyzer(inputString);
// get first token from input, expecting text
_htmlLexicalAnalyzer.GetNextContentToken();
}
#endregion Constructors
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Instantiates an HtmlParser element and calls the parsing function on the given input string
/// </summary>
/// <param name="htmlString">
/// Input string of pssibly badly-formed Html to be parsed into well-formed Html
/// </param>
/// <returns>
/// XmlElement rep
/// </returns>
internal static XmlElement ParseHtml(string htmlString)
{
HtmlParser htmlParser = new HtmlParser(htmlString);
XmlElement htmlRootElement = htmlParser.ParseHtmlContent();
return htmlRootElement;
}
// .....................................................................
//
// Html Header on Clipboard
//
// .....................................................................
// Html header structure.
// Version:1.0
// StartHTML:000000000
// EndHTML:000000000
// StartFragment:000000000
// EndFragment:000000000
// StartSelection:000000000
// EndSelection:000000000
internal const string HtmlHeader = "Version:1.0\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\nStartSelection:{4:D10}\r\nEndSelection:{5:D10}\r\n";
internal const string HtmlStartFragmentComment = "<!--StartFragment-->";
internal const string HtmlEndFragmentComment = "<!--EndFragment-->";
/// <summary>
/// Extracts Html string from clipboard data by parsing header information in htmlDataString
/// </summary>
/// <param name="htmlDataString">
/// String representing Html clipboard data. This includes Html header
/// </param>
/// <returns>
/// String containing only the Html data part of htmlDataString, without header
/// </returns>
internal static string ExtractHtmlFromClipboardData(string htmlDataString)
{
int startHtmlIndex = htmlDataString.IndexOf("StartHTML:");
if (startHtmlIndex < 0)
{
return "ERROR: Urecognized html header";
}
// TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
// which could be wrong assumption. We need to implement more flrxible parsing here
startHtmlIndex = Int32.Parse(htmlDataString.Substring(startHtmlIndex + "StartHTML:".Length, "0123456789".Length));
if (startHtmlIndex < 0 || startHtmlIndex > htmlDataString.Length)
{
return "ERROR: Urecognized html header";
}
int endHtmlIndex = htmlDataString.IndexOf("EndHTML:");
if (endHtmlIndex < 0)
{
return "ERROR: Urecognized html header";
}
// TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
// which could be wrong assumption. We need to implement more flrxible parsing here
endHtmlIndex = Int32.Parse(htmlDataString.Substring(endHtmlIndex + "EndHTML:".Length, "0123456789".Length));
if (endHtmlIndex > htmlDataString.Length)
{
endHtmlIndex = htmlDataString.Length;
}
return htmlDataString.Substring(startHtmlIndex, endHtmlIndex - startHtmlIndex);
}
/// <summary>
/// Adds Xhtml header information to Html data string so that it can be placed on clipboard
/// </summary>
/// <param name="htmlString">
/// Html string to be placed on clipboard with appropriate header
/// </param>
/// <returns>
/// String wrapping htmlString with appropriate Html header
/// </returns>
internal static string AddHtmlClipboardHeader(string htmlString)
{
StringBuilder stringBuilder = new StringBuilder();
// each of 6 numbers is represented by "{0:D10}" in the format string
// must actually occupy 10 digit positions ("0123456789")
int startHTML = HtmlHeader.Length + 6 * ("0123456789".Length - "{0:D10}".Length);
int endHTML = startHTML + htmlString.Length;
int startFragment = htmlString.IndexOf(HtmlStartFragmentComment, 0);
if (startFragment >= 0)
{
startFragment = startHTML + startFragment + HtmlStartFragmentComment.Length;
}
else
{
startFragment = startHTML;
}
int endFragment = htmlString.IndexOf(HtmlEndFragmentComment, 0);
if (endFragment >= 0)
{
endFragment = startHTML + endFragment;
}
else
{
endFragment = endHTML;
}
// Create HTML clipboard header string
stringBuilder.AppendFormat(HtmlHeader, startHTML, endHTML, startFragment, endFragment, startFragment, endFragment);
// Append HTML body.
stringBuilder.Append(htmlString);
return stringBuilder.ToString();
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Private methods
//
// ---------------------------------------------------------------------
#region Private Methods
private void InvariantAssert(bool condition, string message)
{
if (!condition)
{
throw new Exception("Assertion error: " + message);
}
}
/// <summary>
/// Parses the stream of html tokens starting
/// from the name of top-level element.
/// Returns XmlElement representing the top-level
/// html element
/// </summary>
private XmlElement ParseHtmlContent()
{
// Create artificial root elelemt to be able to group multiple top-level elements
// We create "html" element which may be a duplicate of real HTML element, which is ok, as HtmlConverter will swallow it painlessly..
XmlElement htmlRootElement = _document.CreateElement("html", XhtmlNamespace);
OpenStructuringElement(htmlRootElement);
while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF)
{
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.OpeningTagStart)
{
_htmlLexicalAnalyzer.GetNextTagToken();
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower();
_htmlLexicalAnalyzer.GetNextTagToken();
// Create an element
XmlElement htmlElement = _document.CreateElement(htmlElementName, XhtmlNamespace);
// Parse element attributes
ParseAttributes(htmlElement);
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.EmptyTagEnd || HtmlSchema.IsEmptyElement(htmlElementName))
{
// It is an element without content (because of explicit slash or based on implicit knowledge aboout html)
AddEmptyElement(htmlElement);
}
else if (HtmlSchema.IsInlineElement(htmlElementName))
{
// Elements known as formatting are pushed to some special
// pending stack, which allows them to be transferred
// over block tags - by doing this we convert
// overlapping tags into normal heirarchical element structure.
OpenInlineElement(htmlElement);
}
else if (HtmlSchema.IsBlockElement(htmlElementName) || HtmlSchema.IsKnownOpenableElement(htmlElementName))
{
// This includes no-scope elements
OpenStructuringElement(htmlElement);
}
else
{
// Do nothing. Skip the whole opening tag.
// Ignoring all unknown elements on their start tags.
// Thus we will ignore them on closinng tag as well.
// Anyway we don't know what to do withthem on conversion to Xaml.
}
}
else
{
// Note that the token following opening angle bracket must be a name - lexical analyzer must guarantee that.
// Otherwise - we skip the angle bracket and continue parsing the content as if it is just text.
// Add the following asserion here, right? or output "<" as a text run instead?:
// InvariantAssert(false, "Angle bracket without a following name is not expected");
}
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.ClosingTagStart)
{
_htmlLexicalAnalyzer.GetNextTagToken();
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower();
// Skip the name token. Assume that the following token is end of tag,
// but do not check this. If it is not true, we simply ignore one token
// - this is our recovery from bad xml in this case.
_htmlLexicalAnalyzer.GetNextTagToken();
CloseElement(htmlElementName);
}
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Text)
{
AddTextContent(_htmlLexicalAnalyzer.NextToken);
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Comment)
{
AddComment(_htmlLexicalAnalyzer.NextToken);
}
_htmlLexicalAnalyzer.GetNextContentToken();
}
// Get rid of the artificial root element
if (htmlRootElement.FirstChild is XmlElement &&
htmlRootElement.FirstChild == htmlRootElement.LastChild &&
htmlRootElement.FirstChild.LocalName.ToLower() == "html")
{
htmlRootElement = (XmlElement)htmlRootElement.FirstChild;
}
return htmlRootElement;
}
private XmlElement CreateElementCopy(XmlElement htmlElement)
{
XmlElement htmlElementCopy = _document.CreateElement(htmlElement.LocalName, XhtmlNamespace);
for (int i = 0; i < htmlElement.Attributes.Count; i++)
{
XmlAttribute attribute = htmlElement.Attributes[i];
htmlElementCopy.SetAttribute(attribute.Name, attribute.Value);
}
return htmlElementCopy;
}
private void AddEmptyElement(XmlElement htmlEmptyElement)
{
InvariantAssert(_openedElements.Count > 0, "AddEmptyElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlEmptyElement);
}
private void OpenInlineElement(XmlElement htmlInlineElement)
{
_pendingInlineElements.Push(htmlInlineElement);
}
// Opens structurig element such as Div or Table etc.
private void OpenStructuringElement(XmlElement htmlElement)
{
// Close all pending inline elements
// All block elements are considered as delimiters for inline elements
// which forces all inline elements to be closed and re-opened in the following
// structural element (if any).
// By doing that we guarantee that all inline elements appear only within most nested blocks
if (HtmlSchema.IsBlockElement(htmlElement.LocalName))
{
while (_openedElements.Count > 0 && HtmlSchema.IsInlineElement(_openedElements.Peek().LocalName))
{
XmlElement htmlInlineElement = _openedElements.Pop();
InvariantAssert(_openedElements.Count > 0, "OpenStructuringElement: stack of opened elements cannot become empty here");
_pendingInlineElements.Push(CreateElementCopy(htmlInlineElement));
}
}
// Add this block element to its parent
if (_openedElements.Count > 0)
{
XmlElement htmlParent = _openedElements.Peek();
// Check some known block elements for auto-closing (LI and P)
if (HtmlSchema.ClosesOnNextElementStart(htmlParent.LocalName, htmlElement.LocalName))
{
_openedElements.Pop();
htmlParent = _openedElements.Count > 0 ? _openedElements.Peek() : null;
}
if (htmlParent != null)
{
// NOTE:
// Actually we never expect null - it would mean two top-level P or LI (without a parent).
// In such weird case we will loose all paragraphs except the first one...
htmlParent.AppendChild(htmlElement);
}
}
// Push it onto a stack
_openedElements.Push(htmlElement);
}
private bool IsElementOpened(string htmlElementName)
{
foreach (XmlElement openedElement in _openedElements)
{
if (openedElement.LocalName == htmlElementName)
{
return true;
}
}
return false;
}
private void CloseElement(string htmlElementName)
{
// Check if the element is opened and already added to the parent
InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
// Check if the element is opened and still waiting to be added to the parent
if (_pendingInlineElements.Count > 0 && _pendingInlineElements.Peek().LocalName == htmlElementName)
{
// Closing an empty inline element.
// Note that HtmlConverter will skip empty inlines, but for completeness we keep them here on parser level.
XmlElement htmlInlineElement = _pendingInlineElements.Pop();
InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlInlineElement);
return;
}
else if (IsElementOpened(htmlElementName))
{
while (_openedElements.Count > 1) // we never pop the last element - the artificial root
{
// Close all unbalanced elements.
XmlElement htmlOpenedElement = _openedElements.Pop();
if (htmlOpenedElement.LocalName == htmlElementName)
{
return;
}
if (HtmlSchema.IsInlineElement(htmlOpenedElement.LocalName))
{
// Unbalances Inlines will be transfered to the next element content
_pendingInlineElements.Push(CreateElementCopy(htmlOpenedElement));
}
}
}
// If element was not opened, we simply ignore the unbalanced closing tag
return;
}
private void AddTextContent(string textContent)
{
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "AddTextContent: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
XmlText textNode = _document.CreateTextNode(textContent);
htmlParent.AppendChild(textNode);
}
private void AddComment(string comment)
{
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "AddComment: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
XmlComment xmlComment = _document.CreateComment(comment);
htmlParent.AppendChild(xmlComment);
}
// Moves all inline elements pending for opening to actual document
// and adds them to current open stack.
private void OpenPendingInlineElements()
{
if (_pendingInlineElements.Count > 0)
{
XmlElement htmlInlineElement = _pendingInlineElements.Pop();
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "OpenPendingInlineElements: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlInlineElement);
_openedElements.Push(htmlInlineElement);
}
}
private void ParseAttributes(XmlElement xmlElement)
{
while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF && //
_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.TagEnd && //
_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EmptyTagEnd)
{
// read next attribute (name=value)
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string attributeName = _htmlLexicalAnalyzer.NextToken;
_htmlLexicalAnalyzer.GetNextEqualSignToken();
_htmlLexicalAnalyzer.GetNextAtomToken();
string attributeValue = _htmlLexicalAnalyzer.NextToken;
xmlElement.SetAttribute(attributeName, attributeValue);
}
_htmlLexicalAnalyzer.GetNextTagToken();
}
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
internal const string XhtmlNamespace = "http://www.w3.org/1999/xhtml";
private HtmlLexicalAnalyzer _htmlLexicalAnalyzer;
// document from which all elements are created
private XmlDocument _document;
// stack for open elements
Stack<XmlElement> _openedElements;
Stack<XmlElement> _pendingInlineElements;
#endregion Private Fields
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: $
* $Date: $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
#region Using
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Xml;
using IBatisNet.Common;
using IBatisNet.Common.Exceptions;
using IBatisNet.Common.Logging;
using IBatisNet.Common.Utilities;
using IBatisNet.Common.Xml;
using IBatisNet.DataAccess.Configuration.Serializers;
using IBatisNet.DataAccess.Interfaces;
using IBatisNet.DataAccess.Scope;
#endregion
namespace IBatisNet.DataAccess.Configuration
{
/// <summary>
/// Summary description for DomDaoManagerBuilder.
/// </summary>
public class DomDaoManagerBuilder
{
#region Constants
/// <summary>
///
/// </summary>
public const string DAO_NAMESPACE_PREFIX = "dao";
private const string PROVIDERS_NAMESPACE_PREFIX = "provider";
private const string PROVIDER_XML_NAMESPACE = "http://ibatis.apache.org/providers";
private const string DAO_XML_NAMESPACE = "http://ibatis.apache.org/dataAccess";
private const string KEY_ATTRIBUTE = "key";
private const string VALUE_ATTRIBUTE = "value";
private const string ID_ATTRIBUTE = "id";
private readonly object [] EmptyObjects = new object [] {};
/// <summary>
/// Key for default config name
/// </summary>
public const string DEFAULT_FILE_CONFIG_NAME = "dao.config";
/// <summary>
/// Key for default provider name
/// </summary>
public const string DEFAULT_PROVIDER_NAME = "_DEFAULT_PROVIDER_NAME";
/// <summary>
/// Key for default dao session handler name
/// </summary>
public const string DEFAULT_DAOSESSIONHANDLER_NAME = "DEFAULT_DAOSESSIONHANDLER_NAME";
/// <summary>
/// Token for xml path to properties elements.
/// </summary>
private const string XML_PROPERTIES = "properties";
/// <summary>
/// Token for xml path to property elements.
/// </summary>
private const string XML_PROPERTY = "property";
/// <summary>
/// Token for xml path to settings add elements.
/// </summary>
private const string XML_SETTINGS_ADD = "/*/add";
/// <summary>
/// Token for xml path to DaoConfig providers element.
/// </summary>
private static string XML_CONFIG_PROVIDERS = "daoConfig/providers";
/// <summary>
/// Token for providers config file name.
/// </summary>
private const string PROVIDERS_FILE_NAME = "providers.config";
/// <summary>
/// Token for xml path to provider elements.
/// </summary>
private const string XML_PROVIDER = "providers/provider";
/// <summary>
/// Token for xml path to dao session handlers element.
/// </summary>
private const string XML_DAO_SESSION_HANDLERS = "daoConfig/daoSessionHandlers";
/// <summary>
/// Token for xml path to handler element.
/// </summary>
private const string XML_HANDLER = "handler";
/// <summary>
/// Token for xml path to dao context element.
/// </summary>
private const string XML_DAO_CONTEXT = "daoConfig/context";
/// <summary>
/// Token for xml path to database provider elements.
/// </summary>
private const string XML_DATABASE_PROVIDER = "database/provider";
/// <summary>
/// Token for xml path to database source elements.
/// </summary>
private const string XML_DATABASE_DATASOURCE = "database/dataSource";
/// <summary>
/// Token for xml path to dao session handler elements.
/// </summary>
private const string XML_DAO_SESSION_HANDLER = "daoSessionHandler";
/// <summary>
/// Token for xml path to dao elements.
/// </summary>
private const string XML_DAO = "daoFactory/dao";
#endregion
#region Fields
private static readonly ILog _logger = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType );
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Constructor.
/// </summary>
public DomDaoManagerBuilder(){ }
#endregion
#region Configure
/// <summary>
/// Configure DaoManagers from via the default file config.
/// (accesd as relative ressource path from your Application root)
/// </summary>
public void Configure()
{
Configure( DomDaoManagerBuilder.DEFAULT_FILE_CONFIG_NAME );
}
/// <summary>
/// Configure DaoManagers from an XmlDocument.
/// </summary>
/// <param name="document">An xml configuration document.</param>
public void Configure( XmlDocument document )
{
BuildDaoManagers( document, false );
}
/// <summary>
/// Configure DaoManagers from a file path.
/// </summary>
/// <param name="resource">
/// A relative ressource path from your Application root
/// or a absolue file path file:\\c:\dir\a.config
/// </param>
public void Configure(string resource)
{
XmlDocument document = null;
if (resource.StartsWith("file://"))
{
document = Resources.GetUrlAsXmlDocument( resource.Remove(0, 7) );
}
else
{
document = Resources.GetResourceAsXmlDocument( resource );
}
BuildDaoManagers( document, false );
}
/// <summary>
/// Configure DaoManagers from a stream.
/// </summary>
/// <param name="resource">A stream resource</param>
public void Configure(Stream resource)
{
XmlDocument document = Resources.GetStreamAsXmlDocument( resource );
BuildDaoManagers( document, false );
}
/// <summary>
/// Configure DaoManagers from a FileInfo.
/// </summary>
/// <param name="resource">A FileInfo resource</param>
/// <returns>An SqlMap</returns>
public void Configure(FileInfo resource)
{
XmlDocument document = Resources.GetFileInfoAsXmlDocument( resource );
BuildDaoManagers( document, false );
}
/// <summary>
/// Configure DaoManagers from an Uri.
/// </summary>
/// <param name="resource">A Uri resource</param>
/// <returns></returns>
public void Configure(Uri resource)
{
XmlDocument document = Resources.GetUriAsXmlDocument( resource );
BuildDaoManagers( document, false );
}
/// <summary>
/// Configure and monitor the configuration file for modifications and
/// automatically reconfigure
/// </summary>
/// <param name="configureDelegate">
/// Delegate called when a file is changed to rebuild the
/// </param>
public void ConfigureAndWatch(ConfigureHandler configureDelegate)
{
ConfigureAndWatch( DomDaoManagerBuilder.DEFAULT_FILE_CONFIG_NAME, configureDelegate );
}
/// <summary>
/// Configure and monitor the configuration file for modifications and
/// automatically reconfigure
/// </summary>
/// <param name="resource">
/// A relative ressource path from your Application root
/// or an absolue file path file://c:\dir\a.config
/// </param>
///<param name="configureDelegate">
/// Delegate called when the file has changed, to rebuild the dal.
/// </param>
public void ConfigureAndWatch(string resource, ConfigureHandler configureDelegate)
{
XmlDocument document = null;
if (resource.StartsWith("file://"))
{
document = Resources.GetUrlAsXmlDocument( resource.Remove(0, 7) );
}
else
{
document = Resources.GetResourceAsXmlDocument( resource );
}
ConfigWatcherHandler.ClearFilesMonitored();
ConfigWatcherHandler.AddFileToWatch( Resources.GetFileInfo( resource ) );
BuildDaoManagers( document, true );
TimerCallback callBakDelegate = new TimerCallback( DomDaoManagerBuilder.OnConfigFileChange );
StateConfig state = new StateConfig();
state.FileName = resource;
state.ConfigureHandler = configureDelegate;
new ConfigWatcherHandler( callBakDelegate, state );
}
/// <summary>
/// Configure and monitor the configuration file for modifications
/// and automatically reconfigure SqlMap.
/// </summary>
/// <param name="resource">
/// A FileInfo to your config file.
/// </param>
///<param name="configureDelegate">
/// Delegate called when the file has changed, to rebuild the dal.
/// </param>
/// <returns>An SqlMap</returns>
public void ConfigureAndWatch( FileInfo resource, ConfigureHandler configureDelegate )
{
XmlDocument document = Resources.GetFileInfoAsXmlDocument(resource);
ConfigWatcherHandler.ClearFilesMonitored();
ConfigWatcherHandler.AddFileToWatch( resource );
BuildDaoManagers( document, true );
TimerCallback callBakDelegate = new TimerCallback( DomDaoManagerBuilder.OnConfigFileChange );
StateConfig state = new StateConfig();
state.FileName = resource.FullName;
state.ConfigureHandler = configureDelegate;
new ConfigWatcherHandler( callBakDelegate, state );
}
/// <summary>
/// Called when the configuration has been updated.
/// </summary>
/// <param name="obj">The state config.</param>
public static void OnConfigFileChange(object obj)
{
StateConfig state = (StateConfig)obj;
state.ConfigureHandler(null);
}
#endregion
#region Methods
/// <summary>
/// Build DaoManagers from config document.
/// </summary>
// [MethodImpl(MethodImplOptions.Synchronized)]
public void BuildDaoManagers(XmlDocument document, bool useConfigFileWatcher)
{
ConfigurationScope configurationScope = new ConfigurationScope();
configurationScope.UseConfigFileWatcher = useConfigFileWatcher;
configurationScope.DaoConfigDocument = document;
configurationScope.XmlNamespaceManager = new XmlNamespaceManager(configurationScope.DaoConfigDocument.NameTable);
configurationScope.XmlNamespaceManager.AddNamespace(DAO_NAMESPACE_PREFIX, DAO_XML_NAMESPACE);
configurationScope.XmlNamespaceManager.AddNamespace(PROVIDERS_NAMESPACE_PREFIX, PROVIDER_XML_NAMESPACE);
try
{
GetConfig( configurationScope );
}
catch(Exception ex)
{
throw new ConfigurationException( configurationScope.ErrorContext.ToString(), ex);
}
}
/// <summary>
/// Load and build the dao managers.
/// </summary>
/// <param name="configurationScope">The scope of the configuration</param>
private void GetConfig(ConfigurationScope configurationScope)
{
GetProviders( configurationScope );
GetDaoSessionHandlers( configurationScope );
GetContexts( configurationScope );
}
/// <summary>
/// Load and initialize providers from specified file.
/// </summary>
/// <param name="configurationScope">The scope of the configuration</param>
private void GetProviders(ConfigurationScope configurationScope)
{
Provider provider = null;
XmlDocument xmlProviders = null;
configurationScope.ErrorContext.Activity = "Loading Providers config file";
XmlNode providersNode = null;
providersNode = configurationScope.DaoConfigDocument.SelectSingleNode( ApplyNamespacePrefix(XML_CONFIG_PROVIDERS), configurationScope.XmlNamespaceManager);
if (providersNode != null )
{
xmlProviders = Resources.GetAsXmlDocument( providersNode, configurationScope.Properties );
}
else
{
xmlProviders = Resources.GetConfigAsXmlDocument(PROVIDERS_FILE_NAME);
}
foreach (XmlNode node in xmlProviders.SelectNodes(ApplyProviderNamespacePrefix(XML_PROVIDER), configurationScope.XmlNamespaceManager ) )
{
configurationScope.ErrorContext.Resource = node.InnerXml.ToString();
provider = ProviderDeSerializer.Deserialize(node);
if (provider.IsEnabled == true)
{
configurationScope.ErrorContext.ObjectId = provider.Name;
configurationScope.ErrorContext.MoreInfo = "initialize provider";
provider.Initialize() ;
configurationScope.Providers.Add(provider.Name, provider);
if (provider.IsDefault == true)
{
if (configurationScope.Providers[DEFAULT_PROVIDER_NAME] == null)
{
configurationScope.Providers.Add(DEFAULT_PROVIDER_NAME, provider);
}
else
{
throw new ConfigurationException(
string.Format("Error while configuring the Provider named \"{0}\" There can be only one default Provider.",provider.Name));
}
}
}
}
configurationScope.ErrorContext.Reset();
}
/// <summary>
/// Load and initialize custom DaoSession Handlers.
/// </summary>
/// <param name="configurationScope">The scope of the configuration</param>
private void GetDaoSessionHandlers(ConfigurationScope configurationScope)
{
XmlNode daoSessionHandlersNode = null;
configurationScope.ErrorContext.Activity = "loading custom DaoSession Handlers";
daoSessionHandlersNode = configurationScope.DaoConfigDocument.SelectSingleNode( ApplyNamespacePrefix(XML_DAO_SESSION_HANDLERS), configurationScope.XmlNamespaceManager);
if (daoSessionHandlersNode != null)
{
foreach (XmlNode node in daoSessionHandlersNode.SelectNodes( ApplyNamespacePrefix(XML_HANDLER), configurationScope.XmlNamespaceManager))
{
configurationScope.ErrorContext.Resource = node.InnerXml.ToString();
DaoSessionHandler daoSessionHandler = DaoSessionHandlerDeSerializer.Deserialize(node, configurationScope);
configurationScope.ErrorContext.ObjectId = daoSessionHandler.Name;
configurationScope.ErrorContext.MoreInfo = "build daoSession handler";
configurationScope.DaoSectionHandlers[daoSessionHandler.Name] = daoSessionHandler.TypeInstance;
if (daoSessionHandler.IsDefault == true)
{
configurationScope.DaoSectionHandlers[DEFAULT_DAOSESSIONHANDLER_NAME] = daoSessionHandler.TypeInstance;
}
}
}
configurationScope.ErrorContext.Reset();
}
/// <summary>
/// Build dao contexts
/// </summary>
/// <param name="configurationScope">The scope of the configuration</param>
private void GetContexts(ConfigurationScope configurationScope)
{
DaoManager daoManager = null;
XmlAttribute attribute = null;
// Init
DaoManager.Reset();
// Build one daoManager for each context
foreach (XmlNode contextNode in configurationScope.DaoConfigDocument.SelectNodes(ApplyNamespacePrefix(XML_DAO_CONTEXT), configurationScope.XmlNamespaceManager))
{
configurationScope.ErrorContext.Activity = "build daoManager";
configurationScope.NodeContext = contextNode;
#region Configure a new DaoManager
daoManager = DaoManager.NewInstance();
// name
attribute = contextNode.Attributes["id"];
daoManager.Name = attribute.Value;
configurationScope.ErrorContext.Activity += daoManager.Name;
// default
attribute = contextNode.Attributes["default"];
if (attribute != null)
{
if (attribute.Value=="true")
{
daoManager.IsDefault = true;
}
else
{
daoManager.IsDefault= false;
}
}
else
{
daoManager.IsDefault= false;
}
#endregion
#region Properties
ParseGlobalProperties( configurationScope );
#endregion
#region provider
daoManager.Provider = ParseProvider( configurationScope );
configurationScope.ErrorContext.Resource = string.Empty;
configurationScope.ErrorContext.MoreInfo = string.Empty;
configurationScope.ErrorContext.ObjectId = string.Empty;
#endregion
#region DataSource
daoManager.DataSource = ParseDataSource( configurationScope );
daoManager.DataSource.Provider = daoManager.Provider;
#endregion
#region DaoSessionHandler
XmlNode nodeSessionHandler = contextNode.SelectSingleNode( ApplyNamespacePrefix(XML_DAO_SESSION_HANDLER), configurationScope.XmlNamespaceManager);
configurationScope.ErrorContext.Activity = "configure DaoSessionHandler";
// The resources use to initialize the SessionHandler
IDictionary resources = new Hashtable();
// By default, add the DataSource
resources.Add( "DataSource", daoManager.DataSource);
// By default, add the useConfigFileWatcher
resources.Add( "UseConfigFileWatcher", configurationScope.UseConfigFileWatcher);
IDaoSessionHandler sessionHandler = null;
Type typeSessionHandler = null;
if (nodeSessionHandler!= null)
{
configurationScope.ErrorContext.Resource = nodeSessionHandler.InnerXml.ToString();
typeSessionHandler = configurationScope.DaoSectionHandlers[nodeSessionHandler.Attributes[ID_ATTRIBUTE].Value] as Type;
// Parse property node
foreach(XmlNode nodeProperty in nodeSessionHandler.SelectNodes( ApplyNamespacePrefix(XML_PROPERTY), configurationScope.XmlNamespaceManager ))
{
resources.Add(nodeProperty.Attributes["name"].Value,
NodeUtils.ParsePropertyTokens(nodeProperty.Attributes["value"].Value, configurationScope.Properties));
}
}
else
{
typeSessionHandler = configurationScope.DaoSectionHandlers[DEFAULT_DAOSESSIONHANDLER_NAME] as Type;
}
// Configure the sessionHandler
configurationScope.ErrorContext.ObjectId = typeSessionHandler.FullName;
try
{
sessionHandler =(IDaoSessionHandler)Activator.CreateInstance(typeSessionHandler, EmptyObjects);
}
catch(Exception e)
{
throw new ConfigurationException(
string.Format("DaoManager could not configure DaoSessionHandler. DaoSessionHandler of type \"{0}\", failed. Cause: {1}", typeSessionHandler.Name, e.Message),e
);
}
sessionHandler.Configure(configurationScope.Properties, resources );
daoManager.DaoSessionHandler = sessionHandler;
configurationScope.ErrorContext.Resource = string.Empty;
configurationScope.ErrorContext.MoreInfo = string.Empty;
configurationScope.ErrorContext.ObjectId = string.Empty;
#endregion
#region Build Daos
ParseDaoFactory(configurationScope, daoManager);
#endregion
#region Register DaoManager
configurationScope.ErrorContext.MoreInfo = "register DaoManager";
configurationScope.ErrorContext.ObjectId = daoManager.Name;
DaoManager.RegisterDaoManager(daoManager.Name, daoManager);
configurationScope.ErrorContext.Resource = string.Empty;
configurationScope.ErrorContext.MoreInfo = string.Empty;
configurationScope.ErrorContext.ObjectId = string.Empty;
#endregion
}
}
/// <summary>
/// Initialize the list of variables defined in the
/// properties file.
/// </summary>
/// <param name="configurationScope">The scope of the configuration</param>
private void ParseGlobalProperties(ConfigurationScope configurationScope)
{
XmlNode nodeProperties = configurationScope.NodeContext.SelectSingleNode(ApplyNamespacePrefix(XML_PROPERTIES), configurationScope.XmlNamespaceManager);
configurationScope.ErrorContext.Activity = "add global properties";
if (nodeProperties != null)
{
if (nodeProperties.HasChildNodes)
{
foreach (XmlNode propertyNode in nodeProperties.SelectNodes(ApplyNamespacePrefix(XML_PROPERTY), configurationScope.XmlNamespaceManager))
{
XmlAttribute keyAttrib = propertyNode.Attributes[KEY_ATTRIBUTE];
XmlAttribute valueAttrib = propertyNode.Attributes[VALUE_ATTRIBUTE];
if ( keyAttrib != null && valueAttrib!=null)
{
configurationScope.Properties.Add( keyAttrib.Value, valueAttrib.Value);
_logger.Info( string.Format("Add property \"{0}\" value \"{1}\"",keyAttrib.Value,valueAttrib.Value) );
}
else
{
// Load the file defined by the attribute
XmlDocument propertiesConfig = Resources.GetAsXmlDocument(propertyNode, configurationScope.Properties);
foreach (XmlNode node in propertiesConfig.SelectNodes(XML_SETTINGS_ADD))
{
configurationScope.Properties[node.Attributes[KEY_ATTRIBUTE].Value] = node.Attributes[VALUE_ATTRIBUTE].Value;
_logger.Info( string.Format("Add property \"{0}\" value \"{1}\"",node.Attributes[KEY_ATTRIBUTE].Value,node.Attributes[VALUE_ATTRIBUTE].Value) );
}
}
}
}
else
{
// JIRA-38 Fix
// <properties> element's InnerXml is currently an empty string anyway
// since <settings> are in properties file
configurationScope.ErrorContext.Resource = nodeProperties.OuterXml.ToString();
// Load the file defined by the attribute
XmlDocument propertiesConfig = Resources.GetAsXmlDocument(nodeProperties, configurationScope.Properties);
foreach (XmlNode node in propertiesConfig.SelectNodes(XML_SETTINGS_ADD))
{
configurationScope.Properties[node.Attributes[KEY_ATTRIBUTE].Value] = node.Attributes[VALUE_ATTRIBUTE].Value;
_logger.Info( string.Format("Add property \"{0}\" value \"{1}\"",node.Attributes[KEY_ATTRIBUTE].Value,node.Attributes[VALUE_ATTRIBUTE].Value) );
}
}
// // Load the file defined by the resource attribut
// XmlDocument propertiesConfig = Resources.GetAsXmlDocument(nodeProperties, configurationScope.Properties);
//
// foreach (XmlNode node in propertiesConfig.SelectNodes("/settings/add"))
// {
// configurationScope.Properties[node.Attributes["key"].Value] = node.Attributes["value"].Value;
// }
}
configurationScope.ErrorContext.Resource = string.Empty;
configurationScope.ErrorContext.MoreInfo = string.Empty;
}
/// <summary>
/// Initialize the provider
/// </summary>
/// <param name="configurationScope">The scope of the configuration</param>
/// <returns>A provider</returns>
private Provider ParseProvider(ConfigurationScope configurationScope)
{
XmlAttribute attribute = null;
XmlNode node = configurationScope.NodeContext.SelectSingleNode( ApplyNamespacePrefix(XML_DATABASE_PROVIDER), configurationScope.XmlNamespaceManager);
configurationScope.ErrorContext.Activity = "configure provider";
if (node != null)
{
configurationScope.ErrorContext.Resource = node.OuterXml.ToString();
// name
attribute = node.Attributes["name"];
configurationScope.ErrorContext.ObjectId = attribute.Value;
if (configurationScope.Providers.Contains(attribute.Value) == true)
{
return (Provider)configurationScope.Providers[attribute.Value];
}
else
{
throw new ConfigurationException(
string.Format("Error while configuring the Provider named \"{0}\" in the Context named \"{1}\".",
attribute.Value, configurationScope.NodeContext.Attributes["name"].Value));
}
}
else
{
if(configurationScope.Providers.Contains(DEFAULT_PROVIDER_NAME) == true)
{
return (Provider) configurationScope.Providers[DEFAULT_PROVIDER_NAME];
}
else
{
throw new ConfigurationException(
string.Format("Error while configuring the Context named \"{0}\". There is no default provider.",
configurationScope.NodeContext.Attributes["name"].Value));
}
}
}
// /// <summary>
// /// Build a provider
// /// </summary>
// /// <param name="node"></param>
// /// <returns></returns>
// /// <remarks>
// /// Not use, I use it to test if it faster than serializer.
// /// But the tests are not concluant...
// /// </remarks>
// private static Provider BuildProvider(XmlNode node)
// {
// XmlAttribute attribute = null;
// Provider provider = new Provider();
//
// attribute = node.Attributes["assemblyName"];
// provider.AssemblyName = attribute.Value;
// attribute = node.Attributes["default"];
// if (attribute != null)
// {
// provider.IsDefault = Convert.ToBoolean( attribute.Value );
// }
// attribute = node.Attributes["enabled"];
// if (attribute != null)
// {
// provider.IsEnabled = Convert.ToBoolean( attribute.Value );
// }
// attribute = node.Attributes["connectionClass"];
// provider.ConnectionClass = attribute.Value;
// attribute = node.Attributes["UseParameterPrefixInSql"];
// if (attribute != null)
// {
// provider.UseParameterPrefixInSql = Convert.ToBoolean( attribute.Value );
// }
// attribute = node.Attributes["useParameterPrefixInParameter"];
// if (attribute != null)
// {
// provider.UseParameterPrefixInParameter = Convert.ToBoolean( attribute.Value );
// }
// attribute = node.Attributes["usePositionalParameters"];
// if (attribute != null)
// {
// provider.UsePositionalParameters = Convert.ToBoolean( attribute.Value );
// }
// attribute = node.Attributes["commandClass"];
// provider.CommandClass = attribute.Value;
// attribute = node.Attributes["parameterClass"];
// provider.ParameterClass = attribute.Value;
// attribute = node.Attributes["parameterDbTypeClass"];
// provider.ParameterDbTypeClass = attribute.Value;
// attribute = node.Attributes["parameterDbTypeProperty"];
// provider.ParameterDbTypeProperty = attribute.Value;
// attribute = node.Attributes["dataAdapterClass"];
// provider.DataAdapterClass = attribute.Value;
// attribute = node.Attributes["commandBuilderClass"];
// provider.CommandBuilderClass = attribute.Value;
// attribute = node.Attributes["commandBuilderClass"];
// provider.CommandBuilderClass = attribute.Value;
// attribute = node.Attributes["name"];
// provider.Name = attribute.Value;
// attribute = node.Attributes["parameterPrefix"];
// provider.ParameterPrefix = attribute.Value;
//
// return provider;
// }
/// <summary>
/// Build the data source object
/// </summary>
/// <param name="configurationScope">The scope of the configuration</param>
/// <returns>A DataSource</returns>
private DataSource ParseDataSource(ConfigurationScope configurationScope)
{
DataSource dataSource = null;
XmlNode node = configurationScope.NodeContext.SelectSingleNode( ApplyNamespacePrefix(XML_DATABASE_DATASOURCE), configurationScope.XmlNamespaceManager);
configurationScope.ErrorContext.Resource = node.InnerXml.ToString();
configurationScope.ErrorContext.MoreInfo = "configure data source";
dataSource = DataSourceDeSerializer.Deserialize( node );
// (DataSource)serializer.Deserialize(new XmlNodeReader(node));
dataSource.ConnectionString = NodeUtils.ParsePropertyTokens(dataSource.ConnectionString, configurationScope.Properties);
configurationScope.ErrorContext.Resource = string.Empty;
configurationScope.ErrorContext.MoreInfo = string.Empty;
return dataSource;
}
/// <summary>
/// Parse dao factory tag
/// </summary>
/// <param name="configurationScope">The scope of the configuration</param>
/// <param name="daoManager"></param>
private void ParseDaoFactory(ConfigurationScope configurationScope, DaoManager daoManager)
{
Dao dao = null;
configurationScope.ErrorContext.MoreInfo = "configure dao";
foreach (XmlNode node in configurationScope.NodeContext.SelectNodes(ApplyNamespacePrefix(XML_DAO), configurationScope.XmlNamespaceManager ))
{
dao = DaoDeSerializer.Deserialize(node, configurationScope);
//(Dao) serializer.Deserialize(new XmlNodeReader(node));
configurationScope.ErrorContext.ObjectId = dao.Implementation;
dao.Initialize(daoManager);
daoManager.RegisterDao(dao);
}
configurationScope.ErrorContext.Resource = string.Empty;
configurationScope.ErrorContext.MoreInfo = string.Empty;
configurationScope.ErrorContext.ObjectId = string.Empty;
}
/// <summary>
/// Apply an XML NameSpace
/// </summary>
/// <param name="elementName"></param>
/// <returns></returns>
public string ApplyNamespacePrefix( string elementName )
{
return DAO_NAMESPACE_PREFIX+ ":" + elementName.
Replace("/","/"+DAO_NAMESPACE_PREFIX+":");
}
/// <summary>
/// Apply the provider namespace prefix
/// </summary>
/// <param name="elementName"></param>
/// <returns></returns>
public string ApplyProviderNamespacePrefix( string elementName )
{
return PROVIDERS_NAMESPACE_PREFIX+ ":" + elementName.
Replace("/","/"+PROVIDERS_NAMESPACE_PREFIX+":");
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Collections;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace FastDbNet
{
//-------------------------------------------------------------------------
/// <summary>
/// FastDbBuffer encapsulates a binding between a memory buffer and an
/// object used to get/set data in the buffer.
/// </summary>
public class FastDbBuffer: IDisposable {
public static readonly int MIN_CAPACITY = ALIGN(30);
internal static int ALIGN(int size) { return size + size % Marshal.SizeOf(typeof(Int64)); }
public IntPtr buffer;
public string name;
public int flags; // cli_field_flags
public int bound_to_statement = -1;
// Make sure the delegate stays alive while in unmanaged code
internal unsafe static CLI.CliColumnGetEx doGetColumn = new CLI.CliColumnGetEx(GetColumn);
internal unsafe static CLI.CliColumnSetEx doSetColumn = new CLI.CliColumnSetEx(SetColumn);
private bool disposed;
public unsafe FastDbBuffer(string name, CLI.FieldType var_type, CLI.FieldFlags idx_flags) {
buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(CLI.UnmanagedBuffer)));
((CLI.UnmanagedBuffer*)buffer)->fetch_data = true;
((CLI.UnmanagedBuffer*)buffer)->type = (int)var_type;
((CLI.UnmanagedBuffer*)buffer)->size = CLI.SizeOfCliType[(int)var_type];
((CLI.UnmanagedBuffer*)buffer)->capacity = MIN_CAPACITY;
((CLI.UnmanagedBuffer*)buffer)->data = Marshal.AllocCoTaskMem(MIN_CAPACITY);
this.name = name; //Marshal.StringToHGlobalAnsi(name);
this.flags = (int)idx_flags;
disposed = false;
}
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method does not get called.
// It gives the base class the opportunity to finalize.
~FastDbBuffer() {
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
internal unsafe static IntPtr GetColumn(int var_type, IntPtr var_ptr, ref int len,
string column_name, int statement,
void* user_data)
{
CLI.UnmanagedBuffer* buffer = (CLI.UnmanagedBuffer*)user_data;
if (CLI.IsArrayType((CLI.FieldType)var_type))
len = buffer->size / CLI.SizeOfCliType[var_type - (int)CLI.FieldType.cli_array_of_oid];
else if (var_type == (int)CLI.FieldType.cli_asciiz || var_type == (int)CLI.FieldType.cli_pasciiz)
len = buffer->size-1;
else
len = buffer->size;
return buffer->data;
}
internal unsafe static IntPtr SetColumn(int var_type,
IntPtr var_ptr, int len, string column_name,
int statement, IntPtr data_ptr,
void* user_data)
{
CLI.UnmanagedBuffer* buffer = (CLI.UnmanagedBuffer*)user_data;
if (var_type == (int)CLI.FieldType.cli_asciiz || var_type == (int)CLI.FieldType.cli_pasciiz) {
SetBufferTypeAndSize(buffer, (CLI.FieldType)var_type, len, true);
return buffer->data;
}
else if (CLI.IsArrayType((CLI.FieldType)var_type)) {
if (buffer->fetch_data) {
SetBufferTypeAndSize(buffer, (CLI.FieldType)var_type,
len*CLI.SizeOfCliType[(int)var_type - (int)CLI.FieldType.cli_array_of_oid], true);
return buffer->data;
}
else
return IntPtr.Zero; // FastDB won't fetch a field if we return nil
}
else // sanity check
throw new CliError("Unsupported type: "+Enum.GetName(typeof(CLI.FieldType), buffer->type));
}
protected unsafe static void SetBufferTypeAndSize(CLI.UnmanagedBuffer* buf,
CLI.FieldType NewType, int NewSize, bool TypeCheck)
{
int n;
if (!TypeCheck || CLI.IsArrayType(NewType))
n = NewSize;
else if (NewType == CLI.FieldType.cli_asciiz || NewType == CLI.FieldType.cli_pasciiz)
n = NewSize+1;
else
n = CLI.SizeOfCliType[(int)NewType];
if (n > buf->capacity) {
buf->data = Marshal.ReAllocCoTaskMem(buf->data, ALIGN(n));
buf->capacity = n;
}
buf->size = n;
if (buf->type != (int)NewType)
buf->type = (int)NewType;
}
/// <summary>
/// Use Assign() method to copy the content of on FastDbBuffer to another.
/// </summary>
/// <param name="var">is the source FastDbBuffer to be copied from.</param>
public unsafe virtual void Assign(FastDbBuffer var) {
this.name = var.Name;
this.Capacity = var.Capacity;
this.bound_to_statement = var.StatementID;
this.FetchData = var.FetchData;
CopyBufferData(var.Type, var.Size, ((CLI.UnmanagedBuffer*)var.buffer.ToPointer())->data);
}
internal unsafe void CopyBufferData(CLI.FieldType type, int size, IntPtr data)
{
SetBufferTypeAndSize((CLI.UnmanagedBuffer*)buffer.ToPointer(), type, size, true);
Int64* pend = (Int64*)((byte*)data.ToPointer() + ALIGN(size));
Int64* pfrom = (Int64*)data.ToPointer();
Int64* pto = (Int64*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer();
while(pfrom < pend)
*pto++ = *pfrom++;
// for(int i=0; i < size; i++)
// *pto++ = *pfrom++;
// Note: buffers are always aligned to 8 bytes, so we can simply copy by
// iterating over 8 byte integers.
//if (type == CLI.FieldType.cli_asciiz || type == CLI.FieldType.cli_pasciiz)
// *pto = (byte)'\0';
}
/// <summary>
/// Bind() abstract method binds a FastDbBuffer to a FastDb statement obtained by calling
/// cli_statement() API function. The descendants are requiered to override this method.
/// </summary>
/// <param name="StatementID">integer value representing a FastDB statement</param>
internal unsafe virtual void Bind(int StatementID) {} // bound_to_statement = StatementID; }
/// <summary>
/// Unbind() clears the buffer binding to a statement.
/// </summary>
internal virtual unsafe void UnBind() { bound_to_statement = -1; } // Note: since 0 is a valid statement we initialize this to a negative value
/// <summary>
/// Returns the name of this field/parameter.
/// </summary>
public unsafe string Name { get { return name; } }
/// <summary>
/// Capacity controls internally allocated memory for the buffer.
/// By default minimum size of the buffer is 30 bytes, however, if you are
/// reading/writing large arrays or string values, you may consider setting
/// the Capacity field to a larger value in order to minimize memory reallocations.
/// </summary>
public unsafe int Capacity { get { return ((CLI.UnmanagedBuffer*)buffer.ToPointer())->capacity; } set { ((CLI.UnmanagedBuffer*)buffer.ToPointer())->capacity = value; } }
/// <summary>
/// Determines the size in bytes of current value in the buffer.
/// </summary>
public unsafe int Size { get { return ((CLI.UnmanagedBuffer*)buffer.ToPointer())->size; } }
/// <summary>
/// Returns the type of the value in the buffer.
/// </summary>
public unsafe CLI.FieldType Type { get { return (CLI.FieldType)((CLI.UnmanagedBuffer*)buffer.ToPointer())->type; } }
/// <summary>
/// Contains index flags indicating the types of indexes (hash/T-tree) on this field.
/// </summary>
public unsafe CLI.FieldFlags Flags { get { return (CLI.FieldFlags)flags; } }
/// <summary>
/// Internal statement's ID that this buffer is bound to.
/// </summary>
public unsafe int StatementID { get { return bound_to_statement; } }
/// <summary>
/// For array fields FetchData controls whether to copy the field's content
/// to the buffer when a cursor is moved to another record. By setting this
/// value to false, it may increase performance on queries that don't need to use
/// the content of the array field.
/// </summary>
public unsafe bool FetchData { get { return ((CLI.UnmanagedBuffer*)buffer.ToPointer())->fetch_data; } set { ((CLI.UnmanagedBuffer*)buffer.ToPointer())->fetch_data = value; } }
public bool asBoolean {get {return (bool)getValue(typeof(bool));} set {setValue(value);}}
public Int16 asInt16 {get {return (Int16)getValue(typeof(Int16));} set {setValue(value);}}
public int asInteger {get {return (int)getValue(typeof(int));} set {setValue(value);}}
public uint asOID {get {return (uint)getValue(typeof(uint));} set {setValue(value);}}
public Int64 asInt64 {get {return (Int64)getValue(typeof(Int64));} set {setValue(value);}}
public double asDouble {get {return (double)getValue(typeof(double));} set {setValue(value);}}
public string asString {get {return (string)getValue(typeof(string));} set {setValue(value);}}
public byte[] asByteArray {get {return (byte[])getValue(typeof(byte[]));} set {setValue(value);}}
protected unsafe virtual Object getValue(Type t) {
switch((CLI.FieldType)((CLI.UnmanagedBuffer*)buffer.ToPointer())->type) {
case CLI.FieldType.cli_bool:
case CLI.FieldType.cli_int1: return Convert.ChangeType(*(sbyte*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer(), t);
case CLI.FieldType.cli_int2: return Convert.ChangeType(*(short*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer(), t);
case CLI.FieldType.cli_oid: return Convert.ChangeType(*(uint*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer(), t);
case CLI.FieldType.cli_int4: return Convert.ChangeType(*(int*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer(), t);
case CLI.FieldType.cli_int8: return Convert.ChangeType(*(Int64*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer(), t);
case CLI.FieldType.cli_real4: return Convert.ChangeType(*(Single*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer(), t);
case CLI.FieldType.cli_datetime:
case CLI.FieldType.cli_real8: return Convert.ChangeType(*(double*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer(), t);
case CLI.FieldType.cli_asciiz:
case CLI.FieldType.cli_pasciiz: return Convert.ChangeType(Marshal.PtrToStringAnsi(((CLI.UnmanagedBuffer*)buffer.ToPointer())->data), t);
case CLI.FieldType.cli_array_of_int1:
if (t == typeof(byte[])) {
int len = Size;
byte[] arr = new byte[len];
byte* src = (byte*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer();
for (int i = 0; i < len; i++) {
arr[i] = *src++;
}
return arr;
} else {
throw new CliError("getValue: Unsupported conversion type! "+Enum.GetName(typeof(CLI.FieldType), ((CLI.UnmanagedBuffer*)buffer.ToPointer())->type));
}
default: throw new CliError("getValue: Unsupported type!"+Enum.GetName(typeof(CLI.FieldType), ((CLI.UnmanagedBuffer*)buffer.ToPointer())->type));
}
}
protected unsafe void setValue(Object Value) {
switch((CLI.FieldType)((CLI.UnmanagedBuffer*)buffer.ToPointer())->type) {
case CLI.FieldType.cli_oid:
*(uint*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer() = Convert.ToUInt32(Value);
break;
case CLI.FieldType.cli_int4:
*(int*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer() = Convert.ToInt32(Value);
break;
case CLI.FieldType.cli_bool:
case CLI.FieldType.cli_int1:
*(sbyte*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer() = Convert.ToSByte(Value);
break;
case CLI.FieldType.cli_int2:
*(Int16*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer() = Convert.ToInt16(Value);
break;
case CLI.FieldType.cli_int8:
*(Int64*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer() = Convert.ToInt64(Value);
break;
case CLI.FieldType.cli_real4:
*(Single*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer() = Convert.ToSingle(Value);
break;
case CLI.FieldType.cli_datetime:
case CLI.FieldType.cli_real8:
*(double*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer() = Convert.ToDouble(Value);
break;
case CLI.FieldType.cli_asciiz:
case CLI.FieldType.cli_pasciiz:
//byte[] bytes = Encoding.Convert(Encoding.Unicode, Encoding.ASCII, Encoding.Unicode.GetBytes(Value.ToString()));
//cli_ex_buffer_resize(buffer, buffer.type, bytes.Length, true);
//buffer.data = Marshal.AllocCoTaskMem( bytes.Length );
//Marshal.
//Marshal.Copy(bytes, 0, buffer.data, bytes.Length);
//fixed(char* p = &bytes[0])
//{
string s = Value.ToString();
IntPtr str = Marshal.StringToHGlobalAnsi(s);
try {
CopyBufferData((CLI.FieldType)((CLI.UnmanagedBuffer*)buffer.ToPointer())->type, s.Length, str);
}
finally {
Marshal.FreeCoTaskMem(str);
}
break;
case CLI.FieldType.cli_array_of_int1:
if (Value is byte[]) {
byte[] arr = (byte[])Value;
int len = arr.Length;
SetBufferTypeAndSize((CLI.UnmanagedBuffer*)buffer.ToPointer(), CLI.FieldType.cli_array_of_int1, len, false);
byte* dst = (byte*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer();
for (int i = 0; i < len; i++) {
*dst++ = arr[i];
}
break;
} else {
throw new CliError("getValue: Unsupported conversion type! "+Enum.GetName(typeof(CLI.FieldType), ((CLI.UnmanagedBuffer*)buffer.ToPointer())->type));
}
default:
throw new CliError("Unsupported type: "+Enum.GetName(typeof(CLI.FieldType), (CLI.FieldType)((CLI.UnmanagedBuffer*)buffer.ToPointer())->type));
}
}
// Implement IDisposable.
// This method is not virtual. A derived class should not be able to override this method.
public void Dispose() {
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
protected unsafe virtual void Dispose(bool disposing) {
// Check to see if Dispose has already been called.
if(!this.disposed) {
// If disposing equals true, dispose managed resources.
if(disposing) { // Dispose managed resources here.
Marshal.FreeCoTaskMem(((CLI.UnmanagedBuffer*)buffer.ToPointer())->data);
((CLI.UnmanagedBuffer*)buffer.ToPointer())->data = (IntPtr)0;
Marshal.FreeCoTaskMem(buffer);
}
// Release unmanaged resources.
//CLI.cli_ex_buffer_free(buffer);
disposed = true;
}
}
#region IEnumerable Members
public IEnumerator GetEnumerator() {
// TODO: Add FastDbBuffer.GetEnumerator implementation
return null;
}
#endregion
}
//-------------------------------------------------------------------------
/// <summary>
/// FastDbField implements a class that automatically manages the memory
/// associated with a field belonging to a database cursor.
/// </summary>
public class FastDbField: FastDbBuffer {
public string RefTable;
public string InvRefField;
/// <summary>
/// Field's constructor.
/// </summary>
/// <param name="name">Field name</param>
/// <param name="field_type">Field type</param>
/// <param name="idx_flags">Index types (hash/T-tree)</param>
/// <param name="ref_table">Reference table name for inverse reference fields</param>
/// <param name="inv_ref_field">Inverse reference field name</param>
public FastDbField(string name, CLI.FieldType field_type, CLI.FieldFlags idx_flags,
string ref_table, string inv_ref_field) :
base(name, field_type, idx_flags) {
this.RefTable = ref_table;
this.InvRefField = inv_ref_field;
}
/// <summary>
/// Copy field's content to the current field
/// </summary>
/// <param name="field">Source field to copy from</param>
public override void Assign(FastDbBuffer field) {
Debug.Assert(field is FastDbField, "Cannot assign " + field.GetType().Name + " type!");
base.Assign(field);
this.RefTable = ((FastDbField)field).RefTable;
this.InvRefField = ((FastDbField)field).InvRefField;
}
/// <summary>
/// Is true if the field is of array type.
/// </summary>
public bool IsArray { get { return CLI.IsArrayType(Type); } }
/// <summary>
/// Returns the number of array elements for array type fields
/// </summary>
public unsafe int ArraySize {
get {
if (CLI.IsArrayType(this.Type)) {
return Size / CLI.SizeOfCliType[(int)this.Type - (int)CLI.FieldType.cli_array_of_oid];
} else
return 0;
}
set {
Debug.Assert(CLI.IsArrayType(this.Type), "Cannot set array size on non-array fields: "+Enum.GetName(typeof(CLI.FieldType), Type));
int n = CLI.SizeOfCliType[(int)this.Type - (int)CLI.FieldType.cli_array_of_oid] * value;
if (Size != n)
SetBufferTypeAndSize((CLI.UnmanagedBuffer*)buffer.ToPointer(), this.Type, n, true);
}
}
public bool ArrayAsBoolean(int idx) { return (bool)getArrayValue(typeof(bool), idx);}
public Int16 ArrayAsInt16(int idx) { return (Int16)getArrayValue(typeof(Int16), idx);}
public uint ArrayAsOID(int idx) { return (uint)getArrayValue(typeof(uint), idx);}
public Int64 ArrayAsInt64(int idx) { return (Int64)getArrayValue(typeof(Int64), idx);}
public double ArrayAsDouble(int idx) { return (double)getArrayValue(typeof(double), idx);}
public string ArrayAsString(int idx) { return (string)getArrayValue(typeof(string), idx);}
protected unsafe Object getArrayValue(Type t, int idx) {
switch((CLI.FieldType)((CLI.UnmanagedBuffer*)buffer.ToPointer())->type) {
case CLI.FieldType.cli_array_of_bool:
case CLI.FieldType.cli_array_of_int1: return Convert.ChangeType(*((sbyte*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(sbyte)*idx), t);
case CLI.FieldType.cli_array_of_int2: return Convert.ChangeType(*((short*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(short)*idx), t);
case CLI.FieldType.cli_array_of_oid: return Convert.ChangeType(*((uint*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(uint)*idx), t);
case CLI.FieldType.cli_array_of_int4: return Convert.ChangeType(*((int*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(int)*idx), t);
case CLI.FieldType.cli_array_of_int8: return Convert.ChangeType(*((Int64*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(Int64)*idx), t);
case CLI.FieldType.cli_array_of_real4: return Convert.ChangeType(*((Single*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(Single)*idx), t);
case CLI.FieldType.cli_array_of_real8: return Convert.ChangeType(*((double*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(double)*idx), t);
default: throw new CliError("Unsupported type!");
}
}
/// <summary>
/// This method adds functionality to the base class that allows to get
/// the content of an array field as string.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
protected override unsafe Object getValue(Type t) {
if (t == typeof(string)) {
switch((CLI.FieldType)((CLI.UnmanagedBuffer*)buffer.ToPointer())->type) {
case CLI.FieldType.cli_array_of_int1:
case CLI.FieldType.cli_array_of_int2:
case CLI.FieldType.cli_array_of_int4:
case CLI.FieldType.cli_array_of_int8:
case CLI.FieldType.cli_array_of_oid:
case CLI.FieldType.cli_array_of_real4:
case CLI.FieldType.cli_array_of_real8:
StringBuilder s = new StringBuilder("{");
for(int i=0; i < ArraySize; i++) {
s.Append(ArrayAsString(i));
s.Append( (i == ArraySize-1) ? "" : "," );
}
s.Append("}");
return s.ToString();
}
}
return base.getValue(t);
}
/// <summary>
/// Set a value of an array element. <seealso cref="CLI.FieldType"/>
/// </summary>
/// <param name="idx">Element index</param>
/// <param name="Value">Element's new value</param>
public unsafe void SetArrayValue(int idx, Object Value) {
Debug.Assert(idx >= 0 && idx < ArraySize, "Array index " + idx + " out of bounds!");
switch((CLI.FieldType)((CLI.UnmanagedBuffer*)buffer.ToPointer())->type) {
case CLI.FieldType.cli_array_of_oid:
*((uint*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(uint)*idx) = Convert.ToUInt32(Value);
break;
case CLI.FieldType.cli_array_of_int4:
*((int*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(int)*idx) = Convert.ToInt32(Value);
break;
case CLI.FieldType.cli_array_of_bool:
case CLI.FieldType.cli_array_of_int1:
*((sbyte*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(sbyte)*idx) = Convert.ToSByte(Value);
break;
case CLI.FieldType.cli_array_of_int2:
*((Int16*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(Int16)*idx) = Convert.ToInt16(Value);
break;
case CLI.FieldType.cli_array_of_int8:
*((Int64*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(Int64)*idx) = Convert.ToInt64(Value);
break;
case CLI.FieldType.cli_array_of_real4:
*((Single*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(Single)*idx) = Convert.ToSingle(Value);
break;
case CLI.FieldType.cli_array_of_real8:
*((double*)((CLI.UnmanagedBuffer*)buffer.ToPointer())->data.ToPointer()+sizeof(double)*idx) = Convert.ToDouble(Value);
break;
default:
throw new CliError("Unsupported type!");
}
}
internal unsafe override void Bind(int StatementID) {
int res;
base.Bind(StatementID);
if (bound_to_statement == StatementID)
return;
else
bound_to_statement = StatementID;
//IntPtr pname = Marshal.StringToHGlobalAnsi(Name);
try {
if (CLI.IsArrayType(Type) || Type == CLI.FieldType.cli_asciiz || Type == CLI.FieldType.cli_pasciiz)
res = CLI.cli_array_column_ex(StatementID, name,
(Type == CLI.FieldType.cli_pasciiz) ? (int)CLI.FieldType.cli_asciiz : (int)Type,
((CLI.UnmanagedBuffer*)buffer.ToPointer())->data,
doSetColumn, doGetColumn, (CLI.UnmanagedBuffer*)buffer.ToPointer());
else
res = CLI.cli_column(StatementID, name, (int)Type, ref ((CLI.UnmanagedBuffer*)buffer.ToPointer())->size, ((CLI.UnmanagedBuffer*)buffer.ToPointer())->data);
CLI.CliCheck(res);
}
finally {
//Marshal.FreeCoTaskMem(name);
}
}
}
//-------------------------------------------------------------------------
/// <summary>
/// FastDbParameter implements a class that automatically manages the memory
/// associated with a parameter associated with a database statement.
/// </summary>
public class FastDbParameter: FastDbBuffer {
/// <summary>
/// Constructor that creates an instance of the FastDbField. You would
/// normally not use it directly, but by invoking: <see cref="FastDbFields.Add"/> method.
/// </summary>
/// <param name="name">The name of the field.</param>
/// <param name="var_type">The type of the field.</param>
/// <param name="capacity">Optional capacity of the field's buffer.</param>
public FastDbParameter(string name, CLI.FieldType var_type): this(name, var_type, 0) {}
public FastDbParameter(string name, CLI.FieldType var_type, int capacity) :
base(name, var_type, CLI.FieldFlags.cli_noindex) {}
public override void Assign(FastDbBuffer var) {
Debug.Assert(var is FastDbParameter, "Cannot assign " + var.GetType().Name + " type!");
base.Assign(var);
}
internal unsafe override void Bind(int StatementID) {
int res;
base.Bind(StatementID);
if (bound_to_statement == StatementID)
return;
else
bound_to_statement = StatementID;
if (CLI.IsArrayType(Type))
res = (int)CLI.ErrorCode.cli_not_implemented; // Array variables are not supported!
else {
string s = "%" + Name;
res = CLI.cli_parameter(StatementID, s, (int)Type, ((CLI.UnmanagedBuffer*)buffer.ToPointer())->data);
}
CLI.CliCheck(res);
}
}
//-------------------------------------------------------------------------
/// <summary>
/// FastDbCollection is the base class for FastDbFields and FastDbParameters. It
/// implements a collection of fields/parameters used to store
/// FastDbField/FastDbParameter objects.
/// </summary>
public abstract class FastDbCollection: IEnumerable {
protected ArrayList items = new ArrayList();
/// <summary>
/// Find an item by index.
/// </summary>
protected FastDbBuffer this[int index] { get { return (FastDbBuffer)items[index]; } }
/// <summary>
/// Find an item by name.
/// </summary>
protected FastDbBuffer this[string name] {
get {
for(int i=0; i<items.Count; i++)
if (String.Compare(name, ((FastDbBuffer)items[i]).Name, true) == 0)
return (FastDbBuffer)items[i];
throw new CliError("Parameter \"" + name + "\" not found!");
}
}
protected abstract FastDbBuffer Add(FastDbBuffer item);
/// <summary>
/// Get a count of items in the collection.
/// </summary>
public int Count { get { return items.Count; } }
/// <summary>
/// Clear the collection by removing all items.
/// </summary>
public void Clear() { UnBind(); items.Clear(); }
/// <summary>
/// Copy the contents of one collection to another.
/// </summary>
/// <param name="items">Source collection to copy items from.</param>
public virtual void Assign(FastDbCollection items) {
Clear();
for(int i=0; i<items.Count; ++i) this.Add(items[i]);
}
/// <summary>
/// Bind all fields/Parameters in the collection to a statement.
/// </summary>
/// <param name="statement"></param>
internal void Bind(int statement) {
for(int i=0; i<items.Count; ++i) this[i].Bind(statement);
}
/// <summary>
/// Unbind all fields from a statement.
/// </summary>
internal void UnBind() {
for(int i=0; i<items.Count; ++i) this[i].UnBind();
}
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public Iterator GetEnumerator() { return new Iterator(this); }
/// <summary>
/// This class implements IEnumerator interface. Use its methods within a
/// foreach() loop. Iterator.Index tells the field's index within a collection
/// and Iterator.IsLast is true if this is the last item.
/// </summary>
public class Iterator: IEnumerator {
#region Private Fields
int nIndex;
FastDbCollection collection;
#endregion
#region Constructors
public Iterator(FastDbCollection coll) {
collection = coll;
nIndex = -1;
}
#endregion
#region Methods
public void Reset() { nIndex = -1; }
public bool MoveNext() { return ++nIndex < collection.items.Count; }
public FastDbBuffer Current { get { return (FastDbBuffer)collection.items[nIndex]; } }
public int Index { get { return nIndex; } }
public bool IsLast { get { return nIndex == collection.items.Count-1; } }
// The current property on the IEnumerator interface:
object IEnumerator.Current { get { return Current; } }
#endregion
}
#endregion
}
//-------------------------------------------------------------------------
/// <summary>
/// A collection of fields belonging to a FastDbTable. It is usually accessed
/// by calling <see cref="FastDbCommand.Fields"/> property.
/// </summary>
public class FastDbFields: FastDbCollection {
protected override FastDbBuffer Add(FastDbBuffer item) { return this.Add((FastDbField)item); }
public FastDbField Add(FastDbField field) {
return Add(field.Name, field.Type, field.Flags, field.RefTable, field.InvRefField);
}
public FastDbField Add(string name, CLI.FieldType field_type) {
return Add(name, field_type, CLI.FieldFlags.cli_noindex, null, null);
}
public FastDbField Add(string name, CLI.FieldType field_type, CLI.FieldFlags index_type) {
return Add(name, field_type, index_type, null, null);
}
public FastDbField Add(string name, CLI.FieldType field_type, CLI.FieldFlags index_type, string ref_table) {
return Add(name, field_type, index_type, ref_table, null);
}
/// <summary>
/// Use this method to add a field to the collection.
/// </summary>
/// <param name="name">Name of the field</param>
/// <param name="field_type">Type of the field</param>
/// <param name="index_type">Optional index to be built on the field (default: CLI.FieldFlags.no_index)</param>
/// <param name="ref_table">Reference table name (used for inverse references). Default: null.</param>
/// <param name="inv_ref_field">Inverse reference field name (default: null)</param>
/// <returns></returns>
public FastDbField Add(string name, CLI.FieldType field_type, CLI.FieldFlags index_type, string ref_table, string inv_ref_field) {
int i = items.Add(new FastDbField(name, field_type, index_type, ref_table, inv_ref_field));
return (FastDbField)items[i];
}
/// <summary>
/// Get a field by index.
/// </summary>
public new FastDbField this[int index] { get { return (FastDbField)base[index]; } }
/// <summary>
/// Get a field by name.
/// </summary>
public new FastDbField this[string name] { get { return (FastDbField)base[name]; } }
}
/// <summary>
/// A collection of Parameters defined in a FastDb command.
/// <code>
/// FastDbCommand command =
/// new FastDbCommand(connection, "select * from tab where id = %id");
/// </code>
/// In the case above, the "id" is a parameter that can be associated with a
/// value using:
/// <code>
/// command.Parameters.Add("id", CLI.FieldType.cli_int4);
/// command.Parameters[0].Value = 10;
/// int num_rows = command.Execute();
/// </code>
/// </summary>
public class FastDbParameters: FastDbCollection {
protected override FastDbBuffer Add(FastDbBuffer param) {
return this.Add(param.Name, param.Type, param.Capacity);
}
public FastDbParameter Add(string name, CLI.FieldType param_type) {
Debug.Assert(param_type >= CLI.FieldType.cli_oid && param_type < CLI.FieldType.cli_array_of_oid,
String.Format("Parameter type {0} not supported!", Enum.GetName(typeof(CLI.FieldType), param_type)));
return this.Add(name, param_type, 0);
}
/// <summary>
/// Add a parameter to the FastDbParameters collection.
/// </summary>
/// <param name="name">Parameter name (as it appears in the SQL statement) without preceeding "%".</param>
/// <param name="param_type">Parameter type (it must match the type of the associated field).</param>
/// <param name="capacity">Optional capacity of the underlying memory buffer.</param>
/// <returns>A object representing the newly created parameter</returns>
public FastDbParameter Add(string name, CLI.FieldType param_type, int capacity) {
int i = items.Add(new FastDbParameter(name, param_type, capacity));
return (FastDbParameter)items[i];
}
/// <summary>
/// Get a parameter by index.
/// </summary>
public new FastDbParameter this[int index] { get { return (FastDbParameter)base[index]; } }
/// <summary>
/// Get a parameter by name.
/// </summary>
public new FastDbParameter this[string name] { get { return (FastDbParameter)base[name]; } }
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(PORTABLE40 || NET20 || NET35)
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Newtonsoft.Json.Utilities
{
internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory
{
private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory();
internal static ReflectionDelegateFactory Instance
{
get { return _instance; }
}
public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, "method");
Type type = typeof(object);
ParameterExpression targetParameterExpression = Expression.Parameter(type, "target");
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
ParameterInfo[] parametersInfo = method.GetParameters();
Expression[] argsExpression = new Expression[parametersInfo.Length];
for (int i = 0; i < parametersInfo.Length; i++)
{
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
paramAccessorExpression = EnsureCastExpression(paramAccessorExpression, parametersInfo[i].ParameterType);
argsExpression[i] = paramAccessorExpression;
}
Expression callExpression;
if (method.IsConstructor)
{
callExpression = Expression.New((ConstructorInfo)method, argsExpression);
}
else if (method.IsStatic)
{
callExpression = Expression.Call((MethodInfo)method, argsExpression);
}
else
{
Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);
callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression);
}
if (method is MethodInfo)
{
MethodInfo m = (MethodInfo)method;
if (m.ReturnType != typeof(void))
callExpression = EnsureCastExpression(callExpression, type);
else
callExpression = Expression.Block(callExpression, Expression.Constant(null));
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall<T, object>), callExpression, targetParameterExpression, argsParameterExpression);
MethodCall<T, object> compiled = (MethodCall<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
// avoid error from expressions compiler because of abstract class
if (type.IsAbstract())
return () => (T)Activator.CreateInstance(type);
try
{
Type resultType = typeof(T);
Expression expression = Expression.New(type);
expression = EnsureCastExpression(expression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T>), expression);
Func<T> compiled = (Func<T>)lambdaExpression.Compile();
return compiled;
}
catch
{
// an error can be thrown if constructor is not valid on Win8
// will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag
return () => (T)Activator.CreateInstance(type);
}
}
public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
Type instanceType = typeof(T);
Type resultType = typeof(object);
ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance");
Expression resultExpression;
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod.IsStatic)
{
resultExpression = Expression.MakeMemberAccess(null, propertyInfo);
}
else
{
Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType);
resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo);
}
resultExpression = EnsureCastExpression(resultExpression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T, object>), resultExpression, parameterExpression);
Func<T, object> compiled = (Func<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
ParameterExpression sourceParameter = Expression.Parameter(typeof(T), "source");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
fieldExpression = EnsureCastExpression(fieldExpression, typeof(object));
Func<T, object> compiled = Expression.Lambda<Func<T, object>>(fieldExpression, sourceParameter).Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
// use reflection for structs
// expression doesn't correctly set value
if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly)
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo);
ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source");
ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type);
BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), assignExpression, sourceParameterExpression, valueParameterExpression);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
// use reflection for structs
// expression doesn't correctly set value
if (propertyInfo.DeclaringType.IsValueType())
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo);
Type instanceType = typeof(T);
Type valueType = typeof(object);
ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance");
ParameterExpression valueParameter = Expression.Parameter(valueType, "value");
Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType);
MethodInfo setMethod = propertyInfo.GetSetMethod(true);
Expression setExpression;
if (setMethod.IsStatic)
{
setExpression = Expression.Call(setMethod, readValueParameter);
}
else
{
Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType);
setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter);
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), setExpression, instanceParameter, valueParameter);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
private Expression EnsureCastExpression(Expression expression, Type targetType)
{
Type expressionType = expression.Type;
// check if a cast or conversion is required
if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType)))
return expression;
return Expression.Convert(expression, targetType);
}
}
}
#endif
| |
//-----------------------------------------------------------------------
// <copyright file="Framing.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Akka.IO;
using Akka.Streams.Implementation.Stages;
using Akka.Streams.Stage;
using Akka.Util;
namespace Akka.Streams.Dsl
{
/// <summary>
/// TBD
/// </summary>
public static class Framing
{
/// <summary>
/// Creates a Flow that handles decoding a stream of unstructured byte chunks into a stream of frames where the
/// incoming chunk stream uses a specific byte-sequence to mark frame boundaries.
///
/// The decoded frames will not include the separator sequence.
///
/// If there are buffered bytes (an incomplete frame) when the input stream finishes and <paramref name="allowTruncation"/> is set to
/// false then this Flow will fail the stream reporting a truncated frame.
/// </summary>
/// <param name="delimiter">The byte sequence to be treated as the end of the frame.</param>
/// <param name="maximumFrameLength">The maximum length of allowed frames while decoding. If the maximum length is exceeded this Flow will fail the stream.</param>
/// <param name="allowTruncation">If false, then when the last frame being decoded contains no valid delimiter this Flow fails the stream instead of returning a truncated frame.</param>
/// <returns>TBD</returns>
public static Flow<ByteString, ByteString, NotUsed> Delimiter(ByteString delimiter, int maximumFrameLength,
bool allowTruncation = false)
{
return Flow.Create<ByteString>()
.Via(new DelimiterFramingStage(delimiter, maximumFrameLength, allowTruncation))
.Named("DelimiterFraming");
}
/// <summary>
/// Creates a Flow that decodes an incoming stream of unstructured byte chunks into a stream of frames, assuming that
/// incoming frames have a field that encodes their length.
///
/// If the input stream finishes before the last frame has been fully decoded this Flow will fail the stream reporting
/// a truncated frame.
/// </summary>
/// <param name="fieldLength">The length of the "Count" field in bytes</param>
/// <param name="maximumFramelength">The maximum length of allowed frames while decoding. If the maximum length is exceeded this Flow will fail the stream. This length *includes* the header (i.e the offset and the length of the size field)</param>
/// <param name="fieldOffset">The offset of the field from the beginning of the frame in bytes</param>
/// <param name="byteOrder">The <see cref="ByteOrder"/> to be used when decoding the field</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the specified <paramref name="fieldLength"/> is not equal to either 1, 2, 3 or 4.
/// </exception>
/// <returns>TBD</returns>
public static Flow<ByteString, ByteString, NotUsed> LengthField(int fieldLength, int maximumFramelength,
int fieldOffset = 0, ByteOrder byteOrder = ByteOrder.LittleEndian)
{
if (fieldLength < 1 || fieldLength > 4)
throw new ArgumentException("Length field length must be 1,2,3 or 4", nameof(fieldLength));
return Flow.Create<ByteString>()
.Transform(() => new LengthFieldFramingStage(fieldLength, maximumFramelength, fieldOffset, byteOrder))
.Named("LengthFieldFraming");
}
/// <summary>
/// Returns a BidiFlow that implements a simple framing protocol. This is a convenience wrapper over <see cref="LengthField"/>
/// and simply attaches a length field header of four bytes (using big endian encoding) to outgoing messages, and decodes
/// such messages in the inbound direction. The decoded messages do not contain the header.
///
/// This BidiFlow is useful if a simple message framing protocol is needed (for example when TCP is used to send
/// individual messages) but no compatibility with existing protocols is necessary.
///
/// The encoded frames have the layout
/// {{{
/// [4 bytes length field, Big Endian][User Payload]
/// }}}
/// The length field encodes the length of the user payload excluding the header itself.
/// </summary>
/// <param name="maximumMessageLength">Maximum length of allowed messages. If sent or received messages exceed the configured limit this BidiFlow will fail the stream. The header attached by this BidiFlow are not included in this limit.</param>
/// <returns>TBD</returns>
public static BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed> SimpleFramingProtocol(int maximumMessageLength)
{
return BidiFlow.FromFlowsMat(SimpleFramingProtocolEncoder(maximumMessageLength),
SimpleFramingProtocolDecoder(maximumMessageLength), Keep.Left);
}
/// <summary>
/// Protocol decoder that is used by <see cref="SimpleFramingProtocol"/>
/// </summary>
/// <param name="maximumMessageLength">TBD</param>
/// <returns>TBD</returns>
public static Flow<ByteString, ByteString, NotUsed> SimpleFramingProtocolDecoder(int maximumMessageLength)
{
return LengthField(4, maximumMessageLength + 4, 0, ByteOrder.BigEndian).Select(b => b.Slice(4));
}
/// <summary>
/// Protocol encoder that is used by <see cref="SimpleFramingProtocol"/>
/// </summary>
/// <param name="maximumMessageLength">TBD</param>
/// <returns>TBD</returns>
public static Flow<ByteString, ByteString, NotUsed> SimpleFramingProtocolEncoder(int maximumMessageLength)
{
return Flow.Create<ByteString>().Transform(() => new FramingDecoderStage(maximumMessageLength));
}
/// <summary>
/// TBD
/// </summary>
public class FramingException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="FramingException" /> class.
/// </summary>
/// <param name="message">The message that describes the error. </param>
public FramingException(string message) : base(message)
{
}
}
private static readonly Func<IEnumerator<byte>, int, int> BigEndianDecoder = (enumerator, length) =>
{
var count = length;
var decoded = 0;
while (count > 0)
{
decoded <<= 8;
if (!enumerator.MoveNext()) throw new IndexOutOfRangeException("LittleEndianDecoder reached end of byte string");
decoded |= enumerator.Current & 0xFF;
count--;
}
return decoded;
};
private static readonly Func<IEnumerator<byte>, int, int> LittleEndianDecoder = (enumerator, length) =>
{
var highestOcted = (length - 1) << 3;
var mask = (int) (1L << (length << 3)) - 1;
var count = length;
var decoded = 0;
while (count > 0)
{
// decoded >>>= 8 on the jvm
decoded = (int) ((uint) decoded >> 8);
if (!enumerator.MoveNext()) throw new IndexOutOfRangeException("LittleEndianDecoder reached end of byte string");
decoded += (enumerator.Current & 0xFF) << highestOcted;
count--;
}
return decoded & mask;
};
private sealed class FramingDecoderStage : PushStage<ByteString, ByteString>
{
private readonly int _maximumMessageLength;
public FramingDecoderStage(int maximumMessageLength)
{
_maximumMessageLength = maximumMessageLength;
}
public override ISyncDirective OnPush(ByteString element, IContext<ByteString> context)
{
var messageSize = element.Count;
if (messageSize > _maximumMessageLength)
return context.Fail(new FramingException($"Maximum allowed message size is {_maximumMessageLength} but tried to send {messageSize} bytes"));
var header = ByteString.FromBytes(new[]
{
Convert.ToByte((messageSize >> 24) & 0xFF),
Convert.ToByte((messageSize >> 16) & 0xFF),
Convert.ToByte((messageSize >> 8) & 0xFF),
Convert.ToByte(messageSize & 0xFF)
});
return context.Push(header + element);
}
}
private sealed class DelimiterFramingStage : GraphStage<FlowShape<ByteString, ByteString>>
{
#region Logic
private sealed class Logic : InAndOutGraphStageLogic
{
private readonly DelimiterFramingStage _stage;
private readonly byte _firstSeparatorByte;
private ByteString _buffer;
private int _nextPossibleMatch;
public Logic(DelimiterFramingStage stage) : base (stage.Shape)
{
_stage = stage;
_firstSeparatorByte = stage._separatorBytes[0];
_buffer = ByteString.Empty;
SetHandler(stage.In, this);
SetHandler(stage.Out, this);
}
public override void OnPush()
{
_buffer += Grab(_stage.In);
DoParse();
}
public override void OnUpstreamFinish()
{
if (_buffer.IsEmpty)
CompleteStage();
else if (IsAvailable(_stage.Out))
DoParse();
// else swallow the termination and wait for pull
}
public override void OnPull() => DoParse();
private void TryPull()
{
if (IsClosed(_stage.In))
{
if (_stage._allowTruncation)
{
Push(_stage.Out, _buffer);
CompleteStage();
}
else
FailStage(
new FramingException(
"Stream finished but there was a truncated final frame in the buffer"));
}
else
Pull(_stage.In);
}
private void DoParse()
{
while (true)
{
var possibleMatchPosition = _buffer.IndexOf(_firstSeparatorByte, from: _nextPossibleMatch);
if (possibleMatchPosition > _stage._maximumLineBytes)
{
FailStage(new FramingException($"Read {_buffer.Count} bytes which is more than {_stage._maximumLineBytes} without seeing a line terminator"));
}
else if (possibleMatchPosition == -1)
{
if (_buffer.Count > _stage._maximumLineBytes)
FailStage(new FramingException($"Read {_buffer.Count} bytes which is more than {_stage._maximumLineBytes} without seeing a line terminator"));
else
{
// No matching character, we need to accumulate more bytes into the buffer
_nextPossibleMatch = _buffer.Count;
TryPull();
}
}
else if (possibleMatchPosition + _stage._separatorBytes.Count > _buffer.Count)
{
// We have found a possible match (we found the first character of the terminator
// sequence) but we don't have yet enough bytes. We remember the position to
// retry from next time.
_nextPossibleMatch = possibleMatchPosition;
TryPull();
}
else if (_buffer.HasSubstring(_stage._separatorBytes, possibleMatchPosition))
{
// Found a match
var parsedFrame = _buffer.Slice(0, possibleMatchPosition).Compact();
_buffer = _buffer.Slice(possibleMatchPosition + _stage._separatorBytes.Count).Compact();
_nextPossibleMatch = 0;
Push(_stage.Out, parsedFrame);
if (IsClosed(_stage.In) && _buffer.IsEmpty)
CompleteStage();
}
else
{
// possibleMatchPos was not actually a match
_nextPossibleMatch++;
continue;
}
break;
}
}
}
#endregion
private readonly ByteString _separatorBytes;
private readonly int _maximumLineBytes;
private readonly bool _allowTruncation;
public DelimiterFramingStage(ByteString separatorBytes, int maximumLineBytes, bool allowTruncation)
{
_separatorBytes = separatorBytes;
_maximumLineBytes = maximumLineBytes;
_allowTruncation = allowTruncation;
Shape = new FlowShape<ByteString, ByteString>(In, Out);
}
private Inlet<ByteString> In = new Inlet<ByteString>("DelimiterFraming.in");
private Outlet<ByteString> Out = new Outlet<ByteString>("DelimiterFraming.in");
public override FlowShape<ByteString, ByteString> Shape { get; }
protected override Attributes InitialAttributes { get; } = DefaultAttributes.DelimiterFraming;
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
public override string ToString() => "DelimiterFraming";
}
private sealed class LengthFieldFramingStage : PushPullStage<ByteString, ByteString>
{
private readonly int _lengthFieldLength;
private readonly int _maximumFramelength;
private readonly int _lengthFieldOffset;
private ByteString _buffer = ByteString.Empty;
private readonly int _minimumChunkSize;
private int _frameSize;
private readonly Func<IEnumerator<byte>, int, int> _intDecoder;
public LengthFieldFramingStage(int lengthFieldLength, int maximumFramelength, int lengthFieldOffset, ByteOrder byteOrder)
{
_lengthFieldLength = lengthFieldLength;
_maximumFramelength = maximumFramelength;
_lengthFieldOffset = lengthFieldOffset;
_minimumChunkSize = lengthFieldOffset + lengthFieldLength;
_frameSize = int.MaxValue;
_intDecoder = byteOrder == ByteOrder.BigEndian ? BigEndianDecoder : LittleEndianDecoder;
}
public override ISyncDirective OnPush(ByteString element, IContext<ByteString> context)
{
_buffer += element;
return DoParse(context);
}
public override ISyncDirective OnPull(IContext<ByteString> context) => DoParse(context);
public override ITerminationDirective OnUpstreamFinish(IContext<ByteString> context)
{
return !_buffer.IsEmpty ? context.AbsorbTermination() : context.Finish();
}
public override void PostStop() => _buffer = null;
private ISyncDirective TryPull(IContext<ByteString> context)
{
if (context.IsFinishing)
return context.Fail(new FramingException("Stream finished but there was a truncated final frame in the buffer"));
return context.Pull();
}
private ISyncDirective EmitFrame(IContext<ByteString> ctx)
{
var parsedFrame = _buffer.Slice(0, _frameSize).Compact();
_buffer = _buffer.Slice(_frameSize);
_frameSize = int.MaxValue;
if (ctx.IsFinishing && _buffer.IsEmpty)
return ctx.PushAndFinish(parsedFrame);
return ctx.Push(parsedFrame);
}
private ISyncDirective DoParse(IContext<ByteString> context)
{
var bufferSize = _buffer.Count;
if (bufferSize >= _frameSize)
return EmitFrame(context);
if (bufferSize >= _minimumChunkSize)
{
var parsedLength = _intDecoder(_buffer.Slice(_lengthFieldOffset).GetEnumerator(), _lengthFieldLength);
_frameSize = parsedLength + _minimumChunkSize;
if (_frameSize > _maximumFramelength)
return context.Fail(new FramingException($"Maximum allowed frame size is {_maximumFramelength} but decoded frame header reported size {_frameSize}"));
if (bufferSize >= _frameSize)
return EmitFrame(context);
return TryPull(context);
}
return TryPull(context);
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus
{
public class FungusScriptWindow : EditorWindow
{
protected bool resize = false;
protected Rect cursorChangeRect;
public const float minViewWidth = 350;
static bool locked = false;
static GUIStyle lockButtonStyle;
static FungusScript activeFungusScript;
protected List<Sequence> windowSequenceMap = new List<Sequence>();
[MenuItem("Window/Fungus Script")]
static void Init()
{
GetWindow(typeof(FungusScriptWindow), false, "Fungus Script");
}
// Implementing this method causes the padlock image to display on the window
// https://leahayes.wordpress.com/2013/04/30/adding-the-little-padlock-button-to-your-editorwindow/#more-455
protected virtual void ShowButton(Rect position) {
if (lockButtonStyle == null)
{
lockButtonStyle = "IN LockButton";
}
locked = GUI.Toggle(position, locked, GUIContent.none, lockButtonStyle);
}
public virtual void OnInspectorUpdate()
{
Repaint();
}
static public FungusScript GetFungusScript()
{
if (locked && activeFungusScript != null)
{
return activeFungusScript;
}
locked = false;
if (Selection.activeGameObject != null)
{
activeFungusScript = Selection.activeGameObject.GetComponent<FungusScript>();
return activeFungusScript;
}
return null;
}
protected virtual void OnGUI()
{
FungusScript fungusScript = GetFungusScript();
if (fungusScript == null)
{
GUILayout.Label("No Fungus Script scene object selected");
return;
}
if (PrefabUtility.GetPrefabType(fungusScript) == PrefabType.Prefab)
{
GUILayout.Label("No Fungus Script scene object selected (selected object is a prefab)");
return;
}
GUILayout.BeginHorizontal();
DrawScriptView(fungusScript);
ResizeViews(fungusScript);
DrawSequenceView(fungusScript);
GUILayout.EndHorizontal();
}
protected virtual void DrawScriptView(FungusScript fungusScript)
{
EditorUtility.SetDirty(fungusScript);
Sequence[] sequences = fungusScript.GetComponentsInChildren<Sequence>();
Rect scrollViewRect = new Rect();
foreach (Sequence s in sequences)
{
scrollViewRect.xMin = Mathf.Min(scrollViewRect.xMin, s.nodeRect.xMin);
scrollViewRect.xMax = Mathf.Max(scrollViewRect.xMax, s.nodeRect.xMax);
scrollViewRect.yMin = Mathf.Min(scrollViewRect.yMin, s.nodeRect.yMin);
scrollViewRect.yMax = Mathf.Max(scrollViewRect.yMax, s.nodeRect.yMax);
}
// Empty buffer area around edges of scroll rect
float bufferScale = 0.25f;
scrollViewRect.xMin -= position.width * bufferScale;
scrollViewRect.yMin -= position.height * bufferScale;
scrollViewRect.xMax += position.width * bufferScale;
scrollViewRect.yMax += position.height * bufferScale;
// Calc rect for left hand script view
Rect scriptViewRect = new Rect(0, 0, this.position.width - fungusScript.commandViewWidth, this.position.height);
// Clip GL drawing so not to overlap scrollbars
Rect clipRect = new Rect(fungusScript.scriptScrollPos.x + scrollViewRect.x,
fungusScript.scriptScrollPos.y + scrollViewRect.y,
scriptViewRect.width - 15,
scriptViewRect.height - 15);
GUILayoutUtility.GetRect(scriptViewRect.width, scriptViewRect.height);
fungusScript.scriptScrollPos = GLDraw.BeginScrollView(scriptViewRect, fungusScript.scriptScrollPos, scrollViewRect, clipRect);
if (Event.current.type == EventType.ContextClick &&
clipRect.Contains(Event.current.mousePosition))
{
GenericMenu menu = new GenericMenu();
Vector2 mousePos = Event.current.mousePosition;
mousePos += fungusScript.scriptScrollPos;
menu.AddItem (new GUIContent ("Create Sequence"), false, CreateSequenceCallback, mousePos);
menu.ShowAsContext ();
Event.current.Use();
}
BeginWindows();
GUIStyle windowStyle = new GUIStyle(EditorStyles.toolbarButton);
windowStyle.stretchHeight = true;
windowStyle.fixedHeight = 40;
windowSequenceMap.Clear();
for (int i = 0; i < sequences.Length; ++i)
{
Sequence sequence = sequences[i];
float titleWidth = windowStyle.CalcSize(new GUIContent(sequence.name)).x;
float windowWidth = Mathf.Max (titleWidth + 10, 100);
if (fungusScript.selectedSequence == sequence ||
fungusScript.executingSequence == sequence)
{
GUI.backgroundColor = Color.green;
}
sequence.nodeRect = GUILayout.Window(i, sequence.nodeRect, DrawWindow, "", windowStyle, GUILayout.Width(windowWidth), GUILayout.Height(20), GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
GUI.backgroundColor = Color.white;
windowSequenceMap.Add(sequence);
}
// Draw connections
foreach (Sequence s in windowSequenceMap)
{
DrawConnections(fungusScript, s, false);
}
foreach (Sequence s in windowSequenceMap)
{
DrawConnections(fungusScript, s, true);
}
EndWindows();
GLDraw.EndScrollView();
}
protected virtual void ResizeViews(FungusScript fungusScript)
{
cursorChangeRect = new Rect(this.position.width - fungusScript.commandViewWidth, 0, 4f, this.position.height);
GUI.color = Color.grey;
GUI.DrawTexture(cursorChangeRect, EditorGUIUtility.whiteTexture);
GUI.color = Color.white;
EditorGUIUtility.AddCursorRect(cursorChangeRect, MouseCursor.ResizeHorizontal);
if (Event.current.type == EventType.mouseDown && cursorChangeRect.Contains(Event.current.mousePosition))
{
resize = true;
}
if (resize)
{
fungusScript.commandViewWidth = this.position.width - Event.current.mousePosition.x;
fungusScript.commandViewWidth = Mathf.Max(minViewWidth, fungusScript.commandViewWidth);
fungusScript.commandViewWidth = Mathf.Min(this.position.width - minViewWidth, fungusScript.commandViewWidth);
}
if(Event.current.type == EventType.MouseUp)
{
resize = false;
}
}
protected virtual void DrawSequenceView(FungusScript fungusScript)
{
GUILayout.Space(5);
fungusScript.commandScrollPos = GUILayout.BeginScrollView(fungusScript.commandScrollPos);
EditorGUILayout.BeginVertical();
GUILayout.Box("Sequence", GUILayout.ExpandWidth(true));
GUILayout.BeginHorizontal();
if (fungusScript.selectedSequence == null)
{
GUILayout.FlexibleSpace();
}
if (GUILayout.Button(fungusScript.selectedSequence == null ? "Create Sequence" : "Create",
fungusScript.selectedSequence == null ? EditorStyles.miniButton : EditorStyles.miniButtonLeft))
{
Sequence newSequence = fungusScript.CreateSequence(fungusScript.scriptScrollPos);
Undo.RegisterCreatedObjectUndo(newSequence, "New Sequence");
fungusScript.selectedSequence = newSequence;
fungusScript.selectedCommand = null;
}
if (fungusScript.selectedSequence == null)
{
GUILayout.FlexibleSpace();
}
if (fungusScript.selectedSequence != null)
{
if (GUILayout.Button("Delete", EditorStyles.miniButtonMid))
{
Undo.DestroyObjectImmediate(fungusScript.selectedSequence.gameObject);
fungusScript.selectedSequence = null;
fungusScript.selectedCommand = null;
}
if (GUILayout.Button("Duplicate", EditorStyles.miniButtonRight))
{
GameObject copy = GameObject.Instantiate(fungusScript.selectedSequence.gameObject) as GameObject;
copy.transform.parent = fungusScript.transform;
copy.transform.hideFlags = HideFlags.HideInHierarchy;
copy.name = fungusScript.selectedSequence.name;
Sequence sequenceCopy = copy.GetComponent<Sequence>();
sequenceCopy.nodeRect.x += sequenceCopy.nodeRect.width + 10;
Undo.RegisterCreatedObjectUndo(copy, "Duplicate Sequence");
fungusScript.selectedSequence = sequenceCopy;
fungusScript.selectedCommand = null;
}
}
GUILayout.EndHorizontal();
if (fungusScript.selectedSequence != null)
{
EditorGUILayout.Separator();
SequenceEditor sequenceEditor = Editor.CreateEditor(fungusScript.selectedSequence) as SequenceEditor;
sequenceEditor.DrawSequenceGUI(fungusScript);
DestroyImmediate(sequenceEditor);
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndVertical();
GUILayout.EndScrollView();
}
protected virtual void CreateSequenceCallback(object item)
{
FungusScript fungusScript = GetFungusScript();
if (fungusScript != null)
{
Vector2 position = (Vector2)item;
position -= fungusScript.scriptScrollPos;
Sequence newSequence = fungusScript.CreateSequence(position);
Undo.RegisterCreatedObjectUndo(newSequence, "New Sequence");
fungusScript.selectedSequence = newSequence;
}
}
protected virtual void DrawWindow(int windowId)
{
// Select sequence when node is clicked
if (!Application.isPlaying &&
Event.current.button == 0 &&
Event.current.type == EventType.MouseDown)
{
if (windowId < windowSequenceMap.Count)
{
Sequence s = windowSequenceMap[windowId];
if (s != null)
{
FungusScript fungusScript = s.GetFungusScript();
if (fungusScript != null)
{
fungusScript.selectedSequence = s;
fungusScript.selectedCommand = null;
Selection.activeGameObject = fungusScript.gameObject;
GUIUtility.keyboardControl = 0; // Fix for textarea not refeshing (change focus)
}
}
}
}
Sequence sequence = windowSequenceMap[windowId];
GUIStyle labelStyle = new GUIStyle(GUI.skin.label);
labelStyle.alignment = TextAnchor.MiddleCenter;
GUILayout.BeginVertical();
GUILayout.FlexibleSpace();
GUILayout.Label(sequence.name, labelStyle);
GUILayout.FlexibleSpace();
GUILayout.EndVertical();
GUI.DragWindow();
}
protected virtual void DrawConnections(FungusScript fungusScript, Sequence sequence, bool highlightedOnly)
{
if (sequence == null)
{
return;
}
List<Sequence> connectedSequences = new List<Sequence>();
bool sequenceIsSelected = (fungusScript.selectedSequence == sequence);
foreach (Command command in sequence.commandList)
{
bool commandIsSelected = (fungusScript.selectedCommand == command);
//TODO Figure out why we need this added error checking.
if(command == null)
{
continue;
}
bool highlight = command.IsExecuting() || (sequenceIsSelected && commandIsSelected);
if (highlightedOnly && !highlight ||
!highlightedOnly && highlight)
{
continue;
}
connectedSequences.Clear();
command.GetConnectedSequences(ref connectedSequences);
foreach (Sequence sequenceB in connectedSequences)
{
if (sequenceB == null ||
sequenceB.GetFungusScript() != fungusScript)
{
continue;
}
DrawRectConnection(sequence.nodeRect, sequenceB.nodeRect, highlight);
}
}
}
protected virtual void DrawRectConnection(Rect rectA, Rect rectB, bool highlight)
{
Vector2 pointA;
Vector2 pointB;
Vector2 p1 = rectA.center;
Vector2 p2 = rectB.center;
GLDraw.segment_rect_intersection(rectA, ref p1, ref p2);
pointA = p2;
p1 = rectB.center;
p2 = rectA.center;
GLDraw.segment_rect_intersection(rectB, ref p1, ref p2);
pointB = p2;
Color color = Color.grey;
if (highlight)
{
color = Color.green;
}
GLDraw.DrawConnectingCurve(pointA, pointB, color, 2);
}
}
}
| |
/*
Copyright 2002-2008 Corey Trager
Distributed under the terms of the GNU General Public License
*/
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace btnet
{
// This is sample code that gives you an idea of how you could customize the validation
// and workflow. What you want to do, ideally, is isolate your customizations to this
// file so that you can still upgrade to future BugTracker.NET versions without too
// much trouble.
// If you customize this file, just make sure you don't overlay this file when you
// upgrade.
public class Workflow
{
///////////////////////////////////////////////////////////////////////
public static void custom_adjust_controls(
DataRow bug, // null if a new bug, otherwise the state of the bug now in the db
User user, // the currently logged in user
Page page) // the whole page, so that you can customize other stuff
{
// Uncomment the next line to play with the sample code.
//custom_adjust_controls_sample(bug, user, page);
// This method will be called when a new form is displayed and
// when the bug has been updated. You'll get the updated status,
// in DataRow bug, but you won't get the updated version of the
// all other fields, so if your workflow depends on them too, you
// might also want to customize edit_bug.aspx.
// See the "Note about customizing workflow" in edit_bug.aspx
// for the place to edit.
// If you don't want to change edit_bug.aspx, but your logic needs
// other fields, you can fetch them from the database yourself in
// your own code here.
}
///////////////////////////////////////////////////////////////////////
public static bool custom_validations(
DataRow bug, // null if a new bug, otherwise the state of the bug now in the db
User user, // the currently logged in user
Page page,
HtmlContainerControl custom_validation_err_msg)
{
// This method will be called during validation.
// You'll get some updated fielsd in DataRow bug, but not all.
// You might also want to customize edit_bug.aspx.
// See the "Note about customizing workflow" in edit_bug.aspx
// for the place to make the DataRow more accurate.
// Uncomment the next line to play with the sample code.
//return custom_validations_sample(bug, user, page, custom_validation_err_msg);
return true;
}
///////////////////////////////////////////////////////////////////////
public static bool custom_validations_sample(
DataRow bug, // null if a new bug, otherwise the state of the bug now in the db
User user, // the currently logged in user
Page page,
HtmlContainerControl custom_validation_err_msg)
{
// Just a stupid example. Show that we can cross-validate between
// a couple different fields.
DropDownList category = (DropDownList) find_control(page.Controls, "category");
DropDownList priority = (DropDownList) find_control(page.Controls, "priority");
if (category.SelectedItem.Text == "question"
&& priority.SelectedItem.Text == "high")
{
custom_validation_err_msg.InnerHtml = "Questions cannot be high priority<br>";
return false;
}
else
{
custom_validation_err_msg.InnerHtml = "";
return true;
}
}
///////////////////////////////////////////////////////////////////////
// Just to give you an idea of what you could do...
private static void custom_adjust_controls_sample(
DataRow bug, // null if a new bug, otherwise the way the bug is now in the db
User user, // the currently logged in user
Page page) // the options in the dropdown
{
// Adjust the contents of the status dropdown
DropDownList status = (DropDownList) find_control(page.Controls, "status");
if (bug != null) // existing bug
{
// Get the bug's current status.
// See "get_bug_datarow()" in bug.cs for the sql
string status_name = (string) bug["status_name"];
// My logic here first gets rid of all the statuses except the
// selected status. Then it adds back just the statuses we want to
// appear in the dropdown.
remove_all_dropdown_items_that_dont_match_text(status, status_name);
// Add back what we do want.
// Notice that the user is one of the arguments, so
// you can adjust values by user.
// The values here have to match the database values.
if (status_name == "new" || status_name == "re-opened")
{
if (status.Items.FindByValue("2") == null)
status.Items.Add(new ListItem("in progress", "2"));
if (status.Items.FindByValue("5") == null)
status.Items.Add(new ListItem("closed", "5"));
}
else if (status_name == "in progress")
{
if (status.Items.FindByValue("1") == null)
status.Items.Add(new ListItem("new", "1"));
if ((string) bug["category_name"] != "question") // just to show we can reference other fields
{
if (status.Items.FindByValue("3") == null)
status.Items.Add(new ListItem("checked in", "3"));
}
if (status.Items.FindByValue("5") == null)
status.Items.Add(new ListItem("closed", "5"));
}
else if (status_name == "checked in")
{
if (status.Items.FindByValue("2") == null)
status.Items.Add(new ListItem("in progress", "2"));
if (status.Items.FindByValue("5") == null)
status.Items.Add(new ListItem("closed", "5"));
}
else if (status_name == "closed")
{
if (status.Items.FindByValue("4") == null)
status.Items.Add(new ListItem("re-opened", "4"));
}
}
else // new bug
{
status.Items.Clear();
status.Items.Add(new ListItem("new", "1"));
}
}
///////////////////////////////////////////////////////////////////////
public static void remove_all_dropdown_items_that_dont_match_text(DropDownList dropdown, string text)
{
for (int i = dropdown.Items.Count - 1; i > -1; i--)
{
if (dropdown.Items[i].Text != text)
{
dropdown.Items.Remove(dropdown.Items[i]);
}
}
}
///////////////////////////////////////////////////////////////////////
// Returns an HTMLControl or WebControl by its id.
public static Control find_control(ControlCollection controls, string id)
{
foreach (System.Web.UI.Control c in controls)
{
if (c.ID == id)
{
return c;
}
else
{
if (c.Controls.Count > 0)
{
System.Web.UI.Control c2 = null;
c2 = find_control(c.Controls, id);
if (c2 != null)
return c2;
}
}
}
return null;
}
}; // end class
}
| |
using System;
using NUnit.Framework;
using NServiceKit.Common.Tests.Models;
namespace NServiceKit.OrmLite.Tests
{
/// <summary>An ORM lite create table with namig strategy tests.</summary>
[TestFixture]
public class OrmLiteCreateTableWithNamigStrategyTests
: OrmLiteTestBase
{
/// <summary>Can create table with namig strategy table prefix.</summary>
[Test]
public void Can_create_TableWithNamigStrategy_table_prefix()
{
OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy
{
TablePrefix ="tab_",
ColumnPrefix = "col_",
};
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithOnlyStringFields>(true);
}
OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
/// <summary>Can create table with namig strategy table lowered.</summary>
[Test]
public void Can_create_TableWithNamigStrategy_table_lowered()
{
OrmLiteConfig.DialectProvider.NamingStrategy = new LowercaseNamingStrategy();
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithOnlyStringFields>(true);
}
OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
/// <summary>Can create table with namig strategy table name underscore coumpound.</summary>
[Test]
public void Can_create_TableWithNamigStrategy_table_nameUnderscoreCoumpound()
{
OrmLiteConfig.DialectProvider.NamingStrategy = new UnderscoreSeparatedCompoundNamingStrategy();
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithOnlyStringFields>(true);
}
OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
/// <summary>Can get data from table with namig strategy with get by identifier.</summary>
[Test]
public void Can_get_data_from_TableWithNamigStrategy_with_GetById()
{
OrmLiteConfig.DialectProvider.NamingStrategy = OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy
{
TablePrefix = "tab_",
ColumnPrefix = "col_",
};
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithOnlyStringFields>(true);
var m = new ModelWithOnlyStringFields { Id= "999", AlbumId = "112", AlbumName="ElectroShip", Name = "MyNameIsBatman"};
db.Save(m);
var modelFromDb = db.GetById<ModelWithOnlyStringFields>("999");
Assert.AreEqual(m.Name, modelFromDb.Name);
}
OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
/// <summary>Can get data from table with namig strategy with query by example.</summary>
[Test]
public void Can_get_data_from_TableWithNamigStrategy_with_query_by_example()
{
OrmLiteConfig.DialectProvider.NamingStrategy = OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy
{
TablePrefix = "tab_",
ColumnPrefix = "col_",
};
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithOnlyStringFields>(true);
var m = new ModelWithOnlyStringFields { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" };
db.Save(m);
var modelFromDb = db.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0];
Assert.AreEqual(m.Name, modelFromDb.Name);
}
OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
}
/// <summary>
/// Can get data from table with underscore separated compound naming strategy with read
/// connection extension.
/// </summary>
[Test]
public void Can_get_data_from_TableWithUnderscoreSeparatedCompoundNamingStrategy_with_ReadConnectionExtension()
{
OrmLiteConfig.DialectProvider.NamingStrategy = new UnderscoreSeparatedCompoundNamingStrategy();
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithOnlyStringFields>(true);
var m = new ModelWithOnlyStringFields
{
Id = "997",
AlbumId = "112",
AlbumName = "ElectroShip",
Name = "ReadConnectionExtensionFirst"
};
db.Save(m);
var modelFromDb = db.First<ModelWithOnlyStringFields>(x => x.Name == "ReadConnectionExtensionFirst");
Assert.AreEqual(m.AlbumName, modelFromDb.AlbumName);
}
OrmLiteConfig.DialectProvider.NamingStrategy = new OrmLiteNamingStrategyBase();
}
/// <summary>
/// Can get data from table with namig strategy after changing naming strategy.
/// </summary>
[Test]
public void Can_get_data_from_TableWithNamigStrategy_AfterChangingNamingStrategy()
{
OrmLiteConfig.DialectProvider.NamingStrategy = OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy
{
TablePrefix = "tab_",
ColumnPrefix = "col_",
};
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithOnlyStringFields>(true);
var m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" };
db.Save(m);
var modelFromDb = db.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0];
Assert.AreEqual(m.Name, modelFromDb.Name);
modelFromDb = db.GetById<ModelWithOnlyStringFields>("998");
Assert.AreEqual(m.Name, modelFromDb.Name);
}
OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase();
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithOnlyStringFields>(true);
var m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" };
db.Save(m);
var modelFromDb = db.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0];
Assert.AreEqual(m.Name, modelFromDb.Name);
modelFromDb = db.GetById<ModelWithOnlyStringFields>("998");
Assert.AreEqual(m.Name, modelFromDb.Name);
}
OrmLiteConfig.DialectProvider.NamingStrategy = OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy
{
TablePrefix = "tab_",
ColumnPrefix = "col_",
};
using (var db = OpenDbConnection())
{
db.CreateTable<ModelWithOnlyStringFields>(true);
var m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" };
db.Save(m);
var modelFromDb = db.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0];
Assert.AreEqual(m.Name, modelFromDb.Name);
modelFromDb = db.GetById<ModelWithOnlyStringFields>("998");
Assert.AreEqual(m.Name, modelFromDb.Name);
}
OrmLiteConfig.DialectProvider.NamingStrategy = new OrmLiteNamingStrategyBase();
}
}
/// <summary>A prefix naming strategy.</summary>
public class PrefixNamingStrategy : OrmLiteNamingStrategyBase
{
/// <summary>Gets or sets the table prefix.</summary>
/// <value>The table prefix.</value>
public string TablePrefix { get; set; }
/// <summary>Gets or sets the column prefix.</summary>
/// <value>The column prefix.</value>
public string ColumnPrefix { get; set; }
/// <summary>Gets table name.</summary>
/// <param name="name">The name.</param>
/// <returns>The table name.</returns>
public override string GetTableName(string name)
{
return TablePrefix + name;
}
/// <summary>Gets column name.</summary>
/// <param name="name">The name.</param>
/// <returns>The column name.</returns>
public override string GetColumnName(string name)
{
return ColumnPrefix + name;
}
}
/// <summary>A lowercase naming strategy.</summary>
public class LowercaseNamingStrategy : OrmLiteNamingStrategyBase
{
/// <summary>Gets table name.</summary>
/// <param name="name">The name.</param>
/// <returns>The table name.</returns>
public override string GetTableName(string name)
{
return name.ToLower();
}
/// <summary>Gets column name.</summary>
/// <param name="name">The name.</param>
/// <returns>The column name.</returns>
public override string GetColumnName(string name)
{
return name.ToLower();
}
}
/// <summary>An underscore separated compound naming strategy.</summary>
public class UnderscoreSeparatedCompoundNamingStrategy : OrmLiteNamingStrategyBase
{
/// <summary>Gets table name.</summary>
/// <param name="name">The name.</param>
/// <returns>The table name.</returns>
public override string GetTableName(string name)
{
return toUnderscoreSeparatedCompound(name);
}
/// <summary>Gets column name.</summary>
/// <param name="name">The name.</param>
/// <returns>The column name.</returns>
public override string GetColumnName(string name)
{
return toUnderscoreSeparatedCompound(name);
}
/// <summary>Converts a name to an underscore separated compound.</summary>
/// <param name="name">The name.</param>
/// <returns>name as a string.</returns>
string toUnderscoreSeparatedCompound(string name)
{
string r = char.ToLower(name[0]).ToString();
for (int i = 1; i < name.Length; i++)
{
char c = name[i];
if (char.IsUpper(name[i]))
{
r += "_";
r += char.ToLower(name[i]);
}
else
{
r += name[i];
}
}
return r;
}
}
}
| |
using System; // (partial) from mscorlib.dll
using System.Collections;
using System.Collections.Generic;
using VRage;
namespace Rynchodon
{
/// <summary>
/// Dictionary with a <see cref="FastResourceLock"/>.
/// </summary>
public sealed class LockedDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
public readonly Dictionary<TKey, TValue> Dictionary;
public readonly FastResourceLock Lock = new FastResourceLock();
public LockedDictionary()
{
this.Dictionary = new Dictionary<TKey, TValue>();
}
public LockedDictionary(Dictionary<TKey, TValue> dictionary)
{
this.Dictionary = dictionary;
}
public LockedDictionary(IDictionary<TKey, TValue> dictionary)
{
this.Dictionary = new Dictionary<TKey, TValue>(dictionary);
}
public int Count
{
get { return Dictionary.Count; }
}
public KeyCollection Keys
{
get { return new KeyCollection(this); }
}
public ValueCollection Values
{
get { return new ValueCollection(this); }
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return ((ICollection<KeyValuePair<TKey, TValue>>)Dictionary).IsReadOnly; }
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return Keys; }
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return Values; }
}
public TValue this[TKey key]
{
get
{
using (Lock.AcquireSharedUsing())
return Dictionary[key];
}
set
{
using (Lock.AcquireExclusiveUsing())
Dictionary[key] = value;
}
}
public void Add(KeyValuePair<TKey, TValue> pair)
{
Add(pair.Key, pair.Value);
}
public void Add(TKey key, TValue value)
{
using (Lock.AcquireExclusiveUsing())
Dictionary.Add(key, value);
}
public void Clear()
{
using (Lock.AcquireExclusiveUsing())
Dictionary.Clear();
}
public bool ContainsKey(TKey key)
{
using (Lock.AcquireSharedUsing())
return Dictionary.ContainsKey(key);
}
public bool ContainsValue(TValue value)
{
using (Lock.AcquireSharedUsing())
return Dictionary.ContainsValue(value);
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
public bool Remove(TKey key)
{
using (Lock.AcquireExclusiveUsing())
return Dictionary.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
using (Lock.AcquireSharedUsing())
return Dictionary.TryGetValue(key, out value);
}
/// <summary>
/// For setting a value unreliably, if the dictionary does not already contain the specified key.
/// </summary>
public bool TrySet(TKey key, TValue value)
{
bool contains;
using (Lock.AcquireSharedUsing())
contains = Dictionary.ContainsKey(key);
if (!contains)
{
using (Lock.AcquireExclusiveUsing())
Dictionary[key] = value;
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
using (Lock.AcquireSharedUsing())
return ((ICollection<KeyValuePair<TKey, TValue>>)Dictionary).Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
using (Lock.AcquireSharedUsing())
((ICollection<KeyValuePair<TKey, TValue>>)Dictionary).CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
using (Lock.AcquireExclusiveUsing())
return ((ICollection<KeyValuePair<TKey, TValue>>)Dictionary).Remove(item);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Reader : IEnumerable<KeyValuePair<TKey, TValue>>
{
private readonly LockedDictionary<TKey, TValue> _dictionary;
public Reader(LockedDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return GetEnumerator();
}
}
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
private readonly LockedDictionary<TKey, TValue> _dictionary;
private Dictionary<TKey, TValue>.Enumerator _enumerator;
public Enumerator(LockedDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_enumerator = dictionary.Dictionary.GetEnumerator();
_dictionary.Lock.AcquireShared();
}
public KeyValuePair<TKey, TValue> Current
{
get { return _enumerator.Current; }
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
_dictionary.Lock.ReleaseShared();
_enumerator.Dispose();
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
}
public struct KeyCollection : ICollection<TKey>
{
private readonly LockedDictionary<TKey, TValue> _lockedDictionary;
public KeyCollection(LockedDictionary<TKey, TValue> dictionary)
{
_lockedDictionary = dictionary;
}
public int Count
{
get { return _lockedDictionary.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
void ICollection<TKey>.Add(TKey item)
{
throw new NotSupportedException();
}
void ICollection<TKey>.Clear()
{
throw new NotSupportedException();
}
public bool Contains(TKey item)
{
return _lockedDictionary.ContainsKey(item);
}
public void CopyTo(TKey[] array, int arrayIndex)
{
using (_lockedDictionary.Lock.AcquireSharedUsing())
_lockedDictionary.Dictionary.Keys.CopyTo(array, arrayIndex);
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lockedDictionary);
}
bool ICollection<TKey>.Remove(TKey item)
{
throw new NotSupportedException();
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<TKey>
{
private readonly FastResourceLock _lock;
private Dictionary<TKey, TValue>.KeyCollection.Enumerator _enumerator;
public Enumerator(LockedDictionary<TKey, TValue> dictionary)
{
_enumerator = dictionary.Dictionary.Keys.GetEnumerator();
_lock = dictionary.Lock;
_lock.AcquireShared();
}
public TKey Current
{
get { return _enumerator.Current; }
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
_lock.ReleaseShared();
_enumerator.Dispose();
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
void IEnumerator.Reset()
{
throw new NotImplementedException();
}
}
}
public struct ValueCollection : ICollection<TValue>
{
private readonly LockedDictionary<TKey, TValue> _lockedDictionary;
public ValueCollection(LockedDictionary<TKey, TValue> dictionary)
{
_lockedDictionary = dictionary;
}
public int Count
{
get { return _lockedDictionary.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
void ICollection<TValue>.Add(TValue item)
{
throw new NotSupportedException();
}
void ICollection<TValue>.Clear()
{
throw new NotSupportedException();
}
public bool Contains(TValue item)
{
return _lockedDictionary.ContainsValue(item);
}
public void CopyTo(TValue[] array, int arrayIndex)
{
using (_lockedDictionary.Lock.AcquireSharedUsing())
_lockedDictionary.Dictionary.Values.CopyTo(array, arrayIndex);
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lockedDictionary);
}
bool ICollection<TValue>.Remove(TValue item)
{
throw new NotSupportedException();
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<TValue>
{
private readonly FastResourceLock _lock;
private Dictionary<TKey, TValue>.ValueCollection.Enumerator _enumerator;
public Enumerator(LockedDictionary<TKey, TValue> dictionary)
{
_enumerator = dictionary.Dictionary.Values.GetEnumerator();
_lock = dictionary.Lock;
_lock.AcquireShared();
}
public TValue Current
{
get { return _enumerator.Current; }
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
_lock.ReleaseShared();
_enumerator.Dispose();
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
void IEnumerator.Reset()
{
throw new NotImplementedException();
}
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System {
using System.Text;
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Globalization;
// TimeSpan represents a duration of time. A TimeSpan can be negative
// or positive.
//
// TimeSpan is internally represented as a number of milliseconds. While
// this maps well into units of time such as hours and days, any
// periods longer than that aren't representable in a nice fashion.
// For instance, a month can be between 28 and 31 days, while a year
// can contain 365 or 364 days. A decade can have between 1 and 3 leapyears,
// depending on when you map the TimeSpan into the calendar. This is why
// we do not provide Years() or Months().
//
// Note: System.TimeSpan needs to interop with the WinRT structure
// type Windows::Foundation:TimeSpan. These types are currently binary-compatible in
// memory so no custom marshalling is required. If at any point the implementation
// details of this type should change, or new fields added, we need to remember to add
// an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled.
//
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public struct TimeSpan : IComparable
#if GENERICS_WORK
, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
#endif
{
public const long TicksPerMillisecond = 10000;
private const double MillisecondsPerTick = 1.0 / TicksPerMillisecond;
public const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000
private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0001
public const long TicksPerMinute = TicksPerSecond * 60; // 600,000,000
private const double MinutesPerTick = 1.0 / TicksPerMinute; // 1.6666666666667e-9
public const long TicksPerHour = TicksPerMinute * 60; // 36,000,000,000
private const double HoursPerTick = 1.0 / TicksPerHour; // 2.77777777777777778e-11
public const long TicksPerDay = TicksPerHour * 24; // 864,000,000,000
private const double DaysPerTick = 1.0 / TicksPerDay; // 1.1574074074074074074e-12
private const int MillisPerSecond = 1000;
private const int MillisPerMinute = MillisPerSecond * 60; // 60,000
private const int MillisPerHour = MillisPerMinute * 60; // 3,600,000
private const int MillisPerDay = MillisPerHour * 24; // 86,400,000
internal const long MaxSeconds = Int64.MaxValue / TicksPerSecond;
internal const long MinSeconds = Int64.MinValue / TicksPerSecond;
internal const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond;
internal const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond;
internal const long TicksPerTenthSecond = TicksPerMillisecond * 100;
public static readonly TimeSpan Zero = new TimeSpan(0);
public static readonly TimeSpan MaxValue = new TimeSpan(Int64.MaxValue);
public static readonly TimeSpan MinValue = new TimeSpan(Int64.MinValue);
// internal so that DateTime doesn't have to call an extra get
// method for some arithmetic operations.
internal long _ticks;
//public TimeSpan() {
// _ticks = 0;
//}
public TimeSpan(long ticks) {
this._ticks = ticks;
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public TimeSpan(int hours, int minutes, int seconds) {
_ticks = TimeToTicks(hours, minutes, seconds);
}
public TimeSpan(int days, int hours, int minutes, int seconds)
: this(days,hours,minutes,seconds,0)
{
}
public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds)
{
Int64 totalMilliSeconds = ((Int64)days * 3600 * 24 + (Int64)hours * 3600 + (Int64)minutes * 60 + seconds) * 1000 + milliseconds;
if (totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds)
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong"));
_ticks = (long)totalMilliSeconds * TicksPerMillisecond;
}
public long Ticks {
get { return _ticks; }
}
public int Days {
get { return (int)(_ticks / TicksPerDay); }
}
public int Hours {
get { return (int)((_ticks / TicksPerHour) % 24); }
}
public int Milliseconds {
get { return (int)((_ticks / TicksPerMillisecond) % 1000); }
}
public int Minutes {
get { return (int)((_ticks / TicksPerMinute) % 60); }
}
public int Seconds {
get { return (int)((_ticks / TicksPerSecond) % 60); }
}
public double TotalDays {
get { return ((double)_ticks) * DaysPerTick; }
}
public double TotalHours {
get { return (double)_ticks * HoursPerTick; }
}
public double TotalMilliseconds {
get {
double temp = (double)_ticks * MillisecondsPerTick;
if (temp > MaxMilliSeconds)
return (double)MaxMilliSeconds;
if (temp < MinMilliSeconds)
return (double)MinMilliSeconds;
return temp;
}
}
public double TotalMinutes {
get { return (double)_ticks * MinutesPerTick; }
}
public double TotalSeconds {
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
get { return (double)_ticks * SecondsPerTick; }
}
public TimeSpan Add(TimeSpan ts) {
long result = _ticks + ts._ticks;
// Overflow if signs of operands was identical and result's
// sign was opposite.
// >> 63 gives the sign bit (either 64 1's or 64 0's).
if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
return new TimeSpan(result);
}
// Compares two TimeSpan values, returning an integer that indicates their
// relationship.
//
public static int Compare(TimeSpan t1, TimeSpan t2) {
if (t1._ticks > t2._ticks) return 1;
if (t1._ticks < t2._ticks) return -1;
return 0;
}
// Returns a value less than zero if this object
public int CompareTo(Object value) {
if (value == null) return 1;
if (!(value is TimeSpan))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeTimeSpan"));
long t = ((TimeSpan)value)._ticks;
if (_ticks > t) return 1;
if (_ticks < t) return -1;
return 0;
}
#if GENERICS_WORK
public int CompareTo(TimeSpan value) {
long t = value._ticks;
if (_ticks > t) return 1;
if (_ticks < t) return -1;
return 0;
}
#endif
public static TimeSpan FromDays(double value) {
return Interval(value, MillisPerDay);
}
public TimeSpan Duration() {
if (Ticks==TimeSpan.MinValue.Ticks)
throw new OverflowException(Environment.GetResourceString("Overflow_Duration"));
Contract.EndContractBlock();
return new TimeSpan(_ticks >= 0? _ticks: -_ticks);
}
public override bool Equals(Object value) {
if (value is TimeSpan) {
return _ticks == ((TimeSpan)value)._ticks;
}
return false;
}
public bool Equals(TimeSpan obj)
{
return _ticks == obj._ticks;
}
public static bool Equals(TimeSpan t1, TimeSpan t2) {
return t1._ticks == t2._ticks;
}
public override int GetHashCode() {
return (int)_ticks ^ (int)(_ticks >> 32);
}
public static TimeSpan FromHours(double value) {
return Interval(value, MillisPerHour);
}
private static TimeSpan Interval(double value, int scale) {
if (Double.IsNaN(value))
throw new ArgumentException(Environment.GetResourceString("Arg_CannotBeNaN"));
Contract.EndContractBlock();
double tmp = value * scale;
double millis = tmp + (value >= 0? 0.5: -0.5);
if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond))
throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
return new TimeSpan((long)millis * TicksPerMillisecond);
}
public static TimeSpan FromMilliseconds(double value) {
return Interval(value, 1);
}
public static TimeSpan FromMinutes(double value) {
return Interval(value, MillisPerMinute);
}
public TimeSpan Negate() {
if (Ticks==TimeSpan.MinValue.Ticks)
throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
Contract.EndContractBlock();
return new TimeSpan(-_ticks);
}
public static TimeSpan FromSeconds(double value) {
return Interval(value, MillisPerSecond);
}
public TimeSpan Subtract(TimeSpan ts) {
long result = _ticks - ts._ticks;
// Overflow if signs of operands was different and result's
// sign was opposite from the first argument's sign.
// >> 63 gives the sign bit (either 64 1's or 64 0's).
if ((_ticks >> 63 != ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
return new TimeSpan(result);
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public static TimeSpan FromTicks(long value) {
return new TimeSpan(value);
}
internal static long TimeToTicks(int hour, int minute, int second) {
// totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31,
// which is less than 2^44, meaning we won't overflow totalSeconds.
long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second;
if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds)
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong"));
return totalSeconds * TicksPerSecond;
}
// See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat
#region ParseAndFormat
public static TimeSpan Parse(String s) {
/* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */
return TimeSpanParse.Parse(s, null);
}
public static TimeSpan Parse(String input, IFormatProvider formatProvider) {
return TimeSpanParse.Parse(input, formatProvider);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider) {
return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider) {
return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles) {
TimeSpanParse.ValidateStyles(styles, "styles");
return TimeSpanParse.ParseExact(input, format, formatProvider, styles);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) {
TimeSpanParse.ValidateStyles(styles, "styles");
return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles);
}
public static Boolean TryParse(String s, out TimeSpan result) {
return TimeSpanParse.TryParse(s, null, out result);
}
public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result) {
return TimeSpanParse.TryParse(input, formatProvider, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result) {
return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result) {
return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) {
TimeSpanParse.ValidateStyles(styles, "styles");
return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) {
TimeSpanParse.ValidateStyles(styles, "styles");
return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result);
}
public override String ToString() {
return TimeSpanFormat.Format(this, null, null);
}
public String ToString(String format) {
return TimeSpanFormat.Format(this, format, null);
}
public String ToString(String format, IFormatProvider formatProvider) {
if (LegacyMode) {
return TimeSpanFormat.Format(this, null, null);
}
else {
return TimeSpanFormat.Format(this, format, formatProvider);
}
}
#endregion
public static TimeSpan operator -(TimeSpan t) {
if (t._ticks==TimeSpan.MinValue._ticks)
throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
return new TimeSpan(-t._ticks);
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public static TimeSpan operator -(TimeSpan t1, TimeSpan t2) {
return t1.Subtract(t2);
}
public static TimeSpan operator +(TimeSpan t) {
return t;
}
public static TimeSpan operator +(TimeSpan t1, TimeSpan t2) {
return t1.Add(t2);
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public static bool operator ==(TimeSpan t1, TimeSpan t2) {
return t1._ticks == t2._ticks;
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public static bool operator !=(TimeSpan t1, TimeSpan t2) {
return t1._ticks != t2._ticks;
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public static bool operator <(TimeSpan t1, TimeSpan t2) {
return t1._ticks < t2._ticks;
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public static bool operator <=(TimeSpan t1, TimeSpan t2) {
return t1._ticks <= t2._ticks;
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public static bool operator >(TimeSpan t1, TimeSpan t2) {
return t1._ticks > t2._ticks;
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public static bool operator >=(TimeSpan t1, TimeSpan t2) {
return t1._ticks >= t2._ticks;
}
//
// In .NET Framework v1.0 - v3.5 System.TimeSpan did not implement IFormattable
// The composite formatter ignores format specifiers on types that do not implement
// IFormattable, so the following code would 'just work' by using TimeSpan.ToString()
// under the hood:
// String.Format("{0:_someRandomFormatString_}", myTimeSpan);
//
// In .NET Framework v4.0 System.TimeSpan implements IFormattable. This causes the
// composite formatter to call TimeSpan.ToString(string format, FormatProvider provider)
// and pass in "_someRandomFormatString_" for the format parameter. When the format
// parameter is invalid a FormatException is thrown.
//
// The 'NetFx40_TimeSpanLegacyFormatMode' per-AppDomain configuration option and the 'TimeSpan_LegacyFormatMode'
// process-wide configuration option allows applications to run with the v1.0 - v3.5 legacy behavior. When
// either switch is specified the format parameter is ignored and the default output is returned.
//
// There are three ways to use the process-wide configuration option:
//
// 1) Config file (MyApp.exe.config)
// <?xml version ="1.0"?>
// <configuration>
// <runtime>
// <TimeSpan_LegacyFormatMode enabled="true"/>
// </runtime>
// </configuration>
// 2) Environment variable
// set COMPLUS_TimeSpan_LegacyFormatMode=1
// 3) RegistryKey
// [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
// "TimeSpan_LegacyFormatMode"=dword:00000001
//
#if !FEATURE_CORECLR
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool LegacyFormatMode();
#endif // !FEATURE_CORECLR
//
// In Silverlight v4, specifying the APP_EARLIER_THAN_SL4.0 quirks mode allows applications to
// run in v2 - v3 legacy behavior.
//
#if !FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
private static bool GetLegacyFormatMode() {
#if !FEATURE_CORECLR
if (LegacyFormatMode()) // FCALL to check COMPLUS_TimeSpan_LegacyFormatMode
return true;
return CompatibilitySwitches.IsNetFx40TimeSpanLegacyFormatMode;
#else
return CompatibilitySwitches.IsAppEarlierThanSilverlight4;
#endif // !FEATURE_CORECLR
}
private static volatile bool _legacyConfigChecked;
private static volatile bool _legacyMode;
private static bool LegacyMode {
get {
if (!_legacyConfigChecked) {
// no need to lock - idempotent
_legacyMode = GetLegacyFormatMode();
_legacyConfigChecked = true;
}
return _legacyMode;
}
}
}
}
| |
/*
Copyright (c) 2014, RMIT Training
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 CounterCompliance 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.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using CounterReports.Areas.HelpPage.ModelDescriptions;
using CounterReports.Areas.HelpPage.Models;
namespace CounterReports.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
namespace Microsoft.PythonTools.Profiling {
// XmlSerializer requires these types to be public
[Serializable]
public sealed class ProfilingTarget {
internal static XmlSerializer Serializer = new XmlSerializer(typeof(ProfilingTarget));
[XmlElement("ProjectTarget")]
public ProjectTarget ProjectTarget {
get;
set;
}
[XmlElement("StandaloneTarget")]
public StandaloneTarget StandaloneTarget {
get;
set;
}
[XmlElement("Reports")]
public Reports Reports {
get;
set;
}
[XmlElement()]
public bool UseVTune {
get;
set;
}
internal string GetProfilingName(IServiceProvider serviceProvider, out bool save) {
string baseName = null;
if (ProjectTarget != null) {
if (!String.IsNullOrEmpty(ProjectTarget.FriendlyName)) {
baseName = ProjectTarget.FriendlyName;
}
} else if (StandaloneTarget != null) {
if (!String.IsNullOrEmpty(StandaloneTarget.Script)) {
baseName = Path.GetFileNameWithoutExtension(StandaloneTarget.Script);
}
}
if (baseName == null) {
baseName = Strings.PerformanceBaseFileName;
}
baseName = baseName + ".pyperf";
var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE));
if (dte.Solution.IsOpen && !String.IsNullOrEmpty(dte.Solution.FullName)) {
save = true;
return Path.Combine(Path.GetDirectoryName(dte.Solution.FullName), baseName);
}
save = false;
return baseName;
}
internal ProfilingTarget Clone() {
var res = new ProfilingTarget();
if (ProjectTarget != null) {
res.ProjectTarget = ProjectTarget.Clone();
}
if (StandaloneTarget != null) {
res.StandaloneTarget = StandaloneTarget.Clone();
}
if (Reports != null) {
res.Reports = Reports.Clone();
}
res.UseVTune = UseVTune;
return res;
}
internal static bool IsSame(ProfilingTarget self, ProfilingTarget other) {
if (self == null) {
return other == null;
} else if (other != null) {
return ProjectTarget.IsSame(self.ProjectTarget, other.ProjectTarget) &&
StandaloneTarget.IsSame(self.StandaloneTarget, other.StandaloneTarget);
}
return false;
}
}
[Serializable]
public sealed class ProjectTarget {
[XmlElement("TargetProject")]
public Guid TargetProject {
get;
set;
}
[XmlElement("FriendlyName")]
public string FriendlyName {
get;
set;
}
internal ProjectTarget Clone() {
var res = new ProjectTarget();
res.TargetProject = TargetProject;
res.FriendlyName = FriendlyName;
return res;
}
internal static bool IsSame(ProjectTarget self, ProjectTarget other) {
if (self == null) {
return other == null;
} else if (other != null) {
return self.TargetProject == other.TargetProject;
}
return false;
}
}
[Serializable]
public sealed class StandaloneTarget {
[XmlElement(ElementName = "PythonInterpreter")]
public PythonInterpreter PythonInterpreter {
get;
set;
}
[XmlElement(ElementName = "InterpreterPath")]
public string InterpreterPath {
get;
set;
}
[XmlElement("WorkingDirectory")]
public string WorkingDirectory {
get;
set;
}
[XmlElement("Script")]
public string Script {
get;
set;
}
[XmlElement("Arguments")]
public string Arguments {
get;
set;
}
internal StandaloneTarget Clone() {
var res = new StandaloneTarget();
if (PythonInterpreter != null) {
res.PythonInterpreter = PythonInterpreter.Clone();
}
res.InterpreterPath = InterpreterPath;
res.WorkingDirectory = WorkingDirectory;
res.Script = Script;
res.Arguments = Arguments;
return res;
}
internal static bool IsSame(StandaloneTarget self, StandaloneTarget other) {
if (self == null) {
return other == null;
} else if (other != null) {
return PythonInterpreter.IsSame(self.PythonInterpreter, other.PythonInterpreter) &&
self.InterpreterPath == other.InterpreterPath &&
self.WorkingDirectory == other.WorkingDirectory &&
self.Script == other.Script &&
self.Arguments == other.Arguments;
}
return false;
}
}
public sealed class PythonInterpreter {
[XmlElement("Id")]
public string Id {
get;
set;
}
internal PythonInterpreter Clone() {
var res = new PythonInterpreter();
res.Id = Id;
return res;
}
internal static bool IsSame(PythonInterpreter self, PythonInterpreter other) {
if (self == null) {
return other == null;
} else if (other != null) {
return self.Id == other.Id;
}
return false;
}
}
public sealed class Reports {
public Reports() { }
public Reports(Profiling.Report[] reports) {
Report = reports;
}
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[XmlElement("Report")]
public Report[] Report {
get {
return AllReports.Values.ToArray();
}
set {
AllReports = new SortedDictionary<uint, Report>();
for (uint i = 0; i < value.Length; i++) {
AllReports[i + SessionNode.StartingReportId] = value[i];
}
}
}
internal SortedDictionary<uint, Report> AllReports {
get;
set;
}
internal Reports Clone() {
var res = new Reports();
if (Report != null) {
res.Report = new Report[Report.Length];
for (int i = 0; i < res.Report.Length; i++) {
res.Report[i] = Report[i].Clone();
}
}
return res;
}
}
public sealed class Report {
public Report() { }
public Report(string filename) {
Filename = filename;
}
[XmlElement("Filename")]
public string Filename {
get;
set;
}
internal Report Clone() {
var res = new Report();
res.Filename = Filename;
return res;
}
}
}
| |
/*
* 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.
*/
//#define SPAM
using System;
using System.Collections.Generic;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenSim.Region.PhysicsModules.ConvexDecompositionDotNet;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using System.Drawing;
using System.Threading;
using System.IO.Compression;
using PrimMesher;
using log4net;
using Nini.Config;
using System.Reflection;
using System.IO;
using Mono.Addins;
namespace OpenSim.Region.PhysicsModule.ubODEMeshing
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ubODEMeshmerizer")]
public class ubMeshmerizer : IMesher, INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Setting baseDir to a path will enable the dumping of raw files
// raw files can be imported by blender so a visual inspection of the results can be done
private static string cacheControlFilename = "cntr";
private bool m_Enabled = false;
public static object diskLock = new object();
public bool doMeshFileCache = true;
public bool doCacheExpire = true;
public string cachePath = "MeshCache";
public TimeSpan CacheExpire;
// const string baseDir = "rawFiles";
private const string baseDir = null; //"rawFiles";
private bool useMeshiesPhysicsMesh = true;
private bool doConvexPrims = true;
private bool doConvexSculpts = true;
private Dictionary<AMeshKey, Mesh> m_uniqueMeshes = new Dictionary<AMeshKey, Mesh>();
private Dictionary<AMeshKey, Mesh> m_uniqueReleasedMeshes = new Dictionary<AMeshKey, Mesh>();
#region INonSharedRegionModule
public string Name
{
get { return "ubODEMeshmerizer"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource config)
{
IConfig start_config = config.Configs["Startup"];
string mesher = start_config.GetString("meshing", string.Empty);
if (mesher == Name)
{
float fcache = 48.0f;
// float fcache = 0.02f;
IConfig mesh_config = config.Configs["Mesh"];
if (mesh_config != null)
{
useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh);
doConvexPrims = mesh_config.GetBoolean("ConvexPrims",doConvexPrims);
doConvexSculpts = mesh_config.GetBoolean("ConvexSculpts",doConvexPrims);
doMeshFileCache = mesh_config.GetBoolean("MeshFileCache", doMeshFileCache);
cachePath = mesh_config.GetString("MeshFileCachePath", cachePath);
fcache = mesh_config.GetFloat("MeshFileCacheExpireHours", fcache);
doCacheExpire = mesh_config.GetBoolean("MeshFileCacheDoExpire", doCacheExpire);
m_Enabled = true;
}
CacheExpire = TimeSpan.FromHours(fcache);
if(String.IsNullOrEmpty(cachePath))
doMeshFileCache = false;
if(doMeshFileCache)
{
if(!checkCache())
{
doMeshFileCache = false;
doCacheExpire = false;
}
}
else
doCacheExpire = false;
}
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IMesher>(this);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.UnregisterModuleInterface<IMesher>(this);
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
#endregion
private void ReportPrimError(string message, string primName, PrimMesh primMesh)
{
m_log.Error(message);
m_log.Error("\nPrim Name: " + primName);
m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
}
/// <summary>
/// Add a submesh to an existing list of coords and faces.
/// </summary>
/// <param name="subMeshData"></param>
/// <param name="size">Size of entire object</param>
/// <param name="coords"></param>
/// <param name="faces"></param>
private void AddSubMesh(OSDMap subMeshData, List<Coord> coords, List<Face> faces)
{
// Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));
// As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
// of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
// geometry for this submesh.
if (subMeshData.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshData["NoGeometry"]))
return;
OpenMetaverse.Vector3 posMax;
OpenMetaverse.Vector3 posMin;
if (subMeshData.ContainsKey("PositionDomain"))
{
posMax = ((OSDMap)subMeshData["PositionDomain"])["Max"].AsVector3();
posMin = ((OSDMap)subMeshData["PositionDomain"])["Min"].AsVector3();
}
else
{
posMax = new Vector3(0.5f, 0.5f, 0.5f);
posMin = new Vector3(-0.5f, -0.5f, -0.5f);
}
ushort faceIndexOffset = (ushort)coords.Count;
byte[] posBytes = subMeshData["Position"].AsBinary();
for (int i = 0; i < posBytes.Length; i += 6)
{
ushort uX = Utils.BytesToUInt16(posBytes, i);
ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);
Coord c = new Coord(
Utils.UInt16ToFloat(uX, posMin.X, posMax.X),
Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y),
Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z));
coords.Add(c);
}
byte[] triangleBytes = subMeshData["TriangleList"].AsBinary();
for (int i = 0; i < triangleBytes.Length; i += 6)
{
ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
Face f = new Face(v1, v2, v3);
faces.Add(f);
}
}
/// <summary>
/// Create a physics mesh from data that comes with the prim. The actual data used depends on the prim type.
/// </summary>
/// <param name="primName"></param>
/// <param name="primShape"></param>
/// <param name="size"></param>
/// <param name="lod"></param>
/// <returns></returns>
private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, float lod, bool convex)
{
// m_log.DebugFormat(
// "[MESH]: Creating physics proxy for {0}, shape {1}",
// primName, (OpenMetaverse.SculptType)primShape.SculptType);
List<Coord> coords;
List<Face> faces;
bool needsConvexProcessing = convex;
if (primShape.SculptEntry)
{
if (((SculptType)primShape.SculptType) == SculptType.Mesh)
{
if (!useMeshiesPhysicsMesh)
return null;
try
{
if (!GenerateCoordsAndFacesFromPrimMeshData(primName, primShape, out coords, out faces, convex))
return null;
needsConvexProcessing = false;
}
catch
{
m_log.ErrorFormat("[MESH]: fail to process mesh asset for prim {0}", primName);
return null;
}
}
else
{
try
{
if (!GenerateCoordsAndFacesFromPrimSculptData(primName, primShape, lod, out coords, out faces))
return null;
needsConvexProcessing &= doConvexSculpts;
}
catch
{
m_log.ErrorFormat("[MESH]: fail to process sculpt map for prim {0}", primName);
return null;
}
}
}
else
{
try
{
if (!GenerateCoordsAndFacesFromPrimShapeData(primName, primShape, lod, convex, out coords, out faces))
return null;
needsConvexProcessing &= doConvexPrims;
}
catch
{
m_log.ErrorFormat("[MESH]: fail to process shape parameters for prim {0}", primName);
return null;
}
}
int numCoords = coords.Count;
int numFaces = faces.Count;
if(numCoords < 3 || (!needsConvexProcessing && numFaces < 1))
{
m_log.ErrorFormat("[MESH]: invalid degenerated mesh for prim {0} ignored", primName);
return null;
}
if(needsConvexProcessing)
{
List<Coord> convexcoords;
List<Face> convexfaces;
if(CreateBoundingHull(coords, out convexcoords, out convexfaces) && convexcoords != null && convexfaces != null)
{
coords.Clear();
coords = convexcoords;
numCoords = coords.Count;
faces.Clear();
faces = convexfaces;
numFaces = faces.Count;
}
else
m_log.ErrorFormat("[ubMESH]: failed to create convex for {0} using normal mesh", primName);
}
Mesh mesh = new Mesh(true);
// Add the corresponding triangles to the mesh
for (int i = 0; i < numFaces; i++)
{
Face f = faces[i];
mesh.Add(new Triangle(coords[f.v1].X, coords[f.v1].Y, coords[f.v1].Z,
coords[f.v2].X, coords[f.v2].Y, coords[f.v2].Z,
coords[f.v3].X, coords[f.v3].Y, coords[f.v3].Z));
}
coords.Clear();
faces.Clear();
if(mesh.numberVertices() < 3 || mesh.numberTriangles() < 1)
{
m_log.ErrorFormat("[MESH]: invalid degenerated mesh for prim {0} ignored", primName);
return null;
}
primShape.SculptData = Utils.EmptyBytes;
return mesh;
}
/// <summary>
/// Generate the co-ords and faces necessary to construct a mesh from the mesh data the accompanies a prim.
/// </summary>
/// <param name="primName"></param>
/// <param name="primShape"></param>
/// <param name="size"></param>
/// <param name="coords">Coords are added to this list by the method.</param>
/// <param name="faces">Faces are added to this list by the method.</param>
/// <returns>true if coords and faces were successfully generated, false if not</returns>
private bool GenerateCoordsAndFacesFromPrimMeshData(
string primName, PrimitiveBaseShape primShape, out List<Coord> coords, out List<Face> faces, bool convex)
{
// m_log.DebugFormat("[MESH]: experimental mesh proxy generation for {0}", primName);
// for ubOde we have a diferent mesh use priority
// priority is to use full mesh then decomposition
// SL does the oposite
bool usemesh = false;
coords = new List<Coord>();
faces = new List<Face>();
OSD meshOsd = null;
if (primShape.SculptData == null || primShape.SculptData.Length <= 0)
{
// m_log.InfoFormat("[MESH]: asset data for {0} is zero length", primName);
return false;
}
long start = 0;
using (MemoryStream data = new MemoryStream(primShape.SculptData))
{
try
{
OSD osd = OSDParser.DeserializeLLSDBinary(data);
if (osd is OSDMap)
meshOsd = (OSDMap)osd;
else
{
m_log.WarnFormat("[Mesh}: unable to cast mesh asset to OSDMap prim: {0}",primName);
return false;
}
}
catch (Exception e)
{
m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString());
return false;
}
start = data.Position;
}
if (meshOsd is OSDMap)
{
OSDMap physicsParms = null;
OSDMap map = (OSDMap)meshOsd;
if (!convex)
{
if (map.ContainsKey("physics_shape"))
physicsParms = (OSDMap)map["physics_shape"]; // old asset format
else if (map.ContainsKey("physics_mesh"))
physicsParms = (OSDMap)map["physics_mesh"]; // new asset format
if (physicsParms != null)
usemesh = true;
}
if(!usemesh && (map.ContainsKey("physics_convex")))
physicsParms = (OSDMap)map["physics_convex"];
if (physicsParms == null)
{
//m_log.WarnFormat("[MESH]: unknown mesh type for prim {0}",primName);
return false;
}
int physOffset = physicsParms["offset"].AsInteger() + (int)start;
int physSize = physicsParms["size"].AsInteger();
if (physOffset < 0 || physSize == 0)
return false; // no mesh data in asset
OSD decodedMeshOsd = new OSD();
byte[] meshBytes = new byte[physSize];
System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);
try
{
using (MemoryStream inMs = new MemoryStream(meshBytes))
{
using (MemoryStream outMs = new MemoryStream())
{
using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress))
{
byte[] readBuffer = new byte[2048];
inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header
int readLen = 0;
while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
outMs.Write(readBuffer, 0, readLen);
outMs.Seek(0, SeekOrigin.Begin);
byte[] decompressedBuf = outMs.GetBuffer();
decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
}
}
}
}
catch (Exception e)
{
m_log.Error("[MESH]: exception decoding physical mesh prim " + primName +" : " + e.ToString());
return false;
}
if (usemesh)
{
OSDArray decodedMeshOsdArray = null;
// physics_shape is an array of OSDMaps, one for each submesh
if (decodedMeshOsd is OSDArray)
{
// Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd));
decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
foreach (OSD subMeshOsd in decodedMeshOsdArray)
{
if (subMeshOsd is OSDMap)
AddSubMesh(subMeshOsd as OSDMap, coords, faces);
}
}
}
else
{
OSDMap cmap = (OSDMap)decodedMeshOsd;
if (cmap == null)
return false;
byte[] data;
List<float3> vs = new List<float3>();
PHullResult hullr = new PHullResult();
float3 f3;
Coord c;
Face f;
Vector3 range;
Vector3 min;
const float invMaxU16 = 1.0f / 65535f;
int t1;
int t2;
int t3;
int i;
int nverts;
int nindexs;
if (cmap.ContainsKey("Max"))
range = cmap["Max"].AsVector3();
else
range = new Vector3(0.5f, 0.5f, 0.5f);
if (cmap.ContainsKey("Min"))
min = cmap["Min"].AsVector3();
else
min = new Vector3(-0.5f, -0.5f, -0.5f);
range = range - min;
range *= invMaxU16;
if(!convex)
{
// if mesh data not present and not convex then we need convex decomposition data
if (cmap.ContainsKey("HullList") && cmap.ContainsKey("Positions"))
{
List<int> hsizes = new List<int>();
int totalpoints = 0;
data = cmap["HullList"].AsBinary();
for (i = 0; i < data.Length; i++)
{
t1 = data[i];
if (t1 == 0)
t1 = 256;
totalpoints += t1;
hsizes.Add(t1);
}
data = cmap["Positions"].AsBinary();
int ptr = 0;
int vertsoffset = 0;
if (totalpoints == data.Length / 6) // 2 bytes per coord, 3 coords per point
{
foreach (int hullsize in hsizes)
{
for (i = 0; i < hullsize; i++ )
{
t1 = data[ptr++];
t1 += data[ptr++] << 8;
t2 = data[ptr++];
t2 += data[ptr++] << 8;
t3 = data[ptr++];
t3 += data[ptr++] << 8;
f3 = new float3((t1 * range.X + min.X),
(t2 * range.Y + min.Y),
(t3 * range.Z + min.Z));
vs.Add(f3);
}
if(hullsize <3)
{
vs.Clear();
continue;
}
if (hullsize <5)
{
foreach (float3 point in vs)
{
c.X = point.x;
c.Y = point.y;
c.Z = point.z;
coords.Add(c);
}
f = new Face(vertsoffset, vertsoffset + 1, vertsoffset + 2);
faces.Add(f);
if (hullsize == 4)
{
// not sure about orientation..
f = new Face(vertsoffset, vertsoffset + 2, vertsoffset + 3);
faces.Add(f);
f = new Face(vertsoffset, vertsoffset + 3, vertsoffset + 1);
faces.Add(f);
f = new Face(vertsoffset + 3, vertsoffset + 2, vertsoffset + 1);
faces.Add(f);
}
vertsoffset += vs.Count;
vs.Clear();
continue;
}
List<int> indices;
if (!HullUtils.ComputeHull(vs, out indices))
{
vs.Clear();
continue;
}
nverts = vs.Count;
nindexs = indices.Count;
if (nindexs % 3 != 0)
{
vs.Clear();
continue;
}
for (i = 0; i < nverts; i++)
{
c.X = vs[i].x;
c.Y = vs[i].y;
c.Z = vs[i].z;
coords.Add(c);
}
for (i = 0; i < nindexs; i += 3)
{
t1 = indices[i];
if (t1 > nverts)
break;
t2 = indices[i + 1];
if (t2 > nverts)
break;
t3 = indices[i + 2];
if (t3 > nverts)
break;
f = new Face(vertsoffset + t1, vertsoffset + t2, vertsoffset + t3);
faces.Add(f);
}
vertsoffset += nverts;
vs.Clear();
}
}
if (coords.Count > 0 && faces.Count > 0)
return true;
}
else
{
// if neither mesh or decomposition present, warn and use convex
//m_log.WarnFormat("[MESH]: Data for PRIM shape type ( mesh or decomposition) not found for prim {0}",primName);
}
}
vs.Clear();
if (cmap.ContainsKey("BoundingVerts"))
{
data = cmap["BoundingVerts"].AsBinary();
for (i = 0; i < data.Length; )
{
t1 = data[i++];
t1 += data[i++] << 8;
t2 = data[i++];
t2 += data[i++] << 8;
t3 = data[i++];
t3 += data[i++] << 8;
f3 = new float3((t1 * range.X + min.X),
(t2 * range.Y + min.Y),
(t3 * range.Z + min.Z));
vs.Add(f3);
}
nverts = vs.Count;
if (nverts < 3)
{
vs.Clear();
return false;
}
if (nverts < 5)
{
foreach (float3 point in vs)
{
c.X = point.x;
c.Y = point.y;
c.Z = point.z;
coords.Add(c);
}
f = new Face(0, 1, 2);
faces.Add(f);
if (nverts == 4)
{
f = new Face(0, 2, 3);
faces.Add(f);
f = new Face(0, 3, 1);
faces.Add(f);
f = new Face( 3, 2, 1);
faces.Add(f);
}
vs.Clear();
return true;
}
List<int> indices;
if (!HullUtils.ComputeHull(vs, out indices))
return false;
nindexs = indices.Count;
if (nindexs % 3 != 0)
return false;
for (i = 0; i < nverts; i++)
{
c.X = vs[i].x;
c.Y = vs[i].y;
c.Z = vs[i].z;
coords.Add(c);
}
for (i = 0; i < nindexs; i += 3)
{
t1 = indices[i];
if (t1 > nverts)
break;
t2 = indices[i + 1];
if (t2 > nverts)
break;
t3 = indices[i + 2];
if (t3 > nverts)
break;
f = new Face(t1, t2, t3);
faces.Add(f);
}
vs.Clear();
if (coords.Count > 0 && faces.Count > 0)
return true;
}
else
return false;
}
}
return true;
}
/// <summary>
/// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim.
/// </summary>
/// <param name="primName"></param>
/// <param name="primShape"></param>
/// <param name="size"></param>
/// <param name="lod"></param>
/// <param name="coords">Coords are added to this list by the method.</param>
/// <param name="faces">Faces are added to this list by the method.</param>
/// <returns>true if coords and faces were successfully generated, false if not</returns>
private bool GenerateCoordsAndFacesFromPrimSculptData(
string primName, PrimitiveBaseShape primShape, float lod, out List<Coord> coords, out List<Face> faces)
{
coords = new List<Coord>();
faces = new List<Face>();
PrimMesher.SculptMesh sculptMesh;
Image idata = null;
if (primShape.SculptData == null || primShape.SculptData.Length == 0)
return false;
try
{
OpenMetaverse.Imaging.ManagedImage unusedData;
OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
unusedData = null;
if (idata == null)
{
// In some cases it seems that the decode can return a null bitmap without throwing
// an exception
m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName);
return false;
}
}
catch (DllNotFoundException)
{
m_log.Error("[PHYSICS]: OpenJpeg is not installed correctly on this system. Physics Proxy generation failed. Often times this is because of an old version of GLIBC. You must have version 2.4 or above!");
return false;
}
catch (IndexOutOfRangeException)
{
m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
return false;
}
catch (Exception ex)
{
m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
return false;
}
PrimMesher.SculptMesh.SculptType sculptType;
// remove mirror and invert bits
OpenMetaverse.SculptType pbsSculptType = ((OpenMetaverse.SculptType)(primShape.SculptType & 0x3f));
switch (pbsSculptType)
{
case OpenMetaverse.SculptType.Cylinder:
sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
break;
case OpenMetaverse.SculptType.Plane:
sculptType = PrimMesher.SculptMesh.SculptType.plane;
break;
case OpenMetaverse.SculptType.Torus:
sculptType = PrimMesher.SculptMesh.SculptType.torus;
break;
case OpenMetaverse.SculptType.Sphere:
sculptType = PrimMesher.SculptMesh.SculptType.sphere;
break;
default:
sculptType = PrimMesher.SculptMesh.SculptType.plane;
break;
}
bool mirror = ((primShape.SculptType & 128) != 0);
bool invert = ((primShape.SculptType & 64) != 0);
sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, mirror, invert);
idata.Dispose();
// sculptMesh.DumpRaw(baseDir, primName, "primMesh");
coords = sculptMesh.coords;
faces = sculptMesh.faces;
return true;
}
/// <summary>
/// Generate the co-ords and faces necessary to construct a mesh from the shape data the accompanies a prim.
/// </summary>
/// <param name="primName"></param>
/// <param name="primShape"></param>
/// <param name="size"></param>
/// <param name="coords">Coords are added to this list by the method.</param>
/// <param name="faces">Faces are added to this list by the method.</param>
/// <returns>true if coords and faces were successfully generated, false if not</returns>
private bool GenerateCoordsAndFacesFromPrimShapeData(
string primName, PrimitiveBaseShape primShape, float lod, bool convex,
out List<Coord> coords, out List<Face> faces)
{
PrimMesh primMesh;
coords = new List<Coord>();
faces = new List<Face>();
float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
if (profileBegin < 0.0f)
profileBegin = 0.0f;
if (profileEnd < 0.02f)
profileEnd = 0.02f;
else if (profileEnd > 1.0f)
profileEnd = 1.0f;
if (profileBegin >= profileEnd)
profileBegin = profileEnd - 0.02f;
float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
if(convex)
profileHollow = 0.0f;
else if (profileHollow > 0.95f)
profileHollow = 0.95f;
int sides = 4;
LevelOfDetail iLOD = (LevelOfDetail)lod;
byte profshape = (byte)(primShape.ProfileCurve & 0x07);
if (profshape == (byte)ProfileShape.EquilateralTriangle
|| profshape == (byte)ProfileShape.IsometricTriangle
|| profshape == (byte)ProfileShape.RightTriangle)
sides = 3;
else if (profshape == (byte)ProfileShape.Circle)
{
switch (iLOD)
{
case LevelOfDetail.High: sides = 24; break;
case LevelOfDetail.Medium: sides = 12; break;
case LevelOfDetail.Low: sides = 6; break;
case LevelOfDetail.VeryLow: sides = 3; break;
default: sides = 24; break;
}
}
else if (profshape == (byte)ProfileShape.HalfCircle)
{ // half circle, prim is a sphere
switch (iLOD)
{
case LevelOfDetail.High: sides = 24; break;
case LevelOfDetail.Medium: sides = 12; break;
case LevelOfDetail.Low: sides = 6; break;
case LevelOfDetail.VeryLow: sides = 3; break;
default: sides = 24; break;
}
profileBegin = 0.5f * profileBegin + 0.5f;
profileEnd = 0.5f * profileEnd + 0.5f;
}
int hollowSides = sides;
if (primShape.HollowShape == HollowShape.Circle)
{
switch (iLOD)
{
case LevelOfDetail.High: hollowSides = 24; break;
case LevelOfDetail.Medium: hollowSides = 12; break;
case LevelOfDetail.Low: hollowSides = 6; break;
case LevelOfDetail.VeryLow: hollowSides = 3; break;
default: hollowSides = 24; break;
}
}
else if (primShape.HollowShape == HollowShape.Square)
hollowSides = 4;
else if (primShape.HollowShape == HollowShape.Triangle)
{
if (profshape == (byte)ProfileShape.HalfCircle)
hollowSides = 6;
else
hollowSides = 3;
}
primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
if (primMesh.errorMessage != null)
if (primMesh.errorMessage.Length > 0)
m_log.Error("[ERROR] " + primMesh.errorMessage);
primMesh.topShearX = pathShearX;
primMesh.topShearY = pathShearY;
primMesh.pathCutBegin = pathBegin;
primMesh.pathCutEnd = pathEnd;
if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
{
primMesh.twistBegin = (primShape.PathTwistBegin * 18) / 10;
primMesh.twistEnd = (primShape.PathTwist * 18) / 10;
primMesh.taperX = pathScaleX;
primMesh.taperY = pathScaleY;
#if SPAM
m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
#endif
try
{
primMesh.ExtrudeLinear();
}
catch (Exception ex)
{
ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
return false;
}
}
else
{
primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
primMesh.radius = 0.01f * primShape.PathRadiusOffset;
primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
primMesh.skew = 0.01f * primShape.PathSkew;
primMesh.twistBegin = (primShape.PathTwistBegin * 36) / 10;
primMesh.twistEnd = (primShape.PathTwist * 36) / 10;
primMesh.taperX = primShape.PathTaperX * 0.01f;
primMesh.taperY = primShape.PathTaperY * 0.01f;
if(profshape == (byte)ProfileShape.HalfCircle)
{
if(primMesh.holeSizeY < 0.01f)
primMesh.holeSizeY = 0.01f;
else if(primMesh.holeSizeY > 1.0f)
primMesh.holeSizeY = 1.0f;
}
#if SPAM
m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
#endif
try
{
primMesh.ExtrudeCircular();
}
catch (Exception ex)
{
ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
return false;
}
}
// primMesh.DumpRaw(baseDir, primName, "primMesh");
coords = primMesh.coords;
faces = primMesh.faces;
return true;
}
public AMeshKey GetMeshUniqueKey(PrimitiveBaseShape primShape, Vector3 size, byte lod, bool convex)
{
AMeshKey key = new AMeshKey();
Byte[] someBytes;
key.hashB = 5181;
key.hashC = 5181;
ulong hash = 5381;
if (primShape.SculptEntry)
{
key.uuid = primShape.SculptTexture;
key.hashC = mdjb2(key.hashC, primShape.SculptType);
key.hashC = mdjb2(key.hashC, primShape.PCode);
}
else
{
hash = mdjb2(hash, primShape.PathCurve);
hash = mdjb2(hash, (byte)primShape.HollowShape);
hash = mdjb2(hash, (byte)primShape.ProfileShape);
hash = mdjb2(hash, primShape.PathBegin);
hash = mdjb2(hash, primShape.PathEnd);
hash = mdjb2(hash, primShape.PathScaleX);
hash = mdjb2(hash, primShape.PathScaleY);
hash = mdjb2(hash, primShape.PathShearX);
key.hashA = hash;
hash = key.hashB;
hash = mdjb2(hash, primShape.PathShearY);
hash = mdjb2(hash, (byte)primShape.PathTwist);
hash = mdjb2(hash, (byte)primShape.PathTwistBegin);
hash = mdjb2(hash, (byte)primShape.PathRadiusOffset);
hash = mdjb2(hash, (byte)primShape.PathTaperX);
hash = mdjb2(hash, (byte)primShape.PathTaperY);
hash = mdjb2(hash, primShape.PathRevolutions);
hash = mdjb2(hash, (byte)primShape.PathSkew);
hash = mdjb2(hash, primShape.ProfileBegin);
hash = mdjb2(hash, primShape.ProfileEnd);
hash = mdjb2(hash, primShape.ProfileHollow);
hash = mdjb2(hash, primShape.PCode);
key.hashB = hash;
}
hash = key.hashC;
hash = mdjb2(hash, lod);
if (size == m_MeshUnitSize)
{
hash = hash << 8;
hash |= 8;
}
else
{
someBytes = size.GetBytes();
for (int i = 0; i < someBytes.Length; i++)
hash = mdjb2(hash, someBytes[i]);
hash = hash << 8;
}
if (convex)
hash |= 4;
if (primShape.SculptEntry)
{
hash |= 1;
if (primShape.SculptType == (byte)SculptType.Mesh)
hash |= 2;
}
key.hashC = hash;
return key;
}
private ulong mdjb2(ulong hash, byte c)
{
return ((hash << 5) + hash) + (ulong)c;
}
private ulong mdjb2(ulong hash, ushort c)
{
hash = ((hash << 5) + hash) + (ulong)((byte)c);
return ((hash << 5) + hash) + (ulong)(c >> 8);
}
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
{
return CreateMesh(primName, primShape, size, lod, false,false,false);
}
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
{
return CreateMesh(primName, primShape, size, lod, false,false,false);
}
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache, bool convex, bool forOde)
{
return CreateMesh(primName, primShape, size, lod, false, false, false);
}
public IMesh GetMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex)
{
Mesh mesh = null;
if (size.X < 0.01f) size.X = 0.01f;
if (size.Y < 0.01f) size.Y = 0.01f;
if (size.Z < 0.01f) size.Z = 0.01f;
AMeshKey key = GetMeshUniqueKey(primShape, size, (byte)lod, convex);
lock (m_uniqueMeshes)
{
m_uniqueMeshes.TryGetValue(key, out mesh);
if (mesh != null)
{
mesh.RefCount++;
return mesh;
}
// try to find a identical mesh on meshs recently released
lock (m_uniqueReleasedMeshes)
{
m_uniqueReleasedMeshes.TryGetValue(key, out mesh);
if (mesh != null)
{
m_uniqueReleasedMeshes.Remove(key);
try
{
m_uniqueMeshes.Add(key, mesh);
}
catch { }
mesh.RefCount = 1;
return mesh;
}
}
}
return null;
}
private static Vector3 m_MeshUnitSize = new Vector3(1.0f, 1.0f, 1.0f);
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex, bool forOde)
{
#if SPAM
m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
#endif
Mesh mesh = null;
if (size.X < 0.01f) size.X = 0.01f;
if (size.Y < 0.01f) size.Y = 0.01f;
if (size.Z < 0.01f) size.Z = 0.01f;
// try to find a identical mesh on meshs in use
AMeshKey key = GetMeshUniqueKey(primShape,size,(byte)lod, convex);
lock (m_uniqueMeshes)
{
m_uniqueMeshes.TryGetValue(key, out mesh);
if (mesh != null)
{
mesh.RefCount++;
return mesh;
}
// try to find a identical mesh on meshs recently released
lock (m_uniqueReleasedMeshes)
{
m_uniqueReleasedMeshes.TryGetValue(key, out mesh);
if (mesh != null)
{
m_uniqueReleasedMeshes.Remove(key);
try
{
m_uniqueMeshes.Add(key, mesh);
}
catch { }
mesh.RefCount = 1;
return mesh;
}
}
}
Mesh UnitMesh = null;
AMeshKey unitKey = GetMeshUniqueKey(primShape, m_MeshUnitSize, (byte)lod, convex);
lock (m_uniqueReleasedMeshes)
{
m_uniqueReleasedMeshes.TryGetValue(unitKey, out UnitMesh);
if (UnitMesh != null)
{
UnitMesh.RefCount = 1;
}
}
if (UnitMesh == null && primShape.SculptEntry && doMeshFileCache)
UnitMesh = GetFromFileCache(unitKey);
if (UnitMesh == null)
{
UnitMesh = CreateMeshFromPrimMesher(primName, primShape, lod, convex);
if (UnitMesh == null)
return null;
UnitMesh.DumpRaw(baseDir, unitKey.ToString(), "Z");
if (forOde)
{
// force pinned mem allocation
UnitMesh.PrepForOde();
}
else
UnitMesh.TrimExcess();
UnitMesh.Key = unitKey;
UnitMesh.RefCount = 1;
if (doMeshFileCache && primShape.SculptEntry)
StoreToFileCache(unitKey, UnitMesh);
lock (m_uniqueReleasedMeshes)
{
try
{
m_uniqueReleasedMeshes.Add(unitKey, UnitMesh);
}
catch { }
}
}
mesh = UnitMesh.Scale(size);
mesh.Key = key;
mesh.RefCount = 1;
lock (m_uniqueMeshes)
{
try
{
m_uniqueMeshes.Add(key, mesh);
}
catch { }
}
return mesh;
}
public void ReleaseMesh(IMesh imesh)
{
if (imesh == null)
return;
Mesh mesh = (Mesh)imesh;
lock (m_uniqueMeshes)
{
int curRefCount = mesh.RefCount;
curRefCount--;
if (curRefCount > 0)
{
mesh.RefCount = curRefCount;
return;
}
mesh.RefCount = 0;
m_uniqueMeshes.Remove(mesh.Key);
lock (m_uniqueReleasedMeshes)
{
try
{
m_uniqueReleasedMeshes.Add(mesh.Key, mesh);
}
catch { }
}
}
}
public void ExpireReleaseMeshs()
{
if (m_uniqueReleasedMeshes.Count == 0)
return;
List<Mesh> meshstodelete = new List<Mesh>();
int refcntr;
lock (m_uniqueReleasedMeshes)
{
foreach (Mesh m in m_uniqueReleasedMeshes.Values)
{
refcntr = m.RefCount;
refcntr--;
if (refcntr > -6)
m.RefCount = refcntr;
else
meshstodelete.Add(m);
}
foreach (Mesh m in meshstodelete)
{
m_uniqueReleasedMeshes.Remove(m.Key);
m.releaseBuildingMeshData();
m.releasePinned();
}
}
}
public void FileNames(AMeshKey key, out string dir, out string fullFileName)
{
string id = key.ToString();
string init = id.Substring(0, 1);
dir = System.IO.Path.Combine(cachePath, init);
fullFileName = System.IO.Path.Combine(dir, id);
}
public string FullFileName(AMeshKey key)
{
string id = key.ToString();
string init = id.Substring(0,1);
id = System.IO.Path.Combine(init, id);
id = System.IO.Path.Combine(cachePath, id);
return id;
}
private Mesh GetFromFileCache(AMeshKey key)
{
Mesh mesh = null;
string filename = FullFileName(key);
bool ok = true;
lock (diskLock)
{
if (File.Exists(filename))
{
try
{
using(FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// BinaryFormatter bformatter = new BinaryFormatter();
mesh = Mesh.FromStream(stream,key);
}
}
catch (Exception e)
{
ok = false;
m_log.ErrorFormat(
"[MESH CACHE]: Failed to get file {0}. Exception {1} {2}",
filename, e.Message, e.StackTrace);
}
try
{
if (mesh == null || !ok)
File.Delete(filename);
else
File.SetLastAccessTimeUtc(filename, DateTime.UtcNow);
}
catch
{
}
}
}
return mesh;
}
private void StoreToFileCache(AMeshKey key, Mesh mesh)
{
bool ok = false;
// Make sure the target cache directory exists
string dir = String.Empty;
string filename = String.Empty;
FileNames(key, out dir, out filename);
lock (diskLock)
{
Stream stream = null;
try
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
stream = File.Open(filename, FileMode.Create);
ok = mesh.ToStream(stream);
}
catch (IOException e)
{
m_log.ErrorFormat(
"[MESH CACHE]: Failed to write file {0}. Exception {1} {2}.",
filename, e.Message, e.StackTrace);
ok = false;
}
finally
{
if(stream != null)
stream.Dispose();
}
if (!ok && File.Exists(filename))
{
try
{
File.Delete(filename);
}
catch (IOException)
{
m_log.ErrorFormat(
"[MESH CACHE]: Failed to delete file {0}",filename);
}
}
}
}
public void ExpireFileCache()
{
if (!doCacheExpire)
return;
string controlfile = System.IO.Path.Combine(cachePath, cacheControlFilename);
lock (diskLock)
{
try
{
if (File.Exists(controlfile))
{
int ndeleted = 0;
int totalfiles = 0;
int ndirs = 0;
DateTime OlderTime = File.GetLastAccessTimeUtc(controlfile) - CacheExpire;
File.SetLastAccessTimeUtc(controlfile, DateTime.UtcNow);
foreach (string dir in Directory.GetDirectories(cachePath))
{
try
{
foreach (string file in Directory.GetFiles(dir))
{
try
{
if (File.GetLastAccessTimeUtc(file) < OlderTime)
{
File.Delete(file);
ndeleted++;
}
}
catch { }
totalfiles++;
}
}
catch { }
ndirs++;
}
if (ndeleted == 0)
m_log.InfoFormat("[MESH CACHE]: {0} Files in {1} cache folders, no expires",
totalfiles,ndirs);
else
m_log.InfoFormat("[MESH CACHE]: {0} Files in {1} cache folders, expired {2} files accessed before {3}",
totalfiles,ndirs, ndeleted, OlderTime.ToString());
}
else
{
m_log.Info("[MESH CACHE]: Expire delayed to next startup");
FileStream fs = File.Create(controlfile,4096,FileOptions.WriteThrough);
fs.Close();
}
}
catch { }
}
}
public bool checkCache()
{
string controlfile = System.IO.Path.Combine(cachePath, cacheControlFilename);
lock (diskLock)
{
try
{
if (!Directory.Exists(cachePath))
{
Directory.CreateDirectory(cachePath);
Thread.Sleep(100);
FileStream fs = File.Create(controlfile, 4096, FileOptions.WriteThrough);
fs.Close();
return true;
}
}
catch
{
doMeshFileCache = false;
doCacheExpire = false;
return false;
}
finally {}
if (File.Exists(controlfile))
return true;
try
{
Directory.Delete(cachePath, true);
while(Directory.Exists(cachePath))
Thread.Sleep(100);
}
catch(Exception e)
{
m_log.Error("[MESH CACHE]: failed to delete old version of the cache: " + e.Message);
doMeshFileCache = false;
doCacheExpire = false;
return false;
}
finally {}
try
{
Directory.CreateDirectory(cachePath);
while(!Directory.Exists(cachePath))
Thread.Sleep(100);
}
catch(Exception e)
{
m_log.Error("[MESH CACHE]: failed to create new cache folder: " + e.Message);
doMeshFileCache = false;
doCacheExpire = false;
return false;
}
finally {}
try
{
FileStream fs = File.Create(controlfile, 4096, FileOptions.WriteThrough);
fs.Close();
}
catch(Exception e)
{
m_log.Error("[MESH CACHE]: failed to create new control file: " + e.Message);
doMeshFileCache = false;
doCacheExpire = false;
return false;
}
finally {}
return true;
}
}
public bool CreateBoundingHull(List<Coord> inputVertices, out List<Coord> convexcoords, out List<Face> newfaces)
{
convexcoords = null;
newfaces = null;
HullDesc desc = new HullDesc();
HullResult result = new HullResult();
int nInputVerts = inputVertices.Count;
int i;
List<float3> vs = new List<float3>(nInputVerts);
float3 f3;
//useless copy
for(i = 0 ; i < nInputVerts; i++)
{
f3 = new float3(inputVertices[i].X, inputVertices[i].Y, inputVertices[i].Z);
vs.Add(f3);
}
desc.Vertices = vs;
desc.Flags = HullFlag.QF_TRIANGLES;
desc.MaxVertices = 256;
try
{
HullError ret = HullUtils.CreateConvexHull(desc, ref result);
if (ret != HullError.QE_OK)
return false;
int nverts = result.OutputVertices.Count;
int nindx = result.Indices.Count;
if(nverts < 3 || nindx< 3)
return false;
if(nindx % 3 != 0)
return false;
convexcoords = new List<Coord>(nverts);
Coord c;
vs = result.OutputVertices;
for(i = 0 ; i < nverts; i++)
{
c = new Coord(vs[i].x, vs[i].y, vs[i].z);
convexcoords.Add(c);
}
newfaces = new List<Face>(nindx / 3);
List<int> indxs = result.Indices;
int k, l, m;
Face f;
for(i = 0 ; i < nindx;)
{
k = indxs[i++];
l = indxs[i++];
m = indxs[i++];
if(k > nInputVerts)
continue;
if(l > nInputVerts)
continue;
if(m > nInputVerts)
continue;
f = new Face(k,l,m);
newfaces.Add(f);
}
}
catch
{
return false;
}
return true;
}
}
}
| |
// 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.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// The result of running a script.
/// </summary>
public abstract class ScriptState
{
/// <summary>
/// The script that ran to produce this result.
/// </summary>
public Script Script { get; }
internal ScriptExecutionState ExecutionState { get; }
private ImmutableArray<ScriptVariable> _lazyVariables;
private IReadOnlyDictionary<string, int> _lazyVariableMap;
internal ScriptState(ScriptExecutionState executionState, Script script)
{
Debug.Assert(executionState != null);
Debug.Assert(script != null);
ExecutionState = executionState;
Script = script;
}
/// <summary>
/// The final value produced by running the script.
/// </summary>
public object ReturnValue => GetReturnValue();
internal abstract object GetReturnValue();
/// <summary>
/// Returns variables defined by the scripts in the declaration order.
/// </summary>
public ImmutableArray<ScriptVariable> Variables
{
get
{
if (_lazyVariables == null)
{
ImmutableInterlocked.InterlockedInitialize(ref _lazyVariables, CreateVariables());
}
return _lazyVariables;
}
}
/// <summary>
/// Returns a script variable of the specified name.
/// </summary>
/// <remarks>
/// If multiple script variables are defined in the script (in distinct submissions) returns the last one.
/// Name lookup is case sensitive in C# scripts and case insensitive in VB scripts.
/// </remarks>
/// <returns><see cref="ScriptVariable"/> or null, if no variable of the specified <paramref name="name"/> is defined in the script.</returns>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception>
public ScriptVariable GetVariable(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
int index;
return GetVariableMap().TryGetValue(name, out index) ? Variables[index] : null;
}
private ImmutableArray<ScriptVariable> CreateVariables()
{
var result = ImmutableArray.CreateBuilder<ScriptVariable>();
var executionState = ExecutionState;
// Don't include the globals object (slot #0)
for (int i = 1; i < executionState.SubmissionStateCount; i++)
{
var state = executionState.GetSubmissionState(i);
Debug.Assert(state != null);
foreach (var field in state.GetType().GetTypeInfo().DeclaredFields)
{
// TODO: synthesized fields of submissions shouldn't be public
if (field.IsPublic && field.Name.Length > 0 && (char.IsLetterOrDigit(field.Name[0]) || field.Name[0] == '_'))
{
result.Add(new ScriptVariable(state, field));
}
}
}
return result.ToImmutable();
}
private IReadOnlyDictionary<string, int> GetVariableMap()
{
if (_lazyVariableMap == null)
{
var map = new Dictionary<string, int>(Script.Compiler.IdentifierComparer);
for (int i = 0; i < Variables.Length; i++)
{
map[Variables[i].Name] = i;
}
_lazyVariableMap = map;
}
return _lazyVariableMap;
}
public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ContinueWithAsync<object>(code, options, cancellationToken);
}
public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Script.ContinueWith<TResult>(code, options).ContinueAsync(this, cancellationToken);
}
// How do we resolve overloads? We should use the language semantics.
// https://github.com/dotnet/roslyn/issues/3720
#if TODO
/// <summary>
/// Invoke a method declared by the script.
/// </summary>
public object Invoke(string name, params object[] args)
{
var func = this.FindMethod(name, args != null ? args.Length : 0);
if (func != null)
{
return func(args);
}
return null;
}
private Func<object[], object> FindMethod(string name, int argCount)
{
for (int i = _executionState.Count - 1; i >= 0; i--)
{
var sub = _executionState[i];
if (sub != null)
{
var type = sub.GetType();
var method = FindMethod(type, name, argCount);
if (method != null)
{
return (args) => method.Invoke(sub, args);
}
}
}
return null;
}
private MethodInfo FindMethod(Type type, string name, int argCount)
{
return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
/// <summary>
/// Create a delegate to a method declared by the script.
/// </summary>
public TDelegate CreateDelegate<TDelegate>(string name)
{
var delegateInvokeMethod = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public);
for (int i = _executionState.Count - 1; i >= 0; i--)
{
var sub = _executionState[i];
if (sub != null)
{
var type = sub.GetType();
var method = FindMatchingMethod(type, name, delegateInvokeMethod);
if (method != null)
{
return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), sub);
}
}
}
return default(TDelegate);
}
private MethodInfo FindMatchingMethod(Type instanceType, string name, MethodInfo delegateInvokeMethod)
{
var dprms = delegateInvokeMethod.GetParameters();
foreach (var mi in instanceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (mi.Name == name)
{
var prms = mi.GetParameters();
if (prms.Length == dprms.Length)
{
// TODO: better matching..
return mi;
}
}
}
return null;
}
#endif
}
public sealed class ScriptState<T> : ScriptState
{
public new T ReturnValue { get; }
internal override object GetReturnValue() => ReturnValue;
internal ScriptState(ScriptExecutionState executionState, T value, Script script)
: base(executionState, script)
{
ReturnValue = value;
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Linq;
using System.Web.UI.WebControls;
using Adxstudio.Xrm.Commerce;
using Adxstudio.Xrm.Resources;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;
using Site.Controls;
namespace Site.Areas.HelpDesk.Controls
{
public partial class WebFormSupportRequestSelectOrder : WebFormPortalUserControl
{
private const string DefaultPriceListName = "Web";
protected string VisitorID
{
get { return Context.Profile.UserName; }
}
public string PriceListName
{
get
{
var priceListName = DefaultPriceListName;
if (Contact != null)
{
var accountPriceListName = ServiceContext.GetPriceListNameForParentAccount(Contact);
if (string.IsNullOrWhiteSpace(accountPriceListName))
{
var websitePriceListName = ServiceContext.GetDefaultPriceListName(Website);
if (!string.IsNullOrWhiteSpace(websitePriceListName))
{
priceListName = websitePriceListName;
}
}
else
{
priceListName = accountPriceListName;
}
}
return priceListName;
}
}
private Guid _sessionId;
public Guid SessionId
{
get
{
if (!Guid.TryParse(Request["sessionid"], out _sessionId))
{
return Guid.Empty;
}
return _sessionId;
}
}
protected void Page_Init(object sender, EventArgs e)
{
PlanPackageList.ValidationGroup = PlanPackageListRequiredFieldValidator.ValidationGroup = ValidationGroup;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulatePlanPackageList();
}
}
private void PopulatePlanPackageList()
{
PlanPackageList.Items.Clear();
var supportRequest = XrmContext.CreateQuery("adx_supportrequest")
.FirstOrDefault(sr => sr.GetAttributeValue<Guid>("adx_supportrequestid") == CurrentStepEntityID);
if (supportRequest == null)
{
throw new ApplicationException(string.Format("Couldn't find support request record with id equal to {0}.", CurrentStepEntityID));
}
var supportRequestProductReference = supportRequest.GetAttributeValue<EntityReference>("adx_product");
var parentProduct = supportRequestProductReference == null ? null : XrmContext.CreateQuery("product").FirstOrDefault(pp => pp.GetAttributeValue<Guid>("productid") == supportRequestProductReference.Id);
IQueryable<Entity> supportProducts;
if (parentProduct != null)
{
supportProducts = from product in XrmContext.CreateQuery("product")
join supportedset in XrmContext.CreateQuery("adx_supportedproduct_productplan") on product.GetAttributeValue<Guid>("productid") equals supportedset.GetAttributeValue<Guid>("productidone")
join supportedProduct in XrmContext.CreateQuery("product") on supportedset.GetAttributeValue<Guid>("productidtwo") equals supportedProduct.GetAttributeValue<Guid>("productid")
where product.GetAttributeValue<OptionSetValue>("statecode") != null && product.GetAttributeValue<OptionSetValue>("statecode").Value == 0
where product.GetAttributeValue<Guid>("productid") == parentProduct.GetAttributeValue<Guid>("productid")
where supportedProduct.GetAttributeValue<OptionSetValue>("producttypecode") != null && supportedProduct.GetAttributeValue<OptionSetValue>("producttypecode").Value == (int)ProductTypeCode.SupportPlan
select supportedProduct;
}
else
{
supportProducts = XrmContext.CreateQuery("product").Where(p => p.GetAttributeValue<OptionSetValue>("statecode") != null && p.GetAttributeValue<OptionSetValue>("statecode").Value == 0 && p.GetAttributeValue<OptionSetValue>("producttypecode") != null && p.GetAttributeValue<OptionSetValue>("producttypecode").Value == (int)ProductTypeCode.SupportPlan);
}
foreach (var supportProduct in supportProducts)
{
var supportUnit =
XrmContext.CreateQuery("uomschedule").FirstOrDefault(unit => unit.GetAttributeValue<Guid>("uomscheduleid") == (supportProduct.GetAttributeValue<EntityReference>("defaultuomscheduleid") == null ? Guid.Empty : supportProduct.GetAttributeValue<EntityReference>("defaultuomscheduleid").Id));
var baseUom = XrmContext.CreateQuery("uom").FirstOrDefault(baseuom => baseuom.GetAttributeValue<string>("name") == supportUnit.GetAttributeValue<string>("baseuomname"));
var uoms = XrmContext.CreateQuery("uom").Where(uom => uom.GetAttributeValue<Guid>("baseuom") == baseUom.Id);
foreach (var u in uoms)
{
var amount = new Money(0);
var priceListItem = XrmContext.GetPriceListItemByPriceListNameAndUom(supportProduct.GetAttributeValue<Guid>("productid"), u.Id, PriceListName);
if (priceListItem != null)
{
amount = priceListItem.GetAttributeValue<Money>("amount");
}
PlanPackageList.Items.Add(new ListItem(
string.Format("{0} - {1} - {2}", supportProduct.GetAttributeValue<string>("name"), u.GetAttributeValue<string>("name"), amount.Value.ToString("c0")),
string.Format("{0}&{1}", supportProduct.GetAttributeValue<Guid>("productid"), u.GetAttributeValue<Guid>("uomid"))));
}
}
}
protected override void OnSubmit(object sender, Adxstudio.Xrm.Web.UI.WebControls.WebFormSubmitEventArgs e)
{
AddToCart();
base.OnSubmit(sender, e);
}
protected void AddToCart()
{
const string nameFormat = "Case Order for {0}";
var cart = new Entity("adx_shoppingcart");
cart.SetAttributeValue("adx_websiteid", Website.ToEntityReference());
cart.SetAttributeValue("adx_system", true);
if (Contact == null)
{
cart.SetAttributeValue("adx_name", string.Format(nameFormat, VisitorID));
cart.SetAttributeValue("adx_visitorid", VisitorID);
}
else
{
cart.SetAttributeValue("adx_name", string.Format(nameFormat, Contact.GetAttributeValue<string>("fullname")));
cart.SetAttributeValue("adx_contactid", Contact.ToEntityReference());
}
XrmContext.AddObject(cart);
XrmContext.SaveChanges();
// Choose Parent Product
var selectedValue = PlanPackageList.SelectedValue;
var guids = selectedValue.Split('&');
var supportProductId = new Guid(guids[0]);
var uomId = new Guid(guids[1]);
var caseProduct = XrmContext.CreateQuery("product")
.FirstOrDefault(p => p.GetAttributeValue<Guid>("productid") == supportProductId);
var myUom = XrmContext.CreateQuery("uom")
.FirstOrDefault(uom => uom.GetAttributeValue<Guid>("uomid") == uomId);
var productId = caseProduct != null ? caseProduct.Id : Guid.Empty;
cart = XrmContext.CreateQuery("adx_shoppingcart")
.FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_shoppingcartid") == cart.Id);
var myCart = cart == null ? null : new ShoppingCart(cart, XrmContext);
if (myCart == null)
{
throw new ApplicationException("Unable to retrieve the case purchase shopping cart.");
}
myCart.AddProductToCart(productId, myUom, PriceListName);
var total = myCart.GetCartTotal();
if (total < 0)
{
throw new ApplicationException("Case purchase shopping cart cannot have a sub-zero total value.");
}
AddCartToSupportRequest(myCart);
}
private void AddCartToSupportRequest(ShoppingCart myCart)
{
var context = new CrmOrganizationServiceContext(new CrmConnection("Xrm"));
var supportRequest = new Entity("adx_supportrequest") { Id = CurrentStepEntityID };
supportRequest.Attributes["adx_shoppingcartid"] = myCart.Entity.ToEntityReference();
context.Attach(supportRequest);
context.UpdateObject(supportRequest);
context.SaveChanges();
}
}
}
| |
#pragma warning disable
using System.Collections.Generic;
using XPT.Games.Generic.Entities;
using XPT.Games.Generic.Maps;
using XPT.Games.Yserbius;
using XPT.Games.Yserbius.Entities;
namespace XPT.Games.Yserbius.Maps {
class YserMap13 : YsMap {
public override int MapIndex => 13;
protected override int RandomEncounterChance => 10;
protected override int RandomEncounterExtraCount => 0;
public YserMap13() {
MapEvent01 = FnTELEPORT_01;
MapEvent02 = FnPIT_02;
MapEvent03 = FnNPCCHATA_03;
MapEvent04 = FnNPCCHATB_04;
MapEvent05 = FnNPCCHATC_05;
MapEvent06 = FnNPCCHATD_06;
MapEvent07 = FnNPCCHATE_07;
MapEvent08 = FnTELEMESG_08;
MapEvent09 = FnITEMAENC_09;
MapEvent0A = FnITEMBENC_0A;
MapEvent0B = FnITEMCENC_0B;
MapEvent0C = FnITEMDENC_0C;
MapEvent0D = FnSTRMNSTR_0D;
MapEvent0E = FnAVEMNSTR_0E;
MapEvent0F = FnLKPKDORA_0F;
MapEvent10 = FnLKPKDORB_10;
MapEvent11 = FnLKPKDORC_11;
MapEvent12 = FnLKPKDORD_12;
MapEvent13 = FnSTRNDORA_13;
MapEvent14 = FnSTRDOORB_14;
MapEvent15 = FnSTRDOORC_15;
MapEvent16 = FnSTRDOORD_16;
}
// === Strings ================================================
private const string String03FC = "You encounter a Troll Cleric.";
private const string String041A = "I have almost despaired of finding a way out of this prison. Yet there must be an exit of some kind - stairs or teleport. The guards must have had some way of leaving this area.";
private const string String04CC = "To the east are the guard's living quarters and the interrogation rooms. The 36 prison cells are empty now, except for the resident spirits of those who perished here.";
private const string String0574 = "The Troll Cleric bounces her head on the floor in frustration. She must be insane.";
private const string String05C7 = "You encounter an Orc Ranger.";
private const string String05E4 = "I have heard rumors that some few brave souls have escaped the dungeon. If you can find the Rainbow Bridge, you are near the exit.";
private const string String0667 = "The Orc Ranger glares at you and refuses to speak.";
private const string String069A = "You encounter a Halfling Thief.";
private const string String06BA = "A special challenge awaits the brave. If you dare continue after finding what the guard Deldwinn desires, great rewards await you.";
private const string String073D = "Chaos should walk with Chaos and Harmony with Harmony to find the rewards.";
private const string String0788 = "The Halfling Thief thumbs his nose at you and dashes off.";
private const string String07C2 = "You encounter a Gnome Barbarian.";
private const string String07E3 = "Two wizards have crafted a Challenge for the brave. The Wizards' Challenge is on this level, but you cannot reach it from this prison area.";
private const string String086F = "Know that race and Guild must walk together if the Challenge is to be overcome.";
private const string String08BF = "The Gnome Barbarian becomes distracted as he tries to twiddle his thumbs and instead gets them entangled.";
private const string String0929 = "You encounter a Dwarf Wizard.";
private const string String0947 = "King Cleowyn built his palace inside this volcano because he hoped to unearth the secrets of the wizard Arnakkian. Many of the stones that form Cleowyn's palace were taken from the wizard's castle. No wonder this dungeon is cursed.";
private const string String0A2F = "The Dwarf Wizard smiles kindly, but she refuses to speak.";
private const string String0A69 = "There is a teleport in the west wall.";
private const string String0A8F = "Incubi haunt the empty prison cell.";
private const string String0AB3 = "As you reach for a jacket lying on the floor, you see Incubi appear in the cell.";
private const string String0B04 = "Leeches and Black Widows live in the cell.";
private const string String0B2F = "Just out of reach behind a mass of Leeches and Black Widows is a lockpick.";
private const string String0B7A = "Hell Wolves appear in the cell.";
private const string String0B9A = "A circle of Hell Wolves surrounds you and a mace lying on the floor.";
private const string String0BDF = "Phantasms creep into the empty cell.";
private const string String0C04 = "Spirits of the dead guard their precious treasure.";
private const string String0C37 = "Your skill at picking locks soon has the door open.";
private const string String0C6B = "The door is locked.";
private const string String0C7F = "The lock of the door clicks open.";
private const string String0CA1 = "The door is locked.";
private const string String0CB5 = "You successfully pick the lock of the door.";
private const string String0CE1 = "The door is locked.";
private const string String0CF5 = "The lock of the door is quickly opened by your skillfulness.";
private const string String0D32 = "The door is locked.";
private const string String0D46 = "You manage to force the door open.";
private const string String0D69 = "The door is stuck shut.";
private const string String0D81 = "The door flies open as you smash against it.";
private const string String0DAE = "The door is stuck and will not open.";
private const string String0DD3 = "You push hard on the door and it creaks open.";
private const string String0E01 = "The door refuses to open. It is stuck.";
private const string String0E28 = "You manage to open the door by brute strength.";
private const string String0E57 = "You are not strong enough to force the door open.";
// === Functions ================================================
private void FnTELEPORT_01(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: TeleportParty(player, 0x01, 0x06, 0xDC, 0x02, type);
L001E: return; // RETURN;
}
private void FnPIT_02(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: SetFloorItem(player, 0x01, GetCurrentTile(player));
L0018: TeleportParty(player, 0x04, 0x01, 0xE0, 0x02, type);
L0033: return; // RETURN;
}
private void FnNPCCHATA_03(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String03FC); // You encounter a Troll Cleric.
L0010: ShowPortrait(player, 0x0028);
L001D: Compare(GetRandom(0x000F), 0x000C);
L002D: if (JumpAbove) goto L004B;
L002F: ShowMessage(player, doMsgs, String041A); // I have almost despaired of finding a way out of this prison. Yet there must be an exit of some kind - stairs or teleport. The guards must have had some way of leaving this area.
L003C: ShowMessage(player, doMsgs, String04CC); // To the east are the guard's living quarters and the interrogation rooms. The 36 prison cells are empty now, except for the resident spirits of those who perished here.
L0049: goto L0058;
L004B: ShowMessage(player, doMsgs, String0574); // The Troll Cleric bounces her head on the floor in frustration. She must be insane.
L0058: return; // RETURN;
}
private void FnNPCCHATB_04(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String05C7); // You encounter an Orc Ranger.
L0010: ShowPortrait(player, 0x001E);
L001D: Compare(GetRandom(0x000F), 0x0006);
L002D: if (JumpAbove) goto L003E;
L002F: ShowMessage(player, doMsgs, String05E4); // I have heard rumors that some few brave souls have escaped the dungeon. If you can find the Rainbow Bridge, you are near the exit.
L003C: goto L004B;
L003E: ShowMessage(player, doMsgs, String0667); // The Orc Ranger glares at you and refuses to speak.
L004B: return; // RETURN;
}
private void FnNPCCHATC_05(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String069A); // You encounter a Halfling Thief.
L0010: ShowPortrait(player, 0x0025);
L001D: Compare(GetRandom(0x000F), 0x000A);
L002D: if (JumpAbove) goto L004B;
L002F: ShowMessage(player, doMsgs, String06BA); // A special challenge awaits the brave. If you dare continue after finding what the guard Deldwinn desires, great rewards await you.
L003C: ShowMessage(player, doMsgs, String073D); // Chaos should walk with Chaos and Harmony with Harmony to find the rewards.
L0049: goto L0058;
L004B: ShowMessage(player, doMsgs, String0788); // The Halfling Thief thumbs his nose at you and dashes off.
L0058: return; // RETURN;
}
private void FnNPCCHATD_06(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String07C2); // You encounter a Gnome Barbarian.
L0010: ShowPortrait(player, 0x0019);
L001D: Compare(GetRandom(0x000F), 0x000B);
L002D: if (JumpAbove) goto L004B;
L002F: ShowMessage(player, doMsgs, String07E3); // Two wizards have crafted a Challenge for the brave. The Wizards' Challenge is on this level, but you cannot reach it from this prison area.
L003C: ShowMessage(player, doMsgs, String086F); // Know that race and Guild must walk together if the Challenge is to be overcome.
L0049: goto L0058;
L004B: ShowMessage(player, doMsgs, String08BF); // The Gnome Barbarian becomes distracted as he tries to twiddle his thumbs and instead gets them entangled.
L0058: return; // RETURN;
}
private void FnNPCCHATE_07(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String0929); // You encounter a Dwarf Wizard.
L0010: ShowPortrait(player, 0x002C);
L001D: Compare(GetRandom(0x000F), 0x000C);
L002D: if (JumpAbove) goto L003E;
L002F: ShowMessage(player, doMsgs, String0947); // King Cleowyn built his palace inside this volcano because he hoped to unearth the secrets of the wizard Arnakkian. Many of the stones that form Cleowyn's palace were taken from the wizard's castle. No wonder this dungeon is cursed.
L003C: goto L004B;
L003E: ShowMessage(player, doMsgs, String0A2F); // The Dwarf Wizard smiles kindly, but she refuses to speak.
L004B: return; // RETURN;
}
private void FnTELEMESG_08(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String0A69); // There is a teleport in the west wall.
L0010: return; // RETURN;
}
private void FnITEMAENC_09(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ax = HasItem(player, 0x77);
L0011: if (JumpEqual) goto L0041;
L0013: AddTreasure(player, 0x01F4, 0x00, 0x00, 0x00, 0x00, 0xCE);
L0032: ShowMessage(player, doMsgs, String0A8F); // Incubi haunt the empty prison cell.
L003F: goto L006D;
L0041: AddTreasure(player, 0x05DC, 0x00, 0x00, 0x00, 0x00, 0x77);
L0060: ShowMessage(player, doMsgs, String0AB3); // As you reach for a jacket lying on the floor, you see Incubi appear in the cell.
L006D: Compare(PartyCount(player), 0x0001);
L0078: if (JumpNotEqual) goto L00A1;
L007A: AddEncounter(player, 0x01, 0x25);
L008C: AddEncounter(player, 0x02, 0x25);
L009E: goto L0152;
L00A1: Compare(PartyCount(player), 0x0002);
L00AC: if (JumpNotEqual) goto L00E6;
L00AE: AddEncounter(player, 0x01, 0x25);
L00C0: AddEncounter(player, 0x02, 0x25);
L00D2: AddEncounter(player, 0x03, 0x26);
L00E4: goto L0152;
L00E6: AddEncounter(player, 0x01, 0x21);
L00F8: AddEncounter(player, 0x02, 0x21);
L010A: AddEncounter(player, 0x03, 0x26);
L011C: AddEncounter(player, 0x04, 0x26);
L012E: AddEncounter(player, 0x05, 0x25);
L0140: AddEncounter(player, 0x06, 0x25);
L0152: return; // RETURN;
}
private void FnITEMBENC_0A(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ax = HasItem(player, 0xC1);
L0011: if (JumpEqual) goto L0041;
L0013: AddTreasure(player, 0x00FA, 0x00, 0x00, 0x00, 0x00, 0xB6);
L0032: ShowMessage(player, doMsgs, String0B04); // Leeches and Black Widows live in the cell.
L003F: goto L006D;
L0041: AddTreasure(player, 0x03E8, 0x00, 0x00, 0x00, 0x00, 0xC1);
L0060: ShowMessage(player, doMsgs, String0B2F); // Just out of reach behind a mass of Leeches and Black Widows is a lockpick.
L006D: Compare(PartyCount(player), 0x0001);
L0078: if (JumpNotEqual) goto L00A1;
L007A: AddEncounter(player, 0x01, 0x19);
L008C: AddEncounter(player, 0x02, 0x1B);
L009E: goto L0171;
L00A1: Compare(PartyCount(player), 0x0002);
L00AC: if (JumpEqual) goto L00BB;
L00AE: Compare(PartyCount(player), 0x0003);
L00B9: if (JumpNotEqual) goto L0105;
L00BB: AddEncounter(player, 0x01, 0x19);
L00CD: AddEncounter(player, 0x02, 0x1B);
L00DF: AddEncounter(player, 0x03, 0x1B);
L00F1: AddEncounter(player, 0x04, 0x19);
L0103: goto L0171;
L0105: AddEncounter(player, 0x01, 0x1B);
L0117: AddEncounter(player, 0x02, 0x1B);
L0129: AddEncounter(player, 0x03, 0x1C);
L013B: AddEncounter(player, 0x04, 0x1C);
L014D: AddEncounter(player, 0x05, 0x1B);
L015F: AddEncounter(player, 0x06, 0x1B);
L0171: return; // RETURN;
}
private void FnITEMCENC_0B(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ax = HasItem(player, 0x20);
L0011: if (JumpEqual) goto L0041;
L0013: AddTreasure(player, 0x012C, 0x00, 0x00, 0x00, 0x00, 0xCC);
L0032: ShowMessage(player, doMsgs, String0B7A); // Hell Wolves appear in the cell.
L003F: goto L006E;
L0041: AddTreasure(player, 0x03E8, 0x00, 0x00, 0x00, 0xCF, 0x20);
L0061: ShowMessage(player, doMsgs, String0B9A); // A circle of Hell Wolves surrounds you and a mace lying on the floor.
L006E: Compare(PartyCount(player), 0x0001);
L0079: if (JumpNotEqual) goto L00A2;
L007B: AddEncounter(player, 0x01, 0x21);
L008D: AddEncounter(player, 0x02, 0x21);
L009F: goto L0171;
L00A2: Compare(PartyCount(player), 0x0002);
L00AD: if (JumpEqual) goto L00BB;
L00AF: RefreshCompareFlags(PartyCount(player));
L00B9: if (JumpEqual) goto L0105;
L00BB: AddEncounter(player, 0x01, 0x21);
L00CD: AddEncounter(player, 0x02, 0x22);
L00DF: AddEncounter(player, 0x03, 0x22);
L00F1: AddEncounter(player, 0x04, 0x21);
L0103: goto L0171;
L0105: AddEncounter(player, 0x01, 0x22);
L0117: AddEncounter(player, 0x02, 0x22);
L0129: AddEncounter(player, 0x03, 0x22);
L013B: AddEncounter(player, 0x04, 0x22);
L014D: AddEncounter(player, 0x05, 0x22);
L015F: AddEncounter(player, 0x06, 0x22);
L0171: return; // RETURN;
}
private void FnITEMDENC_0C(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ax = HasItem(player, 0x54);
L0011: if (JumpEqual) goto L0041;
L0013: AddTreasure(player, 0x012C, 0x00, 0x00, 0x00, 0x00, 0xB6);
L0032: ShowMessage(player, doMsgs, String0BDF); // Phantasms creep into the empty cell.
L003F: goto L006D;
L0041: AddTreasure(player, 0x07D0, 0x00, 0x00, 0x00, 0x00, 0x54);
L0060: ShowMessage(player, doMsgs, String0C04); // Spirits of the dead guard their precious treasure.
L006D: Compare(PartyCount(player), 0x0001);
L0078: if (JumpEqual) goto L0087;
L007A: Compare(PartyCount(player), 0x0002);
L0085: if (JumpNotEqual) goto L00AE;
L0087: AddEncounter(player, 0x01, 0x27);
L0099: AddEncounter(player, 0x02, 0x28);
L00AB: goto L0171;
L00AE: Compare(PartyCount(player), 0x0003);
L00B9: if (JumpNotEqual) goto L0105;
L00BB: AddEncounter(player, 0x01, 0x27);
L00CD: AddEncounter(player, 0x02, 0x28);
L00DF: AddEncounter(player, 0x03, 0x27);
L00F1: AddEncounter(player, 0x04, 0x28);
L0103: goto L0171;
L0105: AddEncounter(player, 0x01, 0x27);
L0117: AddEncounter(player, 0x02, 0x27);
L0129: AddEncounter(player, 0x03, 0x27);
L013B: AddEncounter(player, 0x04, 0x27);
L014D: AddEncounter(player, 0x05, 0x28);
L015F: AddEncounter(player, 0x06, 0x28);
L0171: return; // RETURN;
}
private void FnSTRMNSTR_0D(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: Compare(PartyCount(player), 0x0001);
L000E: if (JumpEqual) goto L001D;
L0010: Compare(PartyCount(player), 0x0002);
L001B: if (JumpNotEqual) goto L0056;
L001D: AddEncounter(player, 0x01, 0x1F);
L002F: AddEncounter(player, 0x02, 0x1F);
L0041: AddEncounter(player, 0x03, 0x1D);
L0053: goto L012B;
L0056: Compare(PartyCount(player), 0x0003);
L0061: if (JumpNotEqual) goto L00BF;
L0063: AddEncounter(player, 0x01, 0x1E);
L0075: AddEncounter(player, 0x02, 0x1D);
L0087: AddEncounter(player, 0x03, 0x1D);
L0099: AddEncounter(player, 0x04, 0x1E);
L00AB: AddEncounter(player, 0x05, 0x20);
L00BD: goto L012B;
L00BF: AddEncounter(player, 0x01, 0x1F);
L00D1: AddEncounter(player, 0x02, 0x1F);
L00E3: AddEncounter(player, 0x03, 0x20);
L00F5: AddEncounter(player, 0x04, 0x20);
L0107: AddEncounter(player, 0x05, 0x1E);
L0119: AddEncounter(player, 0x06, 0x1E);
L012B: return; // RETURN;
}
private void FnAVEMNSTR_0E(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: Compare(PartyCount(player), 0x0001);
L000E: if (JumpNotEqual) goto L0037;
L0010: AddEncounter(player, 0x01, 0x1A);
L0022: AddEncounter(player, 0x02, 0x1B);
L0034: goto L0176;
L0037: Compare(PartyCount(player), 0x0002);
L0042: if (JumpNotEqual) goto L008F;
L0044: AddEncounter(player, 0x01, 0x1B);
L0056: AddEncounter(player, 0x02, 0x1B);
L0068: AddEncounter(player, 0x03, 0x19);
L007A: AddEncounter(player, 0x04, 0x19);
L008C: goto L0176;
L008F: Compare(PartyCount(player), 0x0003);
L009A: if (JumpNotEqual) goto L010A;
L009C: AddEncounter(player, 0x01, 0x1B);
L00AE: AddEncounter(player, 0x02, 0x1B);
L00C0: AddEncounter(player, 0x03, 0x1B);
L00D2: AddEncounter(player, 0x04, 0x1B);
L00E4: AddEncounter(player, 0x05, 0x1A);
L00F6: AddEncounter(player, 0x06, 0x1A);
L0108: goto L0176;
L010A: AddEncounter(player, 0x01, 0x1C);
L011C: AddEncounter(player, 0x02, 0x1C);
L012E: AddEncounter(player, 0x03, 0x1A);
L0140: AddEncounter(player, 0x04, 0x1A);
L0152: AddEncounter(player, 0x05, 0x1C);
L0164: AddEncounter(player, 0x06, 0x1C);
L0176: return; // RETURN;
}
private void FnLKPKDORA_0F(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ax = HasUsedItem(player, type, ref doMsgs, 0xBF, 0xC4);
L0016: if (JumpNotEqual) goto L0029;
L0018: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0E), 0x0002);
L0027: if (JumpBelow) goto L0074;
L0029: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01);
L0047: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player));
L0065: ShowMessage(player, doMsgs, String0C37); // Your skill at picking locks soon has the door open.
L0072: goto L009E;
L0074: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00);
L0091: ShowMessage(player, doMsgs, String0C6B); // The door is locked.
L009E: return; // RETURN;
}
private void FnLKPKDORB_10(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ax = HasUsedItem(player, type, ref doMsgs, 0xC0, 0xC4);
L0016: if (JumpNotEqual) goto L0029;
L0018: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0E), 0x0004);
L0027: if (JumpBelow) goto L0074;
L0029: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01);
L0047: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player));
L0065: ShowMessage(player, doMsgs, String0C7F); // The lock of the door clicks open.
L0072: goto L009E;
L0074: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00);
L0091: ShowMessage(player, doMsgs, String0CA1); // The door is locked.
L009E: return; // RETURN;
}
private void FnLKPKDORC_11(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ax = HasUsedItem(player, type, ref doMsgs, 0xC2, 0xC4);
L0016: if (JumpNotEqual) goto L0029;
L0018: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0E), 0x0007);
L0027: if (JumpBelow) goto L0074;
L0029: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01);
L0047: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player));
L0065: ShowMessage(player, doMsgs, String0CB5); // You successfully pick the lock of the door.
L0072: goto L009E;
L0074: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00);
L0091: ShowMessage(player, doMsgs, String0CE1); // The door is locked.
L009E: return; // RETURN;
}
private void FnLKPKDORD_12(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ax = HasUsedItem(player, type, ref doMsgs, 0xC3, 0xC4);
L0016: if (JumpNotEqual) goto L0029;
L0018: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0E), 0x0009);
L0027: if (JumpBelow) goto L0074;
L0029: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01);
L0047: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player));
L0065: ShowMessage(player, doMsgs, String0CF5); // The lock of the door is quickly opened by your skillfulness.
L0072: goto L009E;
L0074: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00);
L0091: ShowMessage(player, doMsgs, String0D32); // The door is locked.
L009E: return; // RETURN;
}
private void FnSTRNDORA_13(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: Compare(CheckStrength(player), 0x000C);
L0012: if (JumpBelow) goto L005F;
L0014: ShowMessage(player, doMsgs, String0D46); // You manage to force the door open.
L0021: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01);
L003F: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player));
L005D: goto L0089;
L005F: ShowMessage(player, doMsgs, String0D69); // The door is stuck shut.
L006C: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00);
L0089: return; // RETURN;
}
private void FnSTRDOORB_14(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: Compare(CheckStrength(player), 0x000F);
L0012: if (JumpBelow) goto L005F;
L0014: ShowMessage(player, doMsgs, String0D81); // The door flies open as you smash against it.
L0021: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player));
L003F: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01);
L005D: goto L0089;
L005F: ShowMessage(player, doMsgs, String0DAE); // The door is stuck and will not open.
L006C: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00);
L0089: return; // RETURN;
}
private void FnSTRDOORC_15(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: Compare(CheckStrength(player), 0x0011);
L0012: if (JumpBelow) goto L005F;
L0014: ShowMessage(player, doMsgs, String0DD3); // You push hard on the door and it creaks open.
L0021: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player));
L003F: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01);
L005D: goto L0089;
L005F: ShowMessage(player, doMsgs, String0E01); // The door refuses to open. It is stuck.
L006C: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00);
L0089: return; // RETURN;
}
private void FnSTRDOORD_16(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: Compare(CheckStrength(player), 0x0014);
L0012: if (JumpBelow) goto L005F;
L0014: ShowMessage(player, doMsgs, String0E28); // You manage to open the door by brute strength.
L0021: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player));
L003F: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01);
L005D: goto L0089;
L005F: ShowMessage(player, doMsgs, String0E57); // You are not strong enough to force the door open.
L006C: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00);
L0089: return; // RETURN;
}
}
}
| |
// 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.Configuration;
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using Legacy.Support;
using Xunit;
using ThreadState = System.Threading.ThreadState;
namespace System.IO.Ports.Tests
{
public class SerialStream_Write_byte_int_int_Generic : PortsTest
{
// Set bounds fore random timeout values.
// If the min is to low write will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
// If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
// If the percentage difference between the expected timeout and the actual timeout
// found through Stopwatch is greater then 10% then the timeout value was not correctly
// to the write method and the testcase fails.
private const double maxPercentageDifference = .15;
// The byte size used when veryifying exceptions that write will throw
private const int BYTE_SIZE_EXCEPTION = 4;
// The byte size used when veryifying timeout
private static readonly int s_BYTE_SIZE_TIMEOUT = TCSupport.MinimumBlockingByteCount;
// The byte size used when veryifying BytesToWrite
private static readonly int s_BYTE_SIZE_BYTES_TO_WRITE = TCSupport.MinimumBlockingByteCount;
// The bytes size used when veryifying Handshake
private static readonly int s_BYTE_SIZE_HANDSHAKE = TCSupport.MinimumBlockingByteCount;
private const int NUM_TRYS = 5;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to Cloes()");
com.Open();
Stream serialStream = com.BaseStream;
com.Close();
VerifyWriteException(serialStream, typeof(ObjectDisposedException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterBaseStreamClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to BaseStream.Close()");
com.Open();
Stream serialStream = com.BaseStream;
com.BaseStream.Close();
VerifyWriteException(serialStream, typeof(ObjectDisposedException));
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Timeout()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
var XOffBuffer = new byte[1];
XOffBuffer[0] = 19;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.XOnXOff;
Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout);
com1.Open();
com2.Open();
com2.BaseStream.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
com2.Close();
VerifyTimeout(com1);
}
}
[OuterLoop("Slow Test")]
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void SuccessiveWriteTimeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
var rndGen = new Random(-55);
com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com.Handshake = Handshake.RequestToSendXOnXOff;
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout);
com.Open();
try
{
com.BaseStream.Write(new byte[s_BYTE_SIZE_TIMEOUT], 0, s_BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void SuccessiveWriteTimeoutWithWriteSucceeding()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
var rndGen = new Random(-55);
var asyncEnableRts = new AsyncEnableRts();
var t = new Thread(asyncEnableRts.EnableRTS);
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.RequestToSend;
com1.Encoding = new UTF8Encoding();
Debug.WriteLine(
"Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before it's timeout",
com1.WriteTimeout);
com1.Open();
// Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed
// before the timeout is reached
t.Start();
var waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
// Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
try
{
com1.BaseStream.Write(new byte[s_BYTE_SIZE_TIMEOUT], 0, s_BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
asyncEnableRts.Stop();
while (t.IsAlive)
Thread.Sleep(100);
VerifyTimeout(com1);
}
}
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void BytesToWrite()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
var asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, s_BYTE_SIZE_BYTES_TO_WRITE);
var t = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
Debug.WriteLine("Verifying BytesToWrite with one call to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 500;
// Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t.Start();
var waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
// Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForWriteBufferToLoad(com, s_BYTE_SIZE_BYTES_TO_WRITE);
// Wait for write method to timeout
while (t.IsAlive)
Thread.Sleep(100);
}
}
[OuterLoop("Slow Test")]
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void BytesToWriteSuccessive()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
var asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, s_BYTE_SIZE_BYTES_TO_WRITE);
var t1 = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
var t2 = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
Debug.WriteLine("Verifying BytesToWrite with successive calls to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 4000;
// Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t1.Start();
var waitTime = 0;
while (t1.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
// Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForExactWriteBufferLoad(com, s_BYTE_SIZE_BYTES_TO_WRITE);
// Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t2.Start();
waitTime = 0;
while (t2.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
// Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForExactWriteBufferLoad(com, s_BYTE_SIZE_BYTES_TO_WRITE * 2);
// Wait for both write methods to timeout
while (t1.IsAlive || t2.IsAlive)
Thread.Sleep(100);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Handshake_None()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
var asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, s_BYTE_SIZE_HANDSHAKE);
var t = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
// Write a random byte[] asynchronously so we can verify some things while the write call is blocking
Debug.WriteLine("Verifying Handshake=None");
com.Open();
t.Start();
var waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
// Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
// Wait for write method to timeout
while (t.IsAlive)
Thread.Sleep(100);
Assert.Equal(0, com.BytesToWrite);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSend()
{
Verify_Handshake(Handshake.RequestToSend);
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff()
{
Verify_Handshake(Handshake.XOnXOff);
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSendXOnXOff()
{
Verify_Handshake(Handshake.RequestToSendXOnXOff);
}
private class AsyncEnableRts
{
private bool _stop;
public void EnableRTS()
{
lock (this)
{
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
// Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.RtsEnable = true;
while (!_stop)
Monitor.Wait(this);
com2.RtsEnable = false;
}
}
}
public void Stop()
{
lock (this)
{
_stop = true;
Monitor.Pulse(this);
}
}
}
private class AsyncWriteRndByteArray
{
private readonly SerialPort _com;
private readonly int _byteLength;
public AsyncWriteRndByteArray(SerialPort com, int byteLength)
{
_com = com;
_byteLength = byteLength;
}
public void WriteRndByteArray()
{
var buffer = new byte[_byteLength];
var rndGen = new Random(-55);
for (var i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)rndGen.Next(0, 256);
}
try
{
_com.BaseStream.Write(buffer, 0, buffer.Length);
}
catch (TimeoutException)
{
}
}
}
#endregion
#region Verification for Test Cases
private static void VerifyWriteException(Stream serialStream, Type expectedException)
{
Assert.Throws(expectedException,
() => serialStream.Write(new byte[BYTE_SIZE_EXCEPTION], 0, BYTE_SIZE_EXCEPTION));
}
private void VerifyTimeout(SerialPort com)
{
var timer = new Stopwatch();
int expectedTime = com.WriteTimeout;
var actualTime = 0;
try
{
com.BaseStream.Write(new byte[s_BYTE_SIZE_TIMEOUT], 0, s_BYTE_SIZE_TIMEOUT); // Warm up write method
}
catch (TimeoutException)
{
}
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (var i = 0; i < NUM_TRYS; i++)
{
timer.Start();
try
{
com.BaseStream.Write(new byte[s_BYTE_SIZE_TIMEOUT], 0, s_BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
double percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
// Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime,
expectedTime, percentageDifference);
}
}
private void Verify_Handshake(Handshake handshake)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1, s_BYTE_SIZE_HANDSHAKE);
var t = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
var XOffBuffer = new byte[1];
var XOnBuffer = new byte[1];
int waitTime;
XOffBuffer[0] = 19;
XOnBuffer[0] = 17;
Debug.WriteLine("Verifying Handshake={0}", handshake);
com1.Handshake = handshake;
com1.Open();
com2.Open();
// Setup to ensure write will bock with type of handshake method being used
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = false;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.BaseStream.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
}
// Write a random byte asynchronously so we can verify some things while the write call is blocking
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
// Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForWriteBufferToLoad(com1, s_BYTE_SIZE_HANDSHAKE);
// Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) &&
com1.CtsHolding)
{
Fail("ERROR!!! Expected CtsHolding={0} actual {1}", false, com1.CtsHolding);
}
// Setup to ensure write will succeed
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = true;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.BaseStream.Write(XOnBuffer, 0, 1);
}
// Wait till write finishes
while (t.IsAlive)
Thread.Sleep(100);
// Verify that the correct number of bytes are in the buffer
Assert.Equal(0, com1.BytesToWrite);
// Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) &&
!com1.CtsHolding)
{
Fail("ERROR!!! Expected CtsHolding={0} actual {1}", true, com1.CtsHolding);
}
}
#endregion
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using static System.Buffers.Binary.BinaryPrimitives;
namespace System
{
public static class TestHelpers
{
public static void Validate<T>(this Span<T> span, params T[] expected) where T : struct, IEquatable<T>
{
Assert.True(span.SequenceEqual(expected));
}
public static void ValidateReferenceType<T>(this Span<T> span, params T[] expected)
{
Assert.Equal(span.Length, expected.Length);
for (int i = 0; i < expected.Length; i++)
{
T actual = span[i];
Assert.Same(expected[i], actual);
}
T ignore;
AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]);
}
public delegate void AssertThrowsAction<T>(Span<T> span);
// Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along.
public static void AssertThrows<E, T>(Span<T> span, AssertThrowsAction<T> action) where E : Exception
{
try
{
action(span);
Assert.False(true, "Expected exception: " + typeof(E).GetType());
}
catch (E)
{
}
catch (Exception wrongException)
{
Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType());
}
}
//
// The innocent looking construct:
//
// Assert.Throws<E>( () => new Span() );
//
// generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on
// runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...)
//
// The workaround is to code it like this:
//
// Assert.Throws<E>( () => new Span().DontBox() );
//
// which turns the lambda return type back to "void" and eliminates the troublesome box instruction.
//
public static void DontBox<T>(this Span<T> span)
{
// This space intentionally left blank.
}
public static void Validate<T>(this ReadOnlySpan<T> span, params T[] expected) where T : struct, IEquatable<T>
{
Assert.True(span.SequenceEqual(expected));
}
public static void ValidateReferenceType<T>(this ReadOnlySpan<T> span, params T[] expected)
{
Assert.Equal(span.Length, expected.Length);
for (int i = 0; i < expected.Length; i++)
{
T actual = span[i];
Assert.Same(expected[i], actual);
}
T ignore;
AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]);
}
public delegate void AssertThrowsActionReadOnly<T>(ReadOnlySpan<T> span);
// Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along.
public static void AssertThrows<E, T>(ReadOnlySpan<T> span, AssertThrowsActionReadOnly<T> action) where E : Exception
{
try
{
action(span);
Assert.False(true, "Expected exception: " + typeof(E).GetType());
}
catch (E)
{
}
catch (Exception wrongException)
{
Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType());
}
}
//
// The innocent looking construct:
//
// Assert.Throws<E>( () => new Span() );
//
// generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on
// runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...)
//
// The workaround is to code it like this:
//
// Assert.Throws<E>( () => new Span().DontBox() );
//
// which turns the lambda return type back to "void" and eliminates the troublesome box instruction.
//
public static void DontBox<T>(this ReadOnlySpan<T> span)
{
// This space intentionally left blank.
}
public static void Validate<T>(this Memory<T> memory, params T[] expected) where T : struct, IEquatable<T>
{
Assert.True(memory.Span.SequenceEqual(expected));
}
public static void ValidateReferenceType<T>(this Memory<T> memory, params T[] expected)
{
T[] bufferArray = memory.ToArray();
Assert.Equal(memory.Length, expected.Length);
for (int i = 0; i < expected.Length; i++)
{
T actual = bufferArray[i];
Assert.Same(expected[i], actual);
}
}
public static void Validate<T>(this ReadOnlyMemory<T> memory, params T[] expected) where T : struct, IEquatable<T>
{
Assert.True(memory.Span.SequenceEqual(expected));
}
public static void ValidateReferenceType<T>(this ReadOnlyMemory<T> memory, params T[] expected)
{
T[] bufferArray = memory.ToArray();
Assert.Equal(memory.Length, expected.Length);
for (int i = 0; i < expected.Length; i++)
{
T actual = bufferArray[i];
Assert.Same(expected[i], actual);
}
}
public static void Validate<T>(Span<byte> span, T value) where T : struct
{
T read = ReadMachineEndian<T>(span);
Assert.Equal(value, read);
span.Clear();
}
public static TestStructExplicit s_testExplicitStruct = new TestStructExplicit
{
S0 = short.MaxValue,
I0 = int.MaxValue,
L0 = long.MaxValue,
US0 = ushort.MaxValue,
UI0 = uint.MaxValue,
UL0 = ulong.MaxValue,
S1 = short.MinValue,
I1 = int.MinValue,
L1 = long.MinValue,
US1 = ushort.MinValue,
UI1 = uint.MinValue,
UL1 = ulong.MinValue
};
public static Span<byte> GetSpanBE()
{
Span<byte> spanBE = new byte[Unsafe.SizeOf<TestStructExplicit>()];
WriteInt16BigEndian(spanBE, s_testExplicitStruct.S0);
WriteInt32BigEndian(spanBE.Slice(2), s_testExplicitStruct.I0);
WriteInt64BigEndian(spanBE.Slice(6), s_testExplicitStruct.L0);
WriteUInt16BigEndian(spanBE.Slice(14), s_testExplicitStruct.US0);
WriteUInt32BigEndian(spanBE.Slice(16), s_testExplicitStruct.UI0);
WriteUInt64BigEndian(spanBE.Slice(20), s_testExplicitStruct.UL0);
WriteInt16BigEndian(spanBE.Slice(28), s_testExplicitStruct.S1);
WriteInt32BigEndian(spanBE.Slice(30), s_testExplicitStruct.I1);
WriteInt64BigEndian(spanBE.Slice(34), s_testExplicitStruct.L1);
WriteUInt16BigEndian(spanBE.Slice(42), s_testExplicitStruct.US1);
WriteUInt32BigEndian(spanBE.Slice(44), s_testExplicitStruct.UI1);
WriteUInt64BigEndian(spanBE.Slice(48), s_testExplicitStruct.UL1);
Assert.Equal(56, spanBE.Length);
return spanBE;
}
public static Span<byte> GetSpanLE()
{
Span<byte> spanLE = new byte[Unsafe.SizeOf<TestStructExplicit>()];
WriteInt16LittleEndian(spanLE, s_testExplicitStruct.S0);
WriteInt32LittleEndian(spanLE.Slice(2), s_testExplicitStruct.I0);
WriteInt64LittleEndian(spanLE.Slice(6), s_testExplicitStruct.L0);
WriteUInt16LittleEndian(spanLE.Slice(14), s_testExplicitStruct.US0);
WriteUInt32LittleEndian(spanLE.Slice(16), s_testExplicitStruct.UI0);
WriteUInt64LittleEndian(spanLE.Slice(20), s_testExplicitStruct.UL0);
WriteInt16LittleEndian(spanLE.Slice(28), s_testExplicitStruct.S1);
WriteInt32LittleEndian(spanLE.Slice(30), s_testExplicitStruct.I1);
WriteInt64LittleEndian(spanLE.Slice(34), s_testExplicitStruct.L1);
WriteUInt16LittleEndian(spanLE.Slice(42), s_testExplicitStruct.US1);
WriteUInt32LittleEndian(spanLE.Slice(44), s_testExplicitStruct.UI1);
WriteUInt64LittleEndian(spanLE.Slice(48), s_testExplicitStruct.UL1);
Assert.Equal(56, spanLE.Length);
return spanLE;
}
[StructLayout(LayoutKind.Explicit)]
public struct TestStructExplicit
{
[FieldOffset(0)]
public short S0;
[FieldOffset(2)]
public int I0;
[FieldOffset(6)]
public long L0;
[FieldOffset(14)]
public ushort US0;
[FieldOffset(16)]
public uint UI0;
[FieldOffset(20)]
public ulong UL0;
[FieldOffset(28)]
public short S1;
[FieldOffset(30)]
public int I1;
[FieldOffset(34)]
public long L1;
[FieldOffset(42)]
public ushort US1;
[FieldOffset(44)]
public uint UI1;
[FieldOffset(48)]
public ulong UL1;
}
[StructLayout(LayoutKind.Sequential)]
public sealed class TestClass
{
private double _d;
public char C0;
public char C1;
public char C2;
public char C3;
public char C4;
}
[StructLayout(LayoutKind.Sequential)]
public struct TestValueTypeWithReference
{
public int I;
public string S;
}
public enum TestEnum
{
e0,
e1,
e2,
e3,
e4,
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void DoNotIgnore<T>(T value, int consumed)
{
}
}
}
| |
//
// https://github.com/mythz/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2010 Liquidbit Ltd.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace NServiceKit.Redis.Generic
{
internal class RedisClientList<T>
: IRedisList<T>
{
private readonly RedisTypedClient<T> client;
private readonly string listId;
private const int PageLimit = 1000;
public RedisClientList(RedisTypedClient<T> client, string listId)
{
this.listId = listId;
this.client = client;
}
public string Id
{
get { return listId; }
}
public IEnumerator<T> GetEnumerator()
{
return this.Count <= PageLimit
? client.GetAllItemsFromList(this).GetEnumerator()
: GetPagingEnumerator();
}
public IEnumerator<T> GetPagingEnumerator()
{
var skip = 0;
List<T> pageResults;
do
{
pageResults = client.GetRangeFromList(this, skip, PageLimit);
foreach (var result in pageResults)
{
yield return result;
}
skip += PageLimit;
} while (pageResults.Count == PageLimit);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(T item)
{
client.AddItemToList(this, item);
}
public void Clear()
{
client.RemoveAllFromList(this);
}
public bool Contains(T item)
{
//TODO: replace with native implementation when exists
foreach (var existingItem in this)
{
if (Equals(existingItem, item)) return true;
}
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
var allItemsInList = client.GetAllItemsFromList(this);
allItemsInList.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
return client.RemoveItemFromList(this, item) > 0;
}
public int Count
{
get
{
return client.GetListCount(this);
}
}
public bool IsReadOnly { get { return false; } }
public int IndexOf(T item)
{
//TODO: replace with native implementation when exists
var i = 0;
foreach (var existingItem in this)
{
if (Equals(existingItem, item)) return i;
i++;
}
return -1;
}
public void Insert(int index, T item)
{
//TODO: replace with implementation involving creating on new temp list then replacing
//otherwise wait for native implementation
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
//TODO: replace with native implementation when one exists
var markForDelete = Guid.NewGuid().ToString();
client.NativeClient.LSet(listId, index, Encoding.UTF8.GetBytes(markForDelete));
const int removeAll = 0;
client.NativeClient.LRem(listId, removeAll, Encoding.UTF8.GetBytes(markForDelete));
}
public T this[int index]
{
get { return client.GetItemFromList(this, index); }
set { client.SetItemInList(this, index, value); }
}
public List<T> GetAll()
{
return client.GetAllItemsFromList(this);
}
public List<T> GetRange(int startingFrom, int endingAt)
{
return client.GetRangeFromList(this, startingFrom, endingAt);
}
public List<T> GetRangeFromSortedList(int startingFrom, int endingAt)
{
return client.SortList(this, startingFrom, endingAt);
}
public void RemoveAll()
{
client.RemoveAllFromList(this);
}
public void Trim(int keepStartingFrom, int keepEndingAt)
{
client.TrimList(this, keepStartingFrom, keepEndingAt);
}
public int RemoveValue(T value)
{
return client.RemoveItemFromList(this, value);
}
public int RemoveValue(T value, int noOfMatches)
{
return client.RemoveItemFromList(this, value, noOfMatches);
}
public void Append(T value)
{
Add(value);
}
public void Prepend(T value)
{
client.PrependItemToList(this, value);
}
public T RemoveStart()
{
return client.RemoveStartFromList(this);
}
public T BlockingRemoveStart(TimeSpan? timeOut)
{
return client.BlockingRemoveStartFromList(this, timeOut);
}
public T RemoveEnd()
{
return client.RemoveEndFromList(this);
}
public void Enqueue(T value)
{
client.EnqueueItemOnList(this, value);
}
public T Dequeue()
{
return client.DequeueItemFromList(this);
}
public T BlockingDequeue(TimeSpan? timeOut)
{
return client.BlockingDequeueItemFromList(this, timeOut);
}
public void Push(T value)
{
client.PushItemToList(this, value);
}
public T Pop()
{
return client.PopItemFromList(this);
}
public T BlockingPop(TimeSpan? timeOut)
{
return client.BlockingPopItemFromList(this, timeOut);
}
public T PopAndPush(IRedisList<T> toList)
{
return client.PopAndPushItemBetweenLists(this, toList);
}
}
}
| |
// 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.
#region Namespace Imports
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Prexonite.Commands;
using Prexonite.Modular;
using Prexonite.Types;
#endregion
namespace Prexonite.Compiler.Cil
{
public sealed class CompilerState : StackContext
{
public const int ParamArgsIndex = 2;
public const int ParamResultIndex = 4;
public const int ParamSctxIndex = 1;
public const int ParamSharedVariablesIndex = 3;
public const int ParamSourceIndex = 0;
public const int ParamReturnModeIndex = 5;
private readonly List<ForeachHint> _foreachHints;
private readonly Queue<int> _cilExtensionOffsets;
private readonly ILGenerator _il;
private readonly Dictionary<int, string> _indexMap;
private readonly Label[] _instructionLabels;
private readonly Label _returnLabel;
private readonly PFunction _source;
private readonly SymbolTable<CilSymbol> _symbols;
private readonly Engine _targetEngine;
private readonly Stack<CompiledTryCatchFinallyBlock> _tryBlocks;
private LocalBuilder[] _tempLocals;
private readonly CompilerPass _pass;
private readonly FunctionLinking _linking;
private readonly StructuredExceptionHandling _seh;
private readonly int[] _stackSize;
private string _effectiveArgumentsListId;
/// <summary>
/// The name of the arguments list variable.
/// </summary>
public string EffectiveArgumentsListId
{
get
{
return _effectiveArgumentsListId ??
(_effectiveArgumentsListId = PFunction.ArgumentListId);
}
}
public CompilerState
(PFunction source, Engine targetEngine, ILGenerator il, CompilerPass pass,
FunctionLinking linking)
{
if (source == null)
throw new ArgumentNullException("source");
if (targetEngine == null)
throw new ArgumentNullException("targetEngine");
if (il == null)
throw new ArgumentNullException("il");
_source = source;
_linking = linking;
_pass = pass;
_targetEngine = targetEngine;
_il = il;
_indexMap = new Dictionary<int, string>();
_instructionLabels = new Label[Source.Code.Count + 1];
for (var i = 0; i < InstructionLabels.Length; i++)
InstructionLabels[i] = il.DefineLabel();
_returnLabel = il.DefineLabel();
_symbols = new SymbolTable<CilSymbol>();
_tryBlocks = new Stack<CompiledTryCatchFinallyBlock>();
MetaEntry cilHints;
_foreachHints = new List<ForeachHint>();
_cilExtensionOffsets = new Queue<int>();
if (source.Meta.TryGetValue(Loader.CilHintsKey, out cilHints))
{
SortedSet<int> cilExtensionOffsets = null;
foreach (var entry in cilHints.List)
{
var hint = entry.List;
if (hint.Length < 1)
continue;
switch (hint[0].Text)
{
case CilExtensionHint.Key:
if (cilExtensionOffsets == null)
cilExtensionOffsets = new SortedSet<int>();
var cilExt = CilExtensionHint.FromMetaEntry(hint);
foreach (var offset in cilExt.Offsets)
cilExtensionOffsets.Add(offset);
break;
case ForeachHint.Key:
_ForeachHints.Add(ForeachHint.FromMetaEntry(hint));
break;
}
}
if (cilExtensionOffsets != null)
{
foreach (var offset in cilExtensionOffsets)
_cilExtensionOffsets.Enqueue(offset);
}
}
_seh = new StructuredExceptionHandling(this);
_stackSize = new int[source.Code.Count];
}
#region Accessors
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly",
MessageId = "Argc")]
public LocalBuilder ArgcLocal { get; internal set; }
public PFunction Source
{
get { return _source; }
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly",
MessageId = "Argv")]
public LocalBuilder ArgvLocal { get; internal set; }
public ILGenerator Il
{
get { return _il; }
}
/// <summary>
/// Maps from local variable indices to local variable phyical ids
/// </summary>
public Dictionary<int, string> IndexMap
{
get { return _indexMap; }
}
/// <summary>
/// <para>Maps from instruction addresses to the corresponding logical labels</para>
/// <para>Use these labels to jump to Prexonite Instructions.</para>
/// </summary>
public Label[] InstructionLabels
{
get { return _instructionLabels; }
}
/// <summary>
/// <para>The label that marks the exit of the function. Jump here to return.</para>
/// </summary>
public Label ReturnLabel
{
get { return _returnLabel; }
}
/// <summary>
/// The local variable that holds the CIL stack context
/// </summary>
public LocalBuilder SctxLocal { get; internal set; }
/// <summary>
/// <para>The local variable that holds arrays of shared variables immediately before closure instantiation</para>
/// </summary>
public LocalBuilder SharedLocal { get; internal set; }
/// <summary>
/// CilSymbol table for the CIL compiler. See <see cref = "CilSymbol" /> for details.
/// </summary>
public SymbolTable<CilSymbol> Symbols
{
get { return _symbols; }
}
/// <summary>
/// <para>Array of temporary variables. They are not preserved across Prexonite instructions. You are free to use them within <see
/// cref = "ICilCompilerAware.ImplementInCil" /> or <see cref = "ICilExtension.Implement" /></para>.
/// </summary>
public LocalBuilder[] TempLocals
{
get { return _tempLocals; }
internal set { _tempLocals = value; }
}
/// <summary>
/// The stack of try blocks currently in effect. The innermost try block is on top.
/// </summary>
public Stack<CompiledTryCatchFinallyBlock> TryBlocks
{
get { return _tryBlocks; }
}
/// <summary>
/// The engine in which the function is compiled to CIL. It can be assumed that engine configuration (such as command aliases) will not change anymore.
/// </summary>
public Engine TargetEngine
{
get { return _targetEngine; }
}
/// <summary>
/// List of foreach CIL hints associated with this function.
/// </summary>
internal List<ForeachHint> _ForeachHints
{
get { return _foreachHints; }
}
/// <summary>
/// List of addresses where valid CIL extension code begins.
/// </summary>
internal Queue<int> _CilExtensionOffsets
{
[DebuggerStepThrough]
get { return _cilExtensionOffsets; }
}
private LocalBuilder _partialApplicationMapping;
/// <summary>
/// <para>Local <code>System.Int32[]</code> variable. Used for temporarily holding arguments for partial application constructors.</para>
/// <para>Is not guaranteed to retain its value across instructions</para>
/// </summary>
public LocalBuilder PartialApplicationMappingLocal
{
get
{
return _partialApplicationMapping ??
(_partialApplicationMapping = Il.DeclareLocal(typeof (int[])));
}
}
/// <summary>
/// Represents the engine this context is part of.
/// </summary>
public override Engine ParentEngine
{
get { return _targetEngine; }
}
/// <summary>
/// The parent application.
/// </summary>
public override Application ParentApplication
{
get { return _source.ParentApplication; }
}
/// <summary>
/// Collection of imported namespaces. Serves the same function as <see cref = "StackContext.ImportedNamespaces" />.
/// </summary>
public override SymbolCollection ImportedNamespaces
{
get { return _source.ImportedNamespaces; }
}
/// <summary>
/// Indicates whether the context still has code/work to do.
/// </summary>
/// <returns>True if the context has additional work to perform in the next cycle, False if it has finished it's work and can be removed from the stack</returns>
protected override bool PerformNextCycle(StackContext lastContext)
{
return false;
}
/// <summary>
/// Tries to handle the supplied exception.
/// </summary>
/// <param name = "exc">The exception to be handled.</param>
/// <returns>True if the exception has been handled, false otherwise.</returns>
public override bool TryHandleException(Exception exc)
{
return false;
}
/// <summary>
/// Represents the return value of the context.
/// Just providing a value here does not mean that it gets consumed by the caller.
/// If the context does not provide a return value, this property should return null (not NullPType).
/// </summary>
public override PValue ReturnValue
{
get { return PType.Null; }
}
/// <summary>
/// Returns a reference to the current compiler pass.
/// </summary>
public CompilerPass Pass
{
get { return _pass; }
}
public FunctionLinking Linking
{
get { return _linking; }
}
public LocalBuilder PrimaryTempLocal
{
get { return TempLocals[0]; }
}
public StructuredExceptionHandling Seh
{
get { return _seh; }
}
public int[] StackSize
{
[DebuggerStepThrough]
get { return _stackSize; }
}
#endregion
#region Emit-helper methods
/// <summary>
/// <para>Emits the shortest possible ldc.i4 opcode.</para>
/// </summary>
/// <param name = "i"></param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly",
MessageId = "Ldc")]
public void EmitLdcI4(int i)
{
switch (i)
{
case -1:
Il.Emit(OpCodes.Ldc_I4_M1);
break;
case 0:
Il.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
Il.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
Il.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
Il.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
Il.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
Il.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
Il.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
Il.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
Il.Emit(OpCodes.Ldc_I4_8);
break;
default:
if (i >= SByte.MinValue && i <= SByte.MaxValue)
Il.Emit(OpCodes.Ldc_I4_S, (sbyte) i);
else
Il.Emit(OpCodes.Ldc_I4, i);
break;
}
}
/// <summary>
/// Shove arguments from the stack into the argument array (`argv`). This way the arguments can later be
/// passed to methods. Use <see cref = "ReadArgv" /> to load that array onto the stack.
/// </summary>
/// <param name = "argc">The number of arguments to load from the stack.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly",
MessageId = "Argv")]
public void FillArgv(int argc)
{
if (argc == 0)
{
//Nothing, argv is read from CilRuntime.EmptyPValueArrayField
}
else
{
//Instantiate array -> argv
EmitLdcI4(argc);
Il.Emit(OpCodes.Newarr, typeof (PValue));
EmitStoreLocal(ArgvLocal);
for (var i = argc - 1; i >= 0; i--)
{
//get argument
EmitStoreTemp(0);
//store argument
EmitLoadLocal(ArgvLocal);
EmitLdcI4(i);
EmitLoadTemp(0);
Il.Emit(OpCodes.Stelem_Ref);
}
}
}
/// <summary>
/// Load previously perpared argument array (<see cref = "FillArgv" />) onto the stack.
/// </summary>
/// <param name = "argc">The number of elements in that argument array.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly",
MessageId = "Argv")]
public void ReadArgv(int argc)
{
if (argc == 0)
{
Il.Emit(OpCodes.Ldsfld, Runtime.EmptyPValueArrayField);
}
else
{
EmitLoadLocal(ArgvLocal);
}
}
/// <summary>
/// Emits the shortest possible ldarg instruction.
/// </summary>
/// <param name = "index">The index of the argument to load.</param>
public void EmitLoadArg(int index)
{
switch (index)
{
case 0:
Il.Emit(OpCodes.Ldarg_0);
break;
case 1:
Il.Emit(OpCodes.Ldarg_1);
break;
case 2:
Il.Emit(OpCodes.Ldarg_2);
break;
case 3:
Il.Emit(OpCodes.Ldarg_3);
break;
default:
if (index < Byte.MaxValue)
Il.Emit(OpCodes.Ldarg_S, (byte) index);
else
Il.Emit(OpCodes.Ldarg, index);
break;
}
}
/// <summary>
/// Emits the shortest possible ldloc instruction for the supplied local variable.
/// </summary>
/// <param name = "local">The local variable to load.</param>
public void EmitLoadLocal(LocalBuilder local)
{
EmitLoadLocal(local.LocalIndex);
}
/// <summary>
/// Emits the shortest possible ldloc instruction for the supplied local variable.
/// </summary>
/// <param name = "index">The index of the local variable to load.</param>
public void EmitLoadLocal(int index)
{
switch (index)
{
case 0:
Il.Emit(OpCodes.Ldloc_0);
break;
case 1:
Il.Emit(OpCodes.Ldloc_1);
break;
case 2:
Il.Emit(OpCodes.Ldloc_2);
break;
case 3:
Il.Emit(OpCodes.Ldloc_3);
break;
default:
if (index < Byte.MaxValue)
Il.Emit(OpCodes.Ldloc_S, (byte) index);
else
Il.Emit(OpCodes.Ldloc, index);
break;
}
}
public void EmitStoreLocal(LocalBuilder local)
{
EmitStoreLocal(local.LocalIndex);
}
public void EmitStoreLocal(int index)
{
switch (index)
{
case 0:
Il.Emit(OpCodes.Stloc_0);
break;
case 1:
Il.Emit(OpCodes.Stloc_1);
break;
case 2:
Il.Emit(OpCodes.Stloc_2);
break;
case 3:
Il.Emit(OpCodes.Stloc_3);
break;
default:
if (index < Byte.MaxValue)
Il.Emit(OpCodes.Stloc_S, (byte) index);
else
Il.Emit(OpCodes.Stloc, index);
break;
}
}
public void EmitStoreTemp(int i)
{
if (i >= _tempLocals.Length)
throw new ArgumentOutOfRangeException
(
"i", i,
"This particular cil implementation does not use that many temporary variables.");
EmitStoreLocal(_tempLocals[i]);
}
public void EmitLoadTemp(int i)
{
if (i >= _tempLocals.Length)
throw new ArgumentOutOfRangeException
(
"i", i,
"This particular cil implementation does not use that many temporary variables.");
EmitLoadLocal(_tempLocals[i]);
}
/// <summary>
/// Loads the value of a global variable from the current or any other module. Internal access is optimized.
/// </summary>
/// <param name="id">The name of the global variable to be loaded (an internal id)</param>
/// <param name="moduleName">The name of the module that defines the global variable. May be null to indicate an internal variable.</param>
public void EmitLoadGlobalValue(string id, ModuleName moduleName)
{
EmitLoadGlobalReference(id,moduleName);
Il.EmitCall(OpCodes.Call, Compiler.GetValueMethod, null);
}
public void EmitLoadGlobalRefAsPValue(EntityRef.Variable.Global globalVariable)
{
EmitLoadGlobalRefAsPValue(globalVariable.Id,globalVariable.ModuleName);
}
/// <summary>
/// Loads the <see cref="PVariable"/> object for the specified global variable onto the managed stack.
/// </summary>
/// <param name="id">The internal id of the global variable.</param>
/// <param name="moduleName">The module name containing the global variable definition. May be null to indicate an internal global variable.</param>
public void EmitLoadGlobalReference(string id, ModuleName moduleName)
{
EmitLoadLocal(SctxLocal.LocalIndex);
Il.Emit(OpCodes.Ldstr, id);
if (moduleName == null || Equals(moduleName, _source.ParentApplication.Module.Name))
{
EmitCall(Runtime.LoadGlobalVariableReferenceInternalMethod);
}
else
{
EmitModuleName(moduleName);
EmitCall(Runtime.LoadGlobalVariableReferenceMethod);
}
}
public void EmitIndirectCall(int argc, bool justEffect)
{
EmitLoadLocal(SctxLocal);
ReadArgv(argc);
Il.EmitCall(OpCodes.Call, Compiler.PVIndirectCallMethod, null);
if (justEffect)
Il.Emit(OpCodes.Pop);
}
/// <summary>
/// <para>Write the value produced by <paramref name = "action" /> into the local variable behind <paramref name = "sym" />.</para>
/// <para>Warning: Action must work with an empty stack</para>
/// </summary>
/// <param name = "sym">The local variable to write to.</param>
/// <param name = "action">The action that produces the value.</param>
public void EmitStorePValue(CilSymbol sym, Action action)
{
if (sym.Kind == SymbolKind.Local)
{
action();
EmitStoreLocal(sym.Local);
}
else if (sym.Kind == SymbolKind.LocalRef)
{
EmitLoadLocal(sym.Local);
action();
Il.EmitCall(OpCodes.Call, Compiler.SetValueMethod, null);
}
else
{
throw new PrexoniteException("Cannot emit code for CilSymbol");
}
}
/// <summary>
/// <para>Load a value from the specified local variable.</para>
/// </summary>
/// <param name = "sym">The variable to load.</param>
public void EmitLoadPValue(CilSymbol sym)
{
if (sym.Kind == SymbolKind.Local)
{
EmitLoadLocal(sym.Local);
}
else if (sym.Kind == SymbolKind.LocalRef)
{
EmitLoadLocal(sym.Local);
Il.EmitCall(OpCodes.Call, Compiler.GetValueMethod, null);
}
else
{
throw new PrexoniteException("Cannot emit code for CilSymbol");
}
}
/// <summary>
/// Creates a PValue null value.
/// </summary>
public void EmitLoadNullAsPValue()
{
Il.EmitCall(OpCodes.Call, Compiler.getPTypeNull, null);
Il.EmitCall(OpCodes.Call, Compiler.nullCreatePValue, null);
}
public void MarkInstruction(int instructionAddress)
{
Il.MarkLabel(InstructionLabels[instructionAddress]);
}
public void EmitCall(MethodInfo method)
{
Il.EmitCall(OpCodes.Call, method, null);
}
public void EmitVirtualCall(MethodInfo method)
{
Il.EmitCall(OpCodes.Callvirt, method, null);
}
public void EmitWrapString()
{
Il.EmitCall(OpCodes.Call, Compiler.GetStringPType, null);
Il.Emit(OpCodes.Newobj, Compiler.NewPValue);
}
public void EmitWrapBool()
{
Il.Emit(OpCodes.Box, typeof (bool));
Il.EmitCall(OpCodes.Call, Compiler.GetBoolPType, null);
Il.Emit(OpCodes.Newobj, Compiler.NewPValue);
}
public void EmitWrapReal()
{
Il.Emit(OpCodes.Box, typeof (double));
Il.EmitCall(OpCodes.Call, Compiler.GetRealPType, null);
Il.Emit(OpCodes.Newobj, Compiler.NewPValue);
}
public void EmitWrapInt()
{
Il.Emit(OpCodes.Box, typeof (int));
Il.EmitCall(OpCodes.Call, Compiler.GetIntPType, null);
Il.Emit(OpCodes.Newobj, Compiler.NewPValue);
}
public void EmitWrapChar()
{
Il.Emit(OpCodes.Box, typeof (char));
Il.EmitCall(OpCodes.Call, Compiler.GetCharPType, null);
Il.Emit(OpCodes.Newobj, Compiler.NewPValue);
}
public void EmitLoadType(string typeExpr)
{
var T = ConstructPType(typeExpr);
var cilT = T as ICilCompilerAware;
var virtualInstruction = new Instruction(OpCode.cast_const, typeExpr);
var cf = cilT != null
? cilT.CheckQualification(virtualInstruction)
: CompilationFlags.IsCompatible;
if ((cf & CompilationFlags.HasCustomImplementation) ==
CompilationFlags.HasCustomImplementation &&
cilT != null)
{
cilT.ImplementInCil(this, virtualInstruction);
}
else
{
EmitLoadLocal(SctxLocal);
Il.Emit(OpCodes.Ldstr, typeExpr);
EmitCall(Runtime.ConstructPTypeMethod);
}
}
public void EmitNewObj(string typeExpr, int argc)
{
FillArgv(argc);
EmitLoadType(typeExpr);
EmitLoadLocal(SctxLocal);
ReadArgv(argc);
EmitVirtualCall(_pTypeConstructMethod);
}
private static readonly MethodInfo _pTypeConstructMethod =
typeof (PType).GetMethod("Construct", new[] {typeof (StackContext), typeof (PValue[])});
public void EmitLoadClrType(Type T)
{
Il.Emit(OpCodes.Ldtoken, T);
EmitCall(_typeGetTypeFromHandle);
}
private static readonly MethodInfo _typeGetTypeFromHandle =
typeof (Type).GetMethod("GetTypeFromHandle", new[] {typeof (RuntimeTypeHandle)});
#region Early bound command call
/// <summary>
/// Emits a call to the static method "RunStatically(StackContext sctx, PValue[] args)" of the supplied type.
/// </summary>
/// <param name = "target">The type, that declares the RunStatically to call.</param>
/// <param name = "ins">The call to the command for which code is to be emitted.</param>
public void EmitEarlyBoundCommandCall(Type target, Instruction ins)
{
EmitEarlyBoundCommandCall(target, ins.Arguments, ins.JustEffect);
}
/// <summary>
/// Emits a call to the static method "RunStatically(StackContext sctx, PValue[] args)" of the supplied type.
/// </summary>
/// <param name = "target">The type, that declares the RunStatically to call.</param>
/// <param name = "argc">The number of arguments to pass to the command.</param>
public void EmitEarlyBoundCommandCall(Type target, int argc)
{
EmitEarlyBoundCommandCall(target, argc, false);
}
/// <summary>
/// Emits a call to the static method "RunStatically(StackContext sctx, PValue[] args)" of the supplied type.
/// </summary>
/// <param name = "target">The type, that declares the RunStatically to call.</param>
/// <param name = "argc">The number of arguments to pass to the command.</param>
/// <param name = "justEffect">Indicates whether or not to ignore the return value.</param>
public void EmitEarlyBoundCommandCall(Type target, int argc, bool justEffect)
{
var run =
target.GetMethod("RunStatically", new[] {typeof (StackContext), typeof (PValue[])});
if (run == null)
throw new PrexoniteException
(
String.Format(
"{0} does not provide a static method RunStatically(StackContext, PValue[])",
target));
if (run.ReturnType != typeof (PValue))
throw new PrexoniteException
(
String.Format("{0}'s RunStatically method does not return PValue but {1}.",
target, run.ReturnType));
FillArgv(argc);
EmitLoadLocal(SctxLocal);
ReadArgv(argc);
Il.EmitCall(OpCodes.Call, run, null);
if (justEffect)
Il.Emit(OpCodes.Pop);
}
#endregion
#endregion
/// <summary>
/// Pops the specified number of arguments off the stack.
/// </summary>
/// <param name = "argc">The number of arguments to pop off the stack.</param>
public void EmitIgnoreArguments(int argc)
{
for (var i = 0; i < argc; i++)
Il.Emit(OpCodes.Pop);
}
public void EmitPTypeAsPValue(string expr)
{
EmitLoadLocal(SctxLocal);
Il.Emit(OpCodes.Ldstr, expr);
Il.EmitCall(OpCodes.Call, Runtime.ConstructPTypeAsPValueMethod, null);
}
public bool TryGetStaticallyLinkedFunction(string id, out MethodInfo targetMethod)
{
targetMethod = null;
return (Linking & FunctionLinking.Static) == FunctionLinking.Static &&
Pass.Implementations.TryGetValue(id, out targetMethod);
}
public void EmitCommandCall(Instruction ins)
{
var argc = ins.Arguments;
var id = ins.Id;
var justEffect = ins.JustEffect;
PCommand cmd;
ICilCompilerAware aware = null;
CompilationFlags flags;
if (
TargetEngine.Commands.TryGetValue(id, out cmd) &&
(aware = cmd as ICilCompilerAware) != null)
flags = aware.CheckQualification(ins);
else
flags = CompilationFlags.IsCompatible;
if (
(
(flags & CompilationFlags.PrefersCustomImplementation) ==
CompilationFlags.PrefersCustomImplementation ||
(flags & CompilationFlags.RequiresCustomImplementation)
== CompilationFlags.RequiresCustomImplementation
) && aware != null)
{
//Let the command handle the call
aware.ImplementInCil(this, ins);
}
else if ((flags & CompilationFlags.PrefersRunStatically)
== CompilationFlags.PrefersRunStatically)
{
//Emit a static call to $commandType$.RunStatically
EmitEarlyBoundCommandCall(cmd.GetType(), ins);
}
else
{
//Implement via Runtime.CallCommand (call by name)
FillArgv(argc);
EmitLoadLocal(SctxLocal);
ReadArgv(argc);
Il.Emit(OpCodes.Ldstr, id);
Il.EmitCall(OpCodes.Call, Runtime.CallCommandMethod, null);
if (justEffect)
Il.Emit(OpCodes.Pop);
}
}
public void EmitFuncCall(int argc, string internalId, ModuleName moduleName, bool justEffect)
{
if (internalId == null)
throw new ArgumentNullException("internalId");
MethodInfo staticTargetMethod;
var isInternal = moduleName == null ||
Equals(moduleName, Source.ParentApplication.Module.Name);
if (isInternal && TryGetStaticallyLinkedFunction(internalId, out staticTargetMethod))
{
//Link function statically
FillArgv(argc);
Il.Emit(OpCodes.Ldsfld, Pass.FunctionFields[internalId]);
EmitLoadLocal(SctxLocal);
ReadArgv(argc);
Il.Emit(OpCodes.Ldnull);
Il.Emit(OpCodes.Ldloca_S, TempLocals[0]);
EmitLoadArg(ParamReturnModeIndex);
EmitCall(staticTargetMethod);
if (!justEffect)
EmitLoadTemp(0);
}
else if (isInternal)
{
//Link function dynamically
FillArgv(argc);
EmitLoadLocal(SctxLocal);
ReadArgv(argc);
Il.Emit(OpCodes.Ldstr, internalId);
Il.EmitCall(OpCodes.Call, Runtime.CallInternalFunctionMethod, null);
if (justEffect)
Il.Emit(OpCodes.Pop);
}
//TODO (Ticket #107) bind cross-module calls statically
else
{
//Cross-Module-Link function dynamically
FillArgv(argc);
EmitLoadLocal(SctxLocal);
ReadArgv(argc);
Il.Emit(OpCodes.Ldstr, internalId);
EmitModuleName(moduleName);
Il.EmitCall(OpCodes.Call, Runtime.CallFunctionMethod, null);
if (justEffect)
Il.Emit(OpCodes.Pop);
}
}
/// <summary>
/// Creates a new closure of the specified function. Needs to have the StackContext and the array of shared variables on the managed stack.
/// </summary>
/// <param name="internalId">The internal id of the function to create a closure for.</param>
/// <param name="moduleName">If the function comes from another module, the module name is passed here.</param>
public void EmitNewClo(string internalId, ModuleName moduleName)
{
if (internalId == null)
throw new ArgumentNullException("internalId");
MethodInfo dummyMethodInfo;
var isInternal = moduleName == null ||
Equals(moduleName, Source.ParentApplication.Module.Name);
MethodInfo runtimeMethod;
if(isInternal && TryGetStaticallyLinkedFunction(internalId, out dummyMethodInfo))
{
Il.Emit(OpCodes.Ldsfld, Pass.FunctionFields[internalId]);
runtimeMethod = Runtime.NewClosureMethodStaticallyBound;
}
else if(isInternal)
{
Il.Emit(OpCodes.Ldstr,internalId);
runtimeMethod = Runtime.NewClosureMethodLateBound;
}
//TODO (Ticket #107) bind cross-module calls statically
else
{
Il.Emit(OpCodes.Ldstr,internalId);
EmitModuleName(moduleName);
runtimeMethod = Runtime.NewClosureMethodCrossModule;
}
EmitCall(runtimeMethod);
}
public void EmitLoadEngRefAsPValue()
{
EmitLoadLocal(SctxLocal);
Il.EmitCall(OpCodes.Call, Runtime.LoadEngineReferenceMethod, null);
}
public static void EmitLoadAppRefAsPValue(CompilerState state)
{
state.EmitLoadLocal(state.SctxLocal);
state.Il.EmitCall
(
OpCodes.Call, Runtime.LoadApplicationReferenceMethod, null);
}
public void EmitLoadCmdRefAsPValue(string id)
{
EmitLoadLocal(SctxLocal);
Il.Emit(OpCodes.Ldstr, id);
Il.EmitCall(OpCodes.Call, Runtime.LoadCommandReferenceMethod, null);
}
public void EmitLoadFuncRefAsPValue(string internalId, ModuleName moduleName)
{
MethodInfo dummyMethodInfo;
EmitLoadLocal(SctxLocal);
var isInternal = moduleName == null ||
Equals(moduleName, Source.ParentApplication.Module.Name);
if (!isInternal && TryGetStaticallyLinkedFunction(internalId, out dummyMethodInfo))
{
Il.Emit(OpCodes.Ldsfld, Pass.FunctionFields[internalId]);
EmitVirtualCall(Compiler.CreateNativePValue);
}
//TODO (Ticket #107) Statically linked Cross-Module ldr.func
else if(isInternal)
{
Il.Emit(OpCodes.Ldstr, internalId);
EmitCall(Runtime.LoadFunctionReferenceInternalMethod);
}
else
{
//Cross-module reference, dynamically linked
Il.Emit(OpCodes.Ldstr,internalId);
EmitModuleName(moduleName);
EmitCall(Runtime.LoadFunctionReferenceMethod);
}
}
public void EmitLoadGlobalRefAsPValue(string id, ModuleName moduleName)
{
EmitLoadLocal(SctxLocal);
Il.Emit(OpCodes.Ldstr, id);
if(moduleName == null || Equals(moduleName,Source.ParentApplication.Module.Name))
{
EmitCall(Runtime.LoadGlobalReferenceAsPValueInternalMethod);
}
else
{
EmitModuleName(moduleName);
EmitCall(Runtime.LoadGlobalVariableReferenceAsPValueMethod);
}
}
public void EmitLoadLocalRefAsPValue(string id)
{
EmitLoadLocal(Symbols[id].Local);
Il.EmitCall(OpCodes.Call, Runtime.WrapPVariableMethod, null);
}
public void EmitLoadLocalRefAsPValue(EntityRef.Variable.Local localVariable)
{
EmitLoadLocalRefAsPValue(localVariable.Id);
}
public void EmitLoadStringAsPValue(string id)
{
Il.Emit(OpCodes.Ldstr, id);
EmitWrapString();
}
public void EmitLoadBoolAsPValue(bool value)
{
EmitLdcI4(value ? 1 : 0);
EmitWrapBool();
}
public void EmitLoadRealAsPValue(double value)
{
Il.Emit(OpCodes.Ldc_R8, value);
EmitWrapReal();
}
public void EmitLoadRealAsPValue(Instruction ins)
{
EmitLoadRealAsPValue((double) ins.GenericArgument);
}
public void EmitLoadIntAsPValue(int argc)
{
EmitLdcI4(argc);
EmitWrapInt();
}
internal void _EmitAssignReturnMode(ReturnMode returnMode)
{
EmitLoadArg(ParamReturnModeIndex);
EmitLdcI4((int) returnMode);
Il.Emit(OpCodes.Stind_I4);
}
public void EmitSetReturnValue()
{
EmitStoreLocal(PrimaryTempLocal);
EmitLoadArg(ParamResultIndex);
EmitLoadLocal(PrimaryTempLocal);
Il.Emit(OpCodes.Stind_Ref);
}
private static readonly Lazy<ConstructorInfo[]> _versionCtors = new Lazy<ConstructorInfo[]>(() =>
{
var cs = new ConstructorInfo[3];
cs[0] =
typeof (Version).GetConstructor(new[]
{typeof (int), typeof (int)});
cs[1] =
typeof (Version).GetConstructor(new[]
{typeof (int), typeof (int), typeof (int)});
cs[2] =
typeof (Version).GetConstructor(new[]
{typeof (int), typeof (int), typeof (int), typeof (int)});
return cs;
},LazyThreadSafetyMode.None);
public void EmitVersion(Version version)
{
EmitLdcI4(version.Major);
EmitLdcI4(version.Minor);
//major.minor.build.revision
var offset =
version.Revision >= 0
? 2
: version.Build >= 0
? 1
: 0;
Il.Emit(OpCodes.Newobj, _versionCtors.Value[offset]);
}
public void EmitModuleNameAsPValue(ModuleName moduleName)
{
if (moduleName == null)
throw new ArgumentNullException("moduleName");
EmitLoadLocal(SctxLocal);
Il.Emit(OpCodes.Ldstr, moduleName.Id);
EmitVersion(moduleName.Version);
EmitCall(Runtime.LoadModuleNameAsPValueMethod);
}
public void EmitModuleName(ModuleName moduleName)
{
if (moduleName == null)
throw new ArgumentNullException("moduleName");
EmitLoadLocal(SctxLocal);
Il.Emit(OpCodes.Ldstr, moduleName.Id);
EmitVersion(moduleName.Version);
EmitCall(Runtime.LoadModuleNameMethod);
}
public void EmitLoadFuncRefAsPValue(EntityRef.Function function)
{
EmitLoadFuncRefAsPValue(function.Id,function.ModuleName);
}
public void EmitLoadCmdRefAsPValue(EntityRef.Command command)
{
EmitLoadCmdRefAsPValue(command.Id);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using swc = System.Windows.Controls;
using sw = System.Windows;
using swm = System.Windows.Media;
using Eto.Forms;
using Eto.Drawing;
using swi = System.Windows.Input;
using Eto.Wpf.Drawing;
namespace Eto.Wpf.Forms.Controls
{
public class DrawableHandler : WpfPanel<swc.Canvas, Drawable, Drawable.ICallback>, Drawable.IHandler
{
bool tiled;
sw.FrameworkElement content;
Scrollable scrollable;
readonly Dictionary<int, EtoTile> visibleTiles = new Dictionary<int, EtoTile>();
List<EtoTile> invalidateTiles;
readonly List<EtoTile> unusedTiles = new List<EtoTile>();
Size maxTiles;
Size tileSize = new Size(100, 100);
static readonly object OptimizedInvalidateRectKey = new object();
public bool OptimizedInvalidateRect
{
get { return Widget.Properties.Get<bool>(OptimizedInvalidateRectKey, true); }
set { Widget.Properties.Set(OptimizedInvalidateRectKey, value, true); }
}
public bool AllowTiling { get; set; }
public bool SupportsCreateGraphics { get { return false; } }
public Size TileSize
{
get { return tileSize; }
set
{
if (tileSize != value)
{
tileSize = value;
if (Widget.Loaded)
{
ClearTiles();
SetMaxTiles();
UpdateTiles();
}
}
}
}
class EtoMainCanvas : swc.Canvas
{
public DrawableHandler Handler { get; set; }
protected override void OnMouseDown(sw.Input.MouseButtonEventArgs e)
{
if (Handler.CanFocus)
{
swi.Keyboard.Focus(this);
}
base.OnMouseDown(e);
}
protected override void OnRender(swm.DrawingContext dc)
{
base.OnRender(dc);
if (!Handler.tiled)
{
var rect = new sw.Rect(0, 0, ActualWidth, ActualHeight);
var cliprect = rect.ToEto();
if (!cliprect.IsEmpty)
{
using (var graphics = new Graphics(new GraphicsHandler(this, dc, rect, new RectangleF(Handler.ClientSize), false)))
{
Handler.Callback.OnPaint(Handler.Widget, new PaintEventArgs(graphics, cliprect));
}
}
}
}
}
class EtoTile : sw.FrameworkElement
{
Rectangle bounds;
public DrawableHandler Handler { get; set; }
public Rectangle Bounds
{
get { return bounds; }
set
{
if (bounds != value)
{
bounds = value;
swc.Canvas.SetLeft(this, bounds.X);
swc.Canvas.SetTop(this, bounds.Y);
Width = Handler.tileSize.Width;
Height = Handler.tileSize.Height;
RenderTransform = new swm.TranslateTransform(-bounds.X, -bounds.Y);
}
}
}
public Point Position { get; set; }
public int Key { get { return Position.Y * Handler.maxTiles.Width + Position.X; } }
protected override void OnRender(swm.DrawingContext drawingContext)
{
var graphics = new Graphics(new GraphicsHandler(this, drawingContext, bounds.ToWpf(), new RectangleF(Handler.ClientSize), false));
Handler.Callback.OnPaint(Handler.Widget, new PaintEventArgs(graphics, Bounds));
}
}
public override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
RegisterScrollable();
}
public override void OnUnLoad(EventArgs e)
{
base.OnUnLoad(e);
UnRegisterScrollable();
}
public void Create()
{
Control = new EtoMainCanvas
{
Handler = this,
SnapsToDevicePixels = true,
FocusVisualStyle = null,
Background = swm.Brushes.Transparent
};
Control.Loaded += Control_Loaded;
}
public void Create(bool largeCanvas)
{
AllowTiling = largeCanvas;
Create();
}
void Control_Loaded(object sender, sw.RoutedEventArgs e)
{
UpdateTiles(true);
Control.Loaded -= Control_Loaded; // only perform once
}
public virtual Graphics CreateGraphics()
{
throw new NotSupportedException();
}
void Control_SizeChanged(object sender, sw.SizeChangedEventArgs e)
{
SetMaxTiles();
UpdateTiles(true);
Invalidate();
content.Width = e.NewSize.Width;
content.Height = e.NewSize.Height;
}
void SetMaxTiles()
{
maxTiles = new Size(((int)Control.ActualWidth + tileSize.Width - 1) / tileSize.Width, ((int)Control.ActualHeight + tileSize.Height - 1) / tileSize.Height);
}
void RebuildKeys()
{
var tiles = visibleTiles.Values.ToArray();
visibleTiles.Clear();
foreach (var tile in tiles)
{
visibleTiles[tile.Key] = tile;
}
}
void UnRegisterScrollable()
{
if (scrollable != null)
{
scrollable.Scroll -= scrollable_Scroll;
scrollable = null;
}
if (tiled)
{
tiled = false;
Control.SizeChanged -= Control_SizeChanged;
}
}
void RegisterScrollable()
{
UnRegisterScrollable();
if (AllowTiling)
{
scrollable = Widget.FindParent<Scrollable>();
if (scrollable != null)
scrollable.Scroll += scrollable_Scroll;
Control.SizeChanged += Control_SizeChanged;
SetMaxTiles();
tiled = true;
}
}
void ClearTiles()
{
foreach (var tile in unusedTiles)
{
Control.Children.Remove(tile);
}
unusedTiles.Clear();
foreach (var tile in visibleTiles.Values)
{
Control.Children.Remove(tile);
}
visibleTiles.Clear();
}
void UpdateTiles(bool rebuildKeys = false)
{
if (!tiled || !Control.IsLoaded)
return;
var controlSize = new Size((int)Control.ActualWidth, (int)Control.ActualHeight);
var rect = new Rectangle(controlSize);
var scroll = scrollable;
if (scroll != null)
{
// only show tiles in the visible rect of the scrollable
var visibleRect = new Rectangle(scroll.ClientSize);
var scrollableHandler = (ScrollableHandler)scroll.Handler;
visibleRect.Offset(-Control.TranslatePoint(new sw.Point(), scrollableHandler.ContentControl).ToEtoPoint());
rect.Intersect(visibleRect);
}
// cache unused tiles and remove them from the visible tiles list
var keys = visibleTiles.Keys.ToArray();
for (int i = 0; i < keys.Length; i++)
{
var key = keys[i];
var tile = visibleTiles[keys[i]];
if (!tile.Bounds.Intersects(rect))
{
visibleTiles.Remove(key);
// keep tile, but make it invisible when needed later
tile.Visibility = sw.Visibility.Collapsed;
unusedTiles.Add(tile);
}
}
// rebuild keys (e.g. when the size of the control changes)
if (rebuildKeys)
RebuildKeys();
// calculate tile range that is visible
var top = rect.Top / tileSize.Height;
var bottom = (rect.Bottom + tileSize.Height - 1) / tileSize.Height;
var left = rect.Left / tileSize.Width;
var right = (rect.Right + tileSize.Width - 1) / tileSize.Width;
// make sure all needed tiles are created/visible
for (var y = top; y < bottom; y++)
{
for (var x = left; x < right; x++)
{
var position = new Point(x, y);
if (!maxTiles.Contains(position))
continue;
var key = position.Y * maxTiles.Width + position.X;
// calculate bounds of tile
var xpos = x * tileSize.Width;
var ypos = y * tileSize.Height;
var xsize = Math.Min(tileSize.Width, controlSize.Width - xpos);
var ysize = Math.Min(tileSize.Height, controlSize.Height - ypos);
if (xsize < 0 || ysize < 0)
continue;
var bounds = new Rectangle(xpos, ypos, xsize, ysize);
EtoTile tile;
if (!visibleTiles.TryGetValue(key, out tile))
{
tile = unusedTiles.FirstOrDefault();
if (tile != null)
{
// use existing cached tile and make it visible again
unusedTiles.Remove(tile);
tile.Position = position;
tile.Bounds = bounds;
tile.Visibility = sw.Visibility.Visible;
tile.InvalidateVisual();
}
else
{
// need a new tile, no cached ones left
tile = new EtoTile
{
Handler = this,
SnapsToDevicePixels = true,
Position = position,
Bounds = bounds
};
Control.Children.Add(tile);
}
// set tile as visible
visibleTiles[key] = tile;
}
else
{
tile.Bounds = bounds;
tile.InvalidateVisual();
}
}
}
}
void scrollable_Scroll(object sender, ScrollEventArgs e)
{
UpdateTiles();
}
public override void Invalidate()
{
if (!Control.IsLoaded)
return;
if (tiled)
{
foreach (var tile in visibleTiles.Values)
{
tile.InvalidateVisual();
}
}
else
{
if (invalidateTiles != null)
{
invalidateTiles.ForEach(t => t.Visibility = sw.Visibility.Collapsed);
unusedTiles.AddRange(invalidateTiles);
invalidateTiles.Clear();
}
base.Invalidate();
}
}
public override void Invalidate(Rectangle rect)
{
if (!Control.IsLoaded)
return;
if (tiled)
{
foreach (var tile in visibleTiles.Values)
{
if (tile.Bounds.Intersects(rect))
tile.InvalidateVisual();
}
}
else if (OptimizedInvalidateRect)
{
if (((rect.Width * rect.Height) / (Control.ActualWidth * Control.ActualHeight)) > 0.9)
{
Invalidate();
return;
}
if (invalidateTiles == null)
invalidateTiles = new List<EtoTile>();
var overlappingTiles = new List<EtoTile>();
foreach (var overlappingTile in invalidateTiles)
{
if (rect == overlappingTile.Bounds)
{
overlappingTile.InvalidateVisual();
return;
}
else if (rect.Intersects(overlappingTile.Bounds))
{
rect.Union(overlappingTile.Bounds);
overlappingTiles.Add(overlappingTile);
}
}
EtoTile tile;
if (unusedTiles.Count > 0)
{
tile = unusedTiles[unusedTiles.Count - 1];
tile.Bounds = rect;
tile.Visibility = sw.Visibility.Visible;
unusedTiles.Remove(tile);
}
else
{
tile = new EtoTile
{
Handler = this,
SnapsToDevicePixels = true
};
tile.Bounds = rect;
Control.Children.Add(tile);
}
invalidateTiles.Add(tile);
foreach (var overlappingTile in overlappingTiles)
{
overlappingTile.Visibility = sw.Visibility.Collapsed;
invalidateTiles.Remove(overlappingTile);
unusedTiles.Add(overlappingTile);
}
}
else
base.Invalidate(rect);
}
public void Update(Rectangle rect)
{
Invalidate(rect);
}
public bool CanFocus
{
get { return Control.Focusable; }
set
{
if (value != Control.Focusable)
{
Control.Focusable = value;
}
}
}
public override void SetContainerContent(sw.FrameworkElement content)
{
this.content = content;
Control.Children.Add(content);
}
public override Color BackgroundColor
{
get { return Control.Background.ToEtoColor(); }
set { Control.Background = value.ToWpfBrush(Control.Background); }
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Reflection;
using System.Text;
#if !NETSTANDARD1_0
using System.Transactions;
#endif
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
#if !NETSTANDARD
using System.Configuration;
using ConfigurationManager = System.Configuration.ConfigurationManager;
#endif
/// <summary>
/// Writes log messages to the database using an ADO.NET provider.
/// </summary>
/// <remarks>
/// - NETSTANDARD cannot load connectionstrings from .config
/// </remarks>
/// <seealso href="https://github.com/nlog/nlog/wiki/Database-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <para>
/// The configuration is dependent on the database type, because
/// there are differnet methods of specifying connection string, SQL
/// command and command parameters.
/// </para>
/// <para>MS SQL Server using System.Data.SqlClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/MSSQL/NLog.config" height="450" />
/// <para>Oracle using System.Data.OracleClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.Native/NLog.config" height="350" />
/// <para>Oracle using System.Data.OleDBClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.OleDB/NLog.config" height="350" />
/// <para>To set up the log target programmatically use code like this (an equivalent of MSSQL configuration):</para>
/// <code lang="C#" source="examples/targets/Configuration API/Database/MSSQL/Example.cs" height="630" />
/// </example>
[Target("Database")]
public class DatabaseTarget : Target, IInstallable
{
private static Assembly systemDataAssembly = typeof(IDbConnection).GetAssembly();
private IDbConnection _activeConnection = null;
private string _activeConnectionString;
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseTarget" /> class.
/// </summary>
public DatabaseTarget()
{
Parameters = new List<DatabaseParameterInfo>();
InstallDdlCommands = new List<DatabaseCommandInfo>();
UninstallDdlCommands = new List<DatabaseCommandInfo>();
DBProvider = "sqlserver";
DBHost = ".";
#if !NETSTANDARD
ConnectionStringsSettings = ConfigurationManager.ConnectionStrings;
#endif
CommandType = CommandType.Text;
OptimizeBufferReuse = GetType() == typeof(DatabaseTarget);
}
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseTarget" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
public DatabaseTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets the name of the database provider.
/// </summary>
/// <remarks>
/// <para>
/// The parameter name should be a provider invariant name as registered in machine.config or app.config. Common values are:
/// </para>
/// <ul>
/// <li><c>System.Data.SqlClient</c> - <see href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx">SQL Sever Client</see></li>
/// <li><c>System.Data.SqlServerCe.3.5</c> - <see href="http://www.microsoft.com/sqlserver/2005/en/us/compact.aspx">SQL Sever Compact 3.5</see></li>
/// <li><c>System.Data.OracleClient</c> - <see href="http://msdn.microsoft.com/en-us/library/system.data.oracleclient.aspx">Oracle Client from Microsoft</see> (deprecated in .NET Framework 4)</li>
/// <li><c>Oracle.DataAccess.Client</c> - <see href="http://www.oracle.com/technology/tech/windows/odpnet/index.html">ODP.NET provider from Oracle</see></li>
/// <li><c>System.Data.SQLite</c> - <see href="http://sqlite.phxsoftware.com/">System.Data.SQLite driver for SQLite</see></li>
/// <li><c>Npgsql</c> - <see href="http://npgsql.projects.postgresql.org/">Npgsql driver for PostgreSQL</see></li>
/// <li><c>MySql.Data.MySqlClient</c> - <see href="http://www.mysql.com/downloads/connector/net/">MySQL Connector/Net</see></li>
/// </ul>
/// <para>(Note that provider invariant names are not supported on .NET Compact Framework).</para>
/// <para>
/// Alternatively the parameter value can be be a fully qualified name of the provider
/// connection type (class implementing <see cref="IDbConnection" />) or one of the following tokens:
/// </para>
/// <ul>
/// <li><c>sqlserver</c>, <c>mssql</c>, <c>microsoft</c> or <c>msde</c> - SQL Server Data Provider</li>
/// <li><c>oledb</c> - OLEDB Data Provider</li>
/// <li><c>odbc</c> - ODBC Data Provider</li>
/// </ul>
/// </remarks>
/// <docgen category='Connection Options' order='10' />
[RequiredParameter]
[DefaultValue("sqlserver")]
public string DBProvider { get; set; }
#if !NETSTANDARD
/// <summary>
/// Gets or sets the name of the connection string (as specified in <see href="http://msdn.microsoft.com/en-us/library/bf7sd233.aspx"><connectionStrings> configuration section</see>.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public string ConnectionStringName { get; set; }
#endif
/// <summary>
/// Gets or sets the connection string. When provided, it overrides the values
/// specified in DBHost, DBUserName, DBPassword, DBDatabase.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout ConnectionString { get; set; }
/// <summary>
/// Gets or sets the connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used.
/// </summary>
/// <docgen category='Installation Options' order='10' />
public Layout InstallConnectionString { get; set; }
/// <summary>
/// Gets the installation DDL commands.
/// </summary>
/// <docgen category='Installation Options' order='10' />
[ArrayParameter(typeof(DatabaseCommandInfo), "install-command")]
public IList<DatabaseCommandInfo> InstallDdlCommands { get; private set; }
/// <summary>
/// Gets the uninstallation DDL commands.
/// </summary>
/// <docgen category='Installation Options' order='10' />
[ArrayParameter(typeof(DatabaseCommandInfo), "uninstall-command")]
public IList<DatabaseCommandInfo> UninstallDdlCommands { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether to keep the
/// database connection open between the log events.
/// </summary>
/// <docgen category='Connection Options' order='10' />
[DefaultValue(false)]
public bool KeepConnection { get; set; }
/// <summary>
/// Obsolete - value will be ignored! The logging code always runs outside of transaction.
///
/// Gets or sets a value indicating whether to use database transactions.
/// Some data providers require this.
/// </summary>
/// <docgen category='Connection Options' order='10' />
/// <remarks>
/// This option was removed in NLog 4.0 because the logging code always runs outside of transaction.
/// This ensures that the log gets written to the database if you rollback the main transaction because of an error and want to log the error.
/// </remarks>
[Obsolete("Value will be ignored as logging code always executes outside of a transaction. Marked obsolete on NLog 4.0 and it will be removed in NLog 6.")]
public bool? UseTransactions { get; set; }
/// <summary>
/// Gets or sets the database host name. If the ConnectionString is not provided
/// this value will be used to construct the "Server=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBHost { get; set; }
/// <summary>
/// Gets or sets the database user name. If the ConnectionString is not provided
/// this value will be used to construct the "User ID=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBUserName { get; set; }
/// <summary>
/// Gets or sets the database password. If the ConnectionString is not provided
/// this value will be used to construct the "Password=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBPassword { get; set; }
/// <summary>
/// Gets or sets the database name. If the ConnectionString is not provided
/// this value will be used to construct the "Database=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBDatabase { get; set; }
/// <summary>
/// Gets or sets the text of the SQL command to be run on each log level.
/// </summary>
/// <remarks>
/// Typically this is a SQL INSERT statement or a stored procedure call.
/// It should use the database-specific parameters (marked as <c>@parameter</c>
/// for SQL server or <c>:parameter</c> for Oracle, other data providers
/// have their own notation) and not the layout renderers,
/// because the latter is prone to SQL injection attacks.
/// The layout renderers should be specified as <parameter /> elements instead.
/// </remarks>
/// <docgen category='SQL Statement' order='10' />
[RequiredParameter]
public Layout CommandText { get; set; }
/// <summary>
/// Gets or sets the type of the SQL command to be run on each log level.
/// </summary>
/// <remarks>
/// This specifies how the command text is interpreted, as "Text" (default) or as "StoredProcedure".
/// When using the value StoredProcedure, the commandText-property would
/// normally be the name of the stored procedure. TableDirect method is not supported in this context.
/// </remarks>
/// <docgen category='SQL Statement' order='11' />
[DefaultValue(CommandType.Text)]
public CommandType CommandType { get; set; }
/// <summary>
/// Gets the collection of parameters. Each parameter contains a mapping
/// between NLog layout and a database named or positional parameter.
/// </summary>
/// <docgen category='SQL Statement' order='12' />
[ArrayParameter(typeof(DatabaseParameterInfo), "parameter")]
public IList<DatabaseParameterInfo> Parameters { get; private set; }
#if !NETSTANDARD
internal DbProviderFactory ProviderFactory { get; set; }
// this is so we can mock the connection string without creating sub-processes
internal ConnectionStringSettingsCollection ConnectionStringsSettings { get; set; }
#endif
internal Type ConnectionType { get; set; }
/// <summary>
/// Performs installation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Install(InstallationContext installationContext)
{
RunInstallCommands(installationContext, InstallDdlCommands);
}
/// <summary>
/// Performs uninstallation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Uninstall(InstallationContext installationContext)
{
RunInstallCommands(installationContext, UninstallDdlCommands);
}
/// <summary>
/// Determines whether the item is installed.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <returns>
/// Value indicating whether the item is installed or null if it is not possible to determine.
/// </returns>
public bool? IsInstalled(InstallationContext installationContext)
{
return null;
}
internal IDbConnection OpenConnection(string connectionString)
{
IDbConnection connection;
#if !NETSTANDARD
if (ProviderFactory != null)
{
connection = ProviderFactory.CreateConnection();
}
else
#endif
{
connection = (IDbConnection)Activator.CreateInstance(ConnectionType);
}
if (connection == null)
{
throw new NLogRuntimeException("Creation of connection failed");
}
connection.ConnectionString = connectionString;
connection.Open();
return connection;
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "connectionStrings", Justification = "Name of the config file section.")]
protected override void InitializeTarget()
{
base.InitializeTarget();
#pragma warning disable 618
if (UseTransactions.HasValue)
#pragma warning restore 618
{
InternalLogger.Warn("UseTransactions property is obsolete and will not be used - will be removed in NLog 6");
}
bool foundProvider = false;
#if !NETSTANDARD
if (!string.IsNullOrEmpty(ConnectionStringName))
{
// read connection string and provider factory from the configuration file
var cs = ConnectionStringsSettings[ConnectionStringName];
if (cs == null)
{
throw new NLogConfigurationException($"Connection string '{ConnectionStringName}' is not declared in <connectionStrings /> section.");
}
ConnectionString = SimpleLayout.Escape(cs.ConnectionString);
if (!string.IsNullOrEmpty(cs.ProviderName))
{
ProviderFactory = DbProviderFactories.GetFactory(cs.ProviderName);
foundProvider = true;
}
}
if (!foundProvider)
{
foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows)
{
var invariantname = (string)row["InvariantName"];
if (invariantname == DBProvider)
{
ProviderFactory = DbProviderFactories.GetFactory(DBProvider);
foundProvider = true;
break;
}
}
}
#endif
if (!foundProvider)
{
SetConnectionType();
}
}
/// <summary>
/// Set the <see cref="ConnectionType"/> to use it for opening connections to the database.
/// </summary>
private void SetConnectionType()
{
switch (DBProvider.ToUpperInvariant())
{
case "SQLSERVER":
case "MSSQL":
case "MICROSOFT":
case "MSDE":
#if NETSTANDARD
var assembly = Assembly.Load(new AssemblyName("System.Data.SqlClient"));
#else
var assembly = systemDataAssembly;
#endif
ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true);
break;
#if !NETSTANDARD
case "OLEDB":
ConnectionType = systemDataAssembly.GetType("System.Data.OleDb.OleDbConnection", true);
break;
case "ODBC":
ConnectionType = systemDataAssembly.GetType("System.Data.Odbc.OdbcConnection", true);
break;
#endif
default:
ConnectionType = Type.GetType(DBProvider, true);
break;
}
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected override void CloseTarget()
{
base.CloseTarget();
InternalLogger.Trace("DatabaseTarget: close connection because of CloseTarget");
CloseConnection();
}
/// <summary>
/// Writes the specified logging event to the database. It creates
/// a new database command, prepares parameters for it by calculating
/// layouts and executes the command.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
try
{
WriteEventToDatabase(logEvent);
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error when writing to database.");
if (exception.MustBeRethrownImmediately())
{
throw;
}
InternalLogger.Trace("DatabaseTarget: close connection because of error");
CloseConnection();
throw;
}
finally
{
if (!KeepConnection)
{
InternalLogger.Trace("DatabaseTarget: close connection (KeepConnection = false).");
CloseConnection();
}
}
}
/// <summary>
/// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents)
///
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
[Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")]
protected override void Write(AsyncLogEventInfo[] logEvents)
{
Write((IList<AsyncLogEventInfo>)logEvents);
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected override void Write(IList<AsyncLogEventInfo> logEvents)
{
var buckets = logEvents.BucketSort(c => BuildConnectionString(c.LogEvent));
try
{
foreach (var kvp in buckets)
{
for (int i = 0; i < kvp.Value.Count; i++)
{
AsyncLogEventInfo ev = kvp.Value[i];
try
{
WriteEventToDatabase(ev.LogEvent);
ev.Continuation(null);
}
catch (Exception exception)
{
// in case of exception, close the connection and report it
InternalLogger.Error(exception, "Error when writing to database.");
if (exception.MustBeRethrownImmediately())
{
throw;
}
InternalLogger.Trace("DatabaseTarget: close connection because of exception");
CloseConnection();
ev.Continuation(exception);
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
}
finally
{
if (!KeepConnection)
{
InternalLogger.Trace("DatabaseTarget: close connection because of KeepConnection=false");
CloseConnection();
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "It's up to the user to ensure proper quoting.")]
private void WriteEventToDatabase(LogEventInfo logEvent)
{
//Always suppress transaction so that the caller does not rollback loggin if they are rolling back their transaction.
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
{
EnsureConnectionOpen(BuildConnectionString(logEvent));
using (IDbCommand command = _activeConnection.CreateCommand())
{
command.CommandText = RenderLogEvent(CommandText, logEvent);
command.CommandType = CommandType;
InternalLogger.Trace("Executing {0}: {1}", command.CommandType, command.CommandText);
foreach (DatabaseParameterInfo par in Parameters)
{
IDbDataParameter p = command.CreateParameter();
p.Direction = ParameterDirection.Input;
if (par.Name != null)
{
p.ParameterName = par.Name;
}
if (par.Size != 0)
{
p.Size = par.Size;
}
if (par.Precision != 0)
{
p.Precision = par.Precision;
}
if (par.Scale != 0)
{
p.Scale = par.Scale;
}
string stringValue = RenderLogEvent(par.Layout, logEvent);
p.Value = stringValue;
command.Parameters.Add(p);
InternalLogger.Trace(" Parameter: '{0}' = '{1}' ({2})", p.ParameterName, p.Value, p.DbType);
}
int result = command.ExecuteNonQuery();
InternalLogger.Trace("Finished execution, result = {0}", result);
}
//not really needed as there is no transaction at all.
transactionScope.Complete();
}
}
/// <summary>
/// Build the connectionstring from the properties.
/// </summary>
/// <remarks>
/// Using <see cref="ConnectionString"/> at first, and falls back to the properties <see cref="DBHost"/>,
/// <see cref="DBUserName"/>, <see cref="DBPassword"/> and <see cref="DBDatabase"/>
/// </remarks>
/// <param name="logEvent">Event to render the layout inside the properties.</param>
/// <returns></returns>
protected string BuildConnectionString(LogEventInfo logEvent)
{
if (ConnectionString != null)
{
return RenderLogEvent(ConnectionString, logEvent);
}
var sb = new StringBuilder();
sb.Append("Server=");
sb.Append(RenderLogEvent(DBHost, logEvent));
sb.Append(";");
if (DBUserName == null)
{
sb.Append("Trusted_Connection=SSPI;");
}
else
{
sb.Append("User id=");
sb.Append(RenderLogEvent(DBUserName, logEvent));
sb.Append(";Password=");
sb.Append(RenderLogEvent(DBPassword, logEvent));
sb.Append(";");
}
if (DBDatabase != null)
{
sb.Append("Database=");
sb.Append(RenderLogEvent(DBDatabase, logEvent));
}
return sb.ToString();
}
private void EnsureConnectionOpen(string connectionString)
{
if (_activeConnection != null)
{
if (_activeConnectionString != connectionString)
{
InternalLogger.Trace("DatabaseTarget: close connection because of opening new.");
CloseConnection();
}
}
if (_activeConnection != null)
{
return;
}
InternalLogger.Trace("DatabaseTarget: open connection.");
_activeConnection = OpenConnection(connectionString);
_activeConnectionString = connectionString;
}
private void CloseConnection()
{
if (_activeConnection != null)
{
_activeConnection.Close();
_activeConnection.Dispose();
_activeConnection = null;
_activeConnectionString = null;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "It's up to the user to ensure proper quoting.")]
private void RunInstallCommands(InstallationContext installationContext, IEnumerable<DatabaseCommandInfo> commands)
{
// create log event that will be used to render all layouts
LogEventInfo logEvent = installationContext.CreateLogEvent();
try
{
foreach (var commandInfo in commands)
{
string cs;
if (commandInfo.ConnectionString != null)
{
// if there is connection string specified on the command info, use it
cs = RenderLogEvent(commandInfo.ConnectionString, logEvent);
}
else if (InstallConnectionString != null)
{
// next, try InstallConnectionString
cs = RenderLogEvent(InstallConnectionString, logEvent);
}
else
{
// if it's not defined, fall back to regular connection string
cs = BuildConnectionString(logEvent);
}
// Set ConnectionType if it has not been initialized already
if (ConnectionType == null)
{
SetConnectionType();
}
EnsureConnectionOpen(cs);
using (var command = _activeConnection.CreateCommand())
{
command.CommandType = commandInfo.CommandType;
command.CommandText = RenderLogEvent(commandInfo.Text, logEvent);
try
{
installationContext.Trace("Executing {0} '{1}'", command.CommandType, command.CommandText);
command.ExecuteNonQuery();
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures)
{
installationContext.Warning(exception.Message);
}
else
{
installationContext.Error(exception.Message);
throw;
}
}
}
}
}
finally
{
InternalLogger.Trace("DatabaseTarget: close connection after install.");
CloseConnection();
}
}
#if NETSTANDARD1_0
/// <summary>
/// Fake transaction
///
/// Transactions aren't in .NET Core: https://github.com/dotnet/corefx/issues/2949
/// </summary>
private class TransactionScope : IDisposable
{
private readonly TransactionScopeOption suppress;
public TransactionScope(TransactionScopeOption suppress)
{
this.suppress = suppress;
}
public void Complete() { }
#region Implementation of IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
}
#endregion
}
/// <summary>
/// Fake option
/// </summary>
private enum TransactionScopeOption
{
Required,
RequiresNew,
Suppress,
}
#endif
}
}
#endif
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using STM.Implementation.Lockbased;
using System.Collections.Immutable;
using System.Collections.Generic;
using Evaluation.Common;
namespace LanguagedBasedHashMap
{
public class Program
{
public static void Main()
{
var map = new StmHashMap<int, int>();
TestMap(map);
map = new StmHashMap<int, int>();
TestMapConcurrent(map);
}
private static void TestMapConcurrent(IMap<int, int> map)
{
const int t1From = 0;
const int t1To = 1000;
const int t2From = -1000;
const int t2To = 0;
const int expectedSize = 2000;
var t1 = new Thread(() => MapAdd(map, t1From, t1To));
var t2 = new Thread(() => MapAdd(map, t2From, t2To));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Debug.Assert(expectedSize == map.Count);
t1 = new Thread(() => MapAddIfAbsent(map, t1From, t1To));
t2 = new Thread(() => MapAddIfAbsent(map, t2From, t2To));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Debug.Assert(expectedSize == map.Count);
t1 = new Thread(() => MapGet(map, t1From, t1To));
t2 = new Thread(() => MapGet(map, t2From, t2To));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
t1 = new Thread(() => MapForeach(map));
t2 = new Thread(() => MapForeach(map));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
t1 = new Thread(() => MapRemove(map, t1From, t1To));
t2 = new Thread(() => MapRemove(map, t2From, t2To));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Debug.Assert(0 == map.Count);
}
private static void TestMap(IMap<int, int> map)
{
const int from = -50;
const int to = 50;
Debug.Assert(map.Count == 0);
MapAdd(map, from, to);
Debug.Assert(map.Count == 100);
MapAddIfAbsent(map, from, to);
Debug.Assert(map.Count == 100);
MapGet(map, from, to);
MapRemove(map, from, to);
Debug.Assert(map.Count == 0);
}
public static void MapAdd(IMap<int, int> map, int from, int to)
{
for (var i = from; i < to; i++)
{
map[i] = i;
}
}
public static void MapAddIfAbsent(IMap<int, int> map, int from, int to)
{
for (var i = from; i < to; i++)
{
map.AddIfAbsent(i, i);
}
}
public static void MapRemove(IMap<int, int> map, int from, int to)
{
for (var i = from; i < to; i++)
{
map.Remove(i);
}
}
public static void MapGet(IMap<int, int> map, int from, int to)
{
for (var i = from; i < to; i++)
{
Debug.Assert(i == map.Get(i));
}
}
public static void MapForeach(IMap<int, int> map)
{
foreach (var kvPair in map)
{
Debug.Assert(kvPair.Key == kvPair.Value);
}
}
}
public class StmHashMap<K,V> : BaseHashMap<K,V>
{
private atomic Bucket[] _buckets;
private atomic int _threshold;
private atomic int _size;
public StmHashMap() : this(DefaultNrBuckets)
{
}
public StmHashMap(int nrBuckets)
{
_buckets = MakeBuckets(nrBuckets);
_threshold = CalculateThreshold(nrBuckets);
}
private Bucket[] MakeBuckets(int nrBuckets)
{
var temp = new Bucket[nrBuckets];
for (int i = 0; i < nrBuckets; i++)
{
temp[i] = new Bucket();
}
return temp;
}
#region Utility
private Node CreateNode(K key, V value)
{
return new Node(key, value);
}
private int GetBucketIndex(K key)
{
return GetBucketIndex(_buckets.Length, key);
}
private Node FindNode(K key)
{
return FindNode(key, GetBucketIndex(key));
}
private Node FindNode(K key, int bucketIndex)
{
return FindNode(key, _buckets[bucketIndex].Value);
}
private Node FindNode(K key, ImmutableList<Node> chain)
{
return chain.Find(n => n.Key.Equals(key));
}
#endregion Utility
public override bool ContainsKey(K key)
{
return FindNode(key) != null;
}
public override V Get(K key)
{
atomic
{
var node = FindNode(key);
if(node == null)
{
//If node == null key is not present in dictionary
throw new KeyNotFoundException("Key not found. Key: " + key);
}
return node.Value;
}
}
public override void Add(K key, V value)
{
atomic
{
var bucketIndex = GetBucketIndex(key);
//TMVar wrapping the immutable chain list
var bucketVar = _buckets[bucketIndex];
var node = FindNode(key, bucketVar.Value);
if (node != null)
{
//If node is not null key exist in map. Update the value
node.Value = value;
}
else
{
//Else insert the node
bucketVar.Value = bucketVar.Value.Add(CreateNode(key, value));
_size++;
ResizeIfNeeded();
}
}
}
public override bool AddIfAbsent(K key, V value)
{
atomic
{
var bucketIndex = GetBucketIndex(key);
//TMVar wrapping the immutable chain list
var bucketVar = _buckets[bucketIndex];
var node = FindNode(key, bucketVar.Value);
if (node == null)
{
//If node is not found key does not exist so insert
bucketVar.Value = bucketVar.Value.Add(CreateNode(key, value));
_size++;
ResizeIfNeeded();
return true;
}
return false;
}
}
private void ResizeIfNeeded()
{
if (_size >= _threshold)
{
Resize();
}
}
private void Resize()
{
//Construct new backing array
var newBucketSize = _buckets.Length * 2;
var newBuckets = MakeBuckets(newBucketSize);
//For each key in the map rehash
for (var i = 0; i < _buckets.Length; i++)
{
var bucket = _buckets[i];
foreach (var node in bucket.Value)
{
var bucketIndex = GetBucketIndex(newBucketSize, node.Key);
newBuckets[bucketIndex].Value = newBuckets[bucketIndex].Value.Add(node);
}
}
//Calculate new resize threshold and assign the rehashed backing array
_threshold = CalculateThreshold(newBucketSize);
_buckets = newBuckets;
}
public override bool Remove(K key)
{
atomic
{
var bucketIndex = GetBucketIndex(key);
//TMVar wrapping the immutable chain list
var bucketVar = _buckets[bucketIndex];
var node = FindNode(key, bucketVar.Value);
if (node != null)
{
//If node is not found key does not exist so insert
bucketVar.Value = bucketVar.Value.Remove(node);
_size--;
return true;
}
return false;
}
}
private IEnumerator<KeyValuePair<K, V>> BuildEnumerator()
{
Bucket[] backingArray = _buckets;
Thread.MemoryBarrier();
//Thread.MemoryBarrier(); Forces the compiler to not move the local variable into the loop header
//This is important as the iterator will otherwise start iterating over a resized backing array
// if a resize happes during iteration.
//Result if allowed could be the same key value pair being iterated over more than once or not at all
//This way the iterator only iterates over one backing array if a resize occurs those changes are not taken into account
//Additions or removals are still possible during iteration => same guarantee as System.Collections.Concurrent.ConcurrentDictionary
for (var i = 0; i < backingArray.Length; i++)
{
var bucket = backingArray[i];
foreach (var node in bucket.Value)
{
yield return new KeyValuePair<K, V>(node.Key, node.Value);
}
}
}
public override IEnumerator<KeyValuePair<K, V>> GetEnumerator()
{
atomic
{
var list = new List<KeyValuePair<K, V>>(_size);
for (var i = 0; i < _buckets.Length; i++)
{
var bucket = _buckets[i];
foreach (var node in bucket.Value)
{
var keyValuePair = new KeyValuePair<K, V>(node.Key, node.Value);
list.Add(keyValuePair);
}
}
return list.GetEnumerator();
}
}
public override V this[K key]
{
get { return Get(key); }
set { Add(key, value); }
}
public override int Count
{
get { return _size; }
}
private class Bucket
{
public atomic ImmutableList<Node> Value { get; set; }
public Bucket()
{
Value = ImmutableList.Create<Node>();
}
}
private class Node
{
public K Key { get; private set; }
public atomic V Value { get; set; }
public Node(K key, V value)
{
Key = key;
Value = value;
}
}
}
}
| |
//
// System.Data.OleDb.OleDbDataReader
//
// Author:
// Rodrigo Moya (rodrigo@ximian.com)
// Tim Coleman (tim@timcoleman.com)
//
// Copyright (C) Rodrigo Moya, 2002
// Copyright (C) Tim Coleman, 2002
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.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.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Runtime.InteropServices;
namespace System.Data.OleDb
{
public sealed class OleDbDataReader : MarshalByRefObject, IDataReader, IDisposable, IDataRecord, IEnumerable
{
#region Fields
private OleDbCommand command;
private bool open;
private ArrayList gdaResults;
private int currentResult;
private int currentRow;
private bool disposed = false;
#endregion
#region Constructors
internal OleDbDataReader (OleDbCommand command, ArrayList results)
{
this.command = command;
open = true;
if (results != null)
gdaResults = results;
else
gdaResults = new ArrayList ();
currentResult = -1;
currentRow = -1;
}
#endregion
#region Properties
public int Depth {
get {
return 0; // no nested selects supported
}
}
public int FieldCount {
get {
if (currentResult < 0 ||
currentResult >= gdaResults.Count)
return 0;
return libgda.gda_data_model_get_n_columns (
(IntPtr) gdaResults[currentResult]);
}
}
public bool IsClosed {
get {
return !open;
}
}
public object this[string name] {
get {
int pos;
if (currentResult == -1)
throw new InvalidOperationException ();
pos = libgda.gda_data_model_get_column_position (
(IntPtr) gdaResults[currentResult],
name);
if (pos == -1)
throw new IndexOutOfRangeException ();
return this[pos];
}
}
public object this[int index] {
get {
return (object) GetValue (index);
}
}
public int RecordsAffected {
get {
int total_rows;
if (currentResult < 0 ||
currentResult >= gdaResults.Count)
return 0;
total_rows = libgda.gda_data_model_get_n_rows (
(IntPtr) gdaResults[currentResult]);
if (total_rows > 0) {
if (FieldCount > 0) {
// It's a SELECT statement
return -1;
}
}
return FieldCount > 0 ? -1 : total_rows;
}
}
[MonoTODO]
public bool HasRows {
get {
throw new NotImplementedException ();
}
}
#endregion
#region Methods
public void Close ()
{
for (int i = 0; i < gdaResults.Count; i++) {
IntPtr obj = (IntPtr) gdaResults[i];
libgda.FreeObject (obj);
}
gdaResults.Clear ();
gdaResults = null;
open = false;
currentResult = -1;
currentRow = -1;
}
public bool GetBoolean (int ordinal)
{
IntPtr value;
if (currentResult == -1)
throw new InvalidCastException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new InvalidCastException ();
if (libgda.gda_value_get_type (value) != GdaValueType.Boolean)
throw new InvalidCastException ();
return libgda.gda_value_get_boolean (value);
}
public byte GetByte (int ordinal)
{
IntPtr value;
if (currentResult == -1)
throw new InvalidCastException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new InvalidCastException ();
if (libgda.gda_value_get_type (value) != GdaValueType.Tinyint)
throw new InvalidCastException ();
return libgda.gda_value_get_tinyint (value);
}
[MonoTODO]
public long GetBytes (int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length)
{
throw new NotImplementedException ();
}
[EditorBrowsableAttribute (EditorBrowsableState.Never)]
public char GetChar (int ordinal)
{
IntPtr value;
if (currentResult == -1)
throw new InvalidCastException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new InvalidCastException ();
if (libgda.gda_value_get_type (value) != GdaValueType.Tinyint)
throw new InvalidCastException ();
return (char) libgda.gda_value_get_tinyint (value);
}
[MonoTODO]
public long GetChars (int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length)
{
throw new NotImplementedException ();
}
[MonoTODO]
public OleDbDataReader GetData (int ordinal)
{
throw new NotImplementedException ();
}
public string GetDataTypeName (int index)
{
IntPtr attrs;
GdaValueType type;
if (currentResult == -1)
return "unknown";
attrs = libgda.gda_data_model_describe_column ((IntPtr) gdaResults[currentResult],
index);
if (attrs == IntPtr.Zero)
return "unknown";
type = libgda.gda_field_attributes_get_gdatype (attrs);
libgda.gda_field_attributes_free (attrs);
return libgda.gda_type_to_string (type);
}
public DateTime GetDateTime (int ordinal)
{
IntPtr value;
DateTime dt;
if (currentResult == -1)
throw new InvalidCastException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new InvalidCastException ();
if (libgda.gda_value_get_type (value) == GdaValueType.Date) {
GdaDate gdt;
gdt = (GdaDate) Marshal.PtrToStructure (libgda.gda_value_get_date (value),
typeof (GdaDate));
return new DateTime ((int) gdt.year, (int) gdt.month, (int) gdt.day);
} else if (libgda.gda_value_get_type (value) == GdaValueType.Time) {
GdaTime gdt;
gdt = (GdaTime) Marshal.PtrToStructure (libgda.gda_value_get_time (value),
typeof (GdaTime));
return new DateTime (0, 0, 0, (int) gdt.hour, (int) gdt.minute, (int) gdt.second, 0);
} else if (libgda.gda_value_get_type (value) == GdaValueType.Timestamp) {
GdaTimestamp gdt;
gdt = (GdaTimestamp) Marshal.PtrToStructure (libgda.gda_value_get_timestamp (value),
typeof (GdaTimestamp));
return new DateTime ((int) gdt.year, (int) gdt.month, (int) gdt.day,
(int) gdt.hour, (int) gdt.minute, (int) gdt.second,
(int) gdt.fraction);
}
throw new InvalidCastException ();
}
[MonoTODO]
public decimal GetDecimal (int ordinal)
{
throw new NotImplementedException ();
}
public double GetDouble (int ordinal)
{
IntPtr value;
if (currentResult == -1)
throw new InvalidCastException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new InvalidCastException ();
if (libgda.gda_value_get_type (value) != GdaValueType.Double)
throw new InvalidCastException ();
return libgda.gda_value_get_double (value);
}
[MonoTODO]
public Type GetFieldType (int index)
{
IntPtr value;
GdaValueType type;
if (currentResult == -1)
throw new IndexOutOfRangeException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
index, currentRow);
if (value == IntPtr.Zero)
throw new IndexOutOfRangeException ();
type = libgda.gda_value_get_type (value);
switch (type) {
case GdaValueType.Bigint : return typeof (long);
case GdaValueType.Boolean : return typeof (bool);
case GdaValueType.Date : return typeof (DateTime);
case GdaValueType.Double : return typeof (double);
case GdaValueType.Integer : return typeof (int);
case GdaValueType.Single : return typeof (float);
case GdaValueType.Smallint : return typeof (byte);
case GdaValueType.String : return typeof (string);
case GdaValueType.Time : return typeof (DateTime);
case GdaValueType.Timestamp : return typeof (DateTime);
case GdaValueType.Tinyint : return typeof (byte);
}
return typeof(string); // default
}
public float GetFloat (int ordinal)
{
IntPtr value;
if (currentResult == -1)
throw new InvalidCastException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new InvalidCastException ();
if (libgda.gda_value_get_type (value) != GdaValueType.Single)
throw new InvalidCastException ();
return libgda.gda_value_get_single (value);
}
[MonoTODO]
public Guid GetGuid (int ordinal)
{
throw new NotImplementedException ();
}
public short GetInt16 (int ordinal)
{
IntPtr value;
if (currentResult == -1)
throw new InvalidCastException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new InvalidCastException ();
if (libgda.gda_value_get_type (value) != GdaValueType.Smallint)
throw new InvalidCastException ();
return (short) libgda.gda_value_get_smallint (value);
}
public int GetInt32 (int ordinal)
{
IntPtr value;
if (currentResult == -1)
throw new InvalidCastException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new InvalidCastException ();
if (libgda.gda_value_get_type (value) != GdaValueType.Integer)
throw new InvalidCastException ();
return libgda.gda_value_get_integer (value);
}
public long GetInt64 (int ordinal)
{
IntPtr value;
if (currentResult == -1)
throw new InvalidCastException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new InvalidCastException ();
if (libgda.gda_value_get_type (value) != GdaValueType.Bigint)
throw new InvalidCastException ();
return libgda.gda_value_get_bigint (value);
}
public string GetName (int index)
{
if (currentResult == -1)
return null;
return libgda.gda_data_model_get_column_title (
(IntPtr) gdaResults[currentResult], index);
}
public int GetOrdinal (string name)
{
if (currentResult == -1)
throw new IndexOutOfRangeException ();
for (int i = 0; i < FieldCount; i++) {
if (GetName (i) == name)
return i;
}
throw new IndexOutOfRangeException ();
}
public DataTable GetSchemaTable ()
{
DataTable dataTableSchema = null;
// Only Results from SQL SELECT Queries
// get a DataTable for schema of the result
// otherwise, DataTable is null reference
if(this.FieldCount > 0) {
IntPtr attrs;
GdaValueType gdaType;
long columnSize = 0;
if (currentResult == -1) {
// FIXME: throw an exception?
#if DEBUG_OleDbDataReader
Console.WriteLine("Error: current result -1");
#endif
return null;
}
dataTableSchema = new DataTable ();
dataTableSchema.Columns.Add ("ColumnName", typeof (string));
dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
dataTableSchema.Columns.Add ("NumericScale", typeof (int));
dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
dataTableSchema.Columns.Add ("IsKey", typeof (bool));
DataColumn dc = dataTableSchema.Columns["IsKey"];
dc.AllowDBNull = true; // IsKey can have a DBNull
dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
dataTableSchema.Columns.Add ("DataType", typeof(Type));
dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
dataTableSchema.Columns.Add ("ProviderType", typeof (int));
dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
dataTableSchema.Columns.Add ("IsLong", typeof (bool));
dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
DataRow schemaRow;
DbType dbType;
Type typ;
for (int i = 0; i < this.FieldCount; i += 1 ) {
schemaRow = dataTableSchema.NewRow ();
attrs = libgda.gda_data_model_describe_column ((IntPtr) gdaResults[currentResult],
i);
if (attrs == IntPtr.Zero){
// FIXME: throw exception
#if DEBUG_OleDbDataReader
Console.WriteLine("Error: attrs null");
#endif
return null;
}
gdaType = libgda.gda_field_attributes_get_gdatype (attrs);
columnSize = libgda.gda_field_attributes_get_defined_size (attrs);
libgda.gda_field_attributes_free (attrs);
schemaRow["ColumnName"] = this.GetName(i);
schemaRow["ColumnOrdinal"] = i + 1;
schemaRow["ColumnSize"] = (int) columnSize;
schemaRow["NumericPrecision"] = 0;
schemaRow["NumericScale"] = 0;
// TODO: need to get KeyInfo
//if((cmdBehavior & CommandBehavior.KeyInfo) == CommandBehavior.KeyInfo) {
// bool IsUnique, IsKey;
// GetKeyInfo(field[i].Name, out IsUnique, out IsKey);
//}
//else {
schemaRow["IsUnique"] = false;
schemaRow["IsKey"] = DBNull.Value;
//}
schemaRow["BaseCatalogName"] = "";
schemaRow["BaseColumnName"] = this.GetName(i);
schemaRow["BaseSchemaName"] = "";
schemaRow["BaseTableName"] = "";
schemaRow["DataType"] = this.GetFieldType(i);
schemaRow["AllowDBNull"] = false;
schemaRow["ProviderType"] = (int) gdaType;
schemaRow["IsAliased"] = false;
schemaRow["IsExpression"] = false;
schemaRow["IsIdentity"] = false;
schemaRow["IsAutoIncrement"] = false;
schemaRow["IsRowVersion"] = false;
schemaRow["IsHidden"] = false;
schemaRow["IsLong"] = false;
schemaRow["IsReadOnly"] = false;
schemaRow.AcceptChanges();
dataTableSchema.Rows.Add (schemaRow);
}
#if DEBUG_OleDbDataReader
Console.WriteLine("********** DEBUG Table Schema BEGIN ************");
foreach (DataRow myRow in dataTableSchema.Rows) {
foreach (DataColumn myCol in dataTableSchema.Columns)
Console.WriteLine(myCol.ColumnName + " = " + myRow[myCol]);
Console.WriteLine();
}
Console.WriteLine("********** DEBUG Table Schema END ************");
#endif // DEBUG_OleDbDataReader
}
return dataTableSchema;
}
public string GetString (int ordinal)
{
IntPtr value;
if (currentResult == -1)
throw new InvalidCastException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new InvalidCastException ();
if (libgda.gda_value_get_type (value) != GdaValueType.String)
throw new InvalidCastException ();
return libgda.gda_value_get_string (value);
}
[MonoTODO]
public TimeSpan GetTimeSpan (int ordinal)
{
throw new NotImplementedException ();
}
public object GetValue (int ordinal)
{
IntPtr value;
GdaValueType type;
if (currentResult == -1)
throw new IndexOutOfRangeException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new IndexOutOfRangeException ();
type = libgda.gda_value_get_type (value);
switch (type) {
case GdaValueType.Bigint : return GetInt64 (ordinal);
case GdaValueType.Boolean : return GetBoolean (ordinal);
case GdaValueType.Date : return GetDateTime (ordinal);
case GdaValueType.Double : return GetDouble (ordinal);
case GdaValueType.Integer : return GetInt32 (ordinal);
case GdaValueType.Single : return GetFloat (ordinal);
case GdaValueType.Smallint : return GetByte (ordinal);
case GdaValueType.String : return GetString (ordinal);
case GdaValueType.Time : return GetDateTime (ordinal);
case GdaValueType.Timestamp : return GetDateTime (ordinal);
case GdaValueType.Tinyint : return GetByte (ordinal);
}
return (object) libgda.gda_value_stringify (value);
}
[MonoTODO]
public int GetValues (object[] values)
{
throw new NotImplementedException ();
}
[MonoTODO]
IDataReader IDataRecord.GetData (int ordinal)
{
throw new NotImplementedException ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return new DbEnumerator (this);
}
public bool IsDBNull (int ordinal)
{
IntPtr value;
if (currentResult == -1)
throw new IndexOutOfRangeException ();
value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
ordinal, currentRow);
if (value == IntPtr.Zero)
throw new IndexOutOfRangeException ();
return libgda.gda_value_is_null (value);
}
public bool NextResult ()
{
int i = currentResult + 1;
if (i >= 0 && i < gdaResults.Count) {
currentResult++;
return true;
}
return false;
}
public bool Read ()
{
if (currentResult < 0 ||
currentResult >= gdaResults.Count)
return false;
currentRow++;
if (currentRow <
libgda.gda_data_model_get_n_rows ((IntPtr) gdaResults[currentResult]))
return true;
return false;
}
#endregion
#region Destructors
private void Dispose (bool disposing) {
if (!this.disposed) {
if (disposing) {
// release any managed resources
command = null;
}
// release any unmanaged resources
if (gdaResults != null) {
gdaResults.Clear ();
gdaResults = null;
}
// close any handles
if (open)
Close ();
this.disposed = true;
}
}
void IDisposable.Dispose() {
Dispose (true);
}
~OleDbDataReader() {
Dispose (false);
}
#endregion // Destructors
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.UnitTests;
using Xunit;
namespace Desktop.Analyzers.UnitTests
{
public partial class DoNotUseInsecureXSLTScriptExecutionAnalyzerTests : DiagnosticAnalyzerTestBase
{
private readonly string _CA3076LoadInsecureConstructedMessage = DesktopAnalyzersResources.XslCompiledTransformLoadInsecureConstructedMessage;
private DiagnosticResult GetCA3076LoadInsecureConstructedCSharpResultAt(int line, int column, string name)
{
return GetCSharpResultAt(line, column, CA3076RuleId, string.Format(_CA3076LoadInsecureConstructedMessage, name));
}
private DiagnosticResult GetCA3076LoadInsecureConstructedBasicResultAt(int line, int column, string name)
{
return GetBasicResultAt(line, column, CA3076RuleId, string.Format(_CA3076LoadInsecureConstructedMessage, name));
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNullResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
xslCompiledTransform.Load(""testStylesheet"", settings, null);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Dim xslCompiledTransform As New XslCompiledTransform()
xslCompiledTransform.Load("""", settings, Nothing)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructDefaultAndNonSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.Default;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.[Default]
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverInTryBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverInCatchBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverInFinallyBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverAsyncAwaitShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverAsyncAwaitShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private async Task TestMethod(XsltSettings settings, XmlResolver resolver)
{
await Task.Run(() =>
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
});
}
private async void TestMethod2()
{
await TestMethod(null, null);
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "Run")
);
VerifyBasic(@"
Imports System.Threading.Tasks
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Function TestMethod(settings As XsltSettings, resolver As XmlResolver) As Task
Await Task.Run(Function()
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Function)
End Function
Private Sub TestMethod2()
Await TestMethod(Nothing, Nothing)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 13, "Run")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverInTryBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverInCatchBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverInFinallyBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverAsyncAwaitShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private async Task TestMethod(XsltSettings settings, XmlResolver resolver)
{
await Task.Run(() =>
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
});
}
private async void TestMethod2()
{
await TestMethod(null, null);
}
}
}"
);
VerifyBasic(@"
Imports System.Threading.Tasks
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Function TestMethod(settings As XsltSettings, resolver As XmlResolver) As Task
Await Task.Run(Function()
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Function)
End Function
Private Sub TestMethod2()
Await TestMethod(Nothing, Nothing)
End Sub
End Class
End Namespace");
}
}
}
| |
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Threading;
namespace SDKLib {
internal abstract class ClientWorkItem : AsyncWorkItem {
protected class ProgressCallbackNotifier : Util.CallbackNotifier {
private readonly long mComplete, mMax;
private readonly float mProgress;
public ProgressCallbackNotifier(ResultCallbackHolder callbackHolder)
: this(callbackHolder, 1, 1) {
}
public ProgressCallbackNotifier(ResultCallbackHolder callbackHolder, long complete, long max)
: base(callbackHolder) {
mMax = max;
mComplete = complete;
if (mMax > 0) {
mProgress = (float)(100.0 * ((double)mComplete / (double)mMax));
} else {
mProgress = -1.0f;
}
}
protected override void notify(object callback, object closure) {
VR.Result.ProgressCallback.If tCallback = callback as VR.Result.ProgressCallback.If;
if (mProgress < 0.0f) {
tCallback.onProgress(closure, mComplete);
} else {
tCallback.onProgress(closure, mProgress, mComplete, mMax);
}
}
}
protected class CancelledCallbackNotifier : Util.CallbackNotifier {
public CancelledCallbackNotifier(ResultCallbackHolder callbackHolder)
: base(callbackHolder) {
}
protected override void notify(object callback, object closure) {
VR.Result.BaseCallback.If tCallback = callback as VR.Result.BaseCallback.If;
tCallback.onCancelled(closure);
}
}
private class ExceptionCallbackNotifier : Util.CallbackNotifier {
private readonly Exception mException;
public ExceptionCallbackNotifier(ResultCallbackHolder callbackHolder, Exception exception)
: base(callbackHolder) {
mException = exception;
}
protected override void notify(object callback, object closure) {
VR.Result.BaseCallback.If tCallback = callback as VR.Result.BaseCallback.If;
tCallback.onException(closure, mException);
}
}
protected readonly APIClientImpl mAPIClient;
protected readonly object mLock = new object();
public ClientWorkItem(APIClientImpl apiClient, AsyncWorkItemType type)
: base(type) {
mAPIClient = apiClient;
}
protected abstract void onRun();
private static string TAG = Util.getLogTag(typeof(ClientWorkItem));
private int mDispatchedCount;
protected readonly ResultCallbackHolder mCallbackHolder = new ResultCallbackHolder();
public ResultCallbackHolder getCallbackHolder() {
return mCallbackHolder;
}
protected virtual void dispatchCounted(Util.CallbackNotifier notifier) {
dispatchUncounted(notifier);
mDispatchedCount += 1;
onDispatchCounted(mDispatchedCount);
}
protected virtual void onDispatchCounted(int count) {
}
public virtual void dispatchUncounted(Util.CallbackNotifier notifier) {
notifier.post();
}
protected virtual void dispatchCancelled() {
dispatchCounted(new CancelledCallbackNotifier(mCallbackHolder));
}
protected virtual void dispatchFailure(int status) {
dispatchCounted(new Util.FailureCallbackNotifier(mCallbackHolder, status));
}
protected virtual void dispatchSuccess() {
dispatchCounted(new Util.SuccessCallbackNotifier(mCallbackHolder));
}
protected virtual void dispatchSuccessWithResult<T>(T rf) {
dispatchCounted(new Util.SuccessWithResultCallbackNotifier<T>(mCallbackHolder, rf));
}
protected virtual void dispatchException(Exception ex) {
dispatchCounted(new ExceptionCallbackNotifier(mCallbackHolder, ex));
}
public override void run() {
mDispatchedCount = 0;
Log.d(TAG, "Running work item: " + this + " type: " + getType());
if (isCancelled()) {
dispatchCancelled();
} else {
try {
onRun();
if ((mDispatchedCount < 1) && isCancelled()) {
dispatchCancelled();
}
} catch (Exception ex) {
Log.d(TAG, "Exception occured on work item: " + this
+ " type: " + getType() + " ex: " + ex + " stack: " + ex.StackTrace);
dispatchException(ex);
}
}
if (1 != mDispatchedCount) {
throw new Exception("Invalid number of dispatches made, count: " + mDispatchedCount);
}
}
protected virtual void set(VR.Result.BaseCallback.If callback, SynchronizationContext handler, object closure) {
mCallbackHolder.setNoLock(callback, handler, closure);
}
protected virtual string toRESTUrl(string suffix) {
string result = null;
result = string.Format("{0}/{1}", mAPIClient.getEndPoint(), suffix);
return result;
}
protected enum HttpMethod {
GET,
POST,
DELETE,
PUT
}
protected virtual HttpStatusCode getResponseCode(HttpPlugin.ReadableRequest request) {
HttpStatusCode responseCode = request.responseCode();
Log.d(TAG, "Returning response code " + responseCode + " from request " + request);
return responseCode;
}
protected virtual bool isHTTPSuccess(HttpStatusCode responseCode) {
return HttpStatusCode.OK.CompareTo(responseCode) <= 0 && HttpStatusCode.BadRequest.CompareTo(responseCode) > 0;
}
protected virtual T newRequest<T>(string url, HttpMethod method,
string[,] headers) where T : HttpPlugin.BaseRequest {
HttpPlugin.RequestFactory reqFactory = mAPIClient.getRequestFactory();
T result = default(T);
if (null == reqFactory) {
return result;
}
switch (method) {
case HttpMethod.GET:
result = (T)reqFactory.newGetRequest(url, headers);
break;
case HttpMethod.POST:
result = (T)reqFactory.newPostRequest(url, headers);
break;
case HttpMethod.DELETE:
result = (T)reqFactory.newDeleteRequest(url, headers);
break;
case HttpMethod.PUT:
result = (T)reqFactory.newPutRequest(url, headers);
break;
}
return result;
}
internal static readonly string HEADER_CONTENT_TYPE = "Content-Type";
internal static readonly string HEADER_CONTENT_LENGTH = "Content-Length";
internal static readonly string HEADER_CONTENT_DISPOSITION = "Content-Disposition";
internal static readonly string HEADER_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding";
internal static readonly string HEADER_COOKIE = "Cookie";
internal static readonly string CONTENT_TYPE_CHARSET_SUFFIX_UTF8 = "; charset=utf-8";
internal static readonly string HEADER_TRANSFER_ENCODING = "Transfer-Encoding";
internal static readonly string TRANSFER_ENCODING_CHUNKED = "chunked";
private T newEndPointRequest<T>(string urlSuffix, HttpMethod method, string[,] headers) where T : HttpPlugin.BaseRequest {
T result = default(T);
string restUrl = toRESTUrl(urlSuffix);
if (null == restUrl) {
return result;
}
return newRequest<T>(restUrl, method, headers);
}
protected virtual HttpPlugin.GetRequest newGetRequest(string suffix, string[,] headers) {
return newEndPointRequest<HttpPlugin.GetRequest>(suffix, HttpMethod.GET, headers);
}
protected virtual HttpPlugin.PostRequest newPostRequest(string suffix, string[,] headers) {
return newEndPointRequest<HttpPlugin.PostRequest>(suffix, HttpMethod.POST, headers);
}
protected virtual HttpPlugin.DeleteRequest newDeleteRequest(string suffix, string[,] headers) {
return newEndPointRequest<HttpPlugin.DeleteRequest>(suffix, HttpMethod.DELETE, headers);
}
protected virtual HttpPlugin.PutRequest newPutRequest(string suffix, string[,] headers) {
return newEndPointRequest<HttpPlugin.PutRequest>(suffix, HttpMethod.PUT, headers);
}
private WebRequest initConnection(WebRequest con) {
return con;
}
protected virtual string toCookieString(string[,] cookies) {
string cookieStr = "";
if (null != cookies) {
for (int i = 0; i < cookies.Length; i += 2) {
if (i > 0) {
cookieStr += "; ";
}
cookieStr += cookies[i, 0] + "=" + cookies[i, 1];
}
}
return cookieStr;
}
protected virtual void destroy(HttpPlugin.BaseRequest request) {
Log.d(TAG, "Disconnecting " + request);
if (null != request) {
request.destroy();
}
}
protected virtual void writeBytes(HttpPlugin.WritableRequest request, byte[] data, string debugMsg) {
int len = data.Length;
if (null != debugMsg) {
Log.d(TAG, "Writing len: " + len + " msg: " + debugMsg);
}
MemoryStream bis = new MemoryStream(data);
request.output(bis, mIOBuf);
bis.Close();
}
public byte[] getIOBuf() {
return mIOBuf;
}
private string readHttpStream(Stream stream, string debugMsg) {
StreamReader bos = new StreamReader(stream);
string result = bos.ReadToEnd();
bos.Close();
if (null != debugMsg) {
Log.d(TAG, "readHttpStream str: " + result + " msg: " + debugMsg);
}
return result;
}
private bool closeInputStream(Stream stream) {
if (null == stream) {
return false;
}
stream.Close();
return true;
}
protected virtual string readHttpStream(HttpPlugin.ReadableRequest request, string debugMsg) {
Stream input = null;
try {
input = request.input();
if (null == input) {
return null;
}
return readHttpStream(input, debugMsg);
} finally {
closeInputStream(input);
}
}
protected virtual void writeHttpStream(HttpPlugin.WritableRequest request, Stream input) {
Log.d(TAG, "Writing input stream to output stream " + request);
request.output(input, mIOBuf);
Log.d(TAG, "Done writing to stream " + request);
}
protected override void recycle() {
base.recycle();
mCallbackHolder.clearNoLock();
}
protected virtual void set(object callback, SynchronizationContext handler, object closure) {
mCallbackHolder.setNoLock(callback, handler, closure);
}
protected virtual void set(ResultCallbackHolder callbackHolder) {
mCallbackHolder.copyFromNoLock(callbackHolder);
}
public object getClosure() {
return mCallbackHolder.getClosureNoLock();
}
private SynchronizationContext getHandler() {
return mCallbackHolder.getHandlerNoLock();
}
internal static readonly string HYPHENS = "--";
internal static readonly string QUOTE = "\"";
internal static readonly string ENDL = "\r\n";
protected static string headersToString(string[,] headers) {
if (null == headers) {
return null;
}
int len = headers.Length;
if (len < 1) {
return null;
}
string result = string.Empty;
for (int i = 0; i < headers.Length; i += 1) {
string attr = headers[i, 0];
string value = headers[i, 1];
result += attr + ": " + value + ENDL;
}
return result;
}
private static string makeBoundary() {
return Guid.NewGuid().ToString();
}
protected virtual bool setupPost(WebRequest connection, string contentType, bool includeApiKey, string[][] args) {
connection.Method = "POST";
if (null != contentType) {
connection.ContentType = contentType;
}
if (includeApiKey) {
connection.Headers.Add("X-API-KEY", mAPIClient.getApiKey());
}
if (null != args) {
foreach (string[] arg in args) {
connection.Headers.Add(arg[0], arg[1]);
}
}
return true;
}
protected virtual WebRequest newConnection(string suffix) {
string restUrl = toRESTUrl(suffix);
if (null == restUrl) {
return null;
}
WebRequest con = null;
try {
con = WebRequest.Create(restUrl);
} catch (Exception) {
return null;
}
return initConnection(con);
}
protected virtual bool writeJson(WebRequest connection, JObject jsonObject) {
Stream os = null;
StreamWriter sw = null;
bool success = true;
try {
os = connection.GetRequestStream();
sw = new StreamWriter(os);
string jsonStr = jsonObject.ToString();
sw.Write(jsonStr);
sw.Flush();
} catch (Exception) {
success = false;
} finally {
if (null != sw) {
sw.Dispose();
}
if (null != os) {
os.Dispose();
}
}
return success;
}
protected class SplitStream : Stream {
private class LengthHolder {
private long mTotal, mAvailable;
public void setTotal(long total) {
mTotal = total;
}
public long getAvailable() {
return mAvailable;
}
public void onRead(int len) {
if (-1 == len) {
mAvailable = 0;
} else {
mAvailable = Math.Max(0, mAvailable - len);
}
}
public void renew() {
mAvailable = mTotal;
}
}
private readonly LengthHolder mChunkInfo = new LengthHolder(), mBaseInfo = new LengthHolder();
private readonly Stream mBase;
public SplitStream(Stream aBase, long totalLen, long chunkLen) {
mBase = aBase;
mChunkInfo.setTotal(chunkLen);
mBaseInfo.setTotal(totalLen);
mBaseInfo.renew();
}
public virtual long availableAsLong() {
long a = mChunkInfo.getAvailable();
long b = mBaseInfo.getAvailable();
return Math.Min(a, b);
}
public virtual void renew() {
mChunkInfo.renew();
}
private void onRead(int len) {
mChunkInfo.onRead(len);
mBaseInfo.onRead(len);
}
protected virtual bool canContinue() {
return true;
}
public override bool CanRead {
get {
return true;
}
}
public override bool CanSeek {
get {
return false;
}
}
public override bool CanWrite {
get {
return false;
}
}
public override void Flush() {
throw new NotImplementedException();
}
public override long Length {
get {
return availableAsLong();
}
}
public override long Position {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public override int Read(byte[] buffer, int byteOffset, int byteCount) {
long available = availableAsLong();
if (!canContinue()) {
Log.d(TAG, "Cannot continue, available: " + available);
return -1;
}
byteOffset = Math.Max(byteOffset, 0);
int bufAvailable = Math.Min(buffer.Length - byteOffset, byteCount);
int canRead = (int)Math.Min(bufAvailable, available);
Log.d(TAG, "Split pre read buf remaining: " + available + " canRead: " +
canRead + " byteCount: " + byteCount + " byteOffset: " + byteOffset);
if (canRead < 1) {
return -1;
}
int wasRead = mBase.Read(buffer, byteOffset, canRead);
onRead(wasRead);
Log.d(TAG, "Split post read buf remaining: " + availableAsLong() + " canRead: " +
canRead + " wasRead: " + wasRead + " byteCount: " + byteCount +
" byteOffset: " + byteOffset);
return wasRead;
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotImplementedException();
}
public override void SetLength(long value) {
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count) {
throw new NotImplementedException();
}
}
internal class HttpUploadStream : Stream {
private readonly ByteArrayHolder[] mBufs = new ByteArrayHolder[3] { new ByteArrayHolder(true), new ByteArrayHolder(false), new ByteArrayHolder(true) };
private class ByteArrayHolder {
internal readonly bool mIsPseudo;
internal ByteArrayHolder(bool isPseudo) {
mIsPseudo = isPseudo;
clear();
}
private byte[] mArray;
int mMark, mLen;
internal int set(byte[] array, int offset, int len) {
mLen = len;
mArray = array;
mMark = 0;
return mLen;
}
internal int available() {
return mLen - mMark;
}
internal int set(byte[] array) {
if (null == array) {
return set(null, 0, 0);
} else {
return set(array, 0, array.Length);
}
}
internal void clear() {
set(null, 0, 0);
}
internal int read(byte[] dst, int dstOffset, int dstCount) {
if (null != mArray) {
int remain = available();
if (remain > 0) {
int toCopy = Math.Min(remain, dstCount);
Array.Copy(mArray, mMark, dst, dstOffset, toCopy);
mMark += toCopy;
return toCopy;
}
}
return 0;
}
}
public override long Position {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public override long Length {
get {
return 0;
}
}
public override bool CanRead {
get {
return true;
}
}
public override bool CanSeek {
get {
return false;
}
}
public override bool CanWrite {
get {
return false;
}
}
public override void Flush() {
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotImplementedException();
}
public override void SetLength(long value) {
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count) {
throw new NotImplementedException();
}
public override void Close() {
}
public override int Read(byte[] buffer, int byteOffset, int byteCount) {
if (buffer.Length < (byteOffset + byteCount)) {
throw new IOException();
}
int canRead = byteCount;
int totalRead = 0;
while (canContinue() && canRead > 0 && ensureAvailable()) {
int read = 0;
for (int i = 0; i < mBufs.Length; i += 1) {
ByteArrayHolder holder = mBufs[i];
if (holder.available() > 0) {
int offset = byteOffset + totalRead + read;
int thisRead = holder.read(buffer, offset, canRead);
if (thisRead > 0) {
canRead -= thisRead;
onProvided(holder, buffer, offset, thisRead);
read += thisRead;
}
}
}
totalRead += read;
}
if (totalRead < 1) {
totalRead = -1;
}
onProgress(mProvidedSoFar, totalRead > 0);
return totalRead;
}
private long mProvidedSoFar = 0;
private bool ensureAvailable() {
long available = mBufs[0].available() + mBufs[1].available() + mBufs[2].available();
if (available > 0) {
return true;
}
mBufs[0].clear();
mBufs[1].clear();
mBufs[2].clear();
int read = mInner.Read(mIOBuf, 0, mIOBuf.Length);
if (read < 1) {
return false;
}
available = 0;
if (mIsChunked) {
byte[] header = System.Text.Encoding.UTF8.GetBytes(read.ToString() + ClientWorkItem.ENDL);
available += mBufs[0].set(header);
available += mBufs[2].set(System.Text.Encoding.UTF8.GetBytes(ClientWorkItem.ENDL));
}
available += mBufs[1].set(mIOBuf, 0, read);
return available > 0;
}
protected bool isChunked() {
return mIsChunked;
}
private void onProvided(ByteArrayHolder holder, byte[] data, int offset, int len) {
if (!holder.mIsPseudo) {
onBytesProvided(data, offset, len);
mProvidedSoFar += len;
}
}
protected virtual void onBytesProvided(byte[] data, int offset, int len) {
}
protected virtual void onProgress(long providedSoFar, bool isEOF) {
}
protected virtual bool canContinue() {
return true;
}
private readonly Stream mInner;
private readonly bool mIsChunked;
private readonly byte[] mIOBuf;
protected HttpUploadStream(Stream inner, byte[] ioBuf, bool isChunked) {
mInner = inner;
mIsChunked = isChunked;
mIOBuf = null == ioBuf ? new byte[8192] : ioBuf;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public struct AssemblyReference
{
private readonly MetadataReader _reader;
// Workaround: JIT doesn't generate good code for nested structures, so use raw uint.
private readonly uint _treatmentAndRowId;
private static readonly Version s_version_4_0_0_0 = new Version(4, 0, 0, 0);
internal AssemblyReference(MetadataReader reader, uint treatmentAndRowId)
{
Debug.Assert(reader != null);
Debug.Assert(treatmentAndRowId != 0);
// only virtual bit can be set in highest byte:
Debug.Assert((treatmentAndRowId & ~(TokenTypeIds.VirtualBit | TokenTypeIds.RIDMask)) == 0);
_reader = reader;
_treatmentAndRowId = treatmentAndRowId;
}
private int RowId
{
get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); }
}
private bool IsVirtual
{
get { return (_treatmentAndRowId & TokenTypeIds.VirtualBit) != 0; }
}
public Version Version
{
get
{
if (IsVirtual)
{
return GetVirtualVersion();
}
// change mscorlib version:
if (RowId == _reader.WinMDMscorlibRef)
{
return s_version_4_0_0_0;
}
return _reader.AssemblyRefTable.GetVersion(RowId);
}
}
public AssemblyFlags Flags
{
get
{
if (IsVirtual)
{
return GetVirtualFlags();
}
return _reader.AssemblyRefTable.GetFlags(RowId);
}
}
public StringHandle Name
{
get
{
if (IsVirtual)
{
return GetVirtualName();
}
return _reader.AssemblyRefTable.GetName(RowId);
}
}
public StringHandle Culture
{
get
{
if (IsVirtual)
{
return GetVirtualCulture();
}
return _reader.AssemblyRefTable.GetCulture(RowId);
}
}
public BlobHandle PublicKeyOrToken
{
get
{
if (IsVirtual)
{
return GetVirtualPublicKeyOrToken();
}
return _reader.AssemblyRefTable.GetPublicKeyOrToken(RowId);
}
}
public BlobHandle HashValue
{
get
{
if (IsVirtual)
{
return GetVirtualHashValue();
}
return _reader.AssemblyRefTable.GetHashValue(RowId);
}
}
public CustomAttributeHandleCollection GetCustomAttributes()
{
if (IsVirtual)
{
return GetVirtualCustomAttributes();
}
return new CustomAttributeHandleCollection(_reader, AssemblyReferenceHandle.FromRowId(RowId));
}
#region Virtual Rows
private Version GetVirtualVersion()
{
// currently all projected assembly references have version 4.0.0.0
return s_version_4_0_0_0;
}
private AssemblyFlags GetVirtualFlags()
{
// use flags from mscorlib ref (specifically PublicKey flag):
return _reader.AssemblyRefTable.GetFlags(_reader.WinMDMscorlibRef);
}
private StringHandle GetVirtualName()
{
return StringHandle.FromVirtualIndex(GetVirtualNameIndex((AssemblyReferenceHandle.VirtualIndex)RowId));
}
private StringHandle.VirtualIndex GetVirtualNameIndex(AssemblyReferenceHandle.VirtualIndex index)
{
switch (index)
{
case AssemblyReferenceHandle.VirtualIndex.System_ObjectModel:
return StringHandle.VirtualIndex.System_ObjectModel;
case AssemblyReferenceHandle.VirtualIndex.System_Runtime:
return StringHandle.VirtualIndex.System_Runtime;
case AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime:
return StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime;
case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime:
return StringHandle.VirtualIndex.System_Runtime_WindowsRuntime;
case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml:
return StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml;
case AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors:
return StringHandle.VirtualIndex.System_Numerics_Vectors;
}
Debug.Assert(false, "Unexpected virtual index value");
return 0;
}
private StringHandle GetVirtualCulture()
{
return default(StringHandle);
}
private BlobHandle GetVirtualPublicKeyOrToken()
{
switch ((AssemblyReferenceHandle.VirtualIndex)RowId)
{
case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime:
case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml:
// use key or token from mscorlib ref:
return _reader.AssemblyRefTable.GetPublicKeyOrToken(_reader.WinMDMscorlibRef);
default:
// use contract assembly key or token:
var hasFullKey = (_reader.AssemblyRefTable.GetFlags(_reader.WinMDMscorlibRef) & AssemblyFlags.PublicKey) != 0;
return BlobHandle.FromVirtualIndex(hasFullKey ? BlobHandle.VirtualIndex.ContractPublicKey : BlobHandle.VirtualIndex.ContractPublicKeyToken, 0);
}
}
private BlobHandle GetVirtualHashValue()
{
return default(BlobHandle);
}
private CustomAttributeHandleCollection GetVirtualCustomAttributes()
{
// return custom attributes applied on mscorlib ref
return new CustomAttributeHandleCollection(_reader, AssemblyReferenceHandle.FromRowId(_reader.WinMDMscorlibRef));
}
#endregion
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.lang
{
public class Runtime
{
public static object getField(haxe.lang.HxObject obj, string field, int fieldHash, bool throwErrors)
{
if (obj == null && !throwErrors) return null;
return obj.__hx_getField(field, (fieldHash == 0) ? haxe.lang.FieldLookup.hash(field) : fieldHash, throwErrors, false, false);
}
public static double getField_f(haxe.lang.HxObject obj, string field, int fieldHash, bool throwErrors)
{
if (obj == null && !throwErrors) return 0.0;
return obj.__hx_getField_f(field, (fieldHash == 0) ? haxe.lang.FieldLookup.hash(field) : fieldHash, throwErrors, false);
}
public static object setField(haxe.lang.HxObject obj, string field, int fieldHash, object value)
{
return obj.__hx_setField(field, (fieldHash == 0) ? haxe.lang.FieldLookup.hash(field) : fieldHash, value, false);
}
public static double setField_f(haxe.lang.HxObject obj, string field, int fieldHash, double value)
{
return obj.__hx_setField_f(field, (fieldHash == 0) ? haxe.lang.FieldLookup.hash(field) : fieldHash, value, false);
}
public static object callField(haxe.lang.HxObject obj, string field, int fieldHash, Array args)
{
return obj.__hx_invokeField(field, (fieldHash == 0) ? haxe.lang.FieldLookup.hash(field) : fieldHash, args);
}
static Runtime()
{
#line 69 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
global::haxe.lang.Runtime.undefined = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{}), new global::Array<object>(new object[]{}), new global::Array<int>(new int[]{}), new global::Array<double>(new double[]{}));
}
public Runtime()
{
unchecked
{
#line 67 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
{
}
}
#line default
}
public static object undefined;
public static object closure(object obj, int hash, string field)
{
return new haxe.lang.Closure(obj, field, hash);
}
public static bool eq(object v1, object v2)
{
if (System.Object.ReferenceEquals(v1, v2))
return true;
if (v1 == null || v2 == null)
return false;
System.IConvertible v1c = v1 as System.IConvertible;
if (v1c != null)
{
System.IConvertible v2c = v2 as System.IConvertible;
if (v2c == null)
{
return false;
}
System.TypeCode t1 = v1c.GetTypeCode();
System.TypeCode t2 = v2c.GetTypeCode();
if (t1 == t2)
return v1c.Equals(v2c);
switch(t1)
{
case System.TypeCode.Int64:
case System.TypeCode.UInt64:
return v1c.ToUInt64(null) == v2c.ToUInt64(null);
default:
return v1c.ToDouble(null) == v2c.ToDouble(null);
}
}
System.ValueType v1v = v1 as System.ValueType;
if (v1v != null)
{
return v1.Equals(v2);
} else {
System.Type v1t = v1 as System.Type;
if (v1t != null)
{
System.Type v2t = v2 as System.Type;
if (v2t != null)
return typeEq(v1t, v2t);
return false;
}
}
return false;
}
public static bool refEq(object v1, object v2)
{
if (v1 is System.Type)
return typeEq(v1 as System.Type, v2 as System.Type);
return System.Object.ReferenceEquals(v1, v2);
}
public static double toDouble(object obj)
{
return (obj == null) ? 0.0 : (obj is double) ? (double)obj : ((System.IConvertible) obj).ToDouble(null);
}
public static int toInt(object obj)
{
return (obj == null) ? 0 : (obj is int) ? (int)obj : ((System.IConvertible) obj).ToInt32(null);
}
public static bool isInt(object obj)
{
System.IConvertible cv1 = obj as System.IConvertible;
if (cv1 != null)
{
switch (cv1.GetTypeCode())
{
case System.TypeCode.Double:
double d = (double)obj;
return d >= int.MinValue && d <= int.MaxValue && d == ( (int)d );
case System.TypeCode.UInt32:
case System.TypeCode.Int32:
return true;
default:
return false;
}
}
return false;
}
public static int compare(object v1, object v2)
{
if (v1 == v2) return 0;
if (v1 == null) return -1;
if (v2 == null) return 1;
System.IConvertible cv1 = v1 as System.IConvertible;
if (cv1 != null)
{
System.IConvertible cv2 = v2 as System.IConvertible;
if (cv2 == null)
{
throw new System.ArgumentException("Cannot compare " + v1.GetType().ToString() + " and " + v2.GetType().ToString());
}
switch(cv1.GetTypeCode())
{
case System.TypeCode.String:
if (cv2.GetTypeCode() != System.TypeCode.String)
throw new System.ArgumentException("Cannot compare " + v1.GetType().ToString() + " and " + v2.GetType().ToString());
string s1 = v1 as string;
string s2 = v2 as string;
int i =0;
int l1 = s1.Length;
int l2 = s2.Length;
bool active = true;
while(active)
{
char h1; char h2;
if (i >= l1)
{
h1 = (char) 0;
active = false;
} else {
h1 = s1[i];
}
if (i >= l2)
{
h2 = (char) 0;
active = false;
} else {
h2 = s2[i];
}
int v = h1 - h2;
if (v > 0)
return 1;
else if (v < 0)
return -1;
i++;
}
return 0;
case System.TypeCode.Double:
double d1 = (double) v1;
double d2 = cv2.ToDouble(null);
return (d1 < d2) ? -1 : (d1 > d2) ? 1 : 0;
default:
double d1d = cv1.ToDouble(null);
double d2d = cv2.ToDouble(null);
return (d1d < d2d) ? -1 : (d1d > d2d) ? 1 : 0;
}
}
System.IComparable c1 = v1 as System.IComparable;
System.IComparable c2 = v2 as System.IComparable;
if (c1 == null || c2 == null)
{
if (c1 == c2)
return 0;
throw new System.ArgumentException("Cannot compare " + v1.GetType().ToString() + " and " + v2.GetType().ToString());
}
return c1.CompareTo(c2);
}
public static object plus(object v1, object v2)
{
if (v1 is string || v2 is string)
return Std.@string(v1) + Std.@string(v2);
System.IConvertible cv1 = v1 as System.IConvertible;
if (cv1 != null)
{
System.IConvertible cv2 = v2 as System.IConvertible;
if (cv2 == null)
{
throw new System.ArgumentException("Cannot dynamically add " + v1.GetType().ToString() + " and " + v2.GetType().ToString());
}
return cv1.ToDouble(null) + cv2.ToDouble(null);
}
throw new System.ArgumentException("Cannot dynamically add " + v1 + " and " + v2);
}
public static object slowGetField(object obj, string field, bool throwErrors)
{
if (obj == null)
if (throwErrors)
throw new System.NullReferenceException("Cannot access field '" + field + "' of null.");
else
return null;
System.Type t = obj as System.Type;
System.Reflection.BindingFlags bf;
if (t == null)
{
string s = obj as string;
if (s != null)
return haxe.lang.StringRefl.handleGetField(s, field, throwErrors);
t = obj.GetType();
bf = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy;
} else {
if (obj == typeof(string) && field.Equals("fromCharCode"))
return new haxe.lang.Closure(typeof(haxe.lang.StringExt), field, 0);
obj = null;
bf = System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public;
}
System.Reflection.FieldInfo f = t.GetField(field, bf);
if (f != null)
{
return haxe.lang.Runtime.unbox(f.GetValue(obj));
} else {
System.Reflection.PropertyInfo prop = t.GetProperty(field, bf);
if (prop == null)
{
System.Reflection.MemberInfo[] m = t.GetMember(field, bf);
if (m.Length > 0)
{
return new haxe.lang.Closure(obj != null ? obj : t, field, 0);
} else {
if (throwErrors)
throw HaxeException.wrap("Cannot access field '" + field + "'.");
else
return null;
}
}
return haxe.lang.Runtime.unbox(prop.GetValue(obj, null));
}
}
public static bool slowHasField(object obj, string field)
{
if (obj == null) return false;
System.Type t = obj as System.Type;
System.Reflection.BindingFlags bf;
if (t == null)
{
string s = obj as string;
if (s != null)
return haxe.lang.StringRefl.handleGetField(s, field, false) != null;
t = obj.GetType();
bf = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy;
} else {
if (t == typeof(string))
return field.Equals("fromCharCode");
obj = null;
bf = System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public;
}
System.Reflection.MemberInfo[] mi = t.GetMember(field, bf);
return mi != null && mi.Length > 0;
}
public static object slowSetField(object obj, string field, object @value)
{
if (obj == null)
throw new System.NullReferenceException("Cannot access field '" + field + "' of null.");
System.Type t = obj as System.Type;
System.Reflection.BindingFlags bf;
if (t == null)
{
t = obj.GetType();
bf = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy;
} else {
obj = null;
bf = System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public;
}
System.Reflection.FieldInfo f = t.GetField(field, bf);
if (f != null)
{
if (f.FieldType.ToString().StartsWith("haxe.lang.Null"))
{
@value = haxe.lang.Runtime.mkNullable(@value, f.FieldType);
}
f.SetValue(obj, @value);
return @value;
} else {
System.Reflection.PropertyInfo prop = t.GetProperty(field, bf);
if (prop == null)
{
throw haxe.lang.HaxeException.wrap("Field '" + field + "' not found for writing from Class " + t);
}
if (prop.PropertyType.ToString().StartsWith("haxe.lang.Null"))
{
@value = haxe.lang.Runtime.mkNullable(@value, prop.PropertyType);
}
prop.SetValue(obj, @value, null);
return @value;
}
}
public static object callMethod(object obj, global::System.Reflection.MethodBase[] methods, int methodLength, global::Array args)
{
unchecked
{
#line 421 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
if (( methodLength == 0 ))
{
#line 421 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
throw global::haxe.lang.HaxeException.wrap("No available methods");
}
int length = ((int) (global::haxe.lang.Runtime.getField_f(args, "length", 520590566, true)) );
object[] oargs = new object[((int) (length) )];
global::System.Type[] ts = new global::System.Type[((int) (length) )];
int[] rates = new int[((int) (( methods as global::System.Array ).Length) )];
#line 427 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
{
#line 427 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int _g = 0;
#line 427 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
while (( _g < ((int) (length) ) ))
{
#line 427 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int i = _g++;
#line 429 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
oargs[i] = args[i];
if (( ! (global::haxe.lang.Runtime.eq(args[i], default(object))) ))
{
ts[i] = global::cs.Lib.nativeType(args[i]);
}
}
}
#line 434 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int last = 0;
#line 437 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
if (( methodLength > 1 ))
{
#line 439 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
{
#line 439 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int _g1 = 0;
#line 439 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
while (( _g1 < methodLength ))
{
#line 439 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int i1 = _g1++;
#line 441 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
global::System.Reflection.ParameterInfo[] @params = methods[i1].GetParameters();
if (( ( @params as global::System.Array ).Length != length ))
{
continue;
}
else
{
#line 445 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
bool fits = true;
#line 445 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int crate = 0;
{
#line 446 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int _g2 = 0;
#line 446 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int _g11 = ( @params as global::System.Array ).Length;
#line 446 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
while (( _g2 < _g11 ))
{
#line 446 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int i2 = _g2++;
#line 448 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
global::System.Type param = @params[i2].ParameterType;
string strParam = global::haxe.lang.Runtime.concat(global::Std.@string(param), "");
if (param.IsAssignableFrom(((global::System.Type) (ts[i2]) )))
{
#line 453 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
continue;
}
else
{
if (( strParam.StartsWith("haxe.lang.Null") || ( (( global::haxe.lang.Runtime.eq(oargs[i2], default(object)) || ( oargs[i2] is global::System.IConvertible ) )) && (((global::System.Type) (typeof(global::System.IConvertible)) )).IsAssignableFrom(((global::System.Type) (param) )) ) ))
{
#line 457 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
crate++;
continue;
}
else
{
if ( ! (param.ContainsGenericParameters) )
{
fits = false;
break;
}
}
}
}
}
#line 465 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
if (fits)
{
#line 467 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
rates[last] = crate;
methods[last++] = methods[i1];
}
}
}
}
#line 473 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
methodLength = last;
}
else
{
if (( ( methodLength == 1 ) && ( ( methods[0].GetParameters() as global::System.Array ).Length != length ) ))
{
methodLength = 0;
}
}
#line 483 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
if (( methodLength == 0 ))
{
throw global::haxe.lang.HaxeException.wrap(global::haxe.lang.Runtime.concat("Invalid calling parameters for method ", ( methods[0] as global::System.Reflection.MemberInfo ).Name));
}
#line 486 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
double best = global::Math.POSITIVE_INFINITY;
int bestMethod = 0;
{
#line 488 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int _g3 = 0;
#line 488 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
while (( _g3 < methodLength ))
{
#line 488 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int i3 = _g3++;
#line 490 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
if (( rates[i3] < best ))
{
#line 492 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
bestMethod = i3;
best = ((double) (rates[i3]) );
}
}
}
#line 497 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
methods[0] = methods[bestMethod];
global::System.Reflection.ParameterInfo[] params1 = methods[0].GetParameters();
{
#line 499 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int _g12 = 0;
#line 499 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int _g4 = ( params1 as global::System.Array ).Length;
#line 499 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
while (( _g12 < _g4 ))
{
#line 499 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int i4 = _g12++;
#line 501 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
global::System.Type param1 = params1[i4].ParameterType;
string strParam1 = global::haxe.lang.Runtime.concat(global::Std.@string(param1), "");
if (strParam1.StartsWith("haxe.lang.Null"))
{
#line 505 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
oargs[i4] = global::haxe.lang.Runtime.mkNullable(oargs[i4], param1);
}
else
{
if ((((global::System.Type) (typeof(global::System.IConvertible)) )).IsAssignableFrom(((global::System.Type) (param1) )))
{
if (global::haxe.lang.Runtime.eq(oargs[i4], default(object)))
{
if (param1.IsValueType)
{
oargs[i4] = global::System.Activator.CreateInstance(((global::System.Type) (param1) ));
}
}
else
{
#line 511 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
oargs[i4] = (((global::System.IConvertible) (oargs[i4]) )).ToType(((global::System.Type) (param1) ), ((global::System.IFormatProvider) (default(global::System.IFormatProvider)) ));
}
}
}
}
}
#line 516 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
if (( methods[0].ContainsGenericParameters && ( methods[0] is global::System.Reflection.MethodInfo ) ))
{
#line 518 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
global::System.Reflection.MethodInfo m = ((global::System.Reflection.MethodInfo) (methods[0]) );
global::System.Type[] tgs = ( m as global::System.Reflection.MethodBase ).GetGenericArguments();
{
#line 520 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int _g13 = 0;
#line 520 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int _g5 = ( tgs as global::System.Array ).Length;
#line 520 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
while (( _g13 < _g5 ))
{
#line 520 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
int i5 = _g13++;
#line 522 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
tgs[i5] = typeof(object);
}
}
#line 524 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
m = m.MakeGenericMethod(((global::System.Type[]) (tgs) ));
object retg = ( m as global::System.Reflection.MethodBase ).Invoke(((object) (obj) ), ((object[]) (oargs) ));
return global::haxe.lang.Runtime.unbox(retg);
}
#line 529 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
global::System.Reflection.MethodBase m1 = methods[0];
if (( global::haxe.lang.Runtime.eq(obj, default(object)) && ( m1 is global::System.Reflection.ConstructorInfo ) ))
{
#line 532 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
object ret = (((global::System.Reflection.ConstructorInfo) (m1) )).Invoke(((object[]) (oargs) ));
return global::haxe.lang.Runtime.unbox(ret);
}
#line 536 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
object ret1 = m1.Invoke(((object) (obj) ), ((object[]) (oargs) ));
return global::haxe.lang.Runtime.unbox(ret1);
}
#line default
}
public static object unbox(object dyn)
{
unchecked
{
#line 542 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
if (( ( ! (global::haxe.lang.Runtime.eq(dyn, default(object))) ) && (global::haxe.lang.Runtime.concat(global::Std.@string(global::cs.Lib.nativeType(dyn)), "")).StartsWith("haxe.lang.Null") ))
{
#line 544 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
return ((object) (global::haxe.lang.Runtime.callField(dyn, "toDynamic", 1705629508, default(global::Array))) );
}
else
{
#line 546 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
return dyn;
}
}
#line default
}
public static object mkNullable(object obj, global::System.Type nullableType)
{
if (nullableType.ContainsGenericParameters)
return haxe.lang.Null<object>.ofDynamic<object>(obj);
return nullableType.GetMethod("_ofDynamic").Invoke(null, new object[] { obj });
}
public static object slowCallField(object obj, string field, global::Array args)
{
if (field == "toString")
{
if (args == null)
return obj.ToString();
field = "ToString";
}
if (args == null) args = new Array<object>();
System.Reflection.BindingFlags bf;
System.Type t = obj as System.Type;
if (t == null)
{
string s = obj as string;
if (s != null)
return haxe.lang.StringRefl.handleCallField(s, field, args);
t = obj.GetType();
bf = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy;
} else {
if (t == typeof(string) && field.Equals("fromCharCode"))
return haxe.lang.StringExt.fromCharCode(toInt(args[0]));
obj = null;
bf = System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public;
}
System.Reflection.MethodInfo[] mis = t.GetMethods(bf);
int last = 0;
for (int i = 0; i < mis.Length; i++)
{
if (mis[i].Name.Equals(field))
{
mis[last++] = mis[i];
}
}
if (last == 0)
{
throw haxe.lang.HaxeException.wrap("Method '" + field + "' not found on type " + t);
}
return haxe.lang.Runtime.callMethod(obj, mis, last, args);
}
public static object callField(object obj, string field, int fieldHash, global::Array args)
{
haxe.lang.HxObject hxObj = obj as haxe.lang.HxObject;
if (hxObj != null)
return hxObj.__hx_invokeField(field, (fieldHash == 0) ? haxe.lang.FieldLookup.hash(field) : fieldHash, args);
return slowCallField(obj, field, args);
}
public static object getField(object obj, string field, int fieldHash, bool throwErrors)
{
haxe.lang.HxObject hxObj = obj as haxe.lang.HxObject;
if (hxObj != null)
return hxObj.__hx_getField(field, (fieldHash == 0) ? haxe.lang.FieldLookup.hash(field) : fieldHash, throwErrors, false, false);
return slowGetField(obj, field, throwErrors);
}
public static double getField_f(object obj, string field, int fieldHash, bool throwErrors)
{
haxe.lang.HxObject hxObj = obj as haxe.lang.HxObject;
if (hxObj != null)
return hxObj.__hx_getField_f(field, (fieldHash == 0) ? haxe.lang.FieldLookup.hash(field) : fieldHash, throwErrors, false);
return (double)slowGetField(obj, field, throwErrors);
}
public static object setField(object obj, string field, int fieldHash, object @value)
{
haxe.lang.HxObject hxObj = obj as haxe.lang.HxObject;
if (hxObj != null)
return hxObj.__hx_setField(field, (fieldHash == 0) ? haxe.lang.FieldLookup.hash(field) : fieldHash, value, false);
return slowSetField(obj, field, value);
}
public static double setField_f(object obj, string field, int fieldHash, double @value)
{
haxe.lang.HxObject hxObj = obj as haxe.lang.HxObject;
if (hxObj != null)
return hxObj.__hx_setField_f(field, (fieldHash == 0) ? haxe.lang.FieldLookup.hash(field) : fieldHash, value, false);
return (double)slowSetField(obj, field, value);
}
public static string toString(object obj)
{
unchecked
{
#line 678 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
if (global::haxe.lang.Runtime.eq(obj, default(object)))
{
return default(string);
}
if (( obj is bool ))
{
if (((bool) ((obj)) ))
{
return "true";
}
else
{
#line 684 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
return "false";
}
}
#line 686 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Runtime.hx"
return obj.ToString();
}
#line default
}
public static bool typeEq(global::System.Type t1, global::System.Type t2)
{
if (t1 == null || t2 == null)
return t1 == t2;
string n1 = Type.getClassName(t1);
string n2 = Type.getClassName(t2);
return n1.Equals(n2);
}
public static To genericCast<To>(object obj)
{
if (obj is To)
return (To) obj;
else if (obj == null)
return default(To);
if (typeof(To) == typeof(double))
return (To)(object) toDouble(obj);
else if (typeof(To) == typeof(int))
return (To)(object) toInt(obj);
else
return (To) obj;
}
public static string concat(string s1, string s2)
{
return (s1 == null ? "null" : s1) + (s2 == null ? "null" : s2);
}
}
}
namespace haxe.lang
{
public enum EmptyObject
{
EMPTY
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Ankh.Pusher.Core;
namespace Ankh.Pusher
{
public partial class ChPanel : UserControl
{
private Channel m_Channel;
public event ChannelProfileChangedEventHandler ProfileChanged;
public ChPanel()
{
ListBox.CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
}
public ushort ChannelID
{
get
{
if (m_Channel == null)
return 0;
return m_Channel.ChannelID;
}
set
{
if (m_Channel == null)
{
m_Channel = new Channel();
m_Channel.ChannelID = value;
try
{
m_Channel.Profile.LoadFromFile();
InitUI();
}
catch (NoConfigFileException)
{
}
m_Channel.ShowMessage += new MessageHandler(m_Channel_ShowMessage);
m_Channel.NewFile += new NewFileEventHandler(m_Channel_NewFile);
}
}
}
void m_Channel_NewFile(object Sender, NewFileArgs e)
{
bool bFound = false;
foreach(ListViewItem item in lvFiles.Items)
{
if (item.Tag.ToString() == e.File.ID && !bFound)
{
item.SubItems[3].Text = "Playing";
bFound = true;
}
else
{
item.SubItems[3].Text = "";
}
}
}
public Channel Channel
{
get { return m_Channel; }
}
#region init ui
private void InitUI()
{
InitProperty();
InitSource();
RefreshStatus();
}
private void InitProperty()
{
tChID.Text = m_Channel.ChannelID.ToString();
tChName.Text = lblName.Text = m_Channel.Profile.Name;
tPubName.Text = m_Channel.Profile.Publisher;
tInfo.Text = m_Channel.Profile.Info;
cbType.SelectedIndex = (int)m_Channel.Profile.ChannelType;
tCacheSrvIP.Text = m_Channel.Profile.CacheSrvIP;
tCacheSrvPort.Text = m_Channel.Profile.CacheSrvPort.ToString();
}
private void InitSource()
{
tLiveSrvIP.Text = m_Channel.Profile.LiveSrvIP;
tLiveSrvPort.Text = m_Channel.Profile.LiveSrvPort.ToString();
for (int i = 0; i < m_Channel.Profile.Files.Count; i++)
{
ListViewItem item = new ListViewItem();
item.Text = (i + 1).ToString();
item.SubItems.Add(m_Channel.Profile.Files[i].FileName);
item.SubItems.Add(m_Channel.Profile.Files[i].Duration.ToString());
item.SubItems.Add("");
item.Tag = m_Channel.Profile.Files[i].ID;
lvFiles.Items.Add(item);
}
}
#endregion
private void RefreshStatus()
{
if (m_Channel == null)
return;
lblStatus.Text = m_Channel.Status.ToString();
lblName.Text = m_Channel.Profile.Name;
lblType.Text = m_Channel.Profile.ChannelType.ToString();
if (m_Channel.Status == Status.Running || m_Channel.Status == Status.Error)
{
btStart.Enabled = false;
btStop.Enabled = true;
}
else
{
btStart.Enabled = true;
btStop.Enabled = false;
}
}
#region Apply
private void ApplyProperty()
{
try
{
m_Channel.ChannelID = ushort.Parse(tChID.Text);
m_Channel.Profile.Name = tChName.Text;
m_Channel.Profile.ChannelType = (ChannelType)cbType.SelectedIndex;
m_Channel.Profile.Info = tInfo.Text;
m_Channel.Profile.Publisher = tPubName.Text;
m_Channel.Profile.LiveSrvIP = tLiveSrvIP.Text;
m_Channel.Profile.LiveSrvPort = ushort.Parse(tLiveSrvPort.Text);
m_Channel.Profile.CacheSrvIP = tCacheSrvIP.Text;
m_Channel.Profile.CacheSrvPort = ushort.Parse(tCacheSrvPort.Text);
m_Channel.Profile.WriteToFile();
}
catch (Exception e)
{
MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ApplySource()
{
try
{
m_Channel.Profile.LiveSrvIP = tLiveSrvIP.Text;
m_Channel.Profile.LiveSrvPort = ushort.Parse(tLiveSrvPort.Text);
m_Channel.Profile.Files.Clear();
foreach (ListViewItem item in lvFiles.Items)
{
MediaFile mFile = new MediaFile();
mFile.ID = item.Tag.ToString();
mFile.FileName = item.SubItems[1].Text;
mFile.Duration = TimeSpan.Parse(item.SubItems[2].Text);
m_Channel.Profile.Files.Add(mFile );
}
m_Channel.Profile.WriteToFile();
}
catch (Exception e)
{
MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
private void btProCancel_Click(object sender, EventArgs e)
{
InitProperty();
}
private void btMdCancel_Click(object sender, EventArgs e)
{
InitSource();
}
private void btMdApply_Click(object sender, EventArgs e)
{
ApplySource();
}
private void btProAppy_Click(object sender, EventArgs e)
{
ApplyProperty();
RefreshStatus();
OnProfileChanged();
}
private void btStart_Click(object sender, EventArgs e)
{
if (m_Channel == null)
{
return;
}
m_Channel.Start();
RefreshStatus();
btStart.Enabled = false;
btStop.Enabled = true;
}
void m_Channel_ShowMessage(object Sender, string Message)
{
if (lbLog.Items.Count > 20)
lbLog.Items.RemoveAt(0);
lbLog.Items.Add(Message);
}
private void btStop_Click(object sender, EventArgs e)
{
m_Channel.Stop();
RefreshStatus();
btStop.Enabled = false;
btStart.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
try
{
RefreshStatus();
}
catch { }
}
private void lvFiles_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void OnProfileChanged()
{
if (ProfileChanged != null)
ProfileChanged(this,new ChannelArgs( m_Channel));
}
private void cmFileSource_Opening(object sender, CancelEventArgs e)
{
if (lvFiles.SelectedItems.Count == 0)
{
toolStripMenuItem2.Enabled = toolStripMenuItem3.Enabled = toolStripMenuItem4.Enabled = toolStripMenuItem5.Enabled = false;
}
else
{
toolStripMenuItem2.Enabled = toolStripMenuItem3.Enabled = toolStripMenuItem4.Enabled = toolStripMenuItem5.Enabled = true;
}
}
#region File Source Context menu
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
doAddFile();
}
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
doRemoveFile();
}
private void toolStripMenuItem3_Click(object sender, EventArgs e)
{
doUp();
}
private void toolStripMenuItem4_Click(object sender, EventArgs e)
{
doDown();
}
private void toolStripMenuItem5_Click(object sender, EventArgs e)
{
doRunThis();
}
private void btAddFile_Click(object sender, EventArgs e)
{
doAddFile();
}
private void btRemoveFile_Click(object sender, EventArgs e)
{
doRemoveFile();
}
private void btUp_Click(object sender, EventArgs e)
{
doUp();
}
private void btDown_Click(object sender, EventArgs e)
{
doDown();
}
private void ReindexFiles()
{
lvFiles.BeginUpdate();
m_Channel.Profile.Files.Clear();
foreach (ListViewItem item in lvFiles.Items)
{
MediaFile mFile = new MediaFile();
mFile.FileName = item.SubItems[1].Text;
mFile.ID = item.Tag.ToString();
mFile.Duration = TimeSpan.Parse(item.SubItems[2].Text);
m_Channel.Profile.Files.Add(mFile);
item.Text = (item.Index + 1).ToString();
}
lvFiles.EndUpdate();
}
private void doAddFile()
{
if (dlgOpen.ShowDialog(this) == DialogResult.OK)
{
foreach (string f in dlgOpen.FileNames)
{
try
{
MediaFile mFile = new MediaFile();
mFile.FileName = f;
mFile.ID = MediaFile.ComputeID(f);
AsfHeader header = new AsfHeader();
header.InitFromFile(f);
mFile.Duration = header.SendDuration;
if (header.MaxBitrate > 660 * 1024) //650Kbps
{
MessageBox.Show(string.Format("{0}'s Bitrate is too large!", f), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
continue;
}
lvFiles.BeginUpdate();
ListViewItem item = new ListViewItem();
item.Text = (lvFiles.Items.Count + 1).ToString();
item.SubItems.Add(mFile.FileName);
item.SubItems.Add(mFile.Duration.ToString());
item.SubItems.Add("");
item.Tag = mFile.ID;
lvFiles.Items.Add(item);
// m_Channel.Profile.Files.Add(mFile);
ReindexFiles();
lvFiles.EndUpdate();
}
catch (Exception e)
{
MessageBox.Show(e.Message,Application.ProductName,MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
}
private void doRemoveFile()
{
if (lvFiles.SelectedItems.Count == 0)
return;
ListViewItem item = lvFiles.SelectedItems[0];
if (item.SubItems[3].Text != "")
{
MessageBox.Show("Can't remove file while pushing!");
return;
}
item.Remove();
ReindexFiles();
}
private void doUp()
{
if (lvFiles.SelectedItems.Count == 0 || lvFiles.SelectedIndices[0] == 0)
return;
int index = lvFiles.SelectedItems[0].Index;
ListViewItem item = lvFiles.SelectedItems[0];
item.Remove();
lvFiles.Items.Insert(index - 1, item);
ReindexFiles();
}
private void doDown()
{
if (lvFiles.SelectedItems.Count == 0 || lvFiles.SelectedIndices[0] == lvFiles.Items.Count - 1)
return;
int index = lvFiles.SelectedItems[0].Index;
ListViewItem item = lvFiles.SelectedItems[0];
item.Remove();
lvFiles.Items.Insert(index + 1, item);
ReindexFiles();
}
private void doRunThis()
{
if (Channel == null || lvFiles.SelectedItems.Count == 0 || (Channel.Profile.Custom == lvFiles.SelectedItems[0].Tag.ToString() && Channel.Status == Status.Running))
return;
Channel.Profile.Custom = lvFiles.SelectedItems[0].Tag.ToString();
Channel.Stop();
System.Threading.Thread.Sleep(1000);
Channel.Start();
}
#endregion
private void tLiveSrvIP_TextChanged(object sender, EventArgs e)
{
ApplyProperty();
}
private void tLiveSrvPort_TextChanged(object sender, EventArgs e)
{
ApplyProperty();
}
private void tChID_TextChanged(object sender, EventArgs e)
{
}
private void cbType_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
public class ChannelArgs : EventArgs
{
private Channel m_Channel;
public Channel Channel
{
get { return m_Channel; }
set { m_Channel = value; }
}
public ChannelArgs(Channel ch)
{
m_Channel = ch;
}
}
public delegate void ChannelProfileChangedEventHandler(object Sender,ChannelArgs e);
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Qwack.Dates;
using Qwack.Transport.BasicTypes;
namespace Qwack.Futures
{
public class FutureSettings
{
private readonly ICalendarProvider _calendarProvider;
public List<string> Names { get; set; }
public FutureDatesGenerator ExpiryGen { get; set; }
public FutureDatesGenerator RollGen { get; set; }
public List<string> Months { get; set; }
public TimeZoneInfo TimeZone { get; set; }
public List<TimeSpan> MarketCloseTime { get; set; }
public List<DateTime> MarketOpenRulesValidUntil { get; set; }
public List<TimeSpan> MarketOpenTime { get; set; }
public List<int> MarketOpenModifier { get; set; }
public List<MarketOpenOverride> MarketOpenTimeOverride { get; set; }
public List<TimeSpan> MarketCloseVWAPLength { get; set; }
public List<DateTime> MarketCloseValidTo { get; set; }
public List<MarketShutRuleSet> MarketShutRules { get; set; }
public List<DateTime> MarketShutRulesValidUntil { get; set; }
public Dictionary<string,Dictionary<string,string>> CodeConversions { get; set; }
public double LotSize { get; set; }
public double PriceMultiplier { get; set; }
public double TickSize { get; set; }
public FutureOptionsGenerator Options { get; set; }
public FutureSettings(ICalendarProvider calendarProvider) => _calendarProvider = calendarProvider;
public override string ToString() => string.Join(",", Names);
public DateTime GetUTCCloseFromDay(DateTime date)
{
if (ExpiryGen.NeverExpires)
{
return date.Date.Add(new TimeSpan(23, 59, 59));
}
if (ExpiryGen.CalendarObject.IsHoliday(date))
{
date = date.AddDays(-1).AddPeriod(RollType.F, ExpiryGen.CalendarObject, new Frequency(1, DatePeriodType.B)).Date;
}
DateTime tempDate;
if ((MarketCloseValidTo.Count == 1) && (MarketCloseValidTo[0] == DateTime.MaxValue))
{
tempDate = new DateTime(date.Year, date.Month, date.Day, MarketCloseTime[0].Hours, MarketCloseTime[0].Minutes, MarketCloseTime[0].Seconds);
}
else
{
var q = MarketCloseValidTo.BinarySearch(date);
if (q < 0)
q = ~q;
tempDate = new DateTime(date.Year, date.Month, date.Day, MarketCloseTime[q].Hours, MarketCloseTime[q].Minutes, MarketCloseTime[q].Seconds);
}
return TimeZoneInfo.ConvertTimeToUtc(tempDate, TimeZone);
}
public bool IsOpenFromUTC(DateTime timeToCheck)
{
if ((MarketShutRulesValidUntil.Count == 1) && (MarketShutRulesValidUntil[0] == DateTime.MaxValue))
{
return MarketShutRules[0].IsOpenFromUTC(timeToCheck);
}
else
{
var X = MarketShutRulesValidUntil.BinarySearch(timeToCheck);
if (X < 0)
X = ~X;
return MarketShutRules[X].IsOpenFromUTC(timeToCheck);
}
}
public (DateTime pauseStart, DateTime pauseEnd) GetNextMarketPause(DateTime inDate)
{
if ((MarketShutRulesValidUntil.Count == 1) && (MarketShutRulesValidUntil[0] == DateTime.MaxValue))
{
return MarketShutRules[0].NextMarketPause(inDate);
}
else
{
var X = MarketShutRulesValidUntil.BinarySearch(inDate);
if (X < 0)
X = ~X;
return MarketShutRules[X].NextMarketPause(inDate);
}
}
public DateTime GetNextUTCOpen(DateTime UTCDateTime)
{
var U0 = UTCDateTime;
if (ExpiryGen.CalendarObject.IsHoliday(UTCDateTime))
{
UTCDateTime = UTCDateTime.AddDays(-1).AddPeriod(RollType.F, ExpiryGen.CalendarObject, new Frequency(1, DatePeriodType.B)).Date;
}
var openToday = GetUTCOpenFromDay(UTCDateTime);
if ((UTCDateTime < openToday) || (U0 < UTCDateTime && UTCDateTime <= openToday))
return openToday;
else
{
var tomorrow = UTCDateTime.AddPeriod(RollType.F, ExpiryGen.CalendarObject, new Frequency(1, DatePeriodType.B));
var nextOpen = GetUTCOpenFromDay(tomorrow);
if (nextOpen <= U0)
{
tomorrow = tomorrow.AddPeriod(RollType.F, ExpiryGen.CalendarObject, new Frequency(1, DatePeriodType.B));
nextOpen = GetUTCOpenFromDay(tomorrow);
}
return nextOpen;
}
}
public DateTime GetUTCOpenFromDay(DateTime date)
{
DateTime tempDate;
if ((MarketOpenRulesValidUntil.Count == 1) && (MarketOpenRulesValidUntil[0] == DateTime.MaxValue))
{
date = date.AddDays(MarketOpenModifier[0]);
if (ExpiryGen.CalendarObject.IsHoliday(date))
{
var OOHWNDF = GetOpenOnHolidayWhenNormalDayFollows(date);
tempDate = new DateTime(date.Year, date.Month, date.Day, OOHWNDF.Hours, OOHWNDF.Minutes, OOHWNDF.Seconds);
}
else
{
tempDate = new DateTime(date.Year, date.Month, date.Day, MarketOpenTime[0].Hours, MarketOpenTime[0].Minutes, MarketOpenTime[0].Seconds);
}
}
else
{
var q = MarketOpenRulesValidUntil.BinarySearch(date);
if (q < 0)
q = ~q;
date = date.AddDays(MarketOpenModifier[q]);
if (ExpiryGen.CalendarObject.IsHoliday(date))
{
var OOHWNDF = GetOpenOnHolidayWhenNormalDayFollows(date);
tempDate = new DateTime(date.Year, date.Month, date.Day, OOHWNDF.Hours, OOHWNDF.Minutes, OOHWNDF.Seconds);
}
else
{
tempDate = new DateTime(date.Year, date.Month, date.Day, MarketOpenTime[q].Hours, MarketOpenTime[q].Minutes, MarketOpenTime[q].Seconds);
}
}
return TimeZoneInfo.ConvertTimeToUtc(tempDate, TimeZone);
}
public DateTime GetNextUTCClose(DateTime UTCDateTime)
{
if (ExpiryGen.CalendarObject.IsHoliday(UTCDateTime))
{
UTCDateTime = UTCDateTime.AddDays(-1).AddPeriod(RollType.F, ExpiryGen.CalendarObject, new Frequency(1, DatePeriodType.B)).Date;
}
var closeToday = GetUTCCloseFromDay(UTCDateTime);
if (UTCDateTime < closeToday)
return closeToday;
else
{
var tomorrow = UTCDateTime.AddPeriod(RollType.F, ExpiryGen.CalendarObject, new Frequency(1, DatePeriodType.B));
return GetUTCCloseFromDay(tomorrow);
}
}
public TimeSpan GetOpenOnHolidayWhenNormalDayFollows(DateTime valDate)
{
if ((MarketShutRules.Count == 1) && (MarketShutRulesValidUntil[0] == DateTime.MaxValue))
{
return MarketShutRules[0].OpenOnHolidayWhenNormalDayFollows;
}
else
{
var q = MarketShutRulesValidUntil.BinarySearch(valDate);
if (q < 0)
q = ~q;
return MarketShutRules[q].OpenOnHolidayWhenNormalDayFollows;
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.WebControls.CommandField.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
public partial class CommandField : ButtonFieldBase
{
#region Methods and constructors
public CommandField()
{
}
protected override void CopyProperties(DataControlField newField)
{
}
protected override DataControlField CreateField()
{
return default(DataControlField);
}
public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
{
}
public override void ValidateSupportsCallback()
{
}
#endregion
#region Properties and indexers
public virtual new string CancelImageUrl
{
get
{
return default(string);
}
set
{
}
}
public virtual new string CancelText
{
get
{
return default(string);
}
set
{
}
}
public override bool CausesValidation
{
get
{
return default(bool);
}
set
{
}
}
public virtual new string DeleteImageUrl
{
get
{
return default(string);
}
set
{
}
}
public virtual new string DeleteText
{
get
{
return default(string);
}
set
{
}
}
public virtual new string EditImageUrl
{
get
{
return default(string);
}
set
{
}
}
public virtual new string EditText
{
get
{
return default(string);
}
set
{
}
}
public virtual new string InsertImageUrl
{
get
{
return default(string);
}
set
{
}
}
public virtual new string InsertText
{
get
{
return default(string);
}
set
{
}
}
public virtual new string NewImageUrl
{
get
{
return default(string);
}
set
{
}
}
public virtual new string NewText
{
get
{
return default(string);
}
set
{
}
}
public virtual new string SelectImageUrl
{
get
{
return default(string);
}
set
{
}
}
public virtual new string SelectText
{
get
{
return default(string);
}
set
{
}
}
public virtual new bool ShowCancelButton
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool ShowDeleteButton
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool ShowEditButton
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool ShowInsertButton
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool ShowSelectButton
{
get
{
return default(bool);
}
set
{
}
}
public virtual new string UpdateImageUrl
{
get
{
return default(string);
}
set
{
}
}
public virtual new string UpdateText
{
get
{
return default(string);
}
set
{
}
}
#endregion
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id$")]
namespace Elmah
{
#region Imports
using System;
using System.Diagnostics;
using System.Globalization;
using System.Web;
using System.IO;
using System.Net.Mail;
using MailAttachment = System.Net.Mail.Attachment;
using IDictionary = System.Collections.IDictionary;
using ThreadPool = System.Threading.ThreadPool;
using WaitCallback = System.Threading.WaitCallback;
using Encoding = System.Text.Encoding;
using NetworkCredential = System.Net.NetworkCredential;
#endregion
public sealed class ErrorMailEventArgs : EventArgs
{
private readonly Error _error;
private readonly MailMessage _mail;
public ErrorMailEventArgs(Error error, MailMessage mail)
{
if (error == null)
throw new ArgumentNullException("error");
if (mail == null)
throw new ArgumentNullException("mail");
_error = error;
_mail = mail;
}
public Error Error
{
get { return _error; }
}
public MailMessage Mail
{
get { return _mail; }
}
}
public delegate void ErrorMailEventHandler(object sender, ErrorMailEventArgs args);
/// <summary>
/// HTTP module that sends an e-mail whenever an unhandled exception
/// occurs in an ASP.NET web application.
/// </summary>
public class ErrorMailModule : HttpModuleBase, IExceptionFiltering
{
private string _mailSender;
private string _mailRecipient;
private string _mailCopyRecipient;
private string _mailSubjectFormat;
private MailPriority _mailPriority;
private bool _reportAsynchronously;
private string _smtpServer;
private int _smtpPort;
private string _authUserName;
private string _authPassword;
private bool _noYsod;
private bool _useSsl;
public event ExceptionFilterEventHandler Filtering;
public event ErrorMailEventHandler Mailing;
public event ErrorMailEventHandler Mailed;
public event ErrorMailEventHandler DisposingMail;
/// <summary>
/// Initializes the module and prepares it to handle requests.
/// </summary>
protected override void OnInit(HttpApplication application)
{
if (application == null)
throw new ArgumentNullException("application");
//
// Get the configuration section of this module.
// If it's not there then there is nothing to initialize or do.
// In this case, the module is as good as mute.
//
IDictionary config = (IDictionary) GetConfig();
if (config == null)
return;
//
// Extract the settings.
//
string mailRecipient = GetSetting(config, "to");
string mailSender = GetSetting(config, "from", mailRecipient);
string mailCopyRecipient = GetSetting(config, "cc", string.Empty);
string mailSubjectFormat = GetSetting(config, "subject", string.Empty);
MailPriority mailPriority = (MailPriority) Enum.Parse(typeof(MailPriority), GetSetting(config, "priority", MailPriority.Normal.ToString()), true);
bool reportAsynchronously = Convert.ToBoolean(GetSetting(config, "async", bool.TrueString));
string smtpServer = GetSetting(config, "smtpServer", string.Empty);
int smtpPort = Convert.ToUInt16(GetSetting(config, "smtpPort", "0"), CultureInfo.InvariantCulture);
string authUserName = GetSetting(config, "userName", string.Empty);
string authPassword = GetSetting(config, "password", string.Empty);
bool sendYsod = Convert.ToBoolean(GetSetting(config, "noYsod", bool.FalseString));
bool useSsl = Convert.ToBoolean(GetSetting(config, "useSsl", bool.FalseString));
//
// Hook into the Error event of the application.
//
application.Error += new EventHandler(OnError);
ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled);
//
// Finally, commit the state of the module if we got this far.
// Anything beyond this point should not cause an exception.
//
_mailRecipient = mailRecipient;
_mailSender = mailSender;
_mailCopyRecipient = mailCopyRecipient;
_mailSubjectFormat = mailSubjectFormat;
_mailPriority = mailPriority;
_reportAsynchronously = reportAsynchronously;
_smtpServer = smtpServer;
_smtpPort = smtpPort;
_authUserName = authUserName;
_authPassword = authPassword;
_noYsod = sendYsod;
_useSsl = useSsl;
}
/// <summary>
/// Determines whether the module will be registered for discovery
/// in partial trust environments or not.
/// </summary>
protected override bool SupportDiscoverability
{
get { return true; }
}
/// <summary>
/// Gets the e-mail address of the sender.
/// </summary>
protected virtual string MailSender
{
get { return _mailSender; }
}
/// <summary>
/// Gets the e-mail address of the recipient, or a
/// comma-/semicolon-delimited list of e-mail addresses in case of
/// multiple recipients.
/// </summary>
/// <remarks>
/// When using System.Web.Mail components under .NET Framework 1.x,
/// multiple recipients must be semicolon-delimited.
/// When using System.Net.Mail components under .NET Framework 2.0
/// or later, multiple recipients must be comma-delimited.
/// </remarks>
protected virtual string MailRecipient
{
get { return _mailRecipient; }
}
/// <summary>
/// Gets the e-mail address of the recipient for mail carbon
/// copy (CC), or a comma-/semicolon-delimited list of e-mail
/// addresses in case of multiple recipients.
/// </summary>
/// <remarks>
/// When using System.Web.Mail components under .NET Framework 1.x,
/// multiple recipients must be semicolon-delimited.
/// When using System.Net.Mail components under .NET Framework 2.0
/// or later, multiple recipients must be comma-delimited.
/// </remarks>
protected virtual string MailCopyRecipient
{
get { return _mailCopyRecipient; }
}
/// <summary>
/// Gets the text used to format the e-mail subject.
/// </summary>
/// <remarks>
/// The subject text specification may include {0} where the
/// error message (<see cref="Error.Message"/>) should be inserted
/// and {1} <see cref="Error.Type"/> where the error type should
/// be insert.
/// </remarks>
protected virtual string MailSubjectFormat
{
get { return _mailSubjectFormat; }
}
/// <summary>
/// Gets the priority of the e-mail.
/// </summary>
protected virtual MailPriority MailPriority
{
get { return _mailPriority; }
}
/// <summary>
/// Gets the SMTP server host name used when sending the mail.
/// </summary>
protected string SmtpServer
{
get { return _smtpServer; }
}
/// <summary>
/// Gets the SMTP port used when sending the mail.
/// </summary>
protected int SmtpPort
{
get { return _smtpPort; }
}
/// <summary>
/// Gets the user name to use if the SMTP server requires authentication.
/// </summary>
protected string AuthUserName
{
get { return _authUserName; }
}
/// <summary>
/// Gets the clear-text password to use if the SMTP server requires
/// authentication.
/// </summary>
protected string AuthPassword
{
get { return _authPassword; }
}
/// <summary>
/// Indicates whether <a href="http://en.wikipedia.org/wiki/Screens_of_death#ASP.NET">YSOD</a>
/// is attached to the e-mail or not. If <c>true</c>, the YSOD is
/// not attached.
/// </summary>
protected bool NoYsod
{
get { return _noYsod; }
}
/// <summary>
/// Determines if SSL will be used to encrypt communication with the
/// mail server.
/// </summary>
protected bool UseSsl
{
get { return _useSsl; }
}
/// <summary>
/// The handler called when an unhandled exception bubbles up to
/// the module.
/// </summary>
protected virtual void OnError(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication) sender).Context;
OnError(context.Server.GetLastError(), context);
}
/// <summary>
/// The handler called when an exception is explicitly signaled.
/// </summary>
protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args)
{
OnError(args.Exception, args.Context);
}
/// <summary>
/// Reports the exception.
/// </summary>
protected virtual void OnError(Exception e, HttpContext context)
{
if (e == null)
throw new ArgumentNullException("e");
//
// Fire an event to check if listeners want to filter out
// reporting of the uncaught exception.
//
ExceptionFilterEventArgs args = new ExceptionFilterEventArgs(e, context);
OnFiltering(args);
if (args.Dismissed)
return;
//
// Get the last error and then report it synchronously or
// asynchronously based on the configuration.
//
Error error = new Error(e, context);
if (_reportAsynchronously)
ReportErrorAsync(error);
else
ReportError(error);
}
/// <summary>
/// Raises the <see cref="Filtering"/> event.
/// </summary>
protected virtual void OnFiltering(ExceptionFilterEventArgs args)
{
ExceptionFilterEventHandler handler = Filtering;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Schedules the error to be e-mailed asynchronously.
/// </summary>
/// <remarks>
/// The default implementation uses the <see cref="ThreadPool"/>
/// to queue the reporting.
/// </remarks>
protected virtual void ReportErrorAsync(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
//
// Schedule the reporting at a later time using a worker from
// the system thread pool. This makes the implementation
// simpler, but it might have an impact on reducing the
// number of workers available for processing ASP.NET
// requests in the case where lots of errors being generated.
//
ThreadPool.QueueUserWorkItem(new WaitCallback(ReportError), error);
}
private void ReportError(object state)
{
try
{
ReportError((Error) state);
}
//
// Catch and trace COM/SmtpException here because this
// method will be called on a thread pool thread and
// can either fail silently in 1.x or with a big band in
// 2.0. For latter, see the following MS KB article for
// details:
//
// Unhandled exceptions cause ASP.NET-based applications
// to unexpectedly quit in the .NET Framework 2.0
// http://support.microsoft.com/kb/911816
//
catch (SmtpException e)
{
Trace.TraceError(e.ToString());
}
}
/// <summary>
/// Schedules the error to be e-mailed synchronously.
/// </summary>
protected virtual void ReportError(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
//
// Start by checking if we have a sender and a recipient.
// These values may be null if someone overrides the
// implementation of OnInit but does not override the
// MailSender and MailRecipient properties.
//
string sender = this.MailSender ?? string.Empty;
string recipient = this.MailRecipient ?? string.Empty;
string copyRecipient = this.MailCopyRecipient ?? string.Empty;
if (recipient.Length == 0)
return;
//
// Create the mail, setting up the sender and recipient and priority.
//
MailMessage mail = new MailMessage();
mail.Priority = this.MailPriority;
mail.From = new MailAddress(sender);
mail.To.Add(recipient);
if (copyRecipient.Length > 0)
mail.CC.Add(copyRecipient);
//
// Format the mail subject.
//
string subjectFormat = Mask.EmptyString(this.MailSubjectFormat, "Error ({1}): {0}");
mail.Subject = string.Format(subjectFormat, error.Message, error.Type).
Replace('\r', ' ').Replace('\n', ' ');
//
// Format the mail body.
//
ErrorTextFormatter formatter = CreateErrorFormatter();
StringWriter bodyWriter = new StringWriter();
formatter.Format(bodyWriter, error);
mail.Body = bodyWriter.ToString();
switch (formatter.MimeType)
{
case "text/html": mail.IsBodyHtml = true; break;
case "text/plain": mail.IsBodyHtml = false; break;
default :
{
throw new ApplicationException(string.Format(
"The error mail module does not know how to handle the {1} media type that is created by the {0} formatter.",
formatter.GetType().FullName, formatter.MimeType));
}
}
MailAttachment ysodAttachment = null;
ErrorMailEventArgs args = new ErrorMailEventArgs(error, mail);
try
{
//
// If an HTML message was supplied by the web host then attach
// it to the mail if not explicitly told not to do so.
//
if (!NoYsod && error.WebHostHtmlMessage.Length > 0)
{
ysodAttachment = CreateHtmlAttachment("YSOD", error.WebHostHtmlMessage);
if (ysodAttachment != null)
mail.Attachments.Add(ysodAttachment);
}
//
// Send off the mail with some chance to pre- or post-process
// using event.
//
OnMailing(args);
SendMail(mail);
OnMailed(args);
}
finally
{
OnDisposingMail(args);
mail.Dispose();
}
}
private static MailAttachment CreateHtmlAttachment(string name, string html)
{
Debug.AssertStringNotEmpty(name);
Debug.AssertStringNotEmpty(html);
return MailAttachment.CreateAttachmentFromString(html,
name + ".html", Encoding.UTF8, "text/html");
}
/// <summary>
/// Creates the <see cref="ErrorTextFormatter"/> implementation to
/// be used to format the body of the e-mail.
/// </summary>
protected virtual ErrorTextFormatter CreateErrorFormatter()
{
return new ErrorMailHtmlFormatter();
}
/// <summary>
/// Sends the e-mail using SmtpMail or SmtpClient.
/// </summary>
protected virtual void SendMail(MailMessage mail)
{
if (mail == null)
throw new ArgumentNullException("mail");
//
// Under .NET Framework 2.0, the authentication settings
// go on the SmtpClient object rather than mail message
// so these have to be set up here.
//
SmtpClient client = new SmtpClient();
string host = SmtpServer ?? string.Empty;
if (host.Length > 0)
client.Host = host;
int port = SmtpPort;
if (port > 0)
client.Port = port;
string userName = AuthUserName ?? string.Empty;
string password = AuthPassword ?? string.Empty;
if (userName.Length > 0 && password.Length > 0)
client.Credentials = new NetworkCredential(userName, password);
client.EnableSsl = UseSsl;
client.Send(mail);
}
/// <summary>
/// Fires the <see cref="Mailing"/> event.
/// </summary>
protected virtual void OnMailing(ErrorMailEventArgs args)
{
if (args == null)
throw new ArgumentNullException("args");
ErrorMailEventHandler handler = Mailing;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Fires the <see cref="Mailed"/> event.
/// </summary>
protected virtual void OnMailed(ErrorMailEventArgs args)
{
if (args == null)
throw new ArgumentNullException("args");
ErrorMailEventHandler handler = Mailed;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Fires the <see cref="DisposingMail"/> event.
/// </summary>
protected virtual void OnDisposingMail(ErrorMailEventArgs args)
{
if (args == null)
throw new ArgumentNullException("args");
ErrorMailEventHandler handler = DisposingMail;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Gets the configuration object used by <see cref="OnInit"/> to read
/// the settings for module.
/// </summary>
protected virtual object GetConfig()
{
return Configuration.GetSubsection("errorMail");
}
private static string GetSetting(IDictionary config, string name)
{
return GetSetting(config, name, null);
}
private static string GetSetting(IDictionary config, string name, string defaultValue)
{
Debug.Assert(config != null);
Debug.AssertStringNotEmpty(name);
string value = ((string) config[name]) ?? string.Empty;
if (value.Length == 0)
{
if (defaultValue == null)
{
throw new ApplicationException(string.Format(
"The required configuration setting '{0}' is missing for the error mailing module.", name));
}
value = defaultValue;
}
return value;
}
}
}
| |
using System;
using System.Net;
using System.Text;
using System.Reflection;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.Text;
using ServiceStack.Logging;
#if !NETFX_CORE
using System.Security.Cryptography;
#endif
#if MONOTOUCH || ANDROID
using HttpStatusCode = ServiceStack.ServiceHost.HttpStatusCode;
#endif
#if NETFX_CORE
using System.Net.Http.Headers;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
#endif
namespace ServiceStack.ServiceClient.Web
{
public class AuthenticationException : Exception
{
public AuthenticationException()
{
}
public AuthenticationException(string message) : base(message)
{
}
public AuthenticationException(string message, Exception innerException) : base(message, innerException)
{
}
}
// by adamfowleruk
public class AuthenticationInfo
{
private static readonly ILog Log = LogManager.GetLogger(typeof(AuthenticationInfo));
public string method {get;set;}
public string realm {get;set;}
public string qop {get;set;}
public string nonce { get; set; }
public string opaque { get; set; }
// these values used between requests, and not taken from WWW-Authenticate header of response
public string cnonce { get; set; }
public int nc { get; set; }
public AuthenticationInfo(String authHeader) {
cnonce = "0a4f113b";
nc = 1;
// Example Digest header: WWW-Authenticate: Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41"
// get method from first word
int pos = authHeader.IndexOf (" ");
if (pos < 0) {
throw new AuthenticationException(string.Format("Authentication header not supported, {0}", authHeader));
}
method = authHeader.Substring (0, pos).ToLower ();
string remainder = authHeader.Substring (pos + 1);
// split the rest by comma, then =
string[] pars = remainder.Split (',');
string[] newpars = new string[pars.Length];
int maxnewpars = 0;
// test possibility that a comma is mid value for a split (as in above example)
for (int i = 0; i < pars.Length; i++) {
if (pars[i].EndsWith("\"")) {
newpars[maxnewpars] = pars[i];
maxnewpars++;
} else {
// merge with next one
newpars[maxnewpars] = pars[i] + "," + pars[i+1];
maxnewpars++;
i++; // skips next value
}
}
// now go through each part, splitting on first = character, and removing leading and trailing spaces and " quotes
for (int i = 0;i < maxnewpars;i++) {
int pos2 = newpars[i].IndexOf("=");
string name = newpars[i].Substring(0,pos2).Trim();
string value = newpars[i].Substring(pos2 + 1).Trim ();
if (value.StartsWith("\"")) {
value = value.Substring(1);
}
if (value.EndsWith("\"")) {
value = value.Substring(0,value.Length - 1);
}
if ("qop".Equals (name)) {
qop = value;
} else if ("realm".Equals (name)) {
realm = value;
} else if ("nonce".Equals (name)) {
nonce = value;
} else if ("opaque".Equals (name)) {
opaque = value;
}
}
}
public override string ToString ()
{
return string.Format ("[AuthenticationInfo: method={0}, realm={1}, qop={2}, nonce={3}, opaque={4}, cnonce={5}, nc={6}]", method, realm, qop, nonce, opaque, cnonce, nc);
}
}
public static class WebRequestUtils
{
private static readonly ILog Log = LogManager.GetLogger(typeof(WebRequestUtils));
internal static AuthenticationException CreateCustomException(string uri, AuthenticationException ex)
{
if (uri.StartsWith("https"))
{
return new AuthenticationException(
String.Format("Invalid remote SSL certificate, overide with: \nServicePointManager.ServerCertificateValidationCallback += ((sender, certificate, chain, sslPolicyErrors) => isValidPolicy);"),
ex);
}
return null;
}
internal static bool ShouldAuthenticate(Exception ex, string userName, string password)
{
var webEx = ex as WebException;
return (webEx != null
&& webEx.Response != null
&& (int)((HttpWebResponse) webEx.Response).StatusCode == (int)HttpStatusCode.Unauthorized
&& !String.IsNullOrEmpty(userName)
&& !String.IsNullOrEmpty(password));
}
internal static void AddBasicAuth(this WebRequest client, string userName, string password)
{
client.Headers[ServiceStack.Common.Web.HttpHeaders.Authorization]
= "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password));
}
#if NETFX_CORE
internal static string CalculateMD5Hash(string input)
{
var alg = HashAlgorithmProvider.OpenAlgorithm("MD5");
IBuffer buff = CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8);
var hashed = alg.HashData(buff);
var res = CryptographicBuffer.EncodeToHexString(hashed);
return res.ToLower();
}
#endif
#if !NETFX_CORE && !SILVERLIGHT
internal static string CalculateMD5Hash(string input)
{
// copied/pasted by adamfowleruk
// step 1, calculate MD5 hash from input
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString().ToLower(); // The RFC requires the hex values are lowercase
}
#endif
internal static string padNC(int num)
{
// by adamfowleruk
var pad = "";
for (var i = 0;i < (8 - ("" + num).Length);i++) {
pad += "0";
}
var ret = pad + num;
return ret;
}
#if !SILVERLIGHT
internal static void AddAuthInfo(this WebRequest client,string userName,string password,AuthenticationInfo authInfo) {
if ("basic".Equals (authInfo.method)) {
client.AddBasicAuth (userName, password); // FIXME AddBasicAuth ignores the server provided Realm property. Potential Bug.
} else if ("digest".Equals (authInfo.method)) {
// do digest auth header using auth info
// auth info saved in ServiceClientBase for subsequent requests
client.AddDigestAuth (userName, password, authInfo);
}
}
internal static void AddDigestAuth(this WebRequest client,string userName,string password,AuthenticationInfo authInfo)
{
// by adamfowleruk
// See Client Request at http://en.wikipedia.org/wiki/Digest_access_authentication
string ncUse = padNC(authInfo.nc);
authInfo.nc++; // incrememnt for subsequent requests
string ha1raw = userName + ":" + authInfo.realm + ":" + password;
string ha1 = CalculateMD5Hash(ha1raw);
string ha2raw = client.Method + ":" + client.RequestUri.PathAndQuery;
string ha2 = CalculateMD5Hash(ha2raw);
string md5rraw = ha1 + ":" + authInfo.nonce + ":" + ncUse + ":" + authInfo.cnonce + ":" + authInfo.qop + ":" + ha2;
string response = CalculateMD5Hash(md5rraw);
string header =
"Digest username=\"" + userName + "\", realm=\"" + authInfo.realm + "\", nonce=\"" + authInfo.nonce + "\", uri=\"" +
client.RequestUri.PathAndQuery + "\", cnonce=\"" + authInfo.cnonce + "\", nc=" + ncUse + ", qop=\"" + authInfo.qop + "\", response=\"" + response +
"\", opaque=\"" + authInfo.opaque + "\"";
client.Headers [ServiceStack.Common.Web.HttpHeaders.Authorization] = header;
}
#endif
/// <summary>
/// Naming convention for the request's Response DTO
/// </summary>
public const string ResponseDtoSuffix = "Response";
public static string GetResponseDtoName(object request)
{
var requestType = request.GetType();
return requestType != typeof(object)
? requestType.FullName + ResponseDtoSuffix
: request.GetType().FullName + ResponseDtoSuffix;
}
public static Type GetErrorResponseDtoType(object request)
{
if (request == null)
return typeof(ErrorResponse);
//If a conventionally-named Response type exists use that regardless if it has ResponseStatus or not
var responseDtoType = AssemblyUtils.FindType(GetResponseDtoName(request));
if (responseDtoType == null)
{
var genericDef = request.GetType().GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>));
if (genericDef != null)
{
var returnDtoType = genericDef.GenericTypeArguments()[0];
var hasResponseStatus = returnDtoType is IHasResponseStatus
|| returnDtoType.GetPropertyInfo("ResponseStatus") != null;
//Only use the specified Return type if it has a ResponseStatus property
if (hasResponseStatus)
{
responseDtoType = returnDtoType;
}
}
}
return responseDtoType ?? typeof(ErrorResponse);
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// 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 CoreTweet.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace CoreTweet
{
/// <summary>
/// Represents a user.
/// </summary>
public class User : CoreBase
{
/// <summary>
/// Gets or sets a value that determines if the user has an account with "contributor mode" enabled, allowing for Tweets issued by the user to be co-authored by another account. Rarely true.
/// </summary>
[JsonProperty("contributors_enabled")]
public bool IsContributorsEnabled { get; set; }
/// <summary>
/// Gets or sets the UTC datetime that the user account was created on Twitter.
/// </summary>
[JsonProperty("created_at")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user has not altered the theme or background of its user profile.
/// </summary>
[JsonProperty("default_profile")]
public bool IsDefaultProfile { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user has not uploaded their own avatar and a default egg avatar is used instead.
/// </summary>
[JsonProperty("default_profile_image")]
public bool IsDefaultProfileImage { get; set; }
/// <summary>
/// <para>Gets or sets the user-defined string describing their account.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
/// <summary>
/// Gets or sets the entities which have been parsed out of the URL or description fields defined by the user.
/// </summary>
[JsonProperty("entities")]
public UserEntities Entities { get; set; }
/// <summary>
/// <para>Gets or sets the number of tweets this user has favorited in the account's lifetime.</para>
/// <para>British spelling used in the field name for historical reasons.</para>
/// </summary>
[JsonProperty("favourites_count")]
public int FavouritesCount { get; set; }
/// <summary>
/// <para>Gets or sets a value that determines if the authenticating user has issued a follow request to this protected user account.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("follow_request_sent")]
public bool? IsFollowRequestSent { get; set; }
/// <summary>
/// <para>Gets or sets the number of followers this account currently has.</para>
/// <para>Under certain conditions of duress, the field will temporarily indicates 0.</para>
/// </summary>
[JsonProperty("followers_count")]
public int FollowersCount { get; set; }
/// <summary>
/// <para>Gets or sets the number of the account is following (AKA its followings).</para>
/// <para>Under certain conditions of duress, the field will temporarily indicates 0.</para>
/// </summary>
[JsonProperty("friends_count")]
public int FriendsCount { get; set; }
/// <summary>
/// <para>Gets or sets a value that determines if the user has enabled the possibility of geotagging their Tweets.</para>
/// <para>This field must be true for the current user to attach geographic data when using statuses/update.</para>
/// </summary>
[JsonProperty("geo_enabled")]
public bool IsGeoEnabled { get; set; }
/// <summary>
/// Gets or sets the integer representation of the unique identifier for this User.
/// </summary>
[JsonProperty("id")]
public long? Id { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user is a participant in Twitter's translator community.
/// </summary>
[JsonProperty("is_translator")]
public bool IsTranslator { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user is a participant in Twitter's translator community.
/// </summary>
[JsonProperty("is_translation_enabled")]
public bool IsTranslationEnabled { get; set; }
/// <summary>
/// <para>Gets or sets the BCP 47 code for the user's self-declared user interface language.</para>
/// <para>May or may not have anything to do with the content of their Tweets.</para>
/// </summary>
[JsonProperty("lang")]
public string Language { get; set; }
/// <summary>
/// Gets or sets the number of public lists that the user is a member of.
/// </summary>
[JsonProperty("listed_count")]
public int? ListedCount { get; set; }
/// <summary>
/// <para>Gets or sets the user-defined location for this account's profile.</para>
/// <para>Not necessarily a location nor parsable.</para>
/// <para>This field will occasionally be fuzzily interpreted by the Search service.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("location")]
public string Location { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user is muted by authenticating user.
/// </summary>
[JsonProperty("muting")]
public bool? IsMuting { get; set; }
/// <summary>
/// <para>Gets or sets the name of the user, as they've defined it.</para>
/// <para>Not necessarily a person's name.</para>
/// <para>Typically capped at 20 characters, but subject to be changed.</para>
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("needs_phone_verification")]
public bool? NeedsPhoneVerification { get; set; }
/// <summary>
/// Gets or sets the hexadecimal color chosen by the user for their background.
/// </summary>
[JsonProperty("profile_background_color")]
public string ProfileBackgroundColor { get; set; }
/// <summary>
/// Gets or sets a HTTP-based URL pointing to the background image the user has uploaded for their profile.
/// </summary>
[JsonProperty("profile_background_image_url")]
[JsonConverter(typeof(UriConverter))]
public Uri ProfileBackgroundImageUrl { get; set; }
/// <summary>
/// Gets or sets a HTTPS-based URL pointing to the background image the user has uploaded for their profile.
/// </summary>
[JsonProperty("profile_background_image_url_https")]
[JsonConverter(typeof(UriConverter))]
public Uri ProfileBackgroundImageUrlHttps { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user's <see cref="CoreTweet.User.ProfileBackgroundImageUrl"/> should be tiled when displayed.
/// </summary>
[JsonProperty("profile_background_tile")]
public bool IsProfileBackgroundTile { get; set; }
/// <summary>
/// Gets or sets a HTTPS-based URL pointing to the standard web representation of the user's uploaded profile banner. By adding a final path element of the URL, you can obtain different image sizes optimized for specific displays. In the future, an API method will be provided to serve these URLs so that you need not modify the original URL. For size variations, please see User Profile Images and Banners.
/// </summary>
[JsonProperty("profile_banner_url")]
[JsonConverter(typeof(UriConverter))]
public Uri ProfileBannerUrl { get; set; }
/// <summary>
/// Gets or sets a HTTP-based URL pointing to the user's avatar image. See User Profile Images and Banners.
/// </summary>
[JsonProperty("profile_image_url")]
[JsonConverter(typeof(UriConverter))]
public Uri ProfileImageUrl { get; set; }
/// <summary>
/// Gets or sets a HTTPS-based URL pointing to the user's avatar image.
/// </summary>
[JsonProperty("profile_image_url_https")]
[JsonConverter(typeof(UriConverter))]
public Uri ProfileImageUrlHttps { get; set; }
/// <summary>
/// Gets or sets the hexadecimal color the user has chosen to display links with in their Twitter UI.
/// </summary>
[JsonProperty("profile_link_color")]
public string ProfileLinkColor { get; set; }
/// <summary>
/// Gets or sets the user-defined location for this account's profile.
/// </summary>
[JsonProperty("profile_location")]
public Place ProfileLocation { get; set; }
/// <summary>
/// Gets or sets the hexadecimal color the user has chosen to display sidebar borders with in their Twitter UI.
/// </summary>
[JsonProperty("profile_sidebar_border_color")]
public string ProfileSidebarBorderColor { get; set; }
/// <summary>
/// Gets or sets the hexadecimal color the user has chosen to display sidebar backgrounds with in their Twitter UI.
/// </summary>
[JsonProperty("profile_sidebar_fill_color")]
public string ProfileSidebarFillColor { get; set; }
/// <summary>
/// Gets or sets the hexadecimal color the user has chosen to display text with in their Twitter UI.
/// </summary>
[JsonProperty("profile_text_color")]
public string ProfileTextColor { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user wants their uploaded background image to be used.
/// </summary>
[JsonProperty("profile_use_background_image")]
public bool IsProfileUseBackgroundImage { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user has chosen to protect their Tweets.
/// </summary>
[JsonProperty("protected")]
public bool IsProtected { get; set; }
/// <summary>
/// <para>Gets or sets the screen name, handle, or alias that this user identifies themselves with.</para>
/// <para><see cref="CoreTweet.User.ScreenName"/> are unique but subject to be changed.</para>
/// <para>Use <see cref="CoreTweet.User.Id"/> as a user identifier whenever possible.</para>
/// <para>Typically a maximum of 15 characters long, but some historical accounts may exist with longer names.</para>
/// </summary>
[JsonProperty("screen_name")]
public string ScreenName { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user would like to see media inline. Somewhat disused.
/// </summary>
[JsonProperty("show_all_inline_media")]
public bool? IsShowAllInlineMedia { get; set; }
/// <summary>
/// <para>Gets or sets the user's most recent tweet or retweet.</para>
/// <para>In some circumstances, this data cannot be provided and this field will be omitted, null, or empty.</para>
/// <para>Perspectival attributes within tweets embedded within users cannot always be relied upon.</para>
/// </summary>
[JsonProperty("status")]
public Status Status { get; set; }
/// <summary>
/// Gets or sets the number of tweets (including retweets) issued by the user.
/// </summary>
[JsonProperty("statuses_count")]
public int StatusesCount { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user has been suspended by Twitter.
/// </summary>
[JsonProperty("suspended")]
public bool? IsSuspended { get; set; }
/// <summary>
/// <para>Gets or sets the string describes the time zone the user declares themselves within.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("time_zone")]
public string TimeZone { get; set; }
/// <summary>
/// <para>Gets or sets the URL provided by the user in association with their profile.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
/// <summary>
/// <para>Gets or sets the offset from GMT/UTC in seconds.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("utc_offset")]
public int? UtcOffset { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user has a verified account.
/// </summary>
[JsonProperty("verified")]
public bool IsVerified { get; set; }
/// <summary>
/// Gets or sets a textual representation of the two-letter country codes this user is withheld from.
/// </summary>
[JsonProperty("withheld_in_countries")]
public string WithheldInCountries { get; set; }
/// <summary>
/// Gets or sets the content being withheld is the "status" or a "user."
/// </summary>
[JsonProperty("withheld_scope")]
public string WithheldScope { get; set; }
/// <summary>
/// Returns the ID of this instance.
/// </summary>
/// <returns>The ID of this instance.</returns>
public override string ToString()
{
return this.Id.HasValue ? this.Id.Value.ToString("D") : "";
}
}
/// <summary>
/// Represents a user response with rate limit.
/// </summary>
public class UserResponse : User, ITwitterResponse
{
/// <summary>
/// Gets or sets the rate limit of the response.
/// </summary>
public RateLimit RateLimit { get; set; }
/// <summary>
/// Gets or sets the JSON of the response.
/// </summary>
public string Json { get; set; }
}
/// <summary>
/// Represents a relationship with another user.
/// </summary>
public class Relationship : CoreBase, ITwitterResponse
{
/// <summary>
/// Gets or sets the target of the relationship.
/// </summary>
[JsonProperty("target")]
public RelationshipTarget Target { get; set; }
/// <summary>
/// Gets or sets the source of the relationship.
/// </summary>
[JsonProperty("source")]
public RelationshipSource Source { get; set; }
/// <summary>
/// Gets or sets the rate limit of the response.
/// </summary>
public RateLimit RateLimit { get; set; }
/// <summary>
/// Gets or sets the JSON of the response.
/// </summary>
public string Json { get; set; }
}
/// <summary>
/// Represents a frienship.
/// </summary>
public class RelationshipTarget : CoreBase
{
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the screen name of the user.
/// </summary>
[JsonProperty("screen_name")]
public string ScreenName { get; set; }
/// <summary>
/// Gets or sets a value that determines if you are following the user.
/// </summary>
[JsonProperty("following")]
public bool IsFollowing { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user is following you.
/// </summary>
[JsonProperty("followed_by")]
public bool IsFollowedBy { get; set; }
[JsonProperty("following_received")]
public bool? IsFollowingReceived { get; set; }
[JsonProperty("following_requested")]
public bool? IsFollowingRequested { get; set; }
}
/// <summary>
/// Represents a frienship.
/// </summary>
public class RelationshipSource : RelationshipTarget
{
/// <summary>
/// Gets or sets a value that determines if you can send a direct message to the user.
/// </summary>
[JsonProperty("can_dm")]
public bool CanDM { get; set; }
/// <summary>
/// Gets or sets a value that determines if you get all replies.
/// </summary>
[JsonProperty("all_replies")]
public bool? AllReplies { get; set; }
/// <summary>
/// Gets or sets a value that determines if you want retweets or not.
/// </summary>
[JsonProperty("want_retweets")]
public bool? WantsRetweets { get; set; }
/// <summary>
/// Gets or sets a value that determines if you are blocking the user.
/// </summary>
[JsonProperty("blocking")]
public bool? IsBlocking { get; set; }
/// <summary>
/// Gets or sets a value that determines if you are blocked by the user.
/// </summary>
[JsonProperty("blocked_by")]
public bool? IsBlockedBy { get; set; }
/// <summary>
/// Gets or sets a value that determines if you marked the user as spam.
/// </summary>
[JsonProperty("marked_spam")]
public bool? IsMarkedSpam { get; set; }
/// <summary>
/// Gets or sets a value that determines if the notifications of the user enabled or not.
/// </summary>
[JsonProperty("notifications_enabled")]
public bool? IsNotificationsEnabled { get; set; }
/// <summary>
/// Gets or sets a value that determines if you are muting the user.
/// </summary>
[JsonProperty("muting")]
public bool? IsMuting { get; set; }
}
/// <summary>
/// Represents a frienship.
/// </summary>
public class Friendship : CoreBase
{
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the screen name of the user.
/// </summary>
[JsonProperty("screen_name")]
public string ScreenName { get; set; }
/// <summary>
/// Gets or sets the name of the user.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
//TODO: improve this summary
/// <summary>
/// Gets or sets the connections.
/// </summary>
[JsonProperty("connections")]
public string[] Connections { get; set; }
}
/// <summary>
/// Represents a category.
/// </summary>
public class Category : CoreBase
{
/// <summary>
/// Gets or sets the name of the category.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the slug of the category.
/// </summary>
[JsonProperty("slug")]
public string Slug{ get; set; }
/// <summary>
/// Gets or sets the size of the category.
/// </summary>
[JsonProperty("size")]
public int Size{ get; set; }
/// <summary>
/// Gets or sets the users in this category.
/// </summary>
[JsonProperty("users")]
public User[] Users { get; set; }
}
/// <summary>
/// Represents a category response with rate limit.
/// </summary>
public class CategoryResponse : Category, ITwitterResponse
{
/// <summary>
/// Gets or sets the rate limit of the response.
/// </summary>
public RateLimit RateLimit { get; set; }
/// <summary>
/// Gets or sets the JSON of the response.
/// </summary>
public string Json { get; set; }
}
/// <summary>
/// Represents the variations of a size of a profile banner.
/// </summary>
public class ProfileBannerSizes : CoreBase, ITwitterResponse
{
/// <summary>
/// Gets or sets the size for Web.
/// </summary>
[JsonProperty("web")]
public ProfileBannerSize Web { get; set; }
/// <summary>
/// Gets or sets the size for Web with high resolution devices.
/// </summary>
[JsonProperty("web_retina")]
public ProfileBannerSize WebRetina { get; set; }
/// <summary>
/// Gets or sets the size for Apple iPad.
/// </summary>
[JsonProperty("ipad")]
public ProfileBannerSize IPad { get; set; }
/// <summary>
/// Gets or sets the size for Apple iPad with high resolution.
/// </summary>
[JsonProperty("ipad_retina")]
public ProfileBannerSize IPadRetina { get; set; }
/// <summary>
/// Gets or sets the size for mobile devices.
/// </summary>
[JsonProperty("mobile")]
public ProfileBannerSize Mobile { get; set; }
/// <summary>
/// Gets or sets the size for mobile devices with high resolution devices.
/// </summary>
[JsonProperty("mobile_retina")]
public ProfileBannerSize MobileRetina { get; set; }
/// <summary>
/// Gets or sets the rate limit of the response.
/// </summary>
public RateLimit RateLimit { get; set; }
/// <summary>
/// Gets or sets the JSON of the response.
/// </summary>
public string Json { get; set; }
}
/// <summary>
/// Represents a size of a profile banner.
/// </summary>
public class ProfileBannerSize : CoreBase
{
/// <summary>
/// Gets or sets the width in pixels of the size.
/// </summary>
[JsonProperty("w")]
public int Width { get; set; }
/// <summary>
/// Gets or sets the height in pixels of the size.
/// </summary>
[JsonProperty("h")]
public int Height { get; set; }
/// <summary>
/// Gets or sets the URL of the size.
/// </summary>
[JsonProperty("url")]
[JsonConverter(typeof(UriConverter))]
public Uri Url { get; set; }
}
/// <summary>
/// Represents an entity object for user.
/// </summary>
public class UserEntities : CoreBase
{
/// <summary>
/// Gets or sets the entities for <see cref="CoreTweet.User.Url"/> field.
/// </summary>
[JsonProperty("url")]
public Entities Url { get; set; }
/// <summary>
/// Gets or sets the entities for <see cref="CoreTweet.User.Description"/> field.
/// </summary>
[JsonProperty("description")]
public Entities Description { 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.
using Microsoft.Build.Framework;
using Microsoft.DotNet.VersionTools.Automation;
using Microsoft.DotNet.VersionTools.BuildManifest.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using MSBuild = Microsoft.Build.Utilities;
namespace Microsoft.DotNet.Build.Tasks.Feed
{
public class PushToBlobFeed : MSBuild.Task
{
private static readonly char[] ManifestDataPairSeparators = { ';' };
private const string DisableManifestPushConfigurationBlob = "disable-manifest-push";
private const string AssetsVirtualDir = "assets/";
[Required]
public string ExpectedFeedUrl { get; set; }
[Required]
public string AccountKey { get; set; }
[Required]
public ITaskItem[] ItemsToPush { get; set; }
public bool Overwrite { get; set; }
public bool PublishFlatContainer { get; set; }
public int MaxClients { get; set; } = 8;
public bool SkipCreateContainer { get; set; } = false;
public int UploadTimeoutInMinutes { get; set; } = 5;
public bool SkipCreateManifest { get; set; }
public string ManifestName { get; set; } = "anonymous";
public string ManifestBuildId { get; set; } = "no build id provided";
public string ManifestBranch { get; set; }
public string ManifestCommit { get; set; }
/// <summary>
/// When publishing build outputs to an orchestrated blob feed, do not change this property.
///
/// The virtual dir to place the manifest XML file in, under the assets/ virtual dir. The
/// default value is the well-known location that orchestration searches to find all
/// manifest XML files and combine them into the orchestrated build output manifest.
/// </summary>
public string ManifestAssetOutputDir { get; set; } = "orchestration-metadata/manifests/";
public override bool Execute()
{
return ExecuteAsync().GetAwaiter().GetResult();
}
public async Task<bool> ExecuteAsync()
{
try
{
Log.LogMessage(MessageImportance.High, "Performing feed push...");
if (ItemsToPush == null)
{
Log.LogError($"No items to push. Please check ItemGroup ItemsToPush.");
}
else
{
BlobFeedAction blobFeedAction = new BlobFeedAction(ExpectedFeedUrl, AccountKey, Log);
IEnumerable<BlobArtifactModel> blobArtifacts = Enumerable.Empty<BlobArtifactModel>();
IEnumerable<PackageArtifactModel> packageArtifacts = Enumerable.Empty<PackageArtifactModel>();
if (!SkipCreateContainer)
{
await blobFeedAction.CreateContainerAsync(BuildEngine, PublishFlatContainer);
}
if (PublishFlatContainer)
{
await PublishToFlatContainerAsync(ItemsToPush, blobFeedAction);
blobArtifacts = ConcatBlobArtifacts(blobArtifacts, ItemsToPush);
}
else
{
ITaskItem[] symbolItems = ItemsToPush
.Where(i => i.ItemSpec.Contains("symbols.nupkg"))
.Select(i =>
{
string fileName = Path.GetFileName(i.ItemSpec);
i.SetMetadata("RelativeBlobPath", $"{AssetsVirtualDir}symbols/{fileName}");
return i;
})
.ToArray();
ITaskItem[] packageItems = ItemsToPush
.Where(i => !symbolItems.Contains(i))
.ToArray();
var packagePaths = packageItems.Select(i => i.ItemSpec);
await blobFeedAction.PushToFeed(packagePaths, Overwrite);
await PublishToFlatContainerAsync(symbolItems, blobFeedAction);
packageArtifacts = ConcatPackageArtifacts(packageArtifacts, packageItems);
blobArtifacts = ConcatBlobArtifacts(blobArtifacts, symbolItems);
}
if (!SkipCreateManifest)
{
await PushBuildManifestAsync(blobFeedAction, blobArtifacts, packageArtifacts);
}
}
}
catch (Exception e)
{
Log.LogErrorFromException(e, true);
}
return !Log.HasLoggedErrors;
}
private async Task PushBuildManifestAsync(
BlobFeedAction blobFeedAction,
IEnumerable<BlobArtifactModel> blobArtifacts,
IEnumerable<PackageArtifactModel> packageArtifacts)
{
bool disabledByBlob = await blobFeedAction.feed.CheckIfBlobExists(
$"{blobFeedAction.feed.RelativePath}{DisableManifestPushConfigurationBlob}");
if (disabledByBlob)
{
Log.LogMessage(
MessageImportance.Normal,
$"Skipping manifest push: feed has '{DisableManifestPushConfigurationBlob}'.");
return;
}
string blobPath = $"{AssetsVirtualDir}{ManifestAssetOutputDir}{ManifestName}.xml";
string existingStr = await blobFeedAction.feed.DownloadBlobAsString(
$"{blobFeedAction.feed.RelativePath}{blobPath}");
BuildModel buildModel;
if (existingStr != null)
{
buildModel = BuildModel.Parse(XElement.Parse(existingStr));
}
else
{
buildModel = new BuildModel(
new BuildIdentity(
ManifestName,
ManifestBuildId,
ManifestBranch,
ManifestCommit));
}
buildModel.Artifacts.Blobs.AddRange(blobArtifacts);
buildModel.Artifacts.Packages.AddRange(packageArtifacts);
string tempFile = null;
try
{
tempFile = Path.GetTempFileName();
File.WriteAllText(tempFile, buildModel.ToXml().ToString());
var item = new MSBuild.TaskItem(tempFile, new Dictionary<string, string>
{
["RelativeBlobPath"] = blobPath
});
using (var clientThrottle = new SemaphoreSlim(MaxClients, MaxClients))
{
await blobFeedAction.UploadAssets(
item,
clientThrottle,
UploadTimeoutInMinutes,
allowOverwrite: true);
}
}
finally
{
if (tempFile != null)
{
File.Delete(tempFile);
}
}
}
private async Task PublishToFlatContainerAsync(IEnumerable<ITaskItem> taskItems, BlobFeedAction blobFeedAction)
{
if (taskItems.Any())
{
using (var clientThrottle = new SemaphoreSlim(this.MaxClients, this.MaxClients))
{
Log.LogMessage($"Uploading {taskItems.Count()} items...");
await Task.WhenAll(taskItems.Select(item => blobFeedAction.UploadAssets(item, clientThrottle, UploadTimeoutInMinutes, Overwrite)));
}
}
}
private static IEnumerable<PackageArtifactModel> ConcatPackageArtifacts(
IEnumerable<PackageArtifactModel> artifacts,
IEnumerable<ITaskItem> items)
{
return artifacts.Concat(items
.Select(CreatePackageArtifactModel));
}
private static IEnumerable<BlobArtifactModel> ConcatBlobArtifacts(
IEnumerable<BlobArtifactModel> artifacts,
IEnumerable<ITaskItem> items)
{
return artifacts.Concat(items
.Select(CreateBlobArtifactModel)
.Where(blob => blob != null));
}
private static PackageArtifactModel CreatePackageArtifactModel(ITaskItem item)
{
NupkgInfo info = new NupkgInfo(item.ItemSpec);
return new PackageArtifactModel
{
Attributes = ParseCustomAttributes(item),
Id = info.Id,
Version = info.Version
};
}
private static BlobArtifactModel CreateBlobArtifactModel(ITaskItem item)
{
string path = item.GetMetadata("RelativeBlobPath");
// Only include assets in the manifest if they're in "assets/".
if (path?.StartsWith(AssetsVirtualDir, StringComparison.Ordinal) == true)
{
return new BlobArtifactModel
{
Attributes = ParseCustomAttributes(item),
Id = path.Substring(AssetsVirtualDir.Length)
};
}
return null;
}
private static Dictionary<string, string> ParseCustomAttributes(ITaskItem item)
{
Dictionary<string, string> customAttributes = item
.GetMetadata("ManifestArtifactData")
?.Split(ManifestDataPairSeparators, StringSplitOptions.RemoveEmptyEntries)
.Select(pair =>
{
int keyValueSeparatorIndex = pair.IndexOf('=');
if (keyValueSeparatorIndex > 0)
{
return new
{
Key = pair.Substring(0, keyValueSeparatorIndex).Trim(),
Value = pair.Substring(keyValueSeparatorIndex + 1).Trim()
};
}
return null;
})
.Where(pair => pair != null)
.ToDictionary(pair => pair.Key, pair => pair.Value);
return customAttributes ?? new Dictionary<string, string>();
}
}
}
| |
// 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 AlignRightUInt640()
{
var test = new ImmBinaryOpTest__AlignRightUInt640();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__AlignRightUInt640
{
private struct TestStruct
{
public Vector128<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__AlignRightUInt640 testClass)
{
var result = Ssse3.AlignRight(_fld1, _fld2, 0);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable;
static ImmBinaryOpTest__AlignRightUInt640()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public ImmBinaryOpTest__AlignRightUInt640()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Ssse3.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Ssse3.AlignRight(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
0
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Ssse3.AlignRight(
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
0
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Ssse3.AlignRight(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)),
0
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
(byte)0
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
(byte)0
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)),
(byte)0
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Ssse3.AlignRight(
_clsVar1,
_clsVar2,
0
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Ssse3.AlignRight(left, right, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Ssse3.AlignRight(left, right, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Ssse3.AlignRight(left, right, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__AlignRightUInt640();
var result = Ssse3.AlignRight(test._fld1, test._fld2, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Ssse3.AlignRight(_fld1, _fld2, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Ssse3.AlignRight(test._fld1, test._fld2, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> left, Vector128<UInt64> right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != right[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != right[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.AlignRight)}<UInt64>(Vector128<UInt64>.0, Vector128<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Text;
using NUnit.Framework;
using InTheHand.Net;
namespace InTheHand.Net.Tests.Irda.Net
{
namespace TestIrDAEndPoint
{
public class Values
{
//--------------------------------------------------------------
public static readonly IrDAAddress AddressNull = null;
public static readonly byte[] AddressBytesNull = null;
public static readonly IrDAAddress AddressOne = new IrDAAddress(0x04030201);
public static IrDAEndPoint CreateWithNullAddress()
{
return new IrDAEndPoint(AddressNull, "SvcName1");
}
public static IrDAEndPoint CreateWithNullAddressBytes()
{
#if FX1_1
/*
#endif
#pragma warning disable 618
#if FX1_1
*/
#endif
return new IrDAEndPoint(AddressBytesNull, "SvcName1"); // Don't fix the 'Obsolete warning!
#if FX1_1
/*
#endif
#pragma warning restore 618
#if FX1_1
*/
#endif
}
public static IrDAEndPoint CreateWithNullServiceName()
{
return new IrDAEndPoint(AddressOne, null);
}
public static IrDAEndPoint CreateWithEmptyServiceName()
{
return new IrDAEndPoint(AddressOne, String.Empty);
}
}
[TestFixture]
public class Ctor
{
//--------------------------------------------------------------
// Constructor
//--------------------------------------------------------------
[Test]
[ExpectedException(typeof(System.ArgumentNullException), ExpectedMessage = "Value cannot be null." + Tests_Values.NewLine + "Parameter name: irdaDeviceAddress")]
public void CtorNullAddress() { Values.CreateWithNullAddress(); }
[Test]
[ExpectedException(typeof(System.ArgumentNullException), ExpectedMessage = "Value cannot be null." + Tests_Values.NewLine + "Parameter name: irdaDeviceID")]
public void CtorNullAddressBytes() { Values.CreateWithNullAddressBytes(); }
[Test]
[ExpectedException(typeof(System.ArgumentNullException), ExpectedMessage = "Value cannot be null." + Tests_Values.NewLine + "Parameter name: serviceName")]
public void CtorNullServiceName() { Values.CreateWithNullServiceName(); }
[Test]
// ? [ExpectedException(typeof(System.ArgumentException), "ServiceName cannot be blank." + Tests_Values.NewLine + "Parameter name: serviceName")]
public void CtorEmptyServiceName() { Values.CreateWithEmptyServiceName(); }
//--------------------------------------------------------------
// (Contructor and...) Use the fields. Proving that they've been set correctly!
//--------------------------------------------------------------
// Should test Serialize result, and Create. But they're apparently working... :-)
[Test]
[ExpectedException(typeof(System.ArgumentNullException), ExpectedMessage = "Value cannot be null." + Tests_Values.NewLine + "Parameter name: irdaDeviceAddress")]
public void SerializeNullAddress() {
Values.CreateWithNullAddress().Serialize();
}
// SerializeNullAddressBytes
[Test]
[ExpectedException(typeof(System.ArgumentNullException), ExpectedMessage = "Value cannot be null." + Tests_Values.NewLine + "Parameter name: serviceName")]
public void SerializeNullServiceName() {
Values.CreateWithNullServiceName().Serialize();
}
[Test]
// ? [ExpectedException(typeof(System.ArgumentException), "ServiceName cannot be blank." + Tests_Values.NewLine + "Parameter name: serviceName")]
public void SerializeEmptyServiceName() {
Values.CreateWithEmptyServiceName().Serialize();
}
}
[TestFixture]
public class SerializeToFromSocketAddress
{
//--------------------------------------------------------------
//typedef struct _SOCKADDR_IRDA
//{
// u_short irdaAddressFamily;
// u_char irdaDeviceID[4];
// char irdaServiceName[25];
//} SOCKADDR_IRDA, *PSOCKADDR_IRDA, FAR *LPSOCKADDR_IRDA;
byte[] ExpectedBuffer24LetterAThusOneNullTerminatorAndWithPadByte = {
/* AF */ 26, 0,
/* ID */ 1,2,3,4,
/* SN */ (byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', /**/0,
/*Padding to struct size (due to first member: "u_short irdaAddressFamily;" */
0
};
public static void AssertAreEqualSocketAddressBuffer(byte[] expectedSockaddr, System.Net.SocketAddress sa)
{
byte[] result = new byte[sa.Size];
for (int i = 0; i < result.Length; ++i) {
result[i] = sa[i];
}
Assert.AreEqual(expectedSockaddr, result);
}
//--------------------------------------------------------------
[Test]
public void SerializeA()
{
System.Net.SocketAddress sa = new IrDAEndPoint(Values.AddressOne,
new String('a', 24)).Serialize();
AssertAreEqualSocketAddressBuffer(ExpectedBuffer24LetterAThusOneNullTerminatorAndWithPadByte, sa);
}
[Test]
public void Serialize24ByteServiceName()
{
System.Net.SocketAddress sa = new IrDAEndPoint(Values.AddressOne,
new String('a', 24)).Serialize();
AssertAreEqualSocketAddressBuffer(ExpectedBuffer24LetterAThusOneNullTerminatorAndWithPadByte, sa);
}
[Test]
[ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "ServiceName has a maximum length of 24 bytes.")]
public void SerializeOverlongServiceName()
{
System.Net.SocketAddress sa = new IrDAEndPoint(Values.AddressOne,
new String('a', 50)).Serialize();
}
[Test]
[ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "ServiceName has a maximum length of 24 bytes.")]
public void Serialize25ByteServiceName()
{
System.Net.SocketAddress sa = new IrDAEndPoint(Values.AddressOne,
new String('a', 25)).Serialize();
//AssertAreEqual(ExpectedBuffer24LetterAThusOneNullTerminatorAndWithPadByte, sa);
}
[Test]
[ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "ServiceName has a maximum length of 24 bytes.")]
public void Serialize26ByteServiceName()
{
System.Net.SocketAddress sa = new IrDAEndPoint(Values.AddressOne,
new String('a', 26)).Serialize();
//AssertAreEqual(ExpectedBuffer24LetterAThusOneNullTerminatorAndWithPadByte, sa);
}
[Test]
[ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "ServiceName has a maximum length of 24 bytes.")]
public void Serialize27ByteServiceName()
{
System.Net.SocketAddress sa = new IrDAEndPoint(Values.AddressOne,
new String('a', 27)).Serialize();
//AssertAreEqual(ExpectedBuffer24LetterAThusOneNullTerminatorAndWithPadByte, sa);
}
//--------------------------------------------------------------
//--------------------------------------------------------------
public static System.Net.SocketAddress Factory_SocketAddressForIrDA(byte[] buffer)
{
return Factory_SocketAddress(System.Net.Sockets.AddressFamily.Irda, buffer);
}
/// <summary>
/// Create <see cref="T:System.Net.SocketAddress"/> filling it with
/// the contents of the specified buffer.
/// </summary>
public static System.Net.SocketAddress Factory_SocketAddress(System.Net.Sockets.AddressFamily af, byte[] buffer)
{
System.Net.SocketAddress sa = new System.Net.SocketAddress(af, buffer.Length);
for (int i = 0; i < buffer.Length; ++i) {
sa[i] = buffer[i];
}//foreach
return sa;
}
//--------------------------------------------------------------
[Test]
public void CreateA()
{
byte[] buffer = {
/* AF */ 26, 0,
/* ID */ 1,2,3,4,
/* SN */ (byte)'S', (byte)'v', (byte)'c', (byte)'N', (byte)'a',
(byte)'m', (byte)'e', (byte)'1', 0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
/* struct alignment pad */ (byte)'!'
};
System.Net.SocketAddress sa = Factory_SocketAddressForIrDA(buffer);
IrDAEndPoint ep = (IrDAEndPoint)new IrDAEndPoint(Values.AddressOne, "x").Create(sa);
//
Assert.AreEqual(new byte[] { 1, 2, 3, 4 }, ep.Address.ToByteArray());
Assert.AreEqual("SvcName1", ep.ServiceName);
}
[Test]
public void CreateANoPadByte()
{
byte[] buffer = {
/* AF */ 26, 0,
/* ID */ 1,2,3,4,
/* SN */ (byte)'S', (byte)'v', (byte)'c', (byte)'N', (byte)'a',
(byte)'m', (byte)'e', (byte)'1', 0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
/* No padding byte... */
};
System.Net.SocketAddress sa = Factory_SocketAddressForIrDA(buffer);
IrDAEndPoint ep = (IrDAEndPoint)new IrDAEndPoint(Values.AddressOne, "x").Create(sa);
//
Assert.AreEqual(new byte[] { 1, 2, 3, 4 }, ep.Address.ToByteArray());
Assert.AreEqual("SvcName1", ep.ServiceName);
}
[Test]
// Should this fail? The ServiceName char[] is _not_ null-terminated!!!
public void CreateB()
{
byte[] buffer = {
/* AF */ 26, 0,
/* ID */ 1,2,3,4,
/* SN */ (byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
/* struct alignment pad */ (byte)'!'
};
System.Net.SocketAddress sa = Factory_SocketAddressForIrDA(buffer);
IrDAEndPoint ep = (IrDAEndPoint)new IrDAEndPoint(Values.AddressOne, "x").Create(sa);
//
Assert.AreEqual(new byte[] { 1, 2, 3, 4 }, ep.Address.ToByteArray());
Assert.AreEqual(new String('a', 24), ep.ServiceName);
}
[Test]
// Should this fail? The ServiceName char[] is _not_ null-terminated!!!
public void CreateBNoPadByte()
{
byte[] buffer = {
/* AF */ 26, 0,
/* ID */ 1,2,3,4,
/* SN */ (byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
(byte)'a', (byte)'a', (byte)'a', (byte)'a', (byte)'a',
/* No padding byte. */
};
System.Net.SocketAddress sa = Factory_SocketAddressForIrDA(buffer);
IrDAEndPoint ep = (IrDAEndPoint)new IrDAEndPoint(Values.AddressOne, "x").Create(sa);
//
Assert.AreEqual(new byte[] { 1, 2, 3, 4 }, ep.Address.ToByteArray());
Assert.AreEqual(new String('a', 24), ep.ServiceName);
}
}//class
[TestFixture]
public class ToString
{
//--------------------------------------------------------------
// ToString
//--------------------------------------------------------------
[Test]
public void ToStringAAddress()
{
IrDAEndPoint ep1 = new IrDAEndPoint(new IrDAAddress(new byte[] { 1, 2, 3, 4 }), "SvcName1");
String str = ep1.ToString();
Assert.AreEqual("04030201:SvcName1", str);
}
[Test]
public void ToStringABytes()
{
IrDAEndPoint ep1 = new IrDAEndPoint(Values.AddressOne, "SvcName1");
String str = ep1.ToString();
Assert.AreEqual("04030201:SvcName1", str);
}
[Test]
public void ToStringAddressNone()
{
IrDAEndPoint ep1 = new IrDAEndPoint(IrDAAddress.None, "SvcName1");
String str = ep1.ToString();
Assert.AreEqual("00000000:SvcName1", str);
}
[Test]
public void ToStringC()
{
IrDAEndPoint ep1 = new IrDAEndPoint(new IrDAAddress(new byte[] { 1, 2, 3, 4 }), String.Empty);
String str = ep1.ToString();
Assert.AreEqual("04030201:", str);
}
}//class
}
namespace TestIrDAAddress
{
//--------------------------------------------------------------------------
[TestFixture]
public class Misc
{
//--------------------------------------------------------------
// Constructor: invalid arguments.
//--------------------------------------------------------------
// For testing of the (Int32) constructor see the Formatting tests classes.
// For testing of valid inputs to both constructors see the Formatting tests classes.
[Test]
[ExpectedException(typeof(System.ArgumentNullException), ExpectedMessage = "Value cannot be null." + Tests_Values.NewLine + "Parameter name: address")]
public void CtorNull()
{
new IrDAAddress(null);
}
[Test]
[ExpectedException(typeof(System.ArgumentException), ExpectedMessage = "Address bytes array must be four bytes in size.")]
public void CtorZeroLengthArray()
{
new IrDAAddress(new byte[0]);
}
[Test]
[ExpectedException(typeof(System.ArgumentException), ExpectedMessage = "Address bytes array must be four bytes in size.")]
public void CtorFiveLengthArray()
{
new IrDAAddress(new byte[5]);
}
//--------------------------------------------------------------
// Show dodgy mutating address!!!!
//--------------------------------------------------------------
[Test]
public void MutationNotAllowedViaArrayCtor()
{
const String addrAsString = "04030201";
byte[] bytes = { 0x01, 0x02, 0x03, 0x04 };
IrDAAddress addr = new IrDAAddress(bytes);
Assert.AreEqual(addrAsString, addr.ToString());
bytes[1] = 0xFF; // Attempt to mutate the IrDAAddress!!!
Assert.AreEqual(addrAsString, addr.ToString());
}
[Test]
public void MutationNotAllowedViaToByte()
{
const String addrAsString = "04030201";
IrDAAddress addr = new IrDAAddress(0x04030201);
Assert.AreEqual(addrAsString, addr.ToString());
byte[] internalBytes = addr.ToByteArray();
internalBytes[1] = 0xFF; // Attempt to mutate the IrDAAddress!!!
Assert.AreEqual(addrAsString, addr.ToString());
}
//--------------------------------------------------------------
// * Test that the odd/bad endian-dependent behaviour doesn't change.
// The behaviour is not ideal but to change it would be a breaking change
// so shan't allow.
// If porting to a big-endian platform, have to decide then what behaviour
// to aim for there.
//
// * Also tests ToByteArray and ToInt32 by side-effect.
//--------------------------------------------------------------
[Test]
public void KeepBadEndianBehaviourInt32()
{
IrDAAddress addr = new IrDAAddress(0x01020304);
Assert.AreEqual(0x01020304, addr.ToInt32());
Assert.AreEqual(new byte[] { 0x04, 0x03, 0x02, 0x01, }, addr.ToByteArray());
Assert.AreEqual("01020304", addr.ToString("N"));
}
[Test]
public void KeepBadEndianBehaviourByteArray()
{
IrDAAddress addr = new IrDAAddress(new byte[] { 0x01, 0x02, 0x03, 0x04, });
Assert.AreEqual(0x04030201, addr.ToInt32());
Assert.AreEqual(new byte[] { 0x01, 0x02, 0x03, 0x04, }, addr.ToByteArray());
Assert.AreEqual("04030201", addr.ToString("N"));
}
}//class
//--------------------------------------------------------------------------
/// <summary>
/// Test infrastructure for testing the various forms of ToString.
/// </summary>
// [TestFixture] implemented on derived classes: FormattingToString, and FormattingIFormattable.
public abstract class FormattingBase
{
protected abstract String DoFormatting(Object obj, String format);
protected abstract String DoFormatting(Object obj);
//--------------------------------------------------------------
// Test
//--------------------------------------------------------------
/// <summary>
/// Test (NUnit Asserts) the object's <c>ToString()</c> method.
/// </summary>
/// <param name="expectedString">
/// The expected result, as a <see cref="T:System.String"/>
/// </param>
/// <param name="obj">
/// The object on which <c>ToString(String format)</c> is to be tested.
/// </param>
protected void DoTest(String expectedString, Object obj)
{
String result = DoFormatting(obj);
Assert.AreEqual(expectedString, result);
}
/// <summary>
/// Test (NUnit Asserts) the object's <c>ToString(String format)</c> method.
/// </summary>
/// <param name="expectedString">
/// The expected result, as a <see cref="T:System.String"/>
/// </param>
/// <param name="obj">
/// The object on which <c>ToString(String format)</c> is to be tested.
/// </param>
/// <param name="format">
/// The format string to be tested.
/// For example <c>"X"</c> to format an <see cref="T:System.Int32"/> as hexadecimal,
/// see <see cref="M:System.Int32.ToString(System.String"/> and
/// <see cref="T:System.Globalization.NumberFormatInfo"/>.
/// </param>
protected void DoTest(String expectedString, Object obj, String format)
{
String result = DoFormatting(obj, format);
Assert.AreEqual(expectedString, result);
}
}//class
/// <summary>
/// Provides the actual test method implementations, each marked with attribute
/// <c>[Test]</c>.
/// </summary>
public abstract class Formatting : FormattingBase
{
//--------------------------------------------------------------
// Simply formatting, no format string supplied
//--------------------------------------------------------------
[Test]
public void AddrA()
{
IrDAAddress addr = new IrDAAddress(0x01020304);
DoTest("01020304", addr);
}
[Test]
public void AddrB()
{
IrDAAddress addr = new IrDAAddress(new byte[] { 0x01, 0x02, 0x03, 0x04 });
DoTest("04030201", addr);
}
[Test]
public void AddrZeros()
{
IrDAAddress addr = new IrDAAddress(0);
DoTest("00000000", addr);
}
[Test]
public void AddrAllOnes()
{
IrDAAddress addr = new IrDAAddress(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF });
DoTest("FFFFFFFF", addr);
}
[Test]
public void AddrNegativeOne()
{
IrDAAddress addr = new IrDAAddress(-1);
DoTest("FFFFFFFF", addr);
}
[Test]
public void AddrNone()
{
IrDAAddress addr = IrDAAddress.None;
DoTest("00000000", addr);
}
//--------------------------------------------------------------
// With formatting codes
//--------------------------------------------------------------
const String FcodeNotExists = "G";
//
const String FcodeNull = null;
const String FcodeEmpty = "";
//
const String FcodePlainNumbers = "N";
const String FcodeColons = "C";
const String FcodePeriods = "P";
[Test]
[ExpectedException(typeof(System.FormatException), ExpectedMessage = "Invalid format specified - must be either \"N\", \"C\", \"P\", \"\" or null.")]
public void BadCode()
{
IrDAAddress addr = new IrDAAddress(0x01020304);
DoTest("01020304", addr, FcodeNotExists);
}
//------------------------------------------
// Code null
//------------------------------------------
[Test]
public void NullCodeAddrA()
{
IrDAAddress addr = new IrDAAddress(0x01020304);
DoTest("01020304", addr, FcodeNull);
}
[Test]
public void NullCodeAddrZeros()
{
IrDAAddress addr = new IrDAAddress(0);
DoTest("00000000", addr, FcodeNull);
}
//------------------------------------------
// Code ""
//------------------------------------------
[Test]
public void EmptyCodeAddrA()
{
IrDAAddress addr = new IrDAAddress(0x01020304);
DoTest("01020304", addr, FcodeEmpty);
}
[Test]
public void EmptyCodeAddrZeros()
{
IrDAAddress addr = new IrDAAddress(0);
DoTest("00000000", addr, FcodeEmpty);
}
//------------------------------------------
// Code "N"
//------------------------------------------
[Test]
public void NCodeAddrA()
{
IrDAAddress addr = new IrDAAddress(0x01020304);
DoTest("01020304", addr, FcodePlainNumbers);
}
[Test]
public void NCodeAddrZeros()
{
IrDAAddress addr = new IrDAAddress(0);
DoTest("00000000", addr, FcodePlainNumbers);
}
//------------------------------------------
// Code "C"
//------------------------------------------
[Test]
public void CCodeAddrA()
{
IrDAAddress addr = new IrDAAddress(0x01020304);
DoTest("01:02:03:04", addr, FcodeColons);
}
[Test]
public void CCodeAddrZeros()
{
IrDAAddress addr = new IrDAAddress(0);
DoTest("00:00:00:00", addr, FcodeColons);
}
//------------------------------------------
// Code "P"
//------------------------------------------
[Test]
public void PCodeAddrA()
{
IrDAAddress addr = new IrDAAddress(0x01020304);
DoTest("01.02.03.04", addr, FcodePeriods);
}
[Test]
public void PCodeAddrZeros()
{
IrDAAddress addr = new IrDAAddress(0);
DoTest("00.00.00.00", addr, FcodePeriods);
}
}//class
/// <summary>
/// Test the <c>IrDAAddress.ToString()</c> and <c>IrDAAddress.ToString(String format)</c> methods.
/// </summary>
[TestFixture]
public class FormattingToString : Formatting
{
/// <summary>
/// Call <see cref="S:System.Object(System.String)"/> on the specified object.
/// </summary>
protected override String DoFormatting(Object obj)
{
return obj.ToString();
}
/// <summary>
/// Call <c>ToString(String format)</c> on the specified object.
/// </summary>
protected override String DoFormatting(Object obj, String format)
{
// Call obj.ToString(format), without a interface to do so. :-(
Type type = obj.GetType();
System.Reflection.MethodInfo method = type.GetMethod("ToString", new Type[] { typeof(String) });
try {
Object ret = method.Invoke(obj, new Object[1] { format });
return (String)ret;
} catch (System.Reflection.TargetInvocationException ex) {
// The real exception, please!
throw ex.InnerException;
}
}
}//class
/// <summary>
/// Test the <see cref="System.IFormattable.ToString">IFormattable.ToString(String, IFormatProvider)</see>
/// method on <c>IrDAAddress</c>, both with and without format strings.
/// </summary>
// i.e. <see cref="M:InTheHand.Net.IrDAAddress.ToString(System.String,System.IFormatProvider)"/>.
[TestFixture]
public class FormattingIFormattable : Formatting
{
/// <summary>
/// Call <see cref="System.IFormattable.ToString"/> without a format string.
/// </summary>
protected override String DoFormatting(Object obj)
{
return String.Format("{0}", obj);
}
/// <summary>
/// Call <see cref="System.IFormattable.ToString"/> with a format string.
/// </summary>
protected override String DoFormatting(Object obj, String format)
{
// Do allow null, and empty format values.
//
return String.Format("{0:" + format + "}", obj);
}
}//class
//--------------------------------------------------------------------------
[TestFixture]
public class Parse
{
//--------------------------------------------------------------
private void DoTestParse(IrDAAddress expected, String s)
{
IrDAAddress result = IrDAAddress.Parse(s);
Assert.AreEqual(expected, result);
}
private void DoTestTryParse(IrDAAddress expected, String s)
{
IrDAAddress result;
bool success = IrDAAddress.TryParse(s, out result);
Assert.IsTrue(success, "TryParse failed.");
Assert.AreEqual(expected, result);
}
//----------------
private void DoTestParseFails(String s)
{
IrDAAddress result = IrDAAddress.Parse(s);
// Expected an Exception
Assert.Fail("Expected an error from Parse");
}
private static void DoTestTryParseFails(String s)
{
IrDAAddress addr;
try {
bool success = IrDAAddress.TryParse(s, out addr);
Assert.IsFalse(success);
} catch {
Assert.Fail("TryParse should never throw an Exception.");
}
}
//--------------------------------------------------------------
[Test]
[ExpectedException(typeof(System.ArgumentNullException), ExpectedMessage = "Value cannot be null." + Tests_Values.NewLine + "Parameter name: irdaString")]
public void ParseNull()
{
DoTestParseFails(null);
}
[Test]
public void TryParseNull()
{
DoTestTryParseFails(null);
}
[Test]
[ExpectedException(typeof(System.FormatException), ExpectedMessage = "irdaString is not a valid IrDA address.")]
public void ParseBlank()
{
DoTestParseFails("");
}
[Test]
public void TryParseBlank()
{
DoTestTryParseFails("");
}
//--------------------------------------------------------------
const String DigitZero = "0";
const String StringA = "01020304";
const String StringAColons = "01:02:03:04";
const String StringAPeriods = "01.02.03.04";
const String StringAPrefixHex = "0x01020304";
readonly IrDAAddress AddressA = new IrDAAddress(0x01020304);
//
// *Not* an Int32!
const String StringB = "FEDC00FF";
const String StringBColons = "FE:DC:00:FF";
const String StringBPeriods = "FE.DC.00.FF";
const String StringBPrefixHex = "0xFEDC00FF";
readonly IrDAAddress AddressB = new IrDAAddress(unchecked((int)0xFEDC00FF));
// TODO Tests IrDAAddress.[Try-]Parse, more...
[Test]
[ExpectedException(typeof(System.FormatException), ExpectedMessage = "irdaString is not a valid IrDA address.")]
public void ParseDigitZero ()
{
DoTestParse(IrDAAddress.None, DigitZero);
}
[Test]
public void TryParseDigitZero()
{
DoTestTryParseFails(DigitZero);
}
//----------------------------------------------------------
[Test]
public void ParseA()
{
DoTestParse(AddressA, StringA);
}
[Test]
public void TryParseA()
{
DoTestTryParse(AddressA, StringA);
}
[Test]
public void ParseAColons()
{
DoTestParse(AddressA, StringAColons);
}
[Test]
public void TryParseAColons()
{
DoTestTryParse(AddressA, StringAColons);
}
[Test]
public void ParseAPeriods()
{
DoTestParse(AddressA, StringAPeriods);
}
[Test]
public void TryParseAPeriods()
{
DoTestTryParse(AddressA, StringAPeriods);
}
//----------------------------------------------------------
[Test]
public void Int32ParseHexBigNegative(){
int result = int.Parse(StringB, System.Globalization.NumberStyles.HexNumber);
uint expectedU = 0xFEDC00FF;
int expectedS = unchecked((int)expectedU);
Assert.AreEqual(expectedS, result);
}
[Test]
public void UInt32ParseHexBigNegative()
{
uint result = uint.Parse(StringB, System.Globalization.NumberStyles.HexNumber);
uint expectedU = 0xFEDC00FF;
//int expectedS = unchecked((int)expectedU);
Assert.AreEqual(expectedU, result);
}
[Test]
public void ParseB()
{
DoTestParse(AddressB, StringB);
}
[Test]
public void TryParseB()
{
DoTestTryParse(AddressB, StringB);
}
[Test]
public void ParseBColons()
{
DoTestParse(AddressB, StringBColons);
}
[Test]
public void TryParseBColons()
{
DoTestTryParse(AddressB, StringBColons);
}
[Test]
public void ParseBPeriods()
{
DoTestParse(AddressB, StringBPeriods);
}
[Test]
public void TryParseBPeriods()
{
DoTestTryParse(AddressB, StringBPeriods);
}
//----------------------------------------------------------
[Test]
[ExpectedException(typeof(System.FormatException), ExpectedMessage = "irdaString is not a valid IrDA address.")]
public void ParsePrefixHex()
{
DoTestParseFails(StringAPrefixHex);
}
[Test]
public void TryParsePrefixHex()
{
DoTestTryParseFails(StringAPrefixHex);
}
}
}//namespace
}//namespace
| |
/*
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.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Info;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using System.Windows.Threading;
namespace WPCordovaClassLib.Cordova.Commands
{
/// <summary>
/// Listens for changes to the state of the battery on the device.
/// Currently only the "isPlugged" parameter available via native APIs.
/// </summary>
public class SplashScreen : BaseCommand
{
private Popup popup;
// Time until we dismiss the splashscreen
private int prefDelay = 3000;
// Whether we hide it by default
private bool prefAutoHide = true;
// Path to image to use
private string prefImagePath = "SplashScreenImage.jpg";
// static because autodismiss is only ever applied once, at app launch
// subsequent page loads should not cause the SplashScreen to be shown.
private static bool WasShown = false;
public SplashScreen()
{
LoadConfigPrefs();
Image SplashScreen = new Image()
{
Height = Application.Current.Host.Content.ActualHeight,
Width = Application.Current.Host.Content.ActualWidth,
Stretch = Stretch.Fill
};
var imageResource = GetSplashScreenImageResource();
if (imageResource != null)
{
BitmapImage splash_image = new BitmapImage();
splash_image.SetSource(imageResource.Stream);
SplashScreen.Source = splash_image;
}
// Instansiate the popup and set the Child property of Popup to SplashScreen
popup = new Popup() { IsOpen = false,
Child = SplashScreen,
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Center
};
}
public override void OnInit()
{
// we only want to autoload on the first page load.
// but OnInit is called for every page load.
if (!SplashScreen.WasShown)
{
SplashScreen.WasShown = true;
show();
}
}
private void LoadConfigPrefs()
{
StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("config.xml", UriKind.Relative));
if (streamInfo != null)
{
using (StreamReader sr = new StreamReader(streamInfo.Stream))
{
//This will Read Keys Collection for the xml file
XDocument configFile = XDocument.Parse(sr.ReadToEnd());
string configAutoHide = configFile.Descendants()
.Where(x => (string)x.Attribute("name") == "AutoHideSplashScreen")
.Select(x => (string)x.Attribute("value"))
.FirstOrDefault();
bool bVal;
prefAutoHide = bool.TryParse(configAutoHide, out bVal) ? bVal : prefAutoHide;
string configDelay = configFile.Descendants()
.Where(x => (string)x.Attribute("name") == "SplashScreenDelay")
.Select(x => (string)x.Attribute("value"))
.FirstOrDefault();
int nVal;
prefDelay = int.TryParse(configDelay, out nVal) ? nVal : prefDelay;
string configImage = configFile.Descendants()
.Where(x => (string)x.Attribute("name") == "SplashScreen")
.Select(x => (string)x.Attribute("value"))
.FirstOrDefault();
if (!String.IsNullOrEmpty(configImage))
{
prefImagePath = configImage;
}
}
}
}
private StreamResourceInfo GetSplashScreenImageResource()
{
// Get the base filename for the splash screen images
string imageName = System.IO.Path.GetFileNameWithoutExtension(prefImagePath);
Uri imageUri = null;
StreamResourceInfo imageResource = null;
// First, try to get a resolution-specific splashscreen
try
{
// Determine the device's resolution
switch (ResolutionHelper.CurrentResolution)
{
case Resolutions.HD:
imageUri = new Uri(imageName + ".screen-720p.jpg", UriKind.Relative);
break;
case Resolutions.WVGA:
imageUri = new Uri(imageName + ".screen-WVGA.jpg", UriKind.Relative);
break;
case Resolutions.WXGA:
default:
imageUri = new Uri(imageName + ".screen-WXGA.jpg", UriKind.Relative);
break;
}
imageResource = Application.GetResourceStream(imageUri);
}
catch (Exception)
{
// It's OK if we didn't get a resolution-specific image
}
// Fallback to the default image name without decoration
if (imageResource == null)
{
imageUri = new Uri(prefImagePath, UriKind.Relative);
imageResource = Application.GetResourceStream(imageUri);
}
if (imageUri != null) Debug.WriteLine("INFO :: SplashScreen: using image {0}", imageUri.OriginalString);
return imageResource;
}
public void show(string options = null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (!popup.IsOpen)
{
popup.Child.Opacity = 0;
Storyboard story = new Storyboard();
DoubleAnimation animation = new DoubleAnimation()
{
From = 0.0,
To = 1.0,
Duration = new Duration(TimeSpan.FromSeconds(0.2))
};
Storyboard.SetTarget(animation, popup.Child);
Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity"));
story.Children.Add(animation);
story.Begin();
popup.IsOpen = true;
if (prefAutoHide)
{
StartAutoHideTimer();
}
}
});
}
public void hide(string options = null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (popup.IsOpen)
{
popup.Child.Opacity = 1.0;
Storyboard story = new Storyboard();
DoubleAnimation animation = new DoubleAnimation()
{
From = 1.0,
To = 0.0,
Duration = new Duration(TimeSpan.FromSeconds(0.4))
};
Storyboard.SetTarget(animation, popup.Child);
Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity"));
story.Children.Add(animation);
story.Completed += (object sender, EventArgs e) =>
{
popup.IsOpen = false;
};
story.Begin();
}
});
}
private void StartAutoHideTimer()
{
var timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(prefDelay) };
timer.Tick += (object sender, EventArgs e) =>
{
hide();
timer.Stop();
};
timer.Start();
}
}
}
| |
//
// ListStore.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.Linq;
using System.Collections.Generic;
namespace Xwt
{
[BackendType (typeof(IListStoreBackend))]
public class ListStore: XwtComponent, IListDataSource
{
IDataField[] fields;
class ListStoreBackendHost: BackendHost<ListStore,IListStoreBackend>
{
protected override void OnBackendCreated ()
{
Backend.Initialize (Parent.fields.Select (f => f.FieldType).ToArray ());
base.OnBackendCreated ();
}
}
protected override Xwt.Backends.BackendHost CreateBackendHost ()
{
return new ListStoreBackendHost ();
}
public ListStore (params IDataField[] fields)
{
for (int n=0; n<fields.Length; n++) {
if (fields[n].Index != -1)
throw new InvalidOperationException ("DataField object already belongs to another data store");
((IDataFieldInternal)fields[n]).SetIndex (n);
}
this.fields = fields;
}
IListStoreBackend Backend {
get { return (IListStoreBackend) BackendHost.Backend; }
}
public ListStore ()
{
}
public int RowCount {
get {
return Backend.RowCount;
}
}
public T GetValue<T> (int row, IDataField<T> column)
{
return (T) Backend.GetValue (row, column.Index);
}
public void SetValue<T> (int row, IDataField<T> column, T value)
{
Backend.SetValue (row, column.Index, value);
}
object IListDataSource.GetValue (int row, int column)
{
return Backend.GetValue (row, column);
}
void IListDataSource.SetValue (int row, int column, object value)
{
Backend.SetValue (row, column, value);
}
Type[] IListDataSource.ColumnTypes {
get {
return Backend.ColumnTypes;
}
}
event EventHandler<ListRowEventArgs> IListDataSource.RowInserted {
add { Backend.RowInserted += value; }
remove { Backend.RowInserted -= value; }
}
event EventHandler<ListRowEventArgs> IListDataSource.RowDeleted {
add { Backend.RowDeleted += value; }
remove { Backend.RowDeleted -= value; }
}
event EventHandler<ListRowEventArgs> IListDataSource.RowChanged {
add { Backend.RowChanged += value; }
remove { Backend.RowChanged -= value; }
}
event EventHandler<ListRowOrderEventArgs> IListDataSource.RowsReordered {
add { Backend.RowsReordered += value; }
remove { Backend.RowsReordered -= value; }
}
public int AddRow ()
{
return Backend.AddRow ();
}
public void SetValues<T1,T2> (int row, IDataField<T1> column1, T1 value1, IDataField<T2> column2, T2 value2)
{
SetValue (row, column1, value1);
SetValue (row, column2, value2);
}
public void SetValues<T1,T2,T3> (int row, IDataField<T1> column1, T1 value1, IDataField<T2> column2, T2 value2, IDataField<T3> column3, T3 value3)
{
SetValue (row, column1, value1);
SetValue (row, column2, value2);
SetValue (row, column3, value3);
}
public void SetValues<T1,T2,T3,T4> (
int row,
IDataField<T1> column1, T1 value1,
IDataField<T2> column2, T2 value2,
IDataField<T3> column3, T3 value3,
IDataField<T4> column4, T4 value4
)
{
SetValue (row, column1, value1);
SetValue (row, column2, value2);
SetValue (row, column3, value3);
SetValue (row, column4, value4);
}
public void SetValues<T1,T2,T3,T4,T5> (
int row,
IDataField<T1> column1, T1 value1,
IDataField<T2> column2, T2 value2,
IDataField<T3> column3, T3 value3,
IDataField<T4> column4, T4 value4,
IDataField<T5> column5, T5 value5
)
{
SetValue (row, column1, value1);
SetValue (row, column2, value2);
SetValue (row, column3, value3);
SetValue (row, column4, value4);
SetValue (row, column5, value5);
}
public void SetValues<T1,T2,T3,T4,T5,T6> (
int row,
IDataField<T1> column1, T1 value1,
IDataField<T2> column2, T2 value2,
IDataField<T3> column3, T3 value3,
IDataField<T4> column4, T4 value4,
IDataField<T5> column5, T5 value5,
IDataField<T6> column6, T6 value6
)
{
SetValue (row, column1, value1);
SetValue (row, column2, value2);
SetValue (row, column3, value3);
SetValue (row, column4, value4);
SetValue (row, column5, value5);
SetValue (row, column6, value6);
}
public void SetValues<T1,T2,T3,T4,T5,T6,T7> (
int row,
IDataField<T1> column1, T1 value1,
IDataField<T2> column2, T2 value2,
IDataField<T3> column3, T3 value3,
IDataField<T4> column4, T4 value4,
IDataField<T5> column5, T5 value5,
IDataField<T6> column6, T6 value6,
IDataField<T7> column7, T7 value7
)
{
SetValue (row, column1, value1);
SetValue (row, column2, value2);
SetValue (row, column3, value3);
SetValue (row, column4, value4);
SetValue (row, column5, value5);
SetValue (row, column6, value6);
SetValue (row, column7, value7);
}
public void SetValues<T1,T2,T3,T4,T5,T6,T7,T8> (
int row,
IDataField<T1> column1, T1 value1,
IDataField<T2> column2, T2 value2,
IDataField<T3> column3, T3 value3,
IDataField<T4> column4, T4 value4,
IDataField<T5> column5, T5 value5,
IDataField<T6> column6, T6 value6,
IDataField<T7> column7, T7 value7,
IDataField<T8> column8, T8 value8
)
{
SetValue (row, column1, value1);
SetValue (row, column2, value2);
SetValue (row, column3, value3);
SetValue (row, column4, value4);
SetValue (row, column5, value5);
SetValue (row, column6, value6);
SetValue (row, column7, value7);
SetValue (row, column8, value8);
}
public void SetValues<T1,T2,T3,T4,T5,T6,T7,T8,T9> (
int row,
IDataField<T1> column1, T1 value1,
IDataField<T2> column2, T2 value2,
IDataField<T3> column3, T3 value3,
IDataField<T4> column4, T4 value4,
IDataField<T5> column5, T5 value5,
IDataField<T6> column6, T6 value6,
IDataField<T7> column7, T7 value7,
IDataField<T8> column8, T8 value8,
IDataField<T9> column9, T9 value9
)
{
SetValue (row, column1, value1);
SetValue (row, column2, value2);
SetValue (row, column3, value3);
SetValue (row, column4, value4);
SetValue (row, column5, value5);
SetValue (row, column6, value6);
SetValue (row, column7, value7);
SetValue (row, column8, value8);
SetValue (row, column9, value9);
}
public void SetValues<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10> (
int row,
IDataField<T1> column1, T1 value1,
IDataField<T2> column2, T2 value2,
IDataField<T3> column3, T3 value3,
IDataField<T4> column4, T4 value4,
IDataField<T5> column5, T5 value5,
IDataField<T6> column6, T6 value6,
IDataField<T7> column7, T7 value7,
IDataField<T8> column8, T8 value8,
IDataField<T9> column9, T9 value9,
IDataField<T10> column10, T10 value10
)
{
SetValue (row, column1, value1);
SetValue (row, column2, value2);
SetValue (row, column3, value3);
SetValue (row, column4, value4);
SetValue (row, column5, value5);
SetValue (row, column6, value6);
SetValue (row, column7, value7);
SetValue (row, column8, value8);
SetValue (row, column9, value9);
SetValue (row, column10, value10);
}
public int InsertRowAfter (int row)
{
return Backend.InsertRowAfter (row);
}
public int InsertRowBefore (int row)
{
return Backend.InsertRowBefore (row);
}
public void RemoveRow (int row)
{
Backend.RemoveRow (row);
}
public void Clear ()
{
Backend.Clear ();
}
}
public class DefaultListStoreBackend: IListStoreBackend
{
List<object[]> list = new List<object[]> ();
Type[] columnTypes;
public event EventHandler<ListRowEventArgs> RowInserted;
public event EventHandler<ListRowEventArgs> RowDeleted;
public event EventHandler<ListRowEventArgs> RowChanged;
public event EventHandler<ListRowOrderEventArgs> RowsReordered;
public void InitializeBackend (object frontend, ApplicationContext context)
{
}
public void Initialize (Type[] columnTypes)
{
this.columnTypes = columnTypes;
}
public object GetValue (int row, int column)
{
return list [row][column];
}
public void SetValue (int row, int column, object value)
{
list [row] [column] = value;
if (RowChanged != null)
RowChanged (this, new ListRowEventArgs (row));
}
public Type[] ColumnTypes {
get {
return columnTypes;
}
}
public int RowCount {
get {
return list.Count;
}
}
public int AddRow ()
{
object[] data = new object [columnTypes.Length];
list.Add (data);
int row = list.Count - 1;
if (RowInserted != null)
RowInserted (this, new ListRowEventArgs (row));
return row;
}
public int InsertRowAfter (int row)
{
object[] data = new object [columnTypes.Length];
list.Insert (row + 1, data);
if (RowInserted != null)
RowInserted (this, new ListRowEventArgs (row + 1));
return row + 1;
}
public int InsertRowBefore (int row)
{
object[] data = new object [columnTypes.Length];
list.Insert (row, data);
if (RowInserted != null)
RowInserted (this, new ListRowEventArgs (row));
return row;
}
public void RemoveRow (int row)
{
list.RemoveAt (row);
if (RowDeleted != null)
RowDeleted (this, new ListRowEventArgs (row));
}
public void EnableEvent (object eventId)
{
}
public void DisableEvent (object eventId)
{
}
public void Clear ()
{
int count = list.Count;
list.Clear ();
for (int n=0; n<count; n++) {
if (RowDeleted != null)
RowDeleted (this, new ListRowEventArgs (n));
}
}
}
}
| |
// 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.IO;
using System.Text;
namespace System.Net.Http.Headers
{
// According to the RFC, in places where a "parameter" is required, the value is mandatory
// (e.g. Media-Type, Accept). However, we don't introduce a dedicated type for it. So NameValueHeaderValue supports
// name-only values in addition to name/value pairs.
public class NameValueHeaderValue : ICloneable
{
private static readonly Func<NameValueHeaderValue> s_defaultNameValueCreator = CreateNameValue;
private string _name;
private string _value;
public string Name
{
get { return _name; }
}
public string Value
{
get { return _value; }
set
{
CheckValueFormat(value);
_value = value;
}
}
internal NameValueHeaderValue()
{
}
public NameValueHeaderValue(string name)
: this(name, null)
{
}
public NameValueHeaderValue(string name, string value)
{
CheckNameValueFormat(name, value);
_name = name;
_value = value;
}
protected NameValueHeaderValue(NameValueHeaderValue source)
{
Debug.Assert(source != null);
_name = source._name;
_value = source._value;
}
public override int GetHashCode()
{
Debug.Assert(_name != null);
int nameHashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(_name);
if (!string.IsNullOrEmpty(_value))
{
// If we have a quoted-string, then just use the hash code. If we have a token, convert to lowercase
// and retrieve the hash code.
if (_value[0] == '"')
{
return nameHashCode ^ _value.GetHashCode();
}
return nameHashCode ^ StringComparer.OrdinalIgnoreCase.GetHashCode(_value);
}
return nameHashCode;
}
public override bool Equals(object obj)
{
NameValueHeaderValue other = obj as NameValueHeaderValue;
if (other == null)
{
return false;
}
if (!string.Equals(_name, other._name, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// RFC2616: 14.20: unquoted tokens should use case-INsensitive comparison; quoted-strings should use
// case-sensitive comparison. The RFC doesn't mention how to compare quoted-strings outside the "Expect"
// header. We treat all quoted-strings the same: case-sensitive comparison.
if (string.IsNullOrEmpty(_value))
{
return string.IsNullOrEmpty(other._value);
}
if (_value[0] == '"')
{
// We have a quoted string, so we need to do case-sensitive comparison.
return string.Equals(_value, other._value, StringComparison.Ordinal);
}
else
{
return string.Equals(_value, other._value, StringComparison.OrdinalIgnoreCase);
}
}
public static NameValueHeaderValue Parse(string input)
{
int index = 0;
return (NameValueHeaderValue)GenericHeaderParser.SingleValueNameValueParser.ParseValue(
input, null, ref index);
}
public static bool TryParse(string input, out NameValueHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.SingleValueNameValueParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (NameValueHeaderValue)output;
return true;
}
return false;
}
public override string ToString()
{
if (!string.IsNullOrEmpty(_value))
{
return _name + "=" + _value;
}
return _name;
}
private void AddToStringBuilder(StringBuilder sb)
{
if (GetType() != typeof(NameValueHeaderValue))
{
// If this is a derived instance, we need to give its
// ToString a chance.
sb.Append(ToString());
}
else
{
// Otherwise, we can use the base behavior and avoid
// the string concatenation.
sb.Append(_name);
if (!string.IsNullOrEmpty(_value))
{
sb.Append('=');
sb.Append(_value);
}
}
}
internal static void ToString(ObjectCollection<NameValueHeaderValue> values, char separator, bool leadingSeparator,
StringBuilder destination)
{
Debug.Assert(destination != null);
if ((values == null) || (values.Count == 0))
{
return;
}
foreach (var value in values)
{
if (leadingSeparator || (destination.Length > 0))
{
destination.Append(separator);
destination.Append(' ');
}
value.AddToStringBuilder(destination);
}
}
internal static int GetHashCode(ObjectCollection<NameValueHeaderValue> values)
{
if ((values == null) || (values.Count == 0))
{
return 0;
}
int result = 0;
foreach (var value in values)
{
result = result ^ value.GetHashCode();
}
return result;
}
internal static int GetNameValueLength(string input, int startIndex, out NameValueHeaderValue parsedValue)
{
return GetNameValueLength(input, startIndex, s_defaultNameValueCreator, out parsedValue);
}
internal static int GetNameValueLength(string input, int startIndex,
Func<NameValueHeaderValue> nameValueCreator, out NameValueHeaderValue parsedValue)
{
Debug.Assert(input != null);
Debug.Assert(startIndex >= 0);
Debug.Assert(nameValueCreator != null);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Parse the name, i.e. <name> in name/value string "<name>=<value>". Caller must remove
// leading whitespace.
int nameLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (nameLength == 0)
{
return 0;
}
string name = input.Substring(startIndex, nameLength);
int current = startIndex + nameLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// Parse the separator between name and value
if ((current == input.Length) || (input[current] != '='))
{
// We only have a name and that's OK. Return.
parsedValue = nameValueCreator();
parsedValue._name = name;
current = current + HttpRuleParser.GetWhitespaceLength(input, current); // skip whitespace
return current - startIndex;
}
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// Parse the value, i.e. <value> in name/value string "<name>=<value>"
int valueLength = GetValueLength(input, current);
if (valueLength == 0)
{
return 0; // We have an invalid value.
}
// Use parameterless ctor to avoid double-parsing of name and value, i.e. skip public ctor validation.
parsedValue = nameValueCreator();
parsedValue._name = name;
parsedValue._value = input.Substring(current, valueLength);
current = current + valueLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current); // skip whitespace
return current - startIndex;
}
// Returns the length of a name/value list, separated by 'delimiter'. E.g. "a=b, c=d, e=f" adds 3
// name/value pairs to 'nameValueCollection' if 'delimiter' equals ','.
internal static int GetNameValueListLength(string input, int startIndex, char delimiter,
ObjectCollection<NameValueHeaderValue> nameValueCollection)
{
Debug.Assert(nameValueCollection != null);
Debug.Assert(startIndex >= 0);
if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length))
{
return 0;
}
int current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex);
while (true)
{
NameValueHeaderValue parameter = null;
int nameValueLength = NameValueHeaderValue.GetNameValueLength(input, current,
s_defaultNameValueCreator, out parameter);
if (nameValueLength == 0)
{
return 0;
}
nameValueCollection.Add(parameter);
current = current + nameValueLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
if ((current == input.Length) || (input[current] != delimiter))
{
// We're done and we have at least one valid name/value pair.
return current - startIndex;
}
// input[current] is 'delimiter'. Skip the delimiter and whitespace and try to parse again.
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
}
internal static NameValueHeaderValue Find(ObjectCollection<NameValueHeaderValue> values, string name)
{
Debug.Assert((name != null) && (name.Length > 0));
if ((values == null) || (values.Count == 0))
{
return null;
}
foreach (var value in values)
{
if (string.Equals(value.Name, name, StringComparison.OrdinalIgnoreCase))
{
return value;
}
}
return null;
}
internal static int GetValueLength(string input, int startIndex)
{
Debug.Assert(input != null);
if (startIndex >= input.Length)
{
return 0;
}
int valueLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (valueLength == 0)
{
// A value can either be a token or a quoted string. Check if it is a quoted string.
if (HttpRuleParser.GetQuotedStringLength(input, startIndex, out valueLength) != HttpParseResult.Parsed)
{
// We have an invalid value. Reset the name and return.
return 0;
}
}
return valueLength;
}
private static void CheckNameValueFormat(string name, string value)
{
HeaderUtilities.CheckValidToken(name, nameof(name));
CheckValueFormat(value);
}
private static void CheckValueFormat(string value)
{
// Either value is null/empty or a valid token/quoted string
if (!(string.IsNullOrEmpty(value) || (GetValueLength(value, 0) == value.Length)))
{
throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
private static NameValueHeaderValue CreateNameValue()
{
return new NameValueHeaderValue();
}
// Implement ICloneable explicitly to allow derived types to "override" the implementation.
object ICloneable.Clone()
{
return new NameValueHeaderValue(this);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V10.Services
{
/// <summary>Settings for <see cref="KeywordPlanCampaignKeywordServiceClient"/> instances.</summary>
public sealed partial class KeywordPlanCampaignKeywordServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="KeywordPlanCampaignKeywordServiceSettings"/>.
/// </summary>
/// <returns>A new instance of the default <see cref="KeywordPlanCampaignKeywordServiceSettings"/>.</returns>
public static KeywordPlanCampaignKeywordServiceSettings GetDefault() =>
new KeywordPlanCampaignKeywordServiceSettings();
/// <summary>
/// Constructs a new <see cref="KeywordPlanCampaignKeywordServiceSettings"/> object with default settings.
/// </summary>
public KeywordPlanCampaignKeywordServiceSettings()
{
}
private KeywordPlanCampaignKeywordServiceSettings(KeywordPlanCampaignKeywordServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateKeywordPlanCampaignKeywordsSettings = existing.MutateKeywordPlanCampaignKeywordsSettings;
OnCopy(existing);
}
partial void OnCopy(KeywordPlanCampaignKeywordServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>KeywordPlanCampaignKeywordServiceClient.MutateKeywordPlanCampaignKeywords</c> and
/// <c>KeywordPlanCampaignKeywordServiceClient.MutateKeywordPlanCampaignKeywordsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateKeywordPlanCampaignKeywordsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="KeywordPlanCampaignKeywordServiceSettings"/> object.</returns>
public KeywordPlanCampaignKeywordServiceSettings Clone() => new KeywordPlanCampaignKeywordServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="KeywordPlanCampaignKeywordServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class KeywordPlanCampaignKeywordServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordPlanCampaignKeywordServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public KeywordPlanCampaignKeywordServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public KeywordPlanCampaignKeywordServiceClientBuilder()
{
UseJwtAccessWithScopes = KeywordPlanCampaignKeywordServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref KeywordPlanCampaignKeywordServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordPlanCampaignKeywordServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override KeywordPlanCampaignKeywordServiceClient Build()
{
KeywordPlanCampaignKeywordServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<KeywordPlanCampaignKeywordServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<KeywordPlanCampaignKeywordServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private KeywordPlanCampaignKeywordServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return KeywordPlanCampaignKeywordServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<KeywordPlanCampaignKeywordServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return KeywordPlanCampaignKeywordServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => KeywordPlanCampaignKeywordServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
KeywordPlanCampaignKeywordServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordPlanCampaignKeywordServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>KeywordPlanCampaignKeywordService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage Keyword Plan campaign keywords. KeywordPlanCampaign is
/// required to add the campaign keywords. Only negative keywords are supported.
/// A maximum of 1000 negative keywords are allowed per plan. This includes both
/// campaign negative keywords and ad group negative keywords.
/// </remarks>
public abstract partial class KeywordPlanCampaignKeywordServiceClient
{
/// <summary>
/// The default endpoint for the KeywordPlanCampaignKeywordService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default KeywordPlanCampaignKeywordService scopes.</summary>
/// <remarks>
/// The default KeywordPlanCampaignKeywordService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="KeywordPlanCampaignKeywordServiceClient"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="KeywordPlanCampaignKeywordServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="KeywordPlanCampaignKeywordServiceClient"/>.</returns>
public static stt::Task<KeywordPlanCampaignKeywordServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new KeywordPlanCampaignKeywordServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="KeywordPlanCampaignKeywordServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="KeywordPlanCampaignKeywordServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="KeywordPlanCampaignKeywordServiceClient"/>.</returns>
public static KeywordPlanCampaignKeywordServiceClient Create() =>
new KeywordPlanCampaignKeywordServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="KeywordPlanCampaignKeywordServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="KeywordPlanCampaignKeywordServiceSettings"/>.</param>
/// <returns>The created <see cref="KeywordPlanCampaignKeywordServiceClient"/>.</returns>
internal static KeywordPlanCampaignKeywordServiceClient Create(grpccore::CallInvoker callInvoker, KeywordPlanCampaignKeywordServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient grpcClient = new KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient(callInvoker);
return new KeywordPlanCampaignKeywordServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC KeywordPlanCampaignKeywordService client</summary>
public virtual KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateKeywordPlanCampaignKeywordsResponse MutateKeywordPlanCampaignKeywords(MutateKeywordPlanCampaignKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignKeywordsResponse> MutateKeywordPlanCampaignKeywordsAsync(MutateKeywordPlanCampaignKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignKeywordsResponse> MutateKeywordPlanCampaignKeywordsAsync(MutateKeywordPlanCampaignKeywordsRequest request, st::CancellationToken cancellationToken) =>
MutateKeywordPlanCampaignKeywordsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign keywords are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan campaign
/// keywords.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateKeywordPlanCampaignKeywordsResponse MutateKeywordPlanCampaignKeywords(string customerId, scg::IEnumerable<KeywordPlanCampaignKeywordOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateKeywordPlanCampaignKeywords(new MutateKeywordPlanCampaignKeywordsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign keywords are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan campaign
/// keywords.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignKeywordsResponse> MutateKeywordPlanCampaignKeywordsAsync(string customerId, scg::IEnumerable<KeywordPlanCampaignKeywordOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateKeywordPlanCampaignKeywordsAsync(new MutateKeywordPlanCampaignKeywordsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign keywords are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan campaign
/// keywords.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignKeywordsResponse> MutateKeywordPlanCampaignKeywordsAsync(string customerId, scg::IEnumerable<KeywordPlanCampaignKeywordOperation> operations, st::CancellationToken cancellationToken) =>
MutateKeywordPlanCampaignKeywordsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>KeywordPlanCampaignKeywordService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage Keyword Plan campaign keywords. KeywordPlanCampaign is
/// required to add the campaign keywords. Only negative keywords are supported.
/// A maximum of 1000 negative keywords are allowed per plan. This includes both
/// campaign negative keywords and ad group negative keywords.
/// </remarks>
public sealed partial class KeywordPlanCampaignKeywordServiceClientImpl : KeywordPlanCampaignKeywordServiceClient
{
private readonly gaxgrpc::ApiCall<MutateKeywordPlanCampaignKeywordsRequest, MutateKeywordPlanCampaignKeywordsResponse> _callMutateKeywordPlanCampaignKeywords;
/// <summary>
/// Constructs a client wrapper for the KeywordPlanCampaignKeywordService service, with the specified gRPC
/// client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="KeywordPlanCampaignKeywordServiceSettings"/> used within this client.
/// </param>
public KeywordPlanCampaignKeywordServiceClientImpl(KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient grpcClient, KeywordPlanCampaignKeywordServiceSettings settings)
{
GrpcClient = grpcClient;
KeywordPlanCampaignKeywordServiceSettings effectiveSettings = settings ?? KeywordPlanCampaignKeywordServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateKeywordPlanCampaignKeywords = clientHelper.BuildApiCall<MutateKeywordPlanCampaignKeywordsRequest, MutateKeywordPlanCampaignKeywordsResponse>(grpcClient.MutateKeywordPlanCampaignKeywordsAsync, grpcClient.MutateKeywordPlanCampaignKeywords, effectiveSettings.MutateKeywordPlanCampaignKeywordsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateKeywordPlanCampaignKeywords);
Modify_MutateKeywordPlanCampaignKeywordsApiCall(ref _callMutateKeywordPlanCampaignKeywords);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_MutateKeywordPlanCampaignKeywordsApiCall(ref gaxgrpc::ApiCall<MutateKeywordPlanCampaignKeywordsRequest, MutateKeywordPlanCampaignKeywordsResponse> call);
partial void OnConstruction(KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient grpcClient, KeywordPlanCampaignKeywordServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC KeywordPlanCampaignKeywordService client</summary>
public override KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient GrpcClient { get; }
partial void Modify_MutateKeywordPlanCampaignKeywordsRequest(ref MutateKeywordPlanCampaignKeywordsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateKeywordPlanCampaignKeywordsResponse MutateKeywordPlanCampaignKeywords(MutateKeywordPlanCampaignKeywordsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateKeywordPlanCampaignKeywordsRequest(ref request, ref callSettings);
return _callMutateKeywordPlanCampaignKeywords.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateKeywordPlanCampaignKeywordsResponse> MutateKeywordPlanCampaignKeywordsAsync(MutateKeywordPlanCampaignKeywordsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateKeywordPlanCampaignKeywordsRequest(ref request, ref callSettings);
return _callMutateKeywordPlanCampaignKeywords.Async(request, callSettings);
}
}
}
| |
//
// Application.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 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.Reflection;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using Mono.Unix;
using Hyena;
using Banshee.Library;
using Banshee.Playlist;
using Banshee.SmartPlaylist;
using Banshee.Sources;
using Banshee.Base;
namespace Banshee.ServiceStack
{
public delegate bool ShutdownRequestHandler ();
public delegate bool TimeoutHandler ();
public delegate bool IdleHandler ();
public delegate bool IdleTimeoutRemoveHandler (uint id);
public delegate uint TimeoutImplementationHandler (uint milliseconds, TimeoutHandler handler);
public delegate uint IdleImplementationHandler (IdleHandler handler);
public delegate bool IdleTimeoutRemoveImplementationHandler (uint id);
public static class Application
{
private const string LibGlibLibrary = "libglib-2.0-0.dll";
public static event ShutdownRequestHandler ShutdownRequested;
public static event Action<Client> ClientAdded;
private static event Action<Client> client_started;
public static event Action<Client> ClientStarted {
add {
lock (running_clients) {
foreach (Client client in running_clients) {
if (client.IsStarted) {
OnClientStarted (client);
}
}
}
client_started += value;
}
remove { client_started -= value; }
}
private static Stack<Client> running_clients = new Stack<Client> ();
private static bool shutting_down;
public static void Initialize ()
{
ServiceManager.DefaultInitialize ();
}
#if WIN32
[DllImport ("msvcrt.dll", CallingConvention = CallingConvention.Cdecl) /* willfully unmapped */]
public static extern int _putenv (string varName);
#endif
public static void Run ()
{
#if WIN32
// There are two sets of environement variables we need to impact with our LANG.
// refer to : http://article.gmane.org/gmane.comp.gnu.mingw.user/8272
var lang_code = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
string env = String.Concat ("LANG=", lang_code);
Environment.SetEnvironmentVariable ("LANG", lang_code);
_putenv (env);
#endif
Catalog.Init (Application.InternalName, System.IO.Path.Combine (
Hyena.Paths.InstalledApplicationDataRoot, "locale"));
DBusConnection.Init ();
ServiceManager.Run ();
ServiceManager.SourceManager.AddSource (new MusicLibrarySource (), true);
ServiceManager.SourceManager.AddSource (new VideoLibrarySource (), false);
ServiceManager.SourceManager.LoadExtensionSources ();
}
public static bool ShuttingDown {
get { return shutting_down; }
}
public static void Shutdown ()
{
shutting_down = true;
if (Banshee.Kernel.Scheduler.IsScheduled (typeof (Banshee.Kernel.IInstanceCriticalJob)) ||
ServiceManager.JobScheduler.HasAnyDataLossJobs ||
Banshee.Kernel.Scheduler.CurrentJob is Banshee.Kernel.IInstanceCriticalJob) {
if (shutdown_prompt_handler != null && !shutdown_prompt_handler ()) {
shutting_down = false;
return;
}
}
if (OnShutdownRequested ()) {
Dispose ();
}
shutting_down = false;
}
public static void PushClient (Client client)
{
lock (running_clients) {
running_clients.Push (client);
client.Started += OnClientStarted;
}
Action<Client> handler = ClientAdded;
if (handler != null) {
handler (client);
}
}
public static Client PopClient ()
{
lock (running_clients) {
return running_clients.Pop ();
}
}
public static Client ActiveClient {
get { lock (running_clients) { return running_clients.Peek (); } }
}
private static void OnClientStarted (Client client)
{
client.Started -= OnClientStarted;
Action<Client> handler = client_started;
if (handler != null) {
handler (client);
}
}
static bool paths_initialized;
public static void InitializePaths ()
{
if (!paths_initialized) {
// We changed banshee-1 to banshee everywhere except the
// ~/.config/banshee-1/ and ~/.cache/banshee-1 directories, and
// for gconf
Paths.UserApplicationName = "banshee-1";
Paths.ApplicationName = InternalName;
paths_initialized = true;
}
}
[DllImport (LibGlibLibrary, CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr g_get_language_names ();
public static void DisplayHelp (string page)
{
DisplayHelp ("banshee", page);
}
private static void DisplayHelp (string project, string page)
{
bool shown = false;
foreach (var lang in GLib.Marshaller.NullTermPtrToStringArray (g_get_language_names (), false)) {
string path = String.Format ("{0}/gnome/help/{1}/{2}",
Paths.InstalledApplicationDataRoot, project, lang);
if (System.IO.Directory.Exists (path)) {
shown = Banshee.Web.Browser.Open (String.Format ("ghelp:{0}", path), false);
break;
}
}
if (!shown) {
Banshee.Web.Browser.Open (String.Format ("http://library.gnome.org/users/{0}/", project));
}
}
private static bool OnShutdownRequested ()
{
ShutdownRequestHandler handler = ShutdownRequested;
if (handler != null) {
foreach (ShutdownRequestHandler del in handler.GetInvocationList ()) {
if (!del ()) {
return false;
}
}
}
return true;
}
public static void Invoke (InvokeHandler handler)
{
RunIdle (delegate { handler (); return false; });
}
public static uint RunIdle (IdleHandler handler)
{
if (idle_handler == null) {
throw new NotImplementedException ("The application client must provide an IdleImplementationHandler");
}
return idle_handler (handler);
}
public static uint RunTimeout (uint milliseconds, TimeoutHandler handler)
{
if (timeout_handler == null) {
throw new NotImplementedException ("The application client must provide a TimeoutImplementationHandler");
}
return timeout_handler (milliseconds, handler);
}
public static bool IdleTimeoutRemove (uint id)
{
if (idle_timeout_remove_handler == null) {
throw new NotImplementedException ("The application client must provide a IdleTimeoutRemoveImplementationHandler");
}
return idle_timeout_remove_handler (id);
}
private static void Dispose ()
{
ServiceManager.JobScheduler.CancelAll (true);
ServiceManager.Shutdown ();
lock (running_clients) {
while (running_clients.Count > 0) {
running_clients.Pop ().Dispose ();
}
}
}
private static ShutdownRequestHandler shutdown_prompt_handler = null;
public static ShutdownRequestHandler ShutdownPromptHandler {
get { return shutdown_prompt_handler; }
set { shutdown_prompt_handler = value; }
}
private static TimeoutImplementationHandler timeout_handler = null;
public static TimeoutImplementationHandler TimeoutHandler {
get { return timeout_handler; }
set { timeout_handler = value; }
}
private static IdleImplementationHandler idle_handler = null;
public static IdleImplementationHandler IdleHandler {
get { return idle_handler; }
set { idle_handler = value; }
}
private static IdleTimeoutRemoveImplementationHandler idle_timeout_remove_handler = null;
public static IdleTimeoutRemoveImplementationHandler IdleTimeoutRemoveHandler {
get { return idle_timeout_remove_handler; }
set { idle_timeout_remove_handler = value; }
}
public static string InternalName {
get { return "banshee"; }
}
public static string IconName {
get { return "media-player-banshee"; }
}
private static string api_version;
public static string ApiVersion {
get {
if (api_version != null) {
return api_version;
}
try {
AssemblyName name = Assembly.GetEntryAssembly ().GetName ();
api_version = String.Format ("{0}.{1}.{2}", name.Version.Major,
name.Version.Minor, name.Version.Build);
} catch {
api_version = "unknown";
}
return api_version;
}
}
private static string version;
public static string Version {
get { return version ?? (version = GetVersion ("ReleaseVersion")); }
}
private static string display_version;
public static string DisplayVersion {
get { return display_version ?? (display_version = GetVersion ("DisplayVersion")); }
}
private static string build_time;
public static string BuildTime {
get { return build_time ?? (build_time = GetBuildInfo ("BuildTime")); }
}
private static string build_host_os;
public static string BuildHostOperatingSystem {
get { return build_host_os ?? (build_host_os = GetBuildInfo ("HostOperatingSystem")); }
}
private static string build_host_cpu;
public static string BuildHostCpu {
get { return build_host_cpu ?? (build_host_cpu = GetBuildInfo ("HostCpu")); }
}
private static string build_vendor;
public static string BuildVendor {
get { return build_vendor ?? (build_vendor = GetBuildInfo ("Vendor")); }
}
private static string build_display_info;
public static string BuildDisplayInfo {
get {
if (build_display_info != null) {
return build_display_info;
}
build_display_info = String.Format ("{0} ({1}, {2}) @ {3}",
BuildVendor, BuildHostOperatingSystem, BuildHostCpu, BuildTime);
return build_display_info;
}
}
private static string GetVersion (string versionName)
{
return GetCustomAssemblyMetadata ("ApplicationVersionAttribute", versionName)
?? Catalog.GetString ("Unknown");
}
private static string GetBuildInfo (string buildField)
{
return GetCustomAssemblyMetadata ("ApplicationBuildInformationAttribute", buildField);
}
private static string GetCustomAssemblyMetadata (string attrName, string field)
{
Assembly assembly = Assembly.GetEntryAssembly ();
if (assembly == null) {
return null;
}
foreach (Attribute attribute in assembly.GetCustomAttributes (false)) {
Type type = attribute.GetType ();
PropertyInfo property = type.GetProperty (field);
if (type.Name == attrName && property != null &&
property.PropertyType == typeof (string)) {
return (string)property.GetValue (attribute, null);
}
}
return null;
}
}
}
| |
//-----------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Security;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using MS.Internal;
using System.Runtime.InteropServices;
using MS.Internal.PresentationCore;
namespace System.Windows.Media
{
internal static class MILUtilities
{
internal static readonly D3DMATRIX D3DMATRIXIdentity =
new D3DMATRIX(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
/// <summary>
/// Converts a System.Windows.Media.Matrix to a D3DMATRIX.
/// </summary>
/// <param name="matrix"> Input Matrix to convert </param>
/// <param name="d3dMatrix"> Output convered D3DMATRIX </param>
/// <SecurityNote>
/// Critical -- references and writes out to memory addresses. The
/// caller is safe if the first pointer points to a
/// constant Matrix value and the second points to a
/// D3DMATRIX value.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void ConvertToD3DMATRIX(
/* in */ Matrix* matrix,
/* out */ D3DMATRIX* d3dMatrix
)
{
*d3dMatrix = D3DMATRIXIdentity;
float* pD3DMatrix = (float*)d3dMatrix;
double* pMatrix = (double*)matrix;
// m11 = m11
pD3DMatrix[0] = (float)pMatrix[0];
// m12 = m12
pD3DMatrix[1] = (float)pMatrix[1];
// m21 = m21
pD3DMatrix[4] = (float)pMatrix[2];
// m22 = m22
pD3DMatrix[5] = (float)pMatrix[3];
// m41 = offsetX
pD3DMatrix[12] = (float)pMatrix[4];
// m42 = offsetY
pD3DMatrix[13] = (float)pMatrix[5];
}
/// <summary>
/// Converts a D3DMATRIX to a System.Windows.Media.Matrix.
/// </summary>
/// <param name="d3dMatrix"> Input D3DMATRIX to convert </param>
/// <param name="matrix"> Output converted Matrix </param>
/// <SecurityNote>
/// Critical -- references and writes out to memory addresses. The
/// caller is safe if the first pointer points to a
/// constant D3DMATRIX value and the second points to a
/// Matrix value.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void ConvertFromD3DMATRIX(
/* in */ D3DMATRIX* d3dMatrix,
/* out */ Matrix* matrix
)
{
float* pD3DMatrix = (float*)d3dMatrix;
double* pMatrix = (double*)matrix;
//
// Convert first D3DMatrix Vector
//
pMatrix[0] = (double) pD3DMatrix[0]; // m11 = m11
pMatrix[1] = (double) pD3DMatrix[1]; // m12 = m12
// Assert that non-affine fields are identity or NaN
//
// Multiplication with an affine 2D matrix (i.e., a matrix
// with only _11, _12, _21, _22, _41, & _42 set to non-identity
// values) containing NaN's, can cause the NaN's to propagate to
// all other fields. Thus, we allow NaN's in addition to
// identity values.
Debug.Assert(pD3DMatrix[2] == 0.0f || Single.IsNaN(pD3DMatrix[2]));
Debug.Assert(pD3DMatrix[3] == 0.0f || Single.IsNaN(pD3DMatrix[3]));
//
// Convert second D3DMatrix Vector
//
pMatrix[2] = (double) pD3DMatrix[4]; // m21 = m21
pMatrix[3] = (double) pD3DMatrix[5]; // m22 = m22
Debug.Assert(pD3DMatrix[6] == 0.0f || Single.IsNaN(pD3DMatrix[6]));
Debug.Assert(pD3DMatrix[7] == 0.0f || Single.IsNaN(pD3DMatrix[7]));
//
// Convert third D3DMatrix Vector
//
Debug.Assert(pD3DMatrix[8] == 0.0f || Single.IsNaN(pD3DMatrix[8]));
Debug.Assert(pD3DMatrix[9] == 0.0f || Single.IsNaN(pD3DMatrix[9]));
Debug.Assert(pD3DMatrix[10] == 1.0f || Single.IsNaN(pD3DMatrix[10]));
Debug.Assert(pD3DMatrix[11] == 0.0f || Single.IsNaN(pD3DMatrix[11]));
//
// Convert fourth D3DMatrix Vector
//
pMatrix[4] = (double) pD3DMatrix[12]; // m41 = offsetX
pMatrix[5] = (double) pD3DMatrix[13]; // m42 = offsetY
Debug.Assert(pD3DMatrix[14] == 0.0f || Single.IsNaN(pD3DMatrix[14]));
Debug.Assert(pD3DMatrix[15] == 1.0f || Single.IsNaN(pD3DMatrix[15]));
*((MatrixTypes*)(pMatrix+6)) = MatrixTypes.TRANSFORM_IS_UNKNOWN;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MILRect3D
{
public MILRect3D(ref Rect3D rect)
{
X = (float)rect.X;
Y = (float)rect.Y;
Z = (float)rect.Z;
LengthX = (float)rect.SizeX;
LengthY = (float)rect.SizeY;
LengthZ = (float)rect.SizeZ;
}
public float X;
public float Y;
public float Z;
public float LengthX;
public float LengthY;
public float LengthZ;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MilRectF
{
public float Left;
public float Top;
public float Right;
public float Bottom;
};
///<SecurityNote>
/// Critical as this code performs an elevation.
///
/// It's safe because it's just doing matrix math.
///</SecurityNote>
[SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[DllImport(DllImport.MilCore)]
private extern static /*HRESULT*/ int MIL3DCalcProjected2DBounds(
ref D3DMATRIX pFullTransform3D,
ref MILRect3D pboxBounds,
out MilRectF prcDestRect);
[SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[DllImport(DllImport.MilCore, EntryPoint = "MilUtility_CopyPixelBuffer", PreserveSig = false)]
internal extern static unsafe void MILCopyPixelBuffer(
byte * pOutputBuffer,
uint outputBufferSize,
uint outputBufferStride,
uint outputBufferOffsetInBits,
byte * pInputBuffer,
uint inputBufferSize,
uint inputBufferStride,
uint inputBufferOffsetInBits,
uint height,
uint copyWidthInBits
);
///<SecurityNote>
/// Critical - Calls a critical function -- MilCalcProjectedBounds
/// TreatAsSafe - It only does math on the given matrices.
///</SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal static Rect ProjectBounds(
ref Matrix3D viewProjMatrix,
ref Rect3D originalBox)
{
D3DMATRIX viewProjFloatMatrix = CompositionResourceManager.Matrix3DToD3DMATRIX(viewProjMatrix);
MILRect3D originalBoxFloat = new MILRect3D(ref originalBox);
MilRectF outRect = new MilRectF();
HRESULT.Check(
MIL3DCalcProjected2DBounds(
ref viewProjFloatMatrix,
ref originalBoxFloat,
out outRect));
if (outRect.Left == outRect.Right ||
outRect.Top == outRect.Bottom)
{
return Rect.Empty;
}
else
{
return new Rect(
outRect.Left,
outRect.Top,
outRect.Right - outRect.Left,
outRect.Bottom - outRect.Top
);
}
}
}
}
| |
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.Azure.Management.SignalR;
using Microsoft.Azure.Management.SignalR.Models;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Xunit;
namespace SignalR.Tests
{
public class SignalRTests
{
[Fact]
public void SignalRCheckNameTest()
{
var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (var context = MockContext.Start(this.GetType()))
{
var resourceClient = SignalRTestUtilities.GetResourceManagementClient(context, handler);
var signalrClient = SignalRTestUtilities.GetSignalRManagementClient(context, handler);
// Create resource group
var location = SignalRTestUtilities.GetDefaultSignalRLocation(resourceClient);
var resourceGroup = SignalRTestUtilities.CreateResourceGroup(resourceClient, location);
// Check valid name
var signalrName = TestUtilities.GenerateName("signalr-service-test-0820");
var checkNameRequest = signalrClient.SignalR.CheckNameAvailability(
location,
new NameAvailabilityParameters
{
Type = SignalRTestUtilities.SignalRResourceType,
Name = signalrName
});
Assert.True(checkNameRequest.NameAvailable);
Assert.Null(checkNameRequest.Reason);
Assert.Null(checkNameRequest.Message);
signalrName = SignalRTestUtilities.CreateSignalR(signalrClient, resourceGroup.Name, location).Name;
checkNameRequest = signalrClient.SignalR.CheckNameAvailability(
location,
new NameAvailabilityParameters
{
Type = SignalRTestUtilities.SignalRResourceType,
Name = signalrName,
});
Assert.False(checkNameRequest.NameAvailable);
Assert.Equal("AlreadyExists", checkNameRequest.Reason);
Assert.Equal("The name is already taken. Please try a different name.", checkNameRequest.Message);
}
}
[Fact]
public void SignalRFreeTierToStandardTest()
{
var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (var context = MockContext.Start(this.GetType()))
{
var resourceClient = SignalRTestUtilities.GetResourceManagementClient(context, handler);
var signalrClient = SignalRTestUtilities.GetSignalRManagementClient(context, handler);
var location = SignalRTestUtilities.GetDefaultSignalRLocation(resourceClient);
var resourceGroup = SignalRTestUtilities.CreateResourceGroup(resourceClient, location);
var signalrName = TestUtilities.GenerateName("signalr-service-test-0820");
var signalr = SignalRTestUtilities.CreateSignalR(signalrClient, resourceGroup.Name, location, isStandard: false);
SignalRScenarioVerification(signalrClient, resourceGroup, signalr, false);
}
}
[Fact]
public void SignalRStandardTierToFreeTest()
{
var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (var context = MockContext.Start(this.GetType()))
{
var resourceClient = SignalRTestUtilities.GetResourceManagementClient(context, handler);
var signalrClient = SignalRTestUtilities.GetSignalRManagementClient(context, handler);
var location = SignalRTestUtilities.GetDefaultSignalRLocation(resourceClient);
var resourceGroup = SignalRTestUtilities.CreateResourceGroup(resourceClient, location);
var signalrName = TestUtilities.GenerateName("signalr-service-test-0820");
var capacity = 2;
var signalr = SignalRTestUtilities.CreateSignalR(signalrClient, resourceGroup.Name, location, isStandard: true, capacity: capacity);
SignalRScenarioVerification(signalrClient, resourceGroup, signalr, true, capacity);
}
}
[Fact]
public void SignalRUsageTest()
{
var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (var context = MockContext.Start(this.GetType()))
{
var resourceClient = SignalRTestUtilities.GetResourceManagementClient(context, handler);
var signalrClient = SignalRTestUtilities.GetSignalRManagementClient(context, handler);
var location = SignalRTestUtilities.GetDefaultSignalRLocation(resourceClient);
var usages = signalrClient.Usages.List(location);
Assert.NotEmpty(usages);
var usage = usages.First();
Assert.NotNull(usage);
Assert.NotEmpty(usage.Id);
Assert.NotNull(usage.CurrentValue);
Assert.NotNull(usage.Limit);
Assert.NotNull(usage.Name);
Assert.NotEmpty(usage.Name.Value);
Assert.NotEmpty(usage.Name.LocalizedValue);
Assert.NotEmpty(usage.Unit);
}
}
private void SignalRScenarioVerification(SignalRManagementClient signalrClient, ResourceGroup resourceGroup, SignalRResource signalr, bool isStandard, int capacity = 1)
{
// Validate the newly created SignalR instance
SignalRTestUtilities.ValidateResourceDefaultTags(signalr);
Assert.NotNull(signalr.Sku);
if (isStandard)
{
Assert.Equal(SignalRSkuTier.Standard, signalr.Sku.Tier);
Assert.Equal("Standard_S1", signalr.Sku.Name);
Assert.Equal("S1", signalr.Sku.Size);
Assert.Equal(capacity, signalr.Sku.Capacity);
}
else
{
Assert.Equal(SignalRSkuTier.Free, signalr.Sku.Tier);
Assert.Equal("Free_F1", signalr.Sku.Name);
Assert.Equal("F1", signalr.Sku.Size);
Assert.Equal(capacity, signalr.Sku.Capacity);
}
Assert.Equal(ProvisioningState.Succeeded, signalr.ProvisioningState);
Assert.NotEmpty(signalr.HostName);
Assert.NotEmpty(signalr.ExternalIP);
Assert.NotNull(signalr.PublicPort);
Assert.NotNull(signalr.ServerPort);
Assert.NotEmpty(signalr.Version);
Assert.Equal(1, signalr.Features.Count); // ServiceMode will be set as Default
Assert.Equal("Default", signalr.Features.First().Value);
Assert.Equal(1, signalr.Cors.AllowedOrigins.Count); // all origins(*) are allowed by default.
Assert.Equal("*", signalr.Cors.AllowedOrigins.First());
// List the SignalR instances by resource group
var signalrByResourceGroup = signalrClient.SignalR.ListByResourceGroup(resourceGroup.Name);
Assert.Single(signalrByResourceGroup);
signalr = signalrByResourceGroup.FirstOrDefault(r => StringComparer.OrdinalIgnoreCase.Equals(r.Name, signalr.Name));
SignalRTestUtilities.ValidateResourceDefaultTags(signalr);
// Get the SignalR instance by name
signalr = signalrClient.SignalR.Get(resourceGroup.Name, signalr.Name);
SignalRTestUtilities.ValidateResourceDefaultTags(signalr);
// List keys
var keys = signalrClient.SignalR.ListKeys(resourceGroup.Name, signalr.Name);
Assert.NotNull(keys);
Assert.NotEmpty(keys.PrimaryKey);
Assert.NotEmpty(keys.PrimaryConnectionString);
Assert.NotEmpty(keys.SecondaryKey);
Assert.NotEmpty(keys.SecondaryConnectionString);
// Update the SignalR instance
capacity = isStandard ? 1 : 5;
signalr = signalrClient.SignalR.Update(resourceGroup.Name, signalr.Name, new SignalRUpdateParameters
{
Tags = SignalRTestUtilities.DefaultNewTags,
Sku = new ResourceSku
{
Name = isStandard ? "Free_F1" : "Standard_S1",
Tier = isStandard ? "Free" : "Standard",
Size = isStandard ? "F1" : "S1",
Capacity = capacity,
},
Properties = new SignalRCreateOrUpdateProperties
{
HostNamePrefix = TestUtilities.GenerateName("signalr-service-test"),
Features = new List<SignalRFeature> {
new SignalRFeature { Value = "Serverless" }
},
Cors = new SignalRCorsSettings
{
AllowedOrigins = new List<string>
{
"http://example.com:12345",
"https://contoso.com",
}
},
},
});
// Validate the updated SignalR instance
SignalRTestUtilities.ValidateResourceDefaultNewTags(signalr);
Assert.NotNull(signalr.Sku);
if (isStandard)
{
Assert.Equal(SignalRSkuTier.Free, signalr.Sku.Tier);
Assert.Equal("Free_F1", signalr.Sku.Name);
Assert.Equal("F1", signalr.Sku.Size);
Assert.Equal(capacity, signalr.Sku.Capacity);
}
else
{
Assert.Equal(SignalRSkuTier.Standard, signalr.Sku.Tier);
Assert.Equal("Standard_S1", signalr.Sku.Name);
Assert.Equal("S1", signalr.Sku.Size);
Assert.Equal(capacity, signalr.Sku.Capacity);
}
Assert.Equal(ProvisioningState.Succeeded, signalr.ProvisioningState);
Assert.NotEmpty(signalr.HostName);
Assert.NotEmpty(signalr.ExternalIP);
Assert.NotNull(signalr.PublicPort);
Assert.NotNull(signalr.ServerPort);
Assert.NotEmpty(signalr.Version);
Assert.Equal(1, signalr.Features.Count);
Assert.Equal("Serverless", signalr.Features.First().Value);
Assert.Equal(2, signalr.Cors.AllowedOrigins.Count);
Assert.Equal("http://example.com:12345", signalr.Cors.AllowedOrigins.First());
Assert.Equal("https://contoso.com", signalr.Cors.AllowedOrigins.Last());
// List keys of the updated SignalR instance
keys = signalrClient.SignalR.ListKeys(resourceGroup.Name, signalr.Name);
Assert.NotNull(keys);
Assert.NotEmpty(keys.PrimaryKey);
Assert.NotEmpty(keys.PrimaryConnectionString);
Assert.NotEmpty(keys.SecondaryKey);
Assert.NotEmpty(keys.SecondaryConnectionString);
// Regenerate primary key
var newKeys1 = signalrClient.SignalR.RegenerateKey(resourceGroup.Name, signalr.Name, new RegenerateKeyParameters
{
KeyType = "Primary",
});
// Due to a bug in SignalR RP, the result of RegenerateKey is null. UnComment following lines after we fixed it RP side
//Assert.NotNull(newKeys1);
//Assert.NotEqual(keys.PrimaryKey, newKeys1.PrimaryKey);
//Assert.NotEqual(keys.PrimaryConnectionString, newKeys1.PrimaryConnectionString);
//Assert.Null(newKeys1.SecondaryKey);
//Assert.Null(newKeys1.SecondaryConnectionString);
// Ensure only the primary key is regenerated
newKeys1 = signalrClient.SignalR.ListKeys(resourceGroup.Name, signalr.Name);
Assert.NotNull(newKeys1);
Assert.NotEqual(keys.PrimaryKey, newKeys1.PrimaryKey);
Assert.NotEqual(keys.PrimaryConnectionString, newKeys1.PrimaryConnectionString);
Assert.Equal(keys.SecondaryKey, newKeys1.SecondaryKey);
Assert.Equal(keys.SecondaryConnectionString, newKeys1.SecondaryConnectionString);
// Regenerate secondary key
var newKeys2 = signalrClient.SignalR.RegenerateKey(resourceGroup.Name, signalr.Name, new RegenerateKeyParameters
{
KeyType = "Secondary",
});
// Due to a bug in SignalR RP, the result of RegenerateKey is null. UnComment following lines after we fixed it RP side
//Assert.NotNull(newKeys2);
//Assert.Null(newKeys2.PrimaryKey);
//Assert.Null(newKeys2.PrimaryConnectionString);
//Assert.NotEqual(keys.SecondaryKey, newKeys2.SecondaryKey);
//Assert.NotEqual(keys.SecondaryConnectionString, newKeys2.SecondaryConnectionString);
// ensure only the secondary key is regenerated
newKeys2 = signalrClient.SignalR.ListKeys(resourceGroup.Name, signalr.Name);
Assert.NotNull(newKeys2);
Assert.Equal(newKeys1.PrimaryKey, newKeys2.PrimaryKey);
Assert.Equal(newKeys1.PrimaryConnectionString, newKeys2.PrimaryConnectionString);
Assert.NotEqual(newKeys1.SecondaryKey, newKeys2.SecondaryKey);
Assert.NotEqual(newKeys1.SecondaryConnectionString, newKeys2.SecondaryConnectionString);
// Delete the SignalR instance
signalrClient.SignalR.Delete(resourceGroup.Name, signalr.Name);
// Delete again, should be no-op
signalrClient.SignalR.Delete(resourceGroup.Name, signalr.Name);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace System.Management
{
/// <summary>
/// <para>Describes the possible text formats that can be used with <see cref='System.Management.ManagementBaseObject.GetText'/>.</para>
/// </summary>
public enum TextFormat
{
/// <summary>
/// Managed Object Format
/// </summary>
Mof = 0,
/// <summary>
/// XML DTD that corresponds to CIM DTD version 2.0
/// </summary>
CimDtd20 = 1,
/// <summary>
/// XML WMI DTD that corresponds to CIM DTD version 2.0.
/// Using this value enables a few WMI-specific extensions, like embedded objects.
/// </summary>
WmiDtd20 = 2
};
/// <summary>
/// <para>Describes the possible CIM types for properties, qualifiers, or method parameters.</para>
/// </summary>
public enum CimType
{
/// <summary>
/// <para>Invalid Type</para>
/// </summary>
None = 0,
/// <summary>
/// <para>A signed 8-bit integer.</para>
/// </summary>
SInt8 = 16,
/// <summary>
/// <para>An unsigned 8-bit integer.</para>
/// </summary>
UInt8 = 17,
/// <summary>
/// <para>A signed 16-bit integer.</para>
/// </summary>
SInt16 = 2,
/// <summary>
/// <para>An unsigned 16-bit integer.</para>
/// </summary>
UInt16 = 18,
/// <summary>
/// <para>A signed 32-bit integer.</para>
/// </summary>
SInt32 = 3,
/// <summary>
/// <para>An unsigned 32-bit integer.</para>
/// </summary>
UInt32 = 19,
/// <summary>
/// <para>A signed 64-bit integer.</para>
/// </summary>
SInt64 = 20,
/// <summary>
/// <para>An unsigned 64-bit integer.</para>
/// </summary>
UInt64 = 21,
/// <summary>
/// <para>A floating-point 32-bit number.</para>
/// </summary>
Real32 = 4,
/// <summary>
/// <para>A floating point 64-bit number.</para>
/// </summary>
Real64 = 5,
/// <summary>
/// <para> A boolean.</para>
/// </summary>
Boolean = 11,
/// <summary>
/// <para>A string.</para>
/// </summary>
String = 8,
/// <summary>
/// <para> A date or time value, represented in a string in DMTF
/// date/time format: yyyymmddHHMMSS.mmmmmmsUUU</para>
/// <para>where:</para>
/// <para>yyyymmdd - is the date in year/month/day</para>
/// <para>HHMMSS - is the time in hours/minutes/seconds</para>
/// <para>mmmmmm - is the number of microseconds in 6 digits</para>
/// <para>sUUU - is a sign (+ or -) and a 3-digit UTC offset</para>
/// </summary>
DateTime = 101,
/// <summary>
/// <para>A reference to another object. This is represented by a
/// string containing the path to the referenced object</para>
/// </summary>
Reference = 102,
/// <summary>
/// <para> A 16-bit character.</para>
/// </summary>
Char16 = 103,
/// <summary>
/// <para>An embedded object.</para>
/// <para>Note that embedded objects differ from references in that the embedded object
/// doesn't have a path and its lifetime is identical to the lifetime of the
/// containing object.</para>
/// </summary>
Object = 13,
};
/// <summary>
/// <para>Describes the object comparison modes that can be used with <see cref='System.Management.ManagementBaseObject.CompareTo'/>.
/// Note that these values may be combined.</para>
/// </summary>
[Flags]
public enum ComparisonSettings
{
/// <summary>
/// <para>A mode that compares all elements of the compared objects.</para>
/// </summary>
IncludeAll = 0,
/// <summary>
/// <para>A mode that compares the objects, ignoring qualifiers.</para>
/// </summary>
IgnoreQualifiers = 0x1,
/// <summary>
/// <para> A mode that ignores the source of the objects, namely the server
/// and the namespace they came from, in comparison to other objects.</para>
/// </summary>
IgnoreObjectSource = 0x2,
/// <summary>
/// <para> A mode that ignores the default values of properties.
/// This value is only meaningful when comparing classes.</para>
/// </summary>
IgnoreDefaultValues = 0x4,
/// <summary>
/// <para>A mode that assumes that the objects being compared are instances of
/// the same class. Consequently, this value causes comparison
/// of instance-related information only. Use this flag to optimize
/// performance. If the objects are not of the same class, the results are undefined.</para>
/// </summary>
IgnoreClass = 0x8,
/// <summary>
/// <para> A mode that compares string values in a case-insensitive
/// manner. This applies to strings and to qualifier values. Property and qualifier
/// names are always compared in a case-insensitive manner whether this flag is
/// specified or not.</para>
/// </summary>
IgnoreCase = 0x10,
/// <summary>
/// <para>A mode that ignores qualifier flavors. This flag still takes
/// qualifier values into account, but ignores flavor distinctions such as
/// propagation rules and override restrictions.</para>
/// </summary>
IgnoreFlavor = 0x20
};
internal enum QualifierType
{
ObjectQualifier,
PropertyQualifier,
MethodQualifier
}
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Contains the basic elements of a management
/// object. It serves as a base class to more specific management object classes.</para>
/// </summary>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
[ToolboxItem(false)]
public class ManagementBaseObject : Component, ICloneable, ISerializable
{
// This field holds onto a WbemContext for the lifetime of the appdomain. This should
// prevent Fastprox.dll from unloading prematurely.
// Since this is fixed in WinXP, we only hold onto a WbemContext if we are NOT running XP or later.
#pragma warning disable 0414 // Kept for possible reflection, comment above for history
private static WbemContext lockOnFastProx = null; // RemovedDuringPort System.Management.Instrumentation.WMICapabilities.IsWindowsXPOrHigher()?null:new WbemContext();
#pragma warning restore 0414
//
// The wbemObject is changed from a field to a property. This is to avoid major code churn and simplify the solution to
// the problem where the Initialize call actually binds to the object. This occured even in cases like Get() whereby we
// ended up getting the object twice. Any direct usage of this property will cause a call to Initialize ( true ) to be made
// (if not already done) indicating that we wish to bind to the underlying WMI object.
//
// See changes to Initialize
//
internal IWbemClassObjectFreeThreaded wbemObject
{
get
{
if (_wbemObject == null)
{
Initialize(true);
}
return _wbemObject;
}
set
{
_wbemObject = value;
}
}
internal IWbemClassObjectFreeThreaded _wbemObject ;
private PropertyDataCollection properties;
private PropertyDataCollection systemProperties;
private QualifierDataCollection qualifiers;
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementBaseObject'/> class that is serializable.</para>
/// </summary>
/// <param name='info'>The <see cref='System.Runtime.Serialization.SerializationInfo'/> to populate with data.</param>
/// <param name='context'>The destination (see <see cref='System.Runtime.Serialization.StreamingContext'/> ) for this serialization.</param>
protected ManagementBaseObject(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public new void Dispose()
{
if (_wbemObject != null)
{
_wbemObject.Dispose();
_wbemObject = null;
}
base.Dispose();
GC.SuppressFinalize(this);
}
/// <summary>
/// <para>Provides the internal WMI object represented by a ManagementObject.</para>
/// <para>See remarks with regard to usage.</para>
/// </summary>
/// <param name='managementObject'>The <see cref='System.Management.ManagementBaseObject'/> that references the requested WMI object. </param>
/// <returns>
/// <para>An <see cref='System.IntPtr'/> representing the internal WMI object.</para>
/// </returns>
/// <remarks>
/// <para>This operator is used internally by instrumentation code. It is not intended
/// for direct use by regular client or instrumented applications.</para>
/// </remarks>
public static explicit operator IntPtr(ManagementBaseObject managementObject)
{
if(null == managementObject)
return IntPtr.Zero;
return (IntPtr)managementObject.wbemObject;
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
// Factory
/// <summary>
/// Factory for various types of base object
/// </summary>
/// <param name="wbemObject"> IWbemClassObject </param>
/// <param name="scope"> The scope</param>
internal static ManagementBaseObject GetBaseObject(
IWbemClassObjectFreeThreaded wbemObject,
ManagementScope scope)
{
ManagementBaseObject newObject = null;
if (_IsClass(wbemObject))
newObject = ManagementClass.GetManagementClass(wbemObject, scope);
else
newObject = ManagementObject.GetManagementObject(wbemObject, scope);
return newObject;
}
//Constructor
internal ManagementBaseObject(IWbemClassObjectFreeThreaded wbemObject)
{
this.wbemObject = wbemObject;
properties = null;
systemProperties = null;
qualifiers = null;
}
/// <summary>
/// <para>Returns a copy of the object.</para>
/// </summary>
/// <returns>
/// <para>The new cloned object.</para>
/// </returns>
public virtual object Clone()
{
IWbemClassObjectFreeThreaded theClone = null;
int status = wbemObject.Clone_(out theClone);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return new ManagementBaseObject(theClone);
}
internal virtual void Initialize ( bool getObject ) {}
//
//Properties
//
/// <summary>
/// <para>Gets or sets a collection of <see cref='System.Management.PropertyData'/> objects describing the properties of the
/// management object.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.PropertyDataCollection'/> that represents the
/// properties of the management object.</para>
/// </value>
/// <seealso cref='System.Management.PropertyData'/>
public virtual PropertyDataCollection Properties
{
get
{
Initialize ( true ) ;
if (properties == null)
properties = new PropertyDataCollection(this, false);
return properties;
}
}
/// <summary>
/// <para>Gets or sets the collection of WMI system properties of the management object (for example, the
/// class name, server, and namespace). WMI system property names begin with
/// "__".</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.PropertyDataCollection'/> that represents the system properties of the management object.</para>
/// </value>
/// <seealso cref='System.Management.PropertyData'/>
public virtual PropertyDataCollection SystemProperties
{
get
{
Initialize ( false ) ;
if (systemProperties == null)
systemProperties = new PropertyDataCollection(this, true);
return systemProperties;
}
}
/// <summary>
/// <para>Gets or sets the collection of <see cref='System.Management.QualifierData'/> objects defined on the management object.
/// Each element in the collection holds information such as the qualifier name,
/// value, and flavor.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.QualifierDataCollection'/> that represents the qualifiers
/// defined on the management object.</para>
/// </value>
/// <seealso cref='System.Management.QualifierData'/>
public virtual QualifierDataCollection Qualifiers
{
get
{
Initialize ( true ) ;
if (qualifiers == null)
qualifiers = new QualifierDataCollection(this);
return qualifiers;
}
}
/// <summary>
/// <para>Gets or sets the path to the management object's class.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.ManagementPath'/> that represents the path to the management object's class.</para>
/// </value>
/// <example>
/// <para>For example, for the \\MyBox\root\cimv2:Win32_LogicalDisk=
/// 'C:' object, the class path is \\MyBox\root\cimv2:Win32_LogicalDisk
/// .</para>
/// </example>
public virtual ManagementPath ClassPath
{
get
{
object serverName = null;
object scopeName = null;
object className = null;
int propertyType = 0;
int propertyFlavor = 0;
int status = (int)ManagementStatus.NoError;
status = wbemObject.Get_("__SERVER", 0, ref serverName, ref propertyType, ref propertyFlavor);
if (status == (int)ManagementStatus.NoError)
{
status = wbemObject.Get_("__NAMESPACE", 0, ref scopeName, ref propertyType, ref propertyFlavor);
if (status == (int)ManagementStatus.NoError)
status = wbemObject.Get_("__CLASS", 0, ref className, ref propertyType, ref propertyFlavor);
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
ManagementPath classPath = new ManagementPath();
// initialize in case of throw
classPath.Server = string.Empty;
classPath.NamespacePath = string.Empty;
classPath.ClassName = string.Empty;
// Some of these may throw if they are NULL
try
{
classPath.Server = (string)(serverName is System.DBNull ? "" : serverName);
classPath.NamespacePath = (string)(scopeName is System.DBNull ? "" : scopeName);
classPath.ClassName = (string)(className is System.DBNull ? "" : className);
}
catch
{
}
return classPath;
}
}
//
//Methods
//
//******************************************************
//[] operator by property name
//******************************************************
/// <summary>
/// <para> Gets access to property values through [] notation.</para>
/// </summary>
/// <param name='propertyName'>The name of the property of interest. </param>
/// <value>
/// An <see cref='System.Object'/> containing the
/// value of the requested property.
/// </value>
public object this[string propertyName]
{
get { return GetPropertyValue(propertyName); }
set
{
Initialize ( true ) ;
try
{
SetPropertyValue (propertyName, value);
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo(e);
}
}
}
//******************************************************
//GetPropertyValue
//******************************************************
/// <summary>
/// <para>Gets an equivalent accessor to a property's value.</para>
/// </summary>
/// <param name='propertyName'>The name of the property of interest. </param>
/// <returns>
/// <para>The value of the specified property.</para>
/// </returns>
public object GetPropertyValue(string propertyName)
{
if (null == propertyName)
throw new ArgumentNullException (nameof(propertyName));
// Check for system properties
if (propertyName.StartsWith ("__", StringComparison.Ordinal))
return SystemProperties[propertyName].Value;
else
return Properties[propertyName].Value;
}
//******************************************************
//GetQualifierValue
//******************************************************
/// <summary>
/// <para>Gets the value of the specified qualifier.</para>
/// </summary>
/// <param name='qualifierName'>The name of the qualifier of interest. </param>
/// <returns>
/// <para>The value of the specified qualifier.</para>
/// </returns>
public object GetQualifierValue(string qualifierName)
{
return Qualifiers [qualifierName].Value;
}
//******************************************************
//SetQualifierValue
//******************************************************
/// <summary>
/// <para>Sets the value of the named qualifier.</para>
/// </summary>
/// <param name='qualifierName'>The name of the qualifier to set. This parameter cannot be null.</param>
/// <param name='qualifierValue'>The value to set.</param>
public void SetQualifierValue(string qualifierName, object qualifierValue)
{
Qualifiers [qualifierName].Value = qualifierValue;
}
//******************************************************
//GetPropertyQualifierValue
//******************************************************
/// <summary>
/// <para>Returns the value of the specified property qualifier.</para>
/// </summary>
/// <param name='propertyName'>The name of the property to which the qualifier belongs. </param>
/// <param name='qualifierName'>The name of the property qualifier of interest. </param>
/// <returns>
/// <para>The value of the specified qualifier.</para>
/// </returns>
public object GetPropertyQualifierValue(string propertyName, string qualifierName)
{
return Properties[propertyName].Qualifiers[qualifierName].Value;
}
//******************************************************
//SetPropertyQualifierValue
//******************************************************
/// <summary>
/// <para>Sets the value of the specified property qualifier.</para>
/// </summary>
/// <param name='propertyName'>The name of the property to which the qualifier belongs.</param>
/// <param name='qualifierName'>The name of the property qualifier of interest.</param>
/// <param name='qualifierValue'>The new value for the qualifier.</param>
public void SetPropertyQualifierValue(string propertyName, string qualifierName,
object qualifierValue)
{
Properties[propertyName].Qualifiers[qualifierName].Value = qualifierValue;
}
//******************************************************
//GetText
//******************************************************
/// <summary>
/// <para>Returns a textual representation of the object in the specified format.</para>
/// </summary>
/// <param name='format'>The requested textual format. </param>
/// <returns>
/// <para>The textual representation of the
/// object in the specified format.</para>
/// </returns>
public string GetText(TextFormat format)
{
string objText = null;
int status = (int)ManagementStatus.NoError;
//
// Removed Initialize call since wbemObject is a property that will call Initialize ( true ) on
// its getter.
//
switch(format)
{
case TextFormat.Mof :
status = wbemObject.GetObjectText_(0, out objText);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return objText;
case TextFormat.CimDtd20 :
case TextFormat.WmiDtd20 :
//This may throw on non-XP platforms... - should we catch ?
IWbemObjectTextSrc wbemTextSrc = (IWbemObjectTextSrc)new WbemObjectTextSrc();
IWbemContext ctx = (IWbemContext)new WbemContext();
object v = (bool)true;
ctx.SetValue_("IncludeQualifiers", 0, ref v);
ctx.SetValue_("IncludeClassOrigin", 0, ref v);
if (wbemTextSrc != null)
{
status = wbemTextSrc.GetText_(0,
(IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(wbemObject)),
(uint)format, //note: this assumes the format enum has the same values as the underlying WMI enum !!
ctx,
out objText);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
return objText;
default :
return null;
}
}
/// <summary>
/// <para>Compares two management objects.</para>
/// </summary>
/// <param name='obj'>An object to compare with this instance.</param>
/// <returns>
/// <see langword='true'/> if
/// <paramref name="obj"/> is an instance of <see cref='System.Management.ManagementBaseObject'/> and represents
/// the same object as this instance; otherwise, <see langword='false'/>.
/// </returns>
public override bool Equals(object obj)
{
bool result = false;
try
{
if (obj is ManagementBaseObject)
{
result = CompareTo ((ManagementBaseObject)obj, ComparisonSettings.IncludeAll);
}
else
{
return false;
}
}
catch (ManagementException exc)
{
if (exc.ErrorCode == ManagementStatus.NotFound)
{
//we could wind up here if Initialize() throws (either here or inside CompareTo())
//Since we cannot throw from Equals() imprelemtation and it is invalid to assume
//that two objects are different because they fail to initialize
//so, we can just compare these invalid paths "by value"
if (this is ManagementObject && obj is ManagementObject)
{
int compareRes = string.Compare(((ManagementObject)this).Path.Path,
((ManagementObject)obj).Path.Path,
StringComparison.OrdinalIgnoreCase);
return (compareRes == 0);
}
}
return false;
}
catch
{
return false;
}
return result;
}
/// <summary>
/// <para>Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.</para>
/// <para>The hash code for ManagementBaseObjects is based on the MOF for the WbemObject that this instance is based on. Two different ManagementBaseObject instances pointing to the same WbemObject in WMI will have the same mof and thus the same hash code. Changing a property value of an object will change the hash code. </para>
/// </summary>
/// <returns>
/// <para>A hash code for the current object. </para>
/// </returns>
public override int GetHashCode()
{
//This implementation has to match the Equals() implementation. In Equals(), we use
//the WMI CompareTo() which compares values of properties, qualifiers etc.
//Probably the closest we can get is to take the MOF representation of the object and get it's hash code.
int localHash = 0;
try
{
// GetText may throw if it cannot get a string for the mof for various reasons
// This should be a very rare event
localHash = this.GetText(TextFormat.Mof).GetHashCode();
}
catch (ManagementException)
{
// use the hash code of an empty string on failure to get the mof
localHash = string.Empty.GetHashCode();
}
catch (System.Runtime.InteropServices.COMException)
{
// use the hash code of an empty string on failure to get the mof
localHash = string.Empty.GetHashCode();
}
return localHash;
}
//******************************************************
//CompareTo
//******************************************************
/// <summary>
/// <para>Compares this object to another, based on specified options.</para>
/// </summary>
/// <param name='otherObject'>The object to which to compare this object. </param>
/// <param name='settings'>Options on how to compare the objects. </param>
/// <returns>
/// <para><see langword='true'/> if the objects compared are equal
/// according to the given options; otherwise, <see langword='false'/>
/// .</para>
/// </returns>
public bool CompareTo(ManagementBaseObject otherObject, ComparisonSettings settings)
{
if (null == otherObject)
throw new ArgumentNullException (nameof(otherObject));
bool result = false;
if (null != wbemObject)
{
int status = (int) ManagementStatus.NoError;
status = wbemObject.CompareTo_((int) settings, otherObject.wbemObject);
if ((int)ManagementStatus.Different == status)
result = false;
else if ((int)ManagementStatus.NoError == status)
result = true;
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else if (status < 0)
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return result;
}
internal string ClassName
{
get
{
object val = null;
int dummy1 = 0, dummy2 = 0;
int status = (int)ManagementStatus.NoError;
status = wbemObject.Get_ ("__CLASS", 0, ref val, ref dummy1, ref dummy2);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
if (val is System.DBNull)
return string.Empty;
else
return ((string) val);
}
}
private static bool _IsClass(IWbemClassObjectFreeThreaded wbemObject)
{
object val = null;
int dummy1 = 0, dummy2 = 0;
int status = wbemObject.Get_("__GENUS", 0, ref val, ref dummy1, ref dummy2);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return ((int)val == (int)tag_WBEM_GENUS_TYPE.WBEM_GENUS_CLASS);
}
internal bool IsClass
{
get
{
return _IsClass(wbemObject);
}
}
/// <summary>
/// <para>Sets the value of the named property.</para>
/// </summary>
/// <param name='propertyName'>The name of the property to be changed.</param>
/// <param name='propertyValue'>The new value for this property.</param>
public void SetPropertyValue (
string propertyName,
object propertyValue)
{
if (null == propertyName)
throw new ArgumentNullException (nameof(propertyName));
// Check for system properties
if (propertyName.StartsWith ("__", StringComparison.Ordinal))
SystemProperties[propertyName].Value = propertyValue;
else
Properties[propertyName].Value = propertyValue;
}
}//ManagementBaseObject
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing Certificates.
/// </summary>
internal partial class CertificatesOperations : IServiceOperations<ApiManagementClient>, ICertificatesOperations
{
/// <summary>
/// Initializes a new instance of the CertificatesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal CertificatesOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates new or update existing certificate.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='certificateId'>
/// Required. Identifier of the subscription.
/// </param>
/// <param name='parameters'>
/// Required. Create parameters.
/// </param>
/// <param name='etag'>
/// Optional. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string serviceName, string certificateId, CertificateCreateOrUpdateParameters parameters, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (certificateId == null)
{
throw new ArgumentNullException("certificateId");
}
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("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("certificateId", certificateId);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/certificates/";
url = url + Uri.EscapeDataString(certificateId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
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.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject certificateCreateOrUpdateParametersValue = new JObject();
requestDoc = certificateCreateOrUpdateParametersValue;
if (parameters.Data != null)
{
certificateCreateOrUpdateParametersValue["data"] = parameters.Data;
}
if (parameters.Password != null)
{
certificateCreateOrUpdateParametersValue["password"] = parameters.Password;
}
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.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes specific certificate.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='certificateId'>
/// Required. Identifier of the certificate.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string certificateId, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (certificateId == null)
{
throw new ArgumentNullException("certificateId");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("certificateId", certificateId);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/certificates/";
url = url + Uri.EscapeDataString(certificateId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
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.TryAddWithoutValidation("If-Match", etag);
// 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 && statusCode != HttpStatusCode.NoContent)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets specific certificate.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='certificateId'>
/// Required. Identifier of the certificate.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Get Certificate operation response details.
/// </returns>
public async Task<CertificateGetResponse> GetAsync(string resourceGroupName, string serviceName, string certificateId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (certificateId == null)
{
throw new ArgumentNullException("certificateId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("certificateId", certificateId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/certificates/";
url = url + Uri.EscapeDataString(certificateId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CertificateGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CertificateGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
CertificateContract valueInstance = new CertificateContract();
result.Value = valueInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
valueInstance.IdPath = idInstance;
}
JToken subjectValue = responseDoc["subject"];
if (subjectValue != null && subjectValue.Type != JTokenType.Null)
{
string subjectInstance = ((string)subjectValue);
valueInstance.Subject = subjectInstance;
}
JToken thumbprintValue = responseDoc["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
valueInstance.Thumbprint = thumbprintInstance;
}
JToken expirationDateValue = responseDoc["expirationDate"];
if (expirationDateValue != null && expirationDateValue.Type != JTokenType.Null)
{
DateTime expirationDateInstance = ((DateTime)expirationDateValue);
valueInstance.ExpirationDate = expirationDateInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Certificates operation response details.
/// </returns>
public async Task<CertificateListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/certificates";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CertificateListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CertificateListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
CertificatePaged resultInstance = new CertificatePaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
CertificateContract certificateContractInstance = new CertificateContract();
resultInstance.Values.Add(certificateContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
certificateContractInstance.IdPath = idInstance;
}
JToken subjectValue = valueValue["subject"];
if (subjectValue != null && subjectValue.Type != JTokenType.Null)
{
string subjectInstance = ((string)subjectValue);
certificateContractInstance.Subject = subjectInstance;
}
JToken thumbprintValue = valueValue["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
certificateContractInstance.Thumbprint = thumbprintInstance;
}
JToken expirationDateValue = valueValue["expirationDate"];
if (expirationDateValue != null && expirationDateValue.Type != JTokenType.Null)
{
DateTime expirationDateInstance = ((DateTime)expirationDateValue);
certificateContractInstance.ExpirationDate = expirationDateInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
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>
/// List all certificates of the Api Management service instance.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Certificates operation response details.
/// </returns>
public async Task<CertificateListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CertificateListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CertificateListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
CertificatePaged resultInstance = new CertificatePaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
CertificateContract certificateContractInstance = new CertificateContract();
resultInstance.Values.Add(certificateContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
certificateContractInstance.IdPath = idInstance;
}
JToken subjectValue = valueValue["subject"];
if (subjectValue != null && subjectValue.Type != JTokenType.Null)
{
string subjectInstance = ((string)subjectValue);
certificateContractInstance.Subject = subjectInstance;
}
JToken thumbprintValue = valueValue["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
certificateContractInstance.Thumbprint = thumbprintInstance;
}
JToken expirationDateValue = valueValue["expirationDate"];
if (expirationDateValue != null && expirationDateValue.Type != JTokenType.Null)
{
DateTime expirationDateInstance = ((DateTime)expirationDateValue);
certificateContractInstance.ExpirationDate = expirationDateInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
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();
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.