context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** A specially designed handle wrapper to ensure we never leak
** an OS handle. The runtime treats this class specially during
** P/Invoke marshaling and finalization. Users should write
** subclasses of SafeHandle for each distinct handle type.
**
**
===========================================================*/
using System;
using System.Threading;
using System.Runtime.ConstrainedExecution;
namespace System.Runtime.InteropServices
{
/*
Problems addressed by the SafeHandle class:
1) Critical finalization - ensure we never leak OS resources in SQL. Done
without running truly arbitrary & unbounded amounts of managed code.
2) Reduced graph promotion - during finalization, keep object graph small
3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread race (HandleRef)
4) Elimination of security races w/ explicit calls to Close (HandleProtector)
5) Enforcement of the above via the type system - Don't use IntPtr anymore.
6) Allows the handle lifetime to be controlled externally via a boolean.
Subclasses of SafeHandle will implement the ReleaseHandle abstract method
used to execute any code required to free the handle. This method will be
prepared as a constrained execution region at instance construction time
(along with all the methods in its statically determinable call graph). This
implies that we won't get any inconvenient jit allocation errors or rude
thread abort interrupts while releasing the handle but the user must still
write careful code to avoid injecting fault paths of their own (see the CER
spec for more details). In particular, any sub-methods you call should be
decorated with a reliability contract of the appropriate level. In most cases
this should be:
ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)
Also, any P/Invoke methods should use the SuppressUnmanagedCodeSecurity
attribute to avoid a runtime security check that can also inject failures
(even if the check is guaranteed to pass).
The GC will run ReleaseHandle methods after any normal finalizers have been
run for objects that were collected at the same time. This ensures classes
like FileStream can run a normal finalizer to flush out existing buffered
data. This is key - it means adding this class to a class like FileStream does
not alter our current semantics w.r.t. finalization today.
Subclasses must also implement the IsInvalid property so that the
infrastructure can tell when critical finalization is actually required.
Again, this method is prepared ahead of time. It's envisioned that direct
subclasses of SafeHandle will provide an IsInvalid implementation that suits
the general type of handle they support (null is invalid, -1 is invalid etc.)
and then these classes will be further derived for specific safe handle types.
Most classes using SafeHandle should not provide a finalizer. If they do
need to do so (ie, for flushing out file buffers, needing to write some data
back into memory, etc), then they can provide a finalizer that will be
guaranteed to run before the SafeHandle's critical finalizer.
Note that SafeHandle's ReleaseHandle is called from a constrained execution
region, and is eagerly prepared before we create your class. This means you
should only call methods with an appropriate reliability contract from your
ReleaseHandle method.
Subclasses are expected to be written as follows (note that
SuppressUnmanagedCodeSecurity should always be used on any P/Invoke methods
invoked as part of ReleaseHandle, in order to switch the security check from
runtime to jit time and thus remove a possible failure path from the
invocation of the method):
internal sealed MySafeHandleSubclass : SafeHandle {
// Called by P/Invoke when returning SafeHandles
private MySafeHandleSubclass() : base(IntPtr.Zero, true)
{
}
// If & only if you need to support user-supplied handles
internal MySafeHandleSubclass(IntPtr preexistingHandle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
{
SetHandle(preexistingHandle);
}
// Do not provide a finalizer - SafeHandle's critical finalizer will
// call ReleaseHandle for you.
public override bool IsInvalid {
get { return handle == IntPtr.Zero; }
}
override protected bool ReleaseHandle()
{
return MyNativeMethods.CloseHandle(handle);
}
}
Then elsewhere to create one of these SafeHandles, define a method
with the following type of signature (CreateFile follows this model).
Note that when returning a SafeHandle like this, P/Invoke will call your
class's default constructor. Also, you probably want to define CloseHandle
somewhere, and remember to apply a reliability contract to it.
[SuppressUnmanagedCodeSecurity]
internal static class MyNativeMethods {
[DllImport(Win32Native.CORE_HANDLE)]
private static extern MySafeHandleSubclass CreateHandle(int someState);
[DllImport(Win32Native.CORE_HANDLE, SetLastError=true), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern bool CloseHandle(IntPtr handle);
}
Drawbacks with this implementation:
1) Requires some magic to run the critical finalizer.
*/
public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")]
protected IntPtr handle; // PUBLICLY DOCUMENTED handle field
private int _state; // Combined ref count and closed/disposed flags (so we can atomically modify them).
private bool _ownsHandle; // Whether we can release this handle.
// Bitmasks for the _state field above.
private static class StateBits
{
public const int Closed = 0x00000001;
public const int Disposed = 0x00000002;
public const int RefCount = unchecked((int)0xfffffffc);
public const int RefCountOne = 4; // Amount to increment state field to yield a ref count increment of 1
};
// Creates a SafeHandle class. Users must then set the Handle property.
// To prevent the SafeHandle from being freed, write a subclass that
// doesn't define a finalizer.
protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle)
{
handle = invalidHandleValue;
_state = StateBits.RefCountOne; // Ref count 1 and not closed or disposed.
_ownsHandle = ownsHandle;
if (!ownsHandle)
GC.SuppressFinalize(this);
}
//
// The handle cannot be closed until we are sure that no other objects might
// be using it. In the case of finalization, there may be other objects in
// the finalization queue that still hold a reference to this SafeHandle.
// So we can't assume that just because our finalizer is running, no other
// object will need to access this handle.
//
// The CLR solves this by having SafeHandle derive from CriticalFinalizerObject.
// This ensures that SafeHandle's finalizer will run only after all "normal"
// finalizers in the queue. But MRT doesn't support CriticalFinalizerObject, or
// any other explicit control of finalization order.
//
// For now, we'll hack this by not releasing the handle when our finalizer
// is called. Instead, we create a new DelayedFinalizer instance, whose
// finalizer will release the handle. Thus the handle won't be released in this
// finalization cycle, but should be released in the next.
//
// This has the effect of delaying cleanup for much longer than would have
// happened on the CLR. This also means that we may not close some handles
// at shutdown, since there may not be another finalization cycle to run
// the delayed finalizer. If either of these end up being a problem, we should
// consider adding more control over finalization order to MRT (or, better,
// turning over control of finalization ordering to System.Private.CoreLib).
//
private class DelayedFinalizer
{
private SafeHandle _safeHandle;
public DelayedFinalizer(SafeHandle safeHandle)
{
_safeHandle = safeHandle;
}
~DelayedFinalizer()
{
_safeHandle.Dispose(false);
}
}
~SafeHandle()
{
new DelayedFinalizer(this);
}
// Keep the 'handle' variable named 'handle' to make sure it matches the surface area
protected void SetHandle(IntPtr handle)
{
this.handle = handle;
}
// Used by Interop marshalling code
internal void InitializeHandle(IntPtr _handle)
{
// The SafeHandle should be invalid to be able to initialize it
System.Diagnostics.Debug.Assert(IsInvalid);
handle = _handle;
}
// This method is necessary for getting an IntPtr out of a SafeHandle.
// Used to tell whether a call to create the handle succeeded by comparing
// the handle against a known invalid value, and for backwards
// compatibility to support the handle properties returning IntPtrs on
// many of our Framework classes.
// Note that this method is dangerous for two reasons:
// 1) If the handle has been marked invalid with SetHandleasInvalid,
// DangerousGetHandle will still return the original handle value.
// 2) The handle returned may be recycled at any point. At best this means
// the handle might stop working suddenly. At worst, if the handle or
// the resource the handle represents is exposed to untrusted code in
// any way, this can lead to a handle recycling security attack (i.e. an
// untrusted caller can query data on the handle you've just returned
// and get back information for an entirely unrelated resource).
public IntPtr DangerousGetHandle()
{
return handle;
}
public bool IsClosed
{
get { return (_state & StateBits.Closed) == StateBits.Closed; }
}
public abstract bool IsInvalid
{
get;
}
public void Close()
{
Dispose(true);
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
InternalRelease(true);
GC.SuppressFinalize(this);
}
public void SetHandleAsInvalid()
{
int oldState, newState;
do
{
oldState = _state;
if ((oldState & StateBits.Closed) != 0)
return;
newState = oldState | StateBits.Closed;
} while (Interlocked.CompareExchange(ref _state, newState, oldState) != oldState);
}
// Implement this abstract method in your derived class to specify how to
// free the handle. Be careful not write any code that's subject to faults
// in this method (the runtime will prepare the infrastructure for you so
// that no jit allocations etc. will occur, but don't allocate memory unless
// you can deal with the failure and still free the handle).
// The boolean returned should be true for success and false if the runtime
// should fire a SafeHandleCriticalFailure MDA (CustomerDebugProbe) if that
// MDA is enabled.
protected abstract bool ReleaseHandle();
// Add a reason why this handle should not be relinquished (i.e. have
// ReleaseHandle called on it). This method has dangerous in the name since
// it must always be used carefully (e.g. called within a CER) to avoid
// leakage of the handle. It returns a boolean indicating whether the
// increment was actually performed to make it easy for program logic to
// back out in failure cases (i.e. is a call to DangerousRelease needed).
// It is passed back via a ref parameter rather than as a direct return so
// that callers need not worry about the atomicity of calling the routine
// and assigning the return value to a variable (the variable should be
// explicitly set to false prior to the call). The only failure cases are
// when the method is interrupted prior to processing by a thread abort or
// when the handle has already been (or is in the process of being)
// released.
public void DangerousAddRef(ref bool success)
{
DangerousAddRef_WithNoNullCheck();
success = true;
}
// Partner to DangerousAddRef. This should always be successful when used in
// a correct manner (i.e. matching a successful DangerousAddRef and called
// from a region such as a CER where a thread abort cannot interrupt
// processing). In the same way that unbalanced DangerousAddRef calls can
// cause resource leakage, unbalanced DangerousRelease calls may cause
// invalid handle states to become visible to other threads. This
// constitutes a potential security hole (via handle recycling) as well as a
// correctness problem -- so don't ever expose Dangerous* calls out to
// untrusted code.
public void DangerousRelease()
{
InternalRelease(false);
}
// Do not call this directly - only call through the extension method SafeHandleExtensions.DangerousAddRef.
internal void DangerousAddRef_WithNoNullCheck()
{
// To prevent handle recycling security attacks we must enforce the
// following invariant: we cannot successfully AddRef a handle on which
// we've committed to the process of releasing.
// We ensure this by never AddRef'ing a handle that is marked closed and
// never marking a handle as closed while the ref count is non-zero. For
// this to be thread safe we must perform inspection/updates of the two
// values as a single atomic operation. We achieve this by storing them both
// in a single aligned DWORD and modifying the entire state via interlocked
// compare exchange operations.
// Additionally we have to deal with the problem of the Dispose operation.
// We must assume that this operation is directly exposed to untrusted
// callers and that malicious callers will try and use what is basically a
// Release call to decrement the ref count to zero and free the handle while
// it's still in use (the other way a handle recycling attack can be
// mounted). We combat this by allowing only one Dispose to operate against
// a given safe handle (which balances the creation operation given that
// Dispose suppresses finalization). We record the fact that a Dispose has
// been requested in the same state field as the ref count and closed state.
// So the state field ends up looking like this:
//
// 31 2 1 0
// +-----------------------------------------------------------+---+---+
// | Ref count | D | C |
// +-----------------------------------------------------------+---+---+
//
// Where D = 1 means a Dispose has been performed and C = 1 means the
// underlying handle has (or will be shortly) released.
// Might have to perform the following steps multiple times due to
// interference from other AddRef's and Release's.
int oldState, newState;
do
{
// First step is to read the current handle state. We use this as a
// basis to decide whether an AddRef is legal and, if so, to propose an
// update predicated on the initial state (a conditional write).
oldState = _state;
// Check for closed state.
if ((oldState & StateBits.Closed) != 0)
{
throw new ObjectDisposedException("SafeHandle");
}
// Not closed, let's propose an update (to the ref count, just add
// StateBits.RefCountOne to the state to effectively add 1 to the ref count).
// Continue doing this until the update succeeds (because nobody
// modifies the state field between the read and write operations) or
// the state moves to closed.
newState = oldState + StateBits.RefCountOne;
} while (Interlocked.CompareExchange(ref _state, newState, oldState) != oldState);
// If we got here we managed to update the ref count while the state
// remained non closed. So we're done.
}
private void InternalRelease(bool fDispose)
{
// See AddRef above for the design of the synchronization here. Basically we
// will try to decrement the current ref count and, if that would take us to
// zero refs, set the closed state on the handle as well.
bool fPerformRelease = false;
// Might have to perform the following steps multiple times due to
// interference from other AddRef's and Release's.
int oldState, newState;
do
{
// First step is to read the current handle state. We use this cached
// value to predicate any modification we might decide to make to the
// state).
oldState = _state;
// If this is a Dispose operation we have additional requirements (to
// ensure that Dispose happens at most once as the comments in AddRef
// detail). We must check that the dispose bit is not set in the old
// state and, in the case of successful state update, leave the disposed
// bit set. Silently do nothing if Dispose has already been called
// (because we advertise that as a semantic of Dispose).
if (fDispose && ((oldState & StateBits.Disposed) != 0))
return;
// We should never see a ref count of zero (that would imply we have
// unbalanced AddRef and Releases). (We might see a closed state before
// hitting zero though -- that can happen if SetHandleAsInvalid is
// used).
if ((oldState & StateBits.RefCount) == 0)
{
throw new ObjectDisposedException("SafeHandle");
}
// If we're proposing a decrement to zero and the handle is not closed
// and we own the handle then we need to release the handle upon a
// successful state update.
fPerformRelease = ((oldState & (StateBits.RefCount | StateBits.Closed)) == StateBits.RefCountOne);
fPerformRelease &= _ownsHandle;
// If so we need to check whether the handle is currently invalid by
// asking the SafeHandle subclass. We must do this *before*
// transitioning the handle to closed, however, since setting the closed
// state will cause IsInvalid to always return true.
if (fPerformRelease && IsInvalid)
fPerformRelease = false;
// Attempt the update to the new state, fail and retry if the initial
// state has been modified in the meantime. Decrement the ref count by
// substracting StateBits.RefCountOne from the state then OR in the bits for
// Dispose (if that's the reason for the Release) and closed (if the
// initial ref count was 1).
newState = (oldState - StateBits.RefCountOne) |
((oldState & StateBits.RefCount) == StateBits.RefCountOne ? StateBits.Closed : 0) |
(fDispose ? StateBits.Disposed : 0);
} while (Interlocked.CompareExchange(ref _state, newState, oldState) != oldState);
// If we get here we successfully decremented the ref count. Additionally we
// may have decremented it to zero and set the handle state as closed. In
// this case (providng we own the handle) we will call the ReleaseHandle
// method on the SafeHandle subclass.
if (fPerformRelease)
ReleaseHandle();
}
}
internal static class SafeHandleExtensions
{
public static void DangerousAddRef(this SafeHandle safeHandle)
{
// This check provides rough compatibility with the desktop code (this code's desktop counterpart is AcquireSafeHandleFromWaitHandle() inside clr.dll)
// which throws ObjectDisposed if someone passes an uninitialized WaitHandle into one of the Wait apis. We use an extension method
// because otherwise, the "null this" would trigger a NullReferenceException before we ever get to this check.
if (safeHandle == null)
throw new ObjectDisposedException(SR.ObjectDisposed_Generic);
safeHandle.DangerousAddRef_WithNoNullCheck();
}
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class ReplicationLinkOperationsExtensions
{
/// <summary>
/// Deletes the Azure SQL Database Replication Link with the given id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be dropped.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be deleted.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).DeleteAsync(resourceGroupName, serverName, databaseName, linkId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the Azure SQL Database Replication Link with the given id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be dropped.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be deleted.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return operations.DeleteAsync(resourceGroupName, serverName, databaseName, linkId, CancellationToken.None);
}
/// <summary>
/// Returns information about an Azure SQL Database Replication Link.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to get the link for.
/// </param>
/// <param name='linkId'>
/// Required. The replication link id to be retrieved.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database Replication
/// Link request.
/// </returns>
public static ReplicationLinkGetResponse Get(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).GetAsync(resourceGroupName, serverName, databaseName, linkId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about an Azure SQL Database Replication Link.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to get the link for.
/// </param>
/// <param name='linkId'>
/// Required. The replication link id to be retrieved.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database Replication
/// Link request.
/// </returns>
public static Task<ReplicationLinkGetResponse> GetAsync(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return operations.GetAsync(resourceGroupName, serverName, databaseName, linkId, CancellationToken.None);
}
/// <summary>
/// Returns information about Azure SQL Database Replication Links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server in which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to retrieve links for.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database Replication
/// Link request.
/// </returns>
public static ReplicationLinkListResponse List(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).ListAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about Azure SQL Database Replication Links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server in which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to retrieve links for.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database Replication
/// Link request.
/// </returns>
public static Task<ReplicationLinkListResponse> ListAsync(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.ListAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using NodaTime;
using QuantConnect.Securities;
namespace QuantConnect.Scheduling
{
/// <summary>
/// Helper class used to provide better syntax when defining time rules
/// </summary>
public class TimeRules
{
private DateTimeZone _timeZone;
private readonly SecurityManager _securities;
/// <summary>
/// Initializes a new instance of the <see cref="TimeRules"/> helper class
/// </summary>
/// <param name="securities">The security manager</param>
/// <param name="timeZone">The algorithm's default time zone</param>
public TimeRules(SecurityManager securities, DateTimeZone timeZone)
{
_securities = securities;
_timeZone = timeZone;
}
/// <summary>
/// Sets the default time zone
/// </summary>
/// <param name="timeZone">The time zone to use for helper methods that can't resolve a time zone</param>
public void SetDefaultTimeZone(DateTimeZone timeZone)
{
_timeZone = timeZone;
}
/// <summary>
/// Specifies an event should fire at the specified time of day in the algorithm's time zone
/// </summary>
/// <param name="timeOfDay">The time of day in the algorithm's time zone the event should fire</param>
/// <returns>A time rule that fires at the specified time in the algorithm's time zone</returns>
public ITimeRule At(TimeSpan timeOfDay)
{
return At(timeOfDay, _timeZone);
}
/// <summary>
/// Specifies an event should fire at the specified time of day in the algorithm's time zone
/// </summary>
/// <param name="hour">The hour</param>
/// <param name="minute">The minute</param>
/// <param name="second">The second</param>
/// <returns>A time rule that fires at the specified time in the algorithm's time zone</returns>
public ITimeRule At(int hour, int minute, int second = 0)
{
return At(new TimeSpan(hour, minute, second), _timeZone);
}
/// <summary>
/// Specifies an event should fire at the specified time of day in the specified time zone
/// </summary>
/// <param name="hour">The hour</param>
/// <param name="minute">The minute</param>
/// <param name="timeZone">The time zone the event time is represented in</param>
/// <returns>A time rule that fires at the specified time in the algorithm's time zone</returns>
public ITimeRule At(int hour, int minute, DateTimeZone timeZone)
{
return At(new TimeSpan(hour, minute, 0), timeZone);
}
/// <summary>
/// Specifies an event should fire at the specified time of day in the specified time zone
/// </summary>
/// <param name="hour">The hour</param>
/// <param name="minute">The minute</param>
/// <param name="second">The second</param>
/// <param name="timeZone">The time zone the event time is represented in</param>
/// <returns>A time rule that fires at the specified time in the algorithm's time zone</returns>
public ITimeRule At(int hour, int minute, int second, DateTimeZone timeZone)
{
return At(new TimeSpan(hour, minute, second), timeZone);
}
/// <summary>
/// Specifies an event should fire at the specified time of day in the specified time zone
/// </summary>
/// <param name="timeOfDay">The time of day in the algorithm's time zone the event should fire</param>
/// <param name="timeZone">The time zone the date time is expressed in</param>
/// <returns>A time rule that fires at the specified time in the algorithm's time zone</returns>
public ITimeRule At(TimeSpan timeOfDay, DateTimeZone timeZone)
{
var name = string.Join(",", timeOfDay.TotalHours.ToString("0.##"));
Func<IEnumerable<DateTime>, IEnumerable<DateTime>> applicator = dates =>
from date in dates
let localEventTime = date + timeOfDay
let utcEventTime = localEventTime.ConvertToUtc(timeZone)
select utcEventTime;
return new FuncTimeRule(name, applicator);
}
/// <summary>
/// Specifies an event should fire periodically on the requested interval
/// </summary>
/// <param name="interval">The frequency with which the event should fire</param>
/// <returns>A time rule that fires after each interval passes</returns>
public ITimeRule Every(TimeSpan interval)
{
var name = "Every " + interval.TotalMinutes.ToString("0.##") + " min";
Func<IEnumerable<DateTime>, IEnumerable<DateTime>> applicator = dates => EveryIntervalIterator(dates, interval);
return new FuncTimeRule(name, applicator);
}
/// <summary>
/// Specifies an event should fire at market open +- <paramref name="minutesAfterOpen"/>
/// </summary>
/// <param name="symbol">The symbol whose market open we want an event for</param>
/// <param name="minutesAfterOpen">The time after market open that the event should fire</param>
/// <param name="extendedMarketOpen">True to use extended market open, false to use regular market open</param>
/// <returns>A time rule that fires the specified number of minutes after the symbol's market open</returns>
public ITimeRule AfterMarketOpen(Symbol symbol, double minutesAfterOpen = 0, bool extendedMarketOpen = false)
{
var security = GetSecurity(symbol);
var type = extendedMarketOpen ? "ExtendedMarketOpen" : "MarketOpen";
var name = string.Format("{0}: {1} min after {2}", symbol, minutesAfterOpen.ToString("0.##"), type);
var timeAfterOpen = TimeSpan.FromMinutes(minutesAfterOpen);
Func<IEnumerable<DateTime>, IEnumerable<DateTime>> applicator = dates =>
from date in dates
where security.Exchange.DateIsOpen(date)
let marketOpen = security.Exchange.Hours.GetNextMarketOpen(date, extendedMarketOpen)
let localEventTime = marketOpen + timeAfterOpen
let utcEventTime = localEventTime.ConvertToUtc(security.Exchange.TimeZone)
select utcEventTime;
return new FuncTimeRule(name, applicator);
}
/// <summary>
/// Specifies an event should fire at the market close +- <paramref name="minutesBeforeClose"/>
/// </summary>
/// <param name="symbol">The symbol whose market close we want an event for</param>
/// <param name="minutesBeforeClose">The time before market close that the event should fire</param>
/// <param name="extendedMarketClose">True to use extended market close, false to use regular market close</param>
/// <returns>A time rule that fires the specified number of minutes before the symbol's market close</returns>
public ITimeRule BeforeMarketClose(Symbol symbol, double minutesBeforeClose = 0, bool extendedMarketClose = false)
{
var security = GetSecurity(symbol);
var type = extendedMarketClose ? "ExtendedMarketClose" : "MarketClose";
var name = string.Format("{0}: {1} min before {2}", security.Symbol, minutesBeforeClose.ToString("0.##"), type);
var timeBeforeClose = TimeSpan.FromMinutes(minutesBeforeClose);
Func<IEnumerable<DateTime>, IEnumerable<DateTime>> applicator = dates =>
from date in dates
where security.Exchange.DateIsOpen(date)
let marketClose = security.Exchange.Hours.GetNextMarketClose(date, extendedMarketClose)
let localEventTime = marketClose - timeBeforeClose
let utcEventTime = localEventTime.ConvertToUtc(security.Exchange.TimeZone)
select utcEventTime;
return new FuncTimeRule(name, applicator);
}
private Security GetSecurity(Symbol symbol)
{
Security security;
if (!_securities.TryGetValue(symbol, out security))
{
throw new Exception(symbol.ToString() + " not found in portfolio. Request this data when initializing the algorithm.");
}
return security;
}
private static IEnumerable<DateTime> EveryIntervalIterator(IEnumerable<DateTime> dates, TimeSpan interval)
{
foreach (var date in dates)
{
for (var time = TimeSpan.Zero; time < Time.OneDay; time += interval)
{
yield return date + time;
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InventoryTransferModule")]
public class InventoryTransferModule : ISharedRegionModule
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
private List<Scene> m_Scenelist = new List<Scene>();
private IMessageTransferModule m_TransferModule;
private bool m_Enabled = true;
#region Region Module interface
public void Initialise(IConfigSource config)
{
if (config.Configs["Messaging"] != null)
{
// Allow disabling this module in config
//
if (config.Configs["Messaging"].GetString(
"InventoryTransferModule", "InventoryTransferModule") !=
"InventoryTransferModule")
{
m_Enabled = false;
return;
}
}
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenelist.Add(scene);
// scene.RegisterModuleInterface<IInventoryTransferModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
}
public void RegionLoaded(Scene scene)
{
if (m_TransferModule == null)
{
m_TransferModule = m_Scenelist[0].RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
{
m_log.Error("[INVENTORY TRANSFER]: No Message transfer module found, transfers will be local only");
m_Enabled = false;
// m_Scenelist.Clear();
// scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
}
}
}
public void RemoveRegion(Scene scene)
{
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
m_Scenelist.Remove(scene);
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "InventoryModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
private void OnNewClient(IClientAPI client)
{
// Inventory giving is conducted via instant message
client.OnInstantMessage += OnInstantMessage;
}
private Scene FindClientScene(UUID agentId)
{
lock (m_Scenelist)
{
foreach (Scene scene in m_Scenelist)
{
ScenePresence presence = scene.GetScenePresence(agentId);
if (presence != null)
return scene;
}
}
return null;
}
private void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
// m_log.DebugFormat(
// "[INVENTORY TRANSFER]: {0} IM type received from client {1}. From={2} ({3}), To={4}",
// (InstantMessageDialog)im.dialog, client.Name,
// im.fromAgentID, im.fromAgentName, im.toAgentID);
Scene scene = FindClientScene(client.AgentId);
if (scene == null) // Something seriously wrong here.
return;
if (im.dialog == (byte) InstantMessageDialog.InventoryOffered)
{
//m_log.DebugFormat("Asset type {0}", ((AssetType)im.binaryBucket[0]));
if (im.binaryBucket.Length < 17) // Invalid
return;
UUID receipientID = new UUID(im.toAgentID);
ScenePresence user = scene.GetScenePresence(receipientID);
UUID copyID;
// First byte is the asset type
AssetType assetType = (AssetType)im.binaryBucket[0];
if (AssetType.Folder == assetType)
{
UUID folderID = new UUID(im.binaryBucket, 1);
m_log.DebugFormat(
"[INVENTORY TRANSFER]: Inserting original folder {0} into agent {1}'s inventory",
folderID, new UUID(im.toAgentID));
InventoryFolderBase folderCopy
= scene.GiveInventoryFolder(client, receipientID, client.AgentId, folderID, UUID.Zero);
if (folderCopy == null)
{
client.SendAgentAlertMessage("Can't find folder to give. Nothing given.", false);
return;
}
// The outgoing binary bucket should contain only the byte which signals an asset folder is
// being copied and the following bytes for the copied folder's UUID
copyID = folderCopy.ID;
byte[] copyIDBytes = copyID.GetBytes();
im.binaryBucket = new byte[1 + copyIDBytes.Length];
im.binaryBucket[0] = (byte)AssetType.Folder;
Array.Copy(copyIDBytes, 0, im.binaryBucket, 1, copyIDBytes.Length);
if (user != null)
user.ControllingClient.SendBulkUpdateInventory(folderCopy);
// HACK!!
// Insert the ID of the copied folder into the IM so that we know which item to move to trash if it
// is rejected.
// XXX: This is probably a misuse of the session ID slot.
im.imSessionID = copyID.Guid;
}
else
{
// First byte of the array is probably the item type
// Next 16 bytes are the UUID
UUID itemID = new UUID(im.binaryBucket, 1);
m_log.DebugFormat("[INVENTORY TRANSFER]: (giving) Inserting item {0} "+
"into agent {1}'s inventory",
itemID, new UUID(im.toAgentID));
string message;
InventoryItemBase itemCopy = scene.GiveInventoryItem(new UUID(im.toAgentID), client.AgentId, itemID, out message);
if (itemCopy == null)
{
client.SendAgentAlertMessage(message, false);
return;
}
copyID = itemCopy.ID;
Array.Copy(copyID.GetBytes(), 0, im.binaryBucket, 1, 16);
if (user != null)
user.ControllingClient.SendBulkUpdateInventory(itemCopy);
// HACK!!
// Insert the ID of the copied item into the IM so that we know which item to move to trash if it
// is rejected.
// XXX: This is probably a misuse of the session ID slot.
im.imSessionID = copyID.Guid;
}
// Send the IM to the recipient. The item is already
// in their inventory, so it will not be lost if
// they are offline.
//
if (user != null)
{
user.ControllingClient.SendInstantMessage(im);
return;
}
else
{
if (m_TransferModule != null)
m_TransferModule.SendInstantMessage(im, delegate(bool success)
{
if (!success)
client.SendAlertMessage("User not online. Inventory has been saved");
});
}
}
else if (im.dialog == (byte) InstantMessageDialog.InventoryAccepted)
{
ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID));
if (user != null) // Local
{
user.ControllingClient.SendInstantMessage(im);
}
else
{
if (m_TransferModule != null)
m_TransferModule.SendInstantMessage(im, delegate(bool success) {
// justincc - FIXME: Comment out for now. This code was added in commit db91044 Mon Aug 22 2011
// and is apparently supposed to fix bulk inventory updates after accepting items. But
// instead it appears to cause two copies of an accepted folder for the receiving user in
// at least some cases. Folder/item update is already done when the offer is made (see code above)
// // Send BulkUpdateInventory
// IInventoryService invService = scene.InventoryService;
// UUID inventoryEntityID = new UUID(im.imSessionID); // The inventory item /folder, back from it's trip
//
// InventoryFolderBase folder = new InventoryFolderBase(inventoryEntityID, client.AgentId);
// folder = invService.GetFolder(folder);
//
// ScenePresence fromUser = scene.GetScenePresence(new UUID(im.fromAgentID));
//
// // If the user has left the scene by the time the message comes back then we can't send
// // them the update.
// if (fromUser != null)
// fromUser.ControllingClient.SendBulkUpdateInventory(folder);
});
}
}
// XXX: This code was placed here to try and accomodate RLV which moves given folders named #RLV/~<name>
// to the requested folder, which in this case is #RLV. However, it is the viewer that appears to be
// response from renaming the #RLV/~example folder to ~example. For some reason this is not yet
// happening, possibly because we are not sending the correct inventory update messages with the correct
// transaction IDs
else if (im.dialog == (byte) InstantMessageDialog.TaskInventoryAccepted)
{
UUID destinationFolderID = UUID.Zero;
if (im.binaryBucket != null && im.binaryBucket.Length >= 16)
{
destinationFolderID = new UUID(im.binaryBucket, 0);
}
if (destinationFolderID != UUID.Zero)
{
InventoryFolderBase destinationFolder = new InventoryFolderBase(destinationFolderID, client.AgentId);
if (destinationFolder == null)
{
m_log.WarnFormat(
"[INVENTORY TRANSFER]: TaskInventoryAccepted message from {0} in {1} specified folder {2} which does not exist",
client.Name, scene.Name, destinationFolderID);
return;
}
IInventoryService invService = scene.InventoryService;
UUID inventoryID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip
InventoryItemBase item = new InventoryItemBase(inventoryID, client.AgentId);
item = invService.GetItem(item);
InventoryFolderBase folder = null;
UUID? previousParentFolderID = null;
if (item != null) // It's an item
{
previousParentFolderID = item.Folder;
item.Folder = destinationFolderID;
invService.DeleteItems(item.Owner, new List<UUID>() { item.ID });
scene.AddInventoryItem(client, item);
}
else
{
folder = new InventoryFolderBase(inventoryID, client.AgentId);
folder = invService.GetFolder(folder);
if (folder != null) // It's a folder
{
previousParentFolderID = folder.ParentID;
folder.ParentID = destinationFolderID;
invService.MoveFolder(folder);
}
}
// Tell client about updates to original parent and new parent (this should probably be factored with existing move item/folder code).
if (previousParentFolderID != null)
{
InventoryFolderBase previousParentFolder
= new InventoryFolderBase((UUID)previousParentFolderID, client.AgentId);
previousParentFolder = invService.GetFolder(previousParentFolder);
scene.SendInventoryUpdate(client, previousParentFolder, true, true);
scene.SendInventoryUpdate(client, destinationFolder, true, true);
}
}
}
else if (
im.dialog == (byte)InstantMessageDialog.InventoryDeclined
|| im.dialog == (byte)InstantMessageDialog.TaskInventoryDeclined)
{
// Here, the recipient is local and we can assume that the
// inventory is loaded. Courtesy of the above bulk update,
// It will have been pushed to the client, too
//
IInventoryService invService = scene.InventoryService;
InventoryFolderBase trashFolder =
invService.GetFolderForType(client.AgentId, AssetType.TrashFolder);
UUID inventoryID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip
InventoryItemBase item = new InventoryItemBase(inventoryID, client.AgentId);
item = invService.GetItem(item);
InventoryFolderBase folder = null;
UUID? previousParentFolderID = null;
if (item != null && trashFolder != null)
{
previousParentFolderID = item.Folder;
item.Folder = trashFolder.ID;
// Diva comment: can't we just update this item???
List<UUID> uuids = new List<UUID>();
uuids.Add(item.ID);
invService.DeleteItems(item.Owner, uuids);
scene.AddInventoryItem(client, item);
}
else
{
folder = new InventoryFolderBase(inventoryID, client.AgentId);
folder = invService.GetFolder(folder);
if (folder != null & trashFolder != null)
{
previousParentFolderID = folder.ParentID;
folder.ParentID = trashFolder.ID;
invService.MoveFolder(folder);
}
}
if ((null == item && null == folder) | null == trashFolder)
{
string reason = String.Empty;
if (trashFolder == null)
reason += " Trash folder not found.";
if (item == null)
reason += " Item not found.";
if (folder == null)
reason += " Folder not found.";
client.SendAgentAlertMessage("Unable to delete "+
"received inventory" + reason, false);
}
// Tell client about updates to original parent and new parent (this should probably be factored with existing move item/folder code).
else if (previousParentFolderID != null)
{
InventoryFolderBase previousParentFolder
= new InventoryFolderBase((UUID)previousParentFolderID, client.AgentId);
previousParentFolder = invService.GetFolder(previousParentFolder);
scene.SendInventoryUpdate(client, previousParentFolder, true, true);
scene.SendInventoryUpdate(client, trashFolder, true, true);
}
if (im.dialog == (byte)InstantMessageDialog.InventoryDeclined)
{
ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID));
if (user != null) // Local
{
user.ControllingClient.SendInstantMessage(im);
}
else
{
if (m_TransferModule != null)
m_TransferModule.SendInstantMessage(im, delegate(bool success) { });
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="im"></param>
private void OnGridInstantMessage(GridInstantMessage im)
{
// Check if it's a type of message that we should handle
if (!((im.dialog == (byte) InstantMessageDialog.InventoryOffered)
|| (im.dialog == (byte) InstantMessageDialog.InventoryAccepted)
|| (im.dialog == (byte) InstantMessageDialog.InventoryDeclined)
|| (im.dialog == (byte) InstantMessageDialog.TaskInventoryDeclined)))
return;
m_log.DebugFormat(
"[INVENTORY TRANSFER]: {0} IM type received from grid. From={1} ({2}), To={3}",
(InstantMessageDialog)im.dialog, im.fromAgentID, im.fromAgentName, im.toAgentID);
// Check if this is ours to handle
//
Scene scene = FindClientScene(new UUID(im.toAgentID));
if (scene == null)
return;
// Find agent to deliver to
//
ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID));
if (user != null)
{
user.ControllingClient.SendInstantMessage(im);
if (im.dialog == (byte)InstantMessageDialog.InventoryOffered)
{
AssetType assetType = (AssetType)im.binaryBucket[0];
UUID inventoryID = new UUID(im.binaryBucket, 1);
IInventoryService invService = scene.InventoryService;
InventoryNodeBase node = null;
if (AssetType.Folder == assetType)
{
InventoryFolderBase folder = new InventoryFolderBase(inventoryID, new UUID(im.toAgentID));
node = invService.GetFolder(folder);
}
else
{
InventoryItemBase item = new InventoryItemBase(inventoryID, new UUID(im.toAgentID));
node = invService.GetItem(item);
}
if (node != null)
user.ControllingClient.SendBulkUpdateInventory(node);
}
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// gpr_timespec from grpc/support/time.h
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct Timespec
{
const long NanosPerSecond = 1000 * 1000 * 1000;
const long NanosPerTick = 100;
const long TicksPerSecond = NanosPerSecond / NanosPerTick;
static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
[DllImport("grpc_csharp_ext.dll")]
static extern Timespec gprsharp_now(GPRClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
static extern Timespec gprsharp_inf_future(GPRClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
static extern Timespec gprsharp_inf_past(GPRClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
static extern Timespec gprsharp_convert_clock_type(Timespec t, GPRClockType targetClock);
[DllImport("grpc_csharp_ext.dll")]
static extern int gprsharp_sizeof_timespec();
public Timespec(IntPtr tv_sec, int tv_nsec) : this(tv_sec, tv_nsec, GPRClockType.Realtime)
{
}
public Timespec(IntPtr tv_sec, int tv_nsec, GPRClockType clock_type)
{
this.tv_sec = tv_sec;
this.tv_nsec = tv_nsec;
this.clock_type = clock_type;
}
// NOTE: on linux 64bit sizeof(gpr_timespec) = 16, on windows 32bit sizeof(gpr_timespec) = 8
// so IntPtr seems to have the right size to work on both.
private System.IntPtr tv_sec;
private int tv_nsec;
private GPRClockType clock_type;
/// <summary>
/// Timespec a long time in the future.
/// </summary>
public static Timespec InfFuture
{
get
{
return gprsharp_inf_future(GPRClockType.Realtime);
}
}
/// <summary>
/// Timespec a long time in the past.
/// </summary>
public static Timespec InfPast
{
get
{
return gprsharp_inf_past(GPRClockType.Realtime);
}
}
/// <summary>
/// Return Timespec representing the current time.
/// </summary>
public static Timespec Now
{
get
{
return gprsharp_now(GPRClockType.Realtime);
}
}
/// <summary>
/// Seconds since unix epoch.
/// </summary>
public IntPtr TimevalSeconds
{
get
{
return tv_sec;
}
}
/// <summary>
/// The nanoseconds part of timeval.
/// </summary>
public int TimevalNanos
{
get
{
return tv_nsec;
}
}
/// <summary>
/// Converts the timespec to desired clock type.
/// </summary>
public Timespec ToClockType(GPRClockType targetClock)
{
return gprsharp_convert_clock_type(this, targetClock);
}
/// <summary>
/// Converts Timespec to DateTime.
/// Timespec needs to be of type GPRClockType.Realtime and needs to represent a legal value.
/// DateTime has lower resolution (100ns), so rounding can occurs.
/// Value are always rounded up to the nearest DateTime value in the future.
///
/// For Timespec.InfFuture or if timespec is after the largest representable DateTime, DateTime.MaxValue is returned.
/// For Timespec.InfPast or if timespec is before the lowest representable DateTime, DateTime.MinValue is returned.
///
/// Unless DateTime.MaxValue or DateTime.MinValue is returned, the resulting DateTime is always in UTC
/// (DateTimeKind.Utc)
/// </summary>
public DateTime ToDateTime()
{
Preconditions.CheckState(tv_nsec >= 0 && tv_nsec < NanosPerSecond);
Preconditions.CheckState(clock_type == GPRClockType.Realtime);
// fast path for InfFuture
if (this.Equals(InfFuture))
{
return DateTime.MaxValue;
}
// fast path for InfPast
if (this.Equals(InfPast))
{
return DateTime.MinValue;
}
try
{
// convert nanos to ticks, round up to the nearest tick
long ticksFromNanos = tv_nsec / NanosPerTick + ((tv_nsec % NanosPerTick != 0) ? 1 : 0);
long ticksTotal = checked(tv_sec.ToInt64() * TicksPerSecond + ticksFromNanos);
return UnixEpoch.AddTicks(ticksTotal);
}
catch (OverflowException)
{
// ticks out of long range
return tv_sec.ToInt64() > 0 ? DateTime.MaxValue : DateTime.MinValue;
}
catch (ArgumentOutOfRangeException)
{
// resulting date time would be larger than MaxValue
return tv_sec.ToInt64() > 0 ? DateTime.MaxValue : DateTime.MinValue;
}
}
/// <summary>
/// Creates DateTime to Timespec.
/// DateTime has to be in UTC (DateTimeKind.Utc) unless it's DateTime.MaxValue or DateTime.MinValue.
/// For DateTime.MaxValue of date time after the largest representable Timespec, Timespec.InfFuture is returned.
/// For DateTime.MinValue of date time before the lowest representable Timespec, Timespec.InfPast is returned.
/// </summary>
/// <returns>The date time.</returns>
/// <param name="dateTime">Date time.</param>
public static Timespec FromDateTime(DateTime dateTime)
{
if (dateTime == DateTime.MaxValue)
{
return Timespec.InfFuture;
}
if (dateTime == DateTime.MinValue)
{
return Timespec.InfPast;
}
Preconditions.CheckArgument(dateTime.Kind == DateTimeKind.Utc, "dateTime needs of kind DateTimeKind.Utc or be equal to DateTime.MaxValue or DateTime.MinValue.");
try
{
TimeSpan timeSpan = dateTime - UnixEpoch;
long ticks = timeSpan.Ticks;
long seconds = ticks / TicksPerSecond;
int nanos = (int)((ticks % TicksPerSecond) * NanosPerTick);
if (nanos < 0)
{
// correct the result based on C# modulo semantics for negative dividend
seconds--;
nanos += (int)NanosPerSecond;
}
// new IntPtr possibly throws OverflowException
return new Timespec(new IntPtr(seconds), nanos);
}
catch (OverflowException)
{
return dateTime > UnixEpoch ? Timespec.InfFuture : Timespec.InfPast;
}
catch (ArgumentOutOfRangeException)
{
return dateTime > UnixEpoch ? Timespec.InfFuture : Timespec.InfPast;
}
}
internal static int NativeSize
{
get
{
return gprsharp_sizeof_timespec();
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Attributes.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Akka.Event;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Akka.Streams.Supervision;
namespace Akka.Streams
{
/// <summary>
/// Holds attributes which can be used to alter <see cref="Flow{TIn,TOut,TMat}"/>
/// or <see cref="GraphDsl"/> materialization.
///
/// Note that more attributes for the <see cref="ActorMaterializer"/> are defined in <see cref="ActorAttributes"/>.
/// </summary>
public sealed class Attributes
{
/// <summary>
/// TBD
/// </summary>
public interface IAttribute { }
/// <summary>
/// TBD
/// </summary>
public sealed class Name : IAttribute, IEquatable<Name>
{
/// <summary>
/// TBD
/// </summary>
public readonly string Value;
/// <summary>
/// TBD
/// </summary>
/// <param name="value">TBD</param>
/// <exception cref="ArgumentNullException">
/// This exception is thrown when the specified <paramref name="value"/> is undefined.
/// </exception>
public Name(string value)
{
if (string.IsNullOrEmpty(value)) throw new ArgumentNullException(nameof(value), "Name attribute cannot be empty");
Value = value;
}
/// <inheritdoc/>
public bool Equals(Name other) => !ReferenceEquals(other, null) && Equals(Value, other.Value);
/// <inheritdoc/>
public override bool Equals(object obj) => obj is Name && Equals((Name)obj);
/// <inheritdoc/>
public override int GetHashCode() => Value.GetHashCode();
/// <inheritdoc/>
public override string ToString() => $"Name({Value})";
}
/// <summary>
/// TBD
/// </summary>
public sealed class InputBuffer : IAttribute, IEquatable<InputBuffer>
{
/// <summary>
/// TBD
/// </summary>
public readonly int Initial;
/// <summary>
/// TBD
/// </summary>
public readonly int Max;
/// <summary>
/// TBD
/// </summary>
/// <param name="initial">TBD</param>
/// <param name="max">TBD</param>
public InputBuffer(int initial, int max)
{
Initial = initial;
Max = max;
}
/// <inheritdoc/>
public bool Equals(InputBuffer other)
{
if (ReferenceEquals(other, null)) return false;
if (ReferenceEquals(other, this)) return true;
return Initial == other.Initial && Max == other.Max;
}
/// <inheritdoc/>
public override bool Equals(object obj) => obj is InputBuffer && Equals((InputBuffer) obj);
/// <inheritdoc/>
public override int GetHashCode()
{
unchecked
{
return (Initial*397) ^ Max;
}
}
/// <inheritdoc/>
public override string ToString() => $"InputBuffer(initial={Initial}, max={Max})";
}
/// <summary>
/// TBD
/// </summary>
public sealed class LogLevels : IAttribute, IEquatable<LogLevels>
{
/// <summary>
/// Use to disable logging on certain operations when configuring <see cref="LogLevels"/>
/// </summary>
public static readonly LogLevel Off = Logging.LogLevelFor("off");
/// <summary>
/// TBD
/// </summary>
public readonly LogLevel OnElement;
/// <summary>
/// TBD
/// </summary>
public readonly LogLevel OnFinish;
/// <summary>
/// TBD
/// </summary>
public readonly LogLevel OnFailure;
/// <summary>
/// TBD
/// </summary>
/// <param name="onElement">TBD</param>
/// <param name="onFinish">TBD</param>
/// <param name="onFailure">TBD</param>
public LogLevels(LogLevel onElement, LogLevel onFinish, LogLevel onFailure)
{
OnElement = onElement;
OnFinish = onFinish;
OnFailure = onFailure;
}
/// <inheritdoc/>
public bool Equals(LogLevels other)
{
if (ReferenceEquals(other, null))
return false;
if (ReferenceEquals(other, this))
return true;
return OnElement == other.OnElement && OnFinish == other.OnFinish && OnFailure == other.OnFailure;
}
/// <inheritdoc/>
public override bool Equals(object obj) => obj is LogLevels && Equals((LogLevels) obj);
/// <inheritdoc/>
public override int GetHashCode()
{
unchecked
{
var hashCode = (int) OnElement;
hashCode = (hashCode*397) ^ (int) OnFinish;
hashCode = (hashCode*397) ^ (int) OnFailure;
return hashCode;
}
}
/// <inheritdoc/>
public override string ToString() => $"LogLevel(element={OnElement}, finish={OnFinish}, failure={OnFailure})";
}
/// <summary>
/// TBD
/// </summary>
public sealed class AsyncBoundary : IAttribute, IEquatable<AsyncBoundary>
{
/// <summary>
/// TBD
/// </summary>
public static readonly AsyncBoundary Instance = new AsyncBoundary();
private AsyncBoundary() { }
/// <inheritdoc/>
public bool Equals(AsyncBoundary other) => true;
/// <inheritdoc/>
public override bool Equals(object obj) => obj is AsyncBoundary;
/// <inheritdoc/>
public override string ToString() => "AsyncBoundary";
}
/// <summary>
/// TBD
/// </summary>
public static readonly Attributes None = new Attributes();
private readonly IAttribute[] _attributes;
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
public Attributes(params IAttribute[] attributes)
{
_attributes = attributes ?? new IAttribute[0];
}
/// <summary>
/// TBD
/// </summary>
public IEnumerable<IAttribute> AttributeList => _attributes;
/// <summary>
/// Get all attributes of a given type or subtype thereof
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <returns>TBD</returns>
public IEnumerable<TAttr> GetAttributeList<TAttr>() where TAttr : IAttribute
=> _attributes.Length == 0 ? Enumerable.Empty<TAttr>() : _attributes.Where(a => a is TAttr).Cast<TAttr>();
/// <summary>
/// Get the last (most specific) attribute of a given type or subtype thereof.
/// If no such attribute exists the default value is returned.
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <param name="defaultIfNotFound">TBD</param>
/// <returns>TBD</returns>
public TAttr GetAttribute<TAttr>(TAttr defaultIfNotFound) where TAttr : class, IAttribute
=> GetAttribute<TAttr>() ?? defaultIfNotFound;
/// <summary>
/// Get the first (least specific) attribute of a given type or subtype thereof.
/// If no such attribute exists the default value is returned.
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <param name="defaultIfNotFound">TBD</param>
/// <returns>TBD</returns>
public TAttr GetFirstAttribute<TAttr>(TAttr defaultIfNotFound) where TAttr : class, IAttribute
=> GetFirstAttribute<TAttr>() ?? defaultIfNotFound;
/// <summary>
/// Get the last (most specific) attribute of a given type or subtype thereof.
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <returns>TBD</returns>
public TAttr GetAttribute<TAttr>() where TAttr : class, IAttribute
=> _attributes.LastOrDefault(attr => attr is TAttr) as TAttr;
/// <summary>
/// Get the first (least specific) attribute of a given type or subtype thereof.
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <returns>TBD</returns>
public TAttr GetFirstAttribute<TAttr>() where TAttr : class, IAttribute
=> _attributes.FirstOrDefault(attr => attr is TAttr) as TAttr;
/// <summary>
/// Adds given attributes to the end of these attributes.
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
public Attributes And(Attributes other)
{
if (_attributes.Length == 0)
return other;
if (!other.AttributeList.Any())
return this;
return new Attributes(_attributes.Concat(other.AttributeList).ToArray());
}
/// <summary>
/// Adds given attribute to the end of these attributes.
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
public Attributes And(IAttribute other) => new Attributes(_attributes.Concat(new[] { other }).ToArray());
/// <summary>
/// Extracts Name attributes and concatenates them.
/// </summary>
/// <returns>TBD</returns>
public string GetNameLifted() => GetNameOrDefault(null);
/// <summary>
/// TBD
/// </summary>
/// <param name="defaultIfNotFound">TBD</param>
/// <returns>TBD</returns>
public string GetNameOrDefault(string defaultIfNotFound = "unknown-operation")
{
if (_attributes.Length == 0)
return null;
var sb = new StringBuilder();
foreach (var nameAttribute in _attributes.OfType<Name>())
{
// FIXME this UrlEncode is a bug IMO, if that format is important then that is how it should be store in Name
var encoded = Uri.EscapeDataString(nameAttribute.Value);
if (sb.Length != 0)
sb.Append('-');
sb.Append(encoded);
}
return sb.Length == 0 ? defaultIfNotFound : sb.ToString();
}
/// <summary>
/// Test whether the given attribute is contained within this attributes list.
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <param name="attribute">TBD</param>
/// <returns>TBD</returns>
public bool Contains<TAttr>(TAttr attribute) where TAttr : IAttribute => _attributes.Contains(attribute);
/// <summary>
/// Specifies the name of the operation.
/// If the name is null or empty the name is ignored, i.e. <see cref="None"/> is returned.
/// </summary>
/// <param name="name">TBD</param>
/// <returns>TBD</returns>
public static Attributes CreateName(string name)
=> string.IsNullOrEmpty(name) ? None : new Attributes(new Name(name));
/// <summary>
/// Specifies the initial and maximum size of the input buffer.
/// </summary>
/// <param name="initial">TBD</param>
/// <param name="max">TBD</param>
/// <returns>TBD</returns>
public static Attributes CreateInputBuffer(int initial, int max) => new Attributes(new InputBuffer(initial, max));
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public static Attributes CreateAsyncBoundary() => new Attributes(AsyncBoundary.Instance);
///<summary>
/// Configures <see cref="FlowOperations.Log{TIn,TOut,TMat}"/> stage log-levels to be used when logging.
/// Logging a certain operation can be completely disabled by using <see cref="LogLevels.Off"/>
///
/// Passing in null as any of the arguments sets the level to its default value, which is:
/// <see cref="LogLevel.DebugLevel"/> for <paramref name="onElement"/> and <paramref name="onFinish"/>, and <see cref="LogLevel.ErrorLevel"/> for <paramref name="onError"/>.
///</summary>
/// <param name="onElement">TBD</param>
/// <param name="onFinish">TBD</param>
/// <param name="onError">TBD</param>
/// <returns>TBD</returns>
public static Attributes CreateLogLevels(LogLevel onElement = LogLevel.DebugLevel,
LogLevel onFinish = LogLevel.DebugLevel, LogLevel onError = LogLevel.ErrorLevel)
=> new Attributes(new LogLevels(onElement, onFinish, onError));
/// <summary>
/// Compute a name by concatenating all Name attributes that the given module
/// has, returning the given default value if none are found.
/// </summary>
/// <param name="module">TBD</param>
/// <param name="defaultIfNotFound">TBD</param>
/// <returns>TBD</returns>
public static string ExtractName(IModule module, string defaultIfNotFound)
{
var copy = module as CopiedModule;
return copy != null
? copy.Attributes.And(copy.CopyOf.Attributes).GetNameOrDefault(defaultIfNotFound)
: module.Attributes.GetNameOrDefault(defaultIfNotFound);
}
/// <inheritdoc/>
public override string ToString() => $"Attributes({string.Join(", ", _attributes as IEnumerable<IAttribute>)})";
}
/// <summary>
/// Attributes for the <see cref="ActorMaterializer"/>. Note that more attributes defined in <see cref="ActorAttributes"/>.
/// </summary>
public static class ActorAttributes
{
/// <summary>
/// TBD
/// </summary>
public sealed class Dispatcher : Attributes.IAttribute, IEquatable<Dispatcher>
{
/// <summary>
/// TBD
/// </summary>
public readonly string Name;
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public Dispatcher(string name)
{
Name = name;
}
/// <inheritdoc/>
public bool Equals(Dispatcher other)
{
if (ReferenceEquals(other, null))
return false;
if (ReferenceEquals(other, this))
return true;
return Equals(Name, other.Name);
}
/// <inheritdoc/>
public override bool Equals(object obj) => obj is Dispatcher && Equals((Dispatcher) obj);
/// <inheritdoc/>
public override int GetHashCode() => Name?.GetHashCode() ?? 0;
/// <inheritdoc/>
public override string ToString() => $"Dispatcher({Name})";
}
/// <summary>
/// TBD
/// </summary>
public sealed class SupervisionStrategy : Attributes.IAttribute
{
/// <summary>
/// TBD
/// </summary>
public readonly Decider Decider;
/// <summary>
/// TBD
/// </summary>
/// <param name="decider">TBD</param>
public SupervisionStrategy(Decider decider)
{
Decider = decider;
}
/// <inheritdoc/>
public override string ToString() => "SupervisionStrategy";
}
/// <summary>
/// Specifies the name of the dispatcher.
/// </summary>
/// <param name="dispatcherName">TBD</param>
/// <returns>TBD</returns>
public static Attributes CreateDispatcher(string dispatcherName) => new Attributes(new Dispatcher(dispatcherName));
/// <summary>
/// Specifies the SupervisionStrategy.
/// Decides how exceptions from user are to be handled
/// </summary>
/// <param name="strategy">TBD</param>
/// <returns>TBD</returns>
public static Attributes CreateSupervisionStrategy(Decider strategy)
=> new Attributes(new SupervisionStrategy(strategy));
}
}
| |
namespace LoveSeat
{
partial class FrmMain
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmMain));
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.addReduceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addViewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addShowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addListToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addLuceneIndexToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addDesignToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ctxSeparator = new System.Windows.Forms.ToolStripSeparator();
this.refreshToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ctxSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.cloneViewsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.extractViewsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.importViewsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.tvMain = new System.Windows.Forms.TreeView();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
this.rtSource = new System.Windows.Forms.RichTextBox();
this.contextMenuStrip3 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.fontsAndColorsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tvResults = new System.Windows.Forms.TreeView();
this.contextMenuStrip2 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.collapseAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.expandAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStrip2 = new System.Windows.Forms.ToolStrip();
this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel();
this.txtParams = new System.Windows.Forms.ToolStripTextBox();
this.cmdRun = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.cmdCommit = new System.Windows.Forms.ToolStripButton();
this.cmdResults = new System.Windows.Forms.ToolStripButton();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
this.tstServer = new System.Windows.Forms.ToolStripTextBox();
this.cmdOpen = new System.Windows.Forms.ToolStripButton();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.fontDialog1 = new System.Windows.Forms.FontDialog();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStrip1.SuspendLayout();
this.statusStrip1.SuspendLayout();
this.toolStripContainer1.BottomToolStripPanel.SuspendLayout();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
this.contextMenuStrip3.SuspendLayout();
this.contextMenuStrip2.SuspendLayout();
this.toolStrip2.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addReduceToolStripMenuItem,
this.addViewToolStripMenuItem,
this.addShowToolStripMenuItem,
this.addListToolStripMenuItem,
this.addLuceneIndexToolStripMenuItem,
this.addDesignToolStripMenuItem,
this.addDatabaseToolStripMenuItem,
this.deleteToolStripMenuItem,
this.ctxSeparator,
this.refreshToolStripMenuItem,
this.ctxSeparator2,
this.cloneViewsToolStripMenuItem,
this.extractViewsToolStripMenuItem,
this.importViewsToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(169, 280);
this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening);
//
// addReduceToolStripMenuItem
//
this.addReduceToolStripMenuItem.Name = "addReduceToolStripMenuItem";
this.addReduceToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.addReduceToolStripMenuItem.Text = "Add Reduce";
this.addReduceToolStripMenuItem.Click += new System.EventHandler(this.addReduceToolStripMenuItem_Click);
//
// addViewToolStripMenuItem
//
this.addViewToolStripMenuItem.Name = "addViewToolStripMenuItem";
this.addViewToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.addViewToolStripMenuItem.Text = "Add View";
this.addViewToolStripMenuItem.Click += new System.EventHandler(this.addViewToolStripMenuItem_Click);
//
// addShowToolStripMenuItem
//
this.addShowToolStripMenuItem.Name = "addShowToolStripMenuItem";
this.addShowToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.addShowToolStripMenuItem.Text = "Add Show";
this.addShowToolStripMenuItem.Click += new System.EventHandler(this.addShowToolStripMenuItem_Click);
//
// addListToolStripMenuItem
//
this.addListToolStripMenuItem.Name = "addListToolStripMenuItem";
this.addListToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.addListToolStripMenuItem.Text = "Add List";
this.addListToolStripMenuItem.Click += new System.EventHandler(this.addListToolStripMenuItem_Click);
//
// addLuceneIndexToolStripMenuItem
//
this.addLuceneIndexToolStripMenuItem.Name = "addLuceneIndexToolStripMenuItem";
this.addLuceneIndexToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.addLuceneIndexToolStripMenuItem.Text = "Add Lucene Index";
this.addLuceneIndexToolStripMenuItem.Click += new System.EventHandler(this.addLuceneIndexToolStripMenuItem_Click);
//
// addDesignToolStripMenuItem
//
this.addDesignToolStripMenuItem.Name = "addDesignToolStripMenuItem";
this.addDesignToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.addDesignToolStripMenuItem.Text = "Add Design";
this.addDesignToolStripMenuItem.Click += new System.EventHandler(this.addDesignToolStripMenuItem_Click);
//
// addDatabaseToolStripMenuItem
//
this.addDatabaseToolStripMenuItem.Name = "addDatabaseToolStripMenuItem";
this.addDatabaseToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.addDatabaseToolStripMenuItem.Text = "Add Database";
this.addDatabaseToolStripMenuItem.Click += new System.EventHandler(this.addDatabaseToolStripMenuItem_Click);
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
this.deleteToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.deleteToolStripMenuItem.Text = "Delete";
this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripMenuItem_Click);
//
// ctxSeparator
//
this.ctxSeparator.Name = "ctxSeparator";
this.ctxSeparator.Size = new System.Drawing.Size(165, 6);
//
// refreshToolStripMenuItem
//
this.refreshToolStripMenuItem.Name = "refreshToolStripMenuItem";
this.refreshToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.refreshToolStripMenuItem.Text = "Refresh";
this.refreshToolStripMenuItem.Click += new System.EventHandler(this.refreshToolStripMenuItem_Click);
//
// ctxSeparator2
//
this.ctxSeparator2.Name = "ctxSeparator2";
this.ctxSeparator2.Size = new System.Drawing.Size(165, 6);
//
// cloneViewsToolStripMenuItem
//
this.cloneViewsToolStripMenuItem.Name = "cloneViewsToolStripMenuItem";
this.cloneViewsToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.cloneViewsToolStripMenuItem.Text = "Clone Views";
this.cloneViewsToolStripMenuItem.Click += new System.EventHandler(this.cloneViewsToolStripMenuItem_Click);
//
// extractViewsToolStripMenuItem
//
this.extractViewsToolStripMenuItem.Name = "extractViewsToolStripMenuItem";
this.extractViewsToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.extractViewsToolStripMenuItem.Text = "Extract Views";
this.extractViewsToolStripMenuItem.Click += new System.EventHandler(this.extractViewsToolStripMenuItem_Click);
//
// importViewsToolStripMenuItem
//
this.importViewsToolStripMenuItem.Name = "importViewsToolStripMenuItem";
this.importViewsToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
this.importViewsToolStripMenuItem.Text = "Import Views";
this.importViewsToolStripMenuItem.Click += new System.EventHandler(this.importViewsToolStripMenuItem_Click);
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Magenta;
this.imageList1.Images.SetKeyName(0, "database.bmp");
this.imageList1.Images.SetKeyName(1, "DataSet_TableView.bmp");
this.imageList1.Images.SetKeyName(2, "Table.bmp");
this.imageList1.Images.SetKeyName(3, "FormulaEvaluator.bmp");
this.imageList1.Images.SetKeyName(4, "Textbox.bmp");
this.imageList1.Images.SetKeyName(5, "Webcontrol_Sitemapdatasrc.bmp");
this.imageList1.Images.SetKeyName(6, "Webcontrol_Dataview.bmp");
this.imageList1.Images.SetKeyName(7, "Webcontrol_Detailsview.bmp");
this.imageList1.Images.SetKeyName(8, "Webcontrol_Gridview.bmp");
//
// statusStrip1
//
this.statusStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1});
this.statusStrip1.Location = new System.Drawing.Point(0, 0);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(1017, 22);
this.statusStrip1.TabIndex = 2;
this.statusStrip1.Text = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(118, 17);
this.toolStripStatusLabel1.Text = "toolStripStatusLabel1";
//
// toolStripContainer1
//
//
// toolStripContainer1.BottomToolStripPanel
//
this.toolStripContainer1.BottomToolStripPanel.Controls.Add(this.statusStrip1);
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.AutoScroll = true;
this.toolStripContainer1.ContentPanel.Controls.Add(this.splitContainer1);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(1017, 462);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.LeftToolStripPanelVisible = false;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.RightToolStripPanelVisible = false;
this.toolStripContainer1.Size = new System.Drawing.Size(1017, 558);
this.toolStripContainer1.TabIndex = 5;
this.toolStripContainer1.Text = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.menuStrip1);
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip2);
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip1);
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.tvMain);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.splitContainer2);
this.splitContainer1.Size = new System.Drawing.Size(1017, 462);
this.splitContainer1.SplitterDistance = 235;
this.splitContainer1.TabIndex = 2;
//
// tvMain
//
this.tvMain.ContextMenuStrip = this.contextMenuStrip1;
this.tvMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvMain.ImageIndex = 0;
this.tvMain.ImageList = this.imageList1;
this.tvMain.Location = new System.Drawing.Point(0, 0);
this.tvMain.Name = "tvMain";
this.tvMain.PathSeparator = "/";
this.tvMain.SelectedImageIndex = 0;
this.tvMain.Size = new System.Drawing.Size(235, 462);
this.tvMain.TabIndex = 0;
this.tvMain.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.tvMain_BeforeExpand);
this.tvMain.DoubleClick += new System.EventHandler(this.tvMain_DoubleClick);
//
// splitContainer2
//
this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer2.Location = new System.Drawing.Point(0, 0);
this.splitContainer2.Name = "splitContainer2";
this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.rtSource);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.tvResults);
this.splitContainer2.Panel2Collapsed = true;
this.splitContainer2.Size = new System.Drawing.Size(778, 462);
this.splitContainer2.SplitterDistance = 243;
this.splitContainer2.TabIndex = 0;
//
// rtSource
//
this.rtSource.AcceptsTab = true;
this.rtSource.ContextMenuStrip = this.contextMenuStrip3;
this.rtSource.Dock = System.Windows.Forms.DockStyle.Fill;
this.rtSource.Location = new System.Drawing.Point(0, 0);
this.rtSource.Name = "rtSource";
this.rtSource.Size = new System.Drawing.Size(778, 462);
this.rtSource.TabIndex = 0;
this.rtSource.Text = "";
//
// contextMenuStrip3
//
this.contextMenuStrip3.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fontsAndColorsToolStripMenuItem});
this.contextMenuStrip3.Name = "contextMenuStrip3";
this.contextMenuStrip3.Size = new System.Drawing.Size(164, 26);
//
// fontsAndColorsToolStripMenuItem
//
this.fontsAndColorsToolStripMenuItem.Name = "fontsAndColorsToolStripMenuItem";
this.fontsAndColorsToolStripMenuItem.Size = new System.Drawing.Size(163, 22);
this.fontsAndColorsToolStripMenuItem.Text = "Fonts and Colors";
this.fontsAndColorsToolStripMenuItem.Click += new System.EventHandler(this.fontsAndColorsToolStripMenuItem_Click);
//
// tvResults
//
this.tvResults.ContextMenuStrip = this.contextMenuStrip2;
this.tvResults.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvResults.Location = new System.Drawing.Point(0, 0);
this.tvResults.Name = "tvResults";
this.tvResults.Size = new System.Drawing.Size(150, 46);
this.tvResults.TabIndex = 0;
//
// contextMenuStrip2
//
this.contextMenuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.collapseAllToolStripMenuItem,
this.expandAllToolStripMenuItem});
this.contextMenuStrip2.Name = "contextMenuStrip2";
this.contextMenuStrip2.Size = new System.Drawing.Size(137, 48);
//
// collapseAllToolStripMenuItem
//
this.collapseAllToolStripMenuItem.Name = "collapseAllToolStripMenuItem";
this.collapseAllToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.collapseAllToolStripMenuItem.Text = "Collapse All";
this.collapseAllToolStripMenuItem.Click += new System.EventHandler(this.collapseAllToolStripMenuItem_Click);
//
// expandAllToolStripMenuItem
//
this.expandAllToolStripMenuItem.Name = "expandAllToolStripMenuItem";
this.expandAllToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.expandAllToolStripMenuItem.Text = "Expand All";
this.expandAllToolStripMenuItem.Click += new System.EventHandler(this.expandAllToolStripMenuItem_Click);
//
// toolStrip2
//
this.toolStrip2.Dock = System.Windows.Forms.DockStyle.None;
this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripLabel2,
this.txtParams,
this.cmdRun,
this.toolStripSeparator2,
this.cmdCommit,
this.cmdResults});
this.toolStrip2.Location = new System.Drawing.Point(3, 24);
this.toolStrip2.Name = "toolStrip2";
this.toolStrip2.Size = new System.Drawing.Size(415, 25);
this.toolStrip2.TabIndex = 4;
//
// toolStripLabel2
//
this.toolStripLabel2.Name = "toolStripLabel2";
this.toolStripLabel2.Size = new System.Drawing.Size(101, 22);
this.toolStripLabel2.Text = "Query Parameters";
//
// txtParams
//
this.txtParams.Name = "txtParams";
this.txtParams.Size = new System.Drawing.Size(200, 25);
this.txtParams.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtParams_KeyUp);
//
// cmdRun
//
this.cmdRun.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cmdRun.Image = ((System.Drawing.Image)(resources.GetObject("cmdRun.Image")));
this.cmdRun.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cmdRun.Name = "cmdRun";
this.cmdRun.Size = new System.Drawing.Size(23, 22);
this.cmdRun.Text = "Run Query";
this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// cmdCommit
//
this.cmdCommit.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cmdCommit.Image = ((System.Drawing.Image)(resources.GetObject("cmdCommit.Image")));
this.cmdCommit.ImageTransparentColor = System.Drawing.Color.Black;
this.cmdCommit.Name = "cmdCommit";
this.cmdCommit.Size = new System.Drawing.Size(23, 22);
this.cmdCommit.Text = "Save";
this.cmdCommit.Click += new System.EventHandler(this.cmdCommit_Click);
//
// cmdResults
//
this.cmdResults.CheckOnClick = true;
this.cmdResults.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.cmdResults.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cmdResults.Name = "cmdResults";
this.cmdResults.Size = new System.Drawing.Size(48, 22);
this.cmdResults.Text = "Results";
this.cmdResults.CheckedChanged += new System.EventHandler(this.cmdResults_CheckedChanged);
//
// toolStrip1
//
this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripLabel1,
this.tstServer,
this.cmdOpen});
this.toolStrip1.Location = new System.Drawing.Point(3, 49);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(476, 25);
this.toolStrip1.TabIndex = 3;
this.toolStrip1.Text = "toolStrip1";
//
// toolStripLabel1
//
this.toolStripLabel1.Name = "toolStripLabel1";
this.toolStripLabel1.Size = new System.Drawing.Size(39, 22);
this.toolStripLabel1.Text = "Server";
//
// tstServer
//
this.tstServer.Name = "tstServer";
this.tstServer.Size = new System.Drawing.Size(400, 25);
this.tstServer.KeyUp += new System.Windows.Forms.KeyEventHandler(this.tstServer_KeyUp);
//
// cmdOpen
//
this.cmdOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cmdOpen.Image = ((System.Drawing.Image)(resources.GetObject("cmdOpen.Image")));
this.cmdOpen.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cmdOpen.Name = "cmdOpen";
this.cmdOpen.Size = new System.Drawing.Size(23, 22);
this.cmdOpen.Text = "Connect to Server";
this.cmdOpen.Click += new System.EventHandler(this.cmdOpen_Click);
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
this.openFileDialog1.Filter = "Javascript Files|*.js|All Files|*.*";
//
// saveFileDialog1
//
this.saveFileDialog1.Filter = "Javascript Files|*.js|All Files|*.*";
//
// menuStrip1
//
this.menuStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1017, 24);
this.menuStrip1.TabIndex = 5;
this.menuStrip1.Text = "menuStrip1";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.aboutToolStripMenuItem.Text = "About";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// FrmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1017, 558);
this.Controls.Add(this.toolStripContainer1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.MainMenuStrip = this.menuStrip1;
this.Name = "FrmMain";
this.Text = "LoveSeat";
this.Load += new System.EventHandler(this.FrmMain_Load);
this.Shown += new System.EventHandler(this.FrmMain_Shown);
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.frmMain_KeyUp);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmMain_FormClosing);
this.contextMenuStrip1.ResumeLayout(false);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.toolStripContainer1.BottomToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.BottomToolStripPanel.PerformLayout();
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel2.ResumeLayout(false);
this.splitContainer2.ResumeLayout(false);
this.contextMenuStrip3.ResumeLayout(false);
this.contextMenuStrip2.ResumeLayout(false);
this.toolStrip2.ResumeLayout(false);
this.toolStrip2.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem addReduceToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addViewToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator ctxSeparator;
private System.Windows.Forms.ToolStripMenuItem refreshToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addDesignToolStripMenuItem;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStripMenuItem addLuceneIndexToolStripMenuItem;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripLabel toolStripLabel1;
private System.Windows.Forms.ToolStripTextBox tstServer;
private System.Windows.Forms.ToolStripButton cmdOpen;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.TreeView tvMain;
private System.Windows.Forms.SplitContainer splitContainer2;
private System.Windows.Forms.TreeView tvResults;
private System.Windows.Forms.ToolStrip toolStrip2;
private System.Windows.Forms.ToolStripLabel toolStripLabel2;
private System.Windows.Forms.ToolStripTextBox txtParams;
private System.Windows.Forms.ToolStripButton cmdRun;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripButton cmdCommit;
private System.Windows.Forms.ToolStripButton cmdResults;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip2;
private System.Windows.Forms.ToolStripMenuItem collapseAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem expandAllToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator ctxSeparator2;
private System.Windows.Forms.ToolStripMenuItem cloneViewsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem extractViewsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem importViewsToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip3;
private System.Windows.Forms.ToolStripMenuItem fontsAndColorsToolStripMenuItem;
private System.Windows.Forms.FontDialog fontDialog1;
private System.Windows.Forms.RichTextBox rtSource;
private System.Windows.Forms.ToolStripMenuItem addDatabaseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addShowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addListToolStripMenuItem;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
}
}
| |
using System.Collections.Generic;
using System.IO;
namespace Ecosim.SceneData
{
/**
* Stores tile parameter data for one data type (e.g. pH or salinity)
* Storage is done through a Dictionary and is only suitable for situations where
* there are not too many non-0 values
*/
public class SparseBitMap8 : Data
{
private const int DICT_SIZE = 127;
public SparseBitMap8 (Scene scene)
: base(scene)
{
data = new Dictionary<Coordinate, int> (DICT_SIZE);
}
SparseBitMap8 (Scene scene, Dictionary<Coordinate, int> data)
: base(scene)
{
this.data = data;
}
public override void Save (BinaryWriter writer, Progression progression)
{
writer.Write ("SparseBitMap8");
writer.Write (width);
writer.Write (height);
writer.Write (data.Count);
foreach (KeyValuePair<Coordinate, int> val in data) {
writer.Write ((ushort)(val.Key.x));
writer.Write ((ushort)(val.Key.y));
writer.Write (val.Value);
}
}
static SparseBitMap8 LoadInternal (BinaryReader reader, Progression progression)
{
int width = reader.ReadInt32 ();
int height = reader.ReadInt32 ();
EnforceValidSize (progression.scene, width, height);
int count = reader.ReadInt32 ();
Dictionary<Coordinate, int> data = new Dictionary<Coordinate, int> (DICT_SIZE);
for (int i = 0; i < count; i++) {
int x = reader.ReadUInt16 ();
int y = reader.ReadUInt16 ();
int val = reader.ReadInt32 ();
data.Add (new Coordinate (x, y), val);
}
return new SparseBitMap8 (progression.scene, data);
}
private Dictionary<Coordinate, int> data;
/**
* Sets all values in bitmap to zero
*/
public override void Clear ()
{
data.Clear ();
}
/**
* Calles function fn for every element not zero, passing x, y, value of element and data to fn.
*/
public override void ProcessNotZero (DProcess fn, System.Object data)
{
Dictionary<Coordinate, int> copy = new Dictionary<Coordinate, int> (this.data);
foreach (KeyValuePair<Coordinate, int> item in copy) {
Coordinate c = item.Key;
int val = item.Value;
if (val != 0) {
fn (c.x, c.y, val, data);
}
}
}
/**
* Adds value val to every element
* The value will be clamped to the minimum and maximum values for the datatype
*/
public override void AddAll (int val)
{
throw new System.NotSupportedException ("operation not supported on sparse bitmaps");
}
/**
* set data value val at x, y
*/
public override void Set (int x, int y, int val)
{
val = (val < 0) ? 0 : ((val > 255) ? 255 : val);
Coordinate c = new Coordinate (x, y);
if (val == 0) {
if (data.ContainsKey (c)) {
data.Remove (c);
hasChanged = true;
}
} else {
int currentVal;
if (data.TryGetValue (c, out currentVal)) {
if (currentVal != val) {
data [c] = val;
hasChanged = true;
}
} else {
data.Add (c, val);
hasChanged = true;
}
}
}
/**
* set data value val at c
*/
public override void Set (Coordinate c, int val)
{
val = (val < 0) ? 0 : ((val > 255) ? 255 : val);
if (val == 0) {
if (data.ContainsKey (c)) {
data.Remove (c);
hasChanged = true;
}
} else {
int currentVal;
if (data.TryGetValue (c, out currentVal)) {
if (currentVal != val) {
data [c] = val;
hasChanged = true;
}
} else {
data.Add (c, val);
hasChanged = true;
}
}
}
/**
* get data value at x, y
*/
public override int Get (int x, int y)
{
int val;
Coordinate c = new Coordinate (x, y);
if (data.TryGetValue (c, out val)) {
return val;
}
return 0;
}
/**
* get data value at c
*/
public override int Get (Coordinate c)
{
int val;
if (data.TryGetValue (c, out val)) {
return val;
}
return 0;
}
/**
* copy data from src to data
*/
public void CopyFrom (SparseBitMap8 src)
{
if (src == this)
return;
data.Clear ();
foreach (KeyValuePair<Coordinate, int> val in src.data) {
data.Add (val.Key, val.Value);
}
hasChanged = true;
}
public void ClearData ()
{
data.Clear ();
hasChanged = true;
}
/**
* increase value of all data by 1, limit it to 100;
*/
public void IncreaseBy1 ()
{
throw new System.NotSupportedException ("operation not supported on sparse bitmaps");
}
/**
* increase value of all data by 1, limit it to 0;
*/
public void DecreaseBy1 ()
{
throw new System.NotSupportedException ("operation not supported on sparse bitmaps");
}
public override int GetMin ()
{
return 0;
}
public override int GetMax ()
{
return 255;
}
/**
* Copies this instance data to 'toData'
*/
public override void CopyTo (Data toData)
{
if (toData == this)
return;
toData.Clear ();
foreach (KeyValuePair<Coordinate, int> val in data) {
Coordinate c = val.Key;
toData.Set (c, val.Value);
}
}
/**
* Enumerates ValueCoordinates of all values in data set that are not 0.
*/
public override IEnumerable<ValueCoordinate> EnumerateNotZero() {
// to make enumeration mutable (we can change data during enumeration) we
// make a copy of the current data set and use that for enumeration
Dictionary<Coordinate, int> copy = new Dictionary<Coordinate, int> (data);
foreach (KeyValuePair<Coordinate, int> kv in copy) {
yield return new ValueCoordinate(kv.Key.x, kv.Key.y, kv.Value);
}
}
/**
* Enumerates ValueCoordinates of all values in data set area that are not 0
* minX, minY, maxX, maxY (all inclusive) is the value range for x and y
*/
public override IEnumerable<ValueCoordinate> EnumerateNotZero(int minX, int minY, int maxX, int maxY) {
// to make enumeration mutable (we can change data during enumeration) we
// make a copy of the current data set and use that for enumeration
Dictionary<Coordinate, int> copy = new Dictionary<Coordinate, int> (data);
foreach (KeyValuePair<Coordinate, int> kv in copy) {
int x = kv.Key.x;
int y = kv.Key.y;
if ((x >= minX) && (x <= maxX) && (y >= minY) && (y <= maxY)) {
yield return new ValueCoordinate(x, y, kv.Value);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Configuration;
using System.Web;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Routing;
using System.Web.Security;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Security;
namespace Umbraco.Core.Configuration
{
//NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc...
// we have this two tasks logged:
// http://issues.umbraco.org/issue/U4-58
// http://issues.umbraco.org/issue/U4-115
//TODO: Replace checking for if the app settings exist and returning an empty string, instead return the defaults!
/// <summary>
/// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings
/// </summary>
internal class GlobalSettings
{
#region Private static fields
private static Version _version;
private static readonly object Locker = new object();
//make this volatile so that we can ensure thread safety with a double check lock
private static volatile string _reservedUrlsCache;
private static string _reservedPathsCache;
private static HashSet<string> _reservedList = new HashSet<string>();
private static string _reservedPaths;
private static string _reservedUrls;
//ensure the built on (non-changeable) reserved paths are there at all times
private const string StaticReservedPaths = "~/app_plugins/,~/install/,";
private const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,";
#endregion
/// <summary>
/// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config)
/// </summary>
private static void ResetInternal()
{
_reservedUrlsCache = null;
_reservedPaths = null;
_reservedUrls = null;
HasSmtpServer = null;
}
/// <summary>
/// Resets settings that were set programmatically, to their initial values.
/// </summary>
/// <remarks>To be used in unit tests.</remarks>
internal static void Reset()
{
ResetInternal();
}
public static bool HasSmtpServerConfigured(string appPath)
{
if (HasSmtpServer.HasValue) return HasSmtpServer.Value;
var config = WebConfigurationManager.OpenWebConfiguration(appPath);
var settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
if (settings == null || settings.Smtp == null) return false;
if (settings.Smtp.SpecifiedPickupDirectory != null && string.IsNullOrEmpty(settings.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation) == false)
return true;
if (settings.Smtp.Network != null && string.IsNullOrEmpty(settings.Smtp.Network.Host) == false)
return true;
return false;
}
/// <summary>
/// For testing only
/// </summary>
internal static bool? HasSmtpServer { get; set; }
/// <summary>
/// Gets the reserved urls from web.config.
/// </summary>
/// <value>The reserved urls.</value>
public static string ReservedUrls
{
get
{
if (_reservedUrls == null)
{
var urls = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedUrls")
? ConfigurationManager.AppSettings["umbracoReservedUrls"]
: string.Empty;
//ensure the built on (non-changeable) reserved paths are there at all times
_reservedUrls = StaticReservedUrls + urls;
}
return _reservedUrls;
}
internal set { _reservedUrls = value; }
}
/// <summary>
/// Gets the reserved paths from web.config
/// </summary>
/// <value>The reserved paths.</value>
public static string ReservedPaths
{
get
{
if (_reservedPaths == null)
{
var reservedPaths = StaticReservedPaths;
//always add the umbraco path to the list
if (ConfigurationManager.AppSettings.ContainsKey("umbracoPath")
&& !ConfigurationManager.AppSettings["umbracoPath"].IsNullOrWhiteSpace())
{
reservedPaths += ConfigurationManager.AppSettings["umbracoPath"].EnsureEndsWith(',');
}
var allPaths = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedPaths")
? ConfigurationManager.AppSettings["umbracoReservedPaths"]
: string.Empty;
_reservedPaths = reservedPaths + allPaths;
}
return _reservedPaths;
}
internal set { _reservedPaths = value; }
}
/// <summary>
/// Gets the name of the content XML file.
/// </summary>
/// <value>The content XML.</value>
/// <remarks>
/// Defaults to ~/App_Data/umbraco.config
/// </remarks>
public static string ContentXmlFile
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoContentXML")
? ConfigurationManager.AppSettings["umbracoContentXML"]
: "~/App_Data/umbraco.config";
}
}
/// <summary>
/// Gets the path to the storage directory (/data by default).
/// </summary>
/// <value>The storage directory.</value>
public static string StorageDirectory
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoStorageDirectory")
? ConfigurationManager.AppSettings["umbracoStorageDirectory"]
: "~/App_Data";
}
}
/// <summary>
/// Gets the path to umbraco's root directory (/umbraco by default).
/// </summary>
/// <value>The path.</value>
public static string Path
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoPath")
? IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"])
: string.Empty;
}
}
/// <summary>
/// This returns the string of the MVC Area route.
/// </summary>
/// <remarks>
/// THIS IS TEMPORARY AND SHOULD BE REMOVED WHEN WE MIGRATE/UPDATE THE CONFIG SETTINGS TO BE A REAL CONFIG SECTION
/// AND SHOULD PROBABLY BE HANDLED IN A MORE ROBUST WAY.
///
/// This will return the MVC area that we will route all custom routes through like surface controllers, etc...
/// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin
/// we will convert the '/' to '-' and use that as the path. its a bit lame but will work.
///
/// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something
/// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco".
/// </remarks>
public static string UmbracoMvcArea
{
get
{
if (Path.IsNullOrWhiteSpace())
{
throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified");
}
var path = Path;
if (path.StartsWith(SystemDirectories.Root)) // beware of TrimStart, see U4-2518
path = path.Substring(SystemDirectories.Root.Length);
return path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower();
}
}
/// <summary>
/// Gets the path to umbraco's client directory (/umbraco_client by default).
/// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco'
/// folder since the CSS paths to images depend on it.
/// </summary>
/// <value>The path.</value>
public static string ClientPath
{
get
{
return Path + "/../umbraco_client";
}
}
/// <summary>
/// Gets the database connection string
/// </summary>
/// <value>The database connection string.</value>
[Obsolete("Use System.Configuration.ConfigurationManager.ConnectionStrings[\"umbracoDbDSN\"] instead")]
public static string DbDsn
{
get
{
var settings = ConfigurationManager.ConnectionStrings[Constants.System.UmbracoConnectionName];
var connectionString = string.Empty;
if (settings != null)
{
connectionString = settings.ConnectionString;
// The SqlCe connectionString is formatted slightly differently, so we need to update it
if (settings.ProviderName.Contains("SqlServerCe"))
connectionString = string.Format("datalayer=SQLCE4Umbraco.SqlCEHelper,SQLCE4Umbraco;{0}", connectionString);
}
return connectionString;
}
set
{
if (DbDsn != value)
{
if (value.ToLower().Contains("SQLCE4Umbraco.SqlCEHelper".ToLower()))
{
ApplicationContext.Current.DatabaseContext.ConfigureEmbeddedDatabaseConnection();
}
else
{
ApplicationContext.Current.DatabaseContext.ConfigureDatabaseConnection(value);
}
}
}
}
/// <summary>
/// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance.
/// </summary>
/// <value>The configuration status.</value>
public static string ConfigurationStatus
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoConfigurationStatus")
? ConfigurationManager.AppSettings["umbracoConfigurationStatus"]
: string.Empty;
}
set
{
SaveSetting("umbracoConfigurationStatus", value);
}
}
/// <summary>
/// Gets or sets the Umbraco members membership providers' useLegacyEncoding state. This will return a boolean
/// </summary>
/// <value>The useLegacyEncoding status.</value>
public static bool UmbracoMembershipProviderLegacyEncoding
{
get
{
return IsConfiguredMembershipProviderUsingLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName);
}
set
{
SetMembershipProvidersLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName, value);
}
}
/// <summary>
/// Gets or sets the Umbraco users membership providers' useLegacyEncoding state. This will return a boolean
/// </summary>
/// <value>The useLegacyEncoding status.</value>
public static bool UmbracoUsersMembershipProviderLegacyEncoding
{
get
{
return IsConfiguredMembershipProviderUsingLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider);
}
set
{
SetMembershipProvidersLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider, value);
}
}
/// <summary>
/// Saves a setting into the configuration file.
/// </summary>
/// <param name="key">Key of the setting to be saved.</param>
/// <param name="value">Value of the setting to be saved.</param>
internal static void SaveSetting(string key, string value)
{
var fileName = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root));
var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single();
// Update appSetting if it exists, or else create a new appSetting for the given key and value
var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key);
if (setting == null)
appSettings.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value)));
else
setting.Attribute("value").Value = value;
xml.Save(fileName, SaveOptions.DisableFormatting);
ConfigurationManager.RefreshSection("appSettings");
}
/// <summary>
/// Removes a setting from the configuration file.
/// </summary>
/// <param name="key">Key of the setting to be removed.</param>
internal static void RemoveSetting(string key)
{
var fileName = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root));
var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single();
var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key);
if (setting != null)
{
setting.Remove();
xml.Save(fileName, SaveOptions.DisableFormatting);
ConfigurationManager.RefreshSection("appSettings");
}
}
private static void SetMembershipProvidersLegacyEncoding(string providerName, bool useLegacyEncoding)
{
//check if this can even be configured.
var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase;
if (membershipProvider == null)
{
return;
}
if (membershipProvider.GetType().Namespace == "umbraco.providers.members")
{
//its the legacy one, this cannot be changed
return;
}
var webConfigFilename = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root));
var webConfigXml = XDocument.Load(webConfigFilename, LoadOptions.PreserveWhitespace);
var membershipConfigs = webConfigXml.XPathSelectElements("configuration/system.web/membership/providers/add").ToList();
if (membershipConfigs.Any() == false)
return;
var provider = membershipConfigs.SingleOrDefault(c => c.Attribute("name") != null && c.Attribute("name").Value == providerName);
if (provider == null)
return;
provider.SetAttributeValue("useLegacyEncoding", useLegacyEncoding);
webConfigXml.Save(webConfigFilename, SaveOptions.DisableFormatting);
}
private static bool IsConfiguredMembershipProviderUsingLegacyEncoding(string providerName)
{
//check if this can even be configured.
var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase;
if (membershipProvider == null)
{
return false;
}
return membershipProvider.UseLegacyEncoding;
}
/// <summary>
/// Gets the full path to root.
/// </summary>
/// <value>The fullpath to root.</value>
public static string FullpathToRoot
{
get { return IOHelper.GetRootDirectorySafe(); }
}
/// <summary>
/// Gets a value indicating whether umbraco is running in [debug mode].
/// </summary>
/// <value><c>true</c> if [debug mode]; otherwise, <c>false</c>.</value>
public static bool DebugMode
{
get
{
try
{
if (HttpContext.Current != null)
{
return HttpContext.Current.IsDebuggingEnabled;
}
//go and get it from config directly
var section = ConfigurationManager.GetSection("system.web/compilation") as CompilationSection;
return section != null && section.Debug;
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets a value indicating whether the current version of umbraco is configured.
/// </summary>
/// <value><c>true</c> if configured; otherwise, <c>false</c>.</value>
[Obsolete("Do not use this, it is no longer in use and will be removed from the codebase in future versions")]
internal static bool Configured
{
get
{
try
{
string configStatus = ConfigurationStatus;
string currentVersion = UmbracoVersion.GetSemanticVersion().ToSemanticString();
if (currentVersion != configStatus)
{
LogHelper.Debug<GlobalSettings>("CurrentVersion different from configStatus: '" + currentVersion + "','" + configStatus + "'");
}
return (configStatus == currentVersion);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the time out in minutes.
/// </summary>
/// <value>The time out in minutes.</value>
public static int TimeOutInMinutes
{
get
{
try
{
return int.Parse(ConfigurationManager.AppSettings["umbracoTimeOutInMinutes"]);
}
catch
{
return 20;
}
}
}
/// <summary>
/// Gets a value indicating whether umbraco uses directory urls.
/// </summary>
/// <value><c>true</c> if umbraco uses directory urls; otherwise, <c>false</c>.</value>
public static bool UseDirectoryUrls
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseDirectoryUrls"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Returns the number of days that should take place between version checks.
/// </summary>
/// <value>The version check period in days (0 = never).</value>
public static int VersionCheckPeriod
{
get
{
try
{
return int.Parse(ConfigurationManager.AppSettings["umbracoVersionCheckPeriod"]);
}
catch
{
return 7;
}
}
}
/// <summary>
/// Returns a string value to determine if umbraco should disbable xslt extensions
/// </summary>
/// <value><c>"true"</c> if version xslt extensions are disabled, otherwise, <c>"false"</c></value>
[Obsolete("This is no longer used and will be removed from the codebase in future releases")]
public static string DisableXsltExtensions
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoDisableXsltExtensions")
? ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"]
: "false";
}
}
internal static bool ContentCacheXmlStoredInCodeGen
{
get { return LocalTempStorageLocation == LocalTempStorage.AspNetTemp; }
}
/// <summary>
/// This is the location type to store temporary files such as cache files or other localized files for a given machine
/// </summary>
/// <remarks>
/// Currently used for the xml cache file and the plugin cache files
/// </remarks>
internal static LocalTempStorage LocalTempStorageLocation
{
get
{
//there's a bunch of backwards compat config checks here....
//This is the current one
if (ConfigurationManager.AppSettings.ContainsKey("umbracoLocalTempStorage"))
{
return Enum<LocalTempStorage>.Parse(ConfigurationManager.AppSettings["umbracoLocalTempStorage"]);
}
//This one is old
if (ConfigurationManager.AppSettings.ContainsKey("umbracoContentXMLStorage"))
{
return Enum<LocalTempStorage>.Parse(ConfigurationManager.AppSettings["umbracoContentXMLStorage"]);
}
//This one is older
if (ConfigurationManager.AppSettings.ContainsKey("umbracoContentXMLUseLocalTemp"))
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoContentXMLUseLocalTemp"])
? LocalTempStorage.AspNetTemp
: LocalTempStorage.Default;
}
return LocalTempStorage.Default;
}
}
/// <summary>
/// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor
/// </summary>
/// <value><c>"true"</c> if Xhtml mode is enable, otherwise, <c>"false"</c></value>
[Obsolete("This is no longer used and will be removed from the codebase in future releases")]
public static string EditXhtmlMode
{
get { return "true"; }
}
/// <summary>
/// Gets the default UI language.
/// </summary>
/// <value>The default UI language.</value>
public static string DefaultUILanguage
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoDefaultUILanguage")
? ConfigurationManager.AppSettings["umbracoDefaultUILanguage"]
: string.Empty;
}
}
/// <summary>
/// Gets the profile URL.
/// </summary>
/// <value>The profile URL.</value>
public static string ProfileUrl
{
get
{
//the default will be 'profiler'
return ConfigurationManager.AppSettings.ContainsKey("umbracoProfileUrl")
? ConfigurationManager.AppSettings["umbracoProfileUrl"]
: "profiler";
}
}
/// <summary>
/// Gets a value indicating whether umbraco should hide top level nodes from generated urls.
/// </summary>
/// <value>
/// <c>true</c> if umbraco hides top level nodes from urls; otherwise, <c>false</c>.
/// </value>
public static bool HideTopLevelNodeFromPath
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoHideTopLevelNodeFromPath"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the current version.
/// </summary>
/// <value>The current version.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static string CurrentVersion
{
get { return UmbracoVersion.GetSemanticVersion().ToSemanticString(); }
}
/// <summary>
/// Gets the major version number.
/// </summary>
/// <value>The major version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionMajor
{
get
{
return UmbracoVersion.Current.Major;
}
}
/// <summary>
/// Gets the minor version number.
/// </summary>
/// <value>The minor version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionMinor
{
get
{
return UmbracoVersion.Current.Minor;
}
}
/// <summary>
/// Gets the patch version number.
/// </summary>
/// <value>The patch version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionPatch
{
get
{
return UmbracoVersion.Current.Build;
}
}
/// <summary>
/// Gets the version comment (like beta or RC).
/// </summary>
/// <value>The version comment.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static string VersionComment
{
get
{
return Umbraco.Core.Configuration.UmbracoVersion.CurrentComment;
}
}
/// <summary>
/// Requests the is in umbraco application directory structure.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public static bool RequestIsInUmbracoApplication(HttpContext context)
{
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
}
public static bool RequestIsInUmbracoApplication(HttpContextBase context)
{
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
}
/// <summary>
/// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice.
/// </summary>
/// <value><c>true</c> if [use SSL]; otherwise, <c>false</c>.</value>
public static bool UseSSL
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the umbraco license.
/// </summary>
/// <value>The license.</value>
public static string License
{
get
{
string license =
"<A href=\"http://umbraco.org/redir/license\" target=\"_blank\">the open source license MIT</A>. The umbraco UI is freeware licensed under the umbraco license.";
var versionDoc = new XmlDocument();
var versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml"));
versionDoc.Load(versionReader);
versionReader.Close();
// check for license
try
{
string licenseUrl =
versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value;
string licenseValidation =
versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value;
string licensedTo =
versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value;
if (licensedTo != "" && licenseUrl != "")
{
license = "umbraco Commercial License<br/><b>Registered to:</b><br/>" +
licensedTo.Replace("\n", "<br/>") + "<br/><b>For use with domain:</b><br/>" +
licenseUrl;
}
}
catch
{
}
return license;
}
}
/// <summary>
/// Determines whether the current request is reserved based on the route table and
/// whether the specified URL is reserved or is inside a reserved path.
/// </summary>
/// <param name="url"></param>
/// <param name="httpContext"></param>
/// <param name="routes">The route collection to lookup the request in</param>
/// <returns></returns>
public static bool IsReservedPathOrUrl(string url, HttpContextBase httpContext, RouteCollection routes)
{
if (httpContext == null) throw new ArgumentNullException("httpContext");
if (routes == null) throw new ArgumentNullException("routes");
//check if the current request matches a route, if so then it is reserved.
var route = routes.GetRouteData(httpContext);
if (route != null)
return true;
//continue with the standard ignore routine
return IsReservedPathOrUrl(url);
}
/// <summary>
/// Determines whether the specified URL is reserved or is inside a reserved path.
/// </summary>
/// <param name="url">The URL to check.</param>
/// <returns>
/// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>.
/// </returns>
public static bool IsReservedPathOrUrl(string url)
{
if (_reservedUrlsCache == null)
{
lock (Locker)
{
if (_reservedUrlsCache == null)
{
// store references to strings to determine changes
_reservedPathsCache = GlobalSettings.ReservedPaths;
_reservedUrlsCache = GlobalSettings.ReservedUrls;
// add URLs and paths to a new list
var newReservedList = new HashSet<string>();
foreach (var reservedUrlTrimmed in _reservedUrlsCache
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim().ToLowerInvariant())
.Where(x => x.IsNullOrWhiteSpace() == false)
.Select(reservedUrl => IOHelper.ResolveUrl(reservedUrl).Trim().EnsureStartsWith("/"))
.Where(reservedUrlTrimmed => reservedUrlTrimmed.IsNullOrWhiteSpace() == false))
{
newReservedList.Add(reservedUrlTrimmed);
}
foreach (var reservedPathTrimmed in _reservedPathsCache
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim().ToLowerInvariant())
.Where(x => x.IsNullOrWhiteSpace() == false)
.Select(reservedPath => IOHelper.ResolveUrl(reservedPath).Trim().EnsureStartsWith("/").EnsureEndsWith("/"))
.Where(reservedPathTrimmed => reservedPathTrimmed.IsNullOrWhiteSpace() == false))
{
newReservedList.Add(reservedPathTrimmed);
}
// use the new list from now on
_reservedList = newReservedList;
}
}
}
//The url should be cleaned up before checking:
// * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/'
// * We shouldn't be comparing the query at all
var pathPart = url.Split(new[] {'?'}, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant();
if (pathPart.Contains(".") == false)
{
pathPart = pathPart.EnsureEndsWith('/');
}
// return true if url starts with an element of the reserved list
return _reservedList.Any(x => pathPart.InvariantStartsWith(x));
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2016, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SafetySharp.Runtime
{
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using Analysis;
using CompilerServices;
using Modeling;
using Serialization;
using Utilities;
/// <summary>
/// Represents a runtime model that can be used for model checking or simulation.
/// </summary>
internal sealed unsafe class RuntimeModel : DisposableObject
{
/// <summary>
/// The unique name of the construction state.
/// </summary>
internal const string ConstructionStateName = "constructionState259C2EE0D9884B92989DF442BA268E8E";
/// <summary>
/// The <see cref="ChoiceResolver" /> used by the model.
/// </summary>
private readonly ChoiceResolver _choiceResolver;
/// <summary>
/// Deserializes a state of the model.
/// </summary>
private readonly SerializationDelegate _deserialize;
/// <summary>
/// Serializes a state of the model.
/// </summary>
private readonly SerializationDelegate _serialize;
/// <summary>
/// Restricts the ranges of the model's state variables.
/// </summary>
private readonly Action _restrictRanges;
/// <summary>
/// The objects referenced by the model that participate in state serialization.
/// </summary>
private readonly ObjectTable _serializedObjects;
/// <summary>
/// The number of bytes reserved at the beginning of each state vector by the model checker tool.
/// </summary>
private readonly int _stateHeaderBytes;
/// <summary>
/// Initializes a new instance.
/// </summary>
/// <param name="serializedData">The serialized data describing the model.</param>
/// <param name="stateHeaderBytes">
/// The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
/// </param>
internal RuntimeModel(SerializedRuntimeModel serializedData, int stateHeaderBytes = 0)
{
Requires.That(serializedData.Model != null, "Expected a valid model instance.");
var buffer = serializedData.Buffer;
var rootComponents = serializedData.Model.Roots;
var objectTable = serializedData.ObjectTable;
var formulas = serializedData.Formulas;
Requires.NotNull(buffer, nameof(buffer));
Requires.NotNull(rootComponents, nameof(rootComponents));
Requires.NotNull(objectTable, nameof(objectTable));
Requires.NotNull(formulas, nameof(formulas));
Requires.That(stateHeaderBytes % 4 == 0, nameof(stateHeaderBytes), "Expected a multiple of 4.");
Model = serializedData.Model;
SerializedModel = buffer;
RootComponents = rootComponents.Cast<Component>().ToArray();
Faults = objectTable.OfType<Fault>().Where(fault => fault.Activation == Activation.Nondeterministic && fault.IsUsed).ToArray();
ActivationSensitiveFaults = Faults.Where(fault => fault.RequiresActivationNotification).ToArray();
StateFormulas = objectTable.OfType<StateFormula>().ToArray();
Formulas = formulas;
// Create a local object table just for the objects referenced by the model; only these objects
// have to be serialized and deserialized. The local object table does not contain, for instance,
// the closure types of the state formulas
var objects = Model.ReferencedObjects;
var deterministicFaults = objectTable.OfType<Fault>().Where(fault => fault.Activation != Activation.Nondeterministic);
_serializedObjects = new ObjectTable(objects.Except(deterministicFaults, ReferenceEqualityComparer<object>.Default));
Objects = objectTable;
StateVectorLayout = SerializationRegistry.Default.GetStateVectorLayout(Model, _serializedObjects, SerializationMode.Optimized);
_deserialize = StateVectorLayout.CreateDeserializer(_serializedObjects);
_serialize = StateVectorLayout.CreateSerializer(_serializedObjects);
_restrictRanges = StateVectorLayout.CreateRangeRestrictor(_serializedObjects);
_stateHeaderBytes = stateHeaderBytes;
PortBinding.BindAll(objectTable);
_choiceResolver = new ChoiceResolver(objectTable);
ConstructionState = new byte[StateVectorSize];
fixed (byte* state = ConstructionState)
{
Serialize(state);
_restrictRanges();
}
FaultSet.CheckFaultCount(Faults.Length);
StateFormulaSet.CheckFormulaCount(StateFormulas.Length);
}
/// <summary>
/// Gets a copy of the original model the runtime model was generated from.
/// </summary>
internal ModelBase Model { get; }
/// <summary>
/// Gets the construction state of the model.
/// </summary>
internal byte[] ConstructionState { get; }
/// <summary>
/// Gets the objects referenced by the model.
/// </summary>
internal ObjectTable Objects { get; }
/// <summary>
/// Gets the buffer the model was deserialized from.
/// </summary>
internal byte[] SerializedModel { get; }
/// <summary>
/// Gets the model's <see cref="StateVectorLayout" />.
/// </summary>
internal StateVectorLayout StateVectorLayout { get; }
/// <summary>
/// The formulas that are checked on the model.
/// </summary>
public Formula[] Formulas { get; }
/// <summary>
/// Gets the size of the state vector in bytes. The size is always a multiple of 4.
/// </summary>
internal int StateVectorSize => StateVectorLayout.SizeInBytes + _stateHeaderBytes;
/// <summary>
/// Gets the root components of the model.
/// </summary>
public Component[] RootComponents { get; }
/// <summary>
/// Gets the faults contained in the model that can be activated nondeterministically.
/// </summary>
public Fault[] Faults { get; }
/// <summary>
/// Gets the faults contained in the model that can be activated nondeterministically and that must be notified about their
/// activation.
/// </summary>
internal Fault[] ActivationSensitiveFaults { get; }
/// <summary>
/// Gets the state formulas of the model.
/// </summary>
internal StateFormula[] StateFormulas { get; }
/// <summary>
/// Deserializes the model's state from <paramref name="serializedState" />.
/// </summary>
/// <param name="serializedState">The state of the model that should be deserialized.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Deserialize(byte* serializedState)
{
_deserialize(serializedState + _stateHeaderBytes);
}
/// <summary>
/// Serializes the model's state to <paramref name="serializedState" />.
/// </summary>
/// <param name="serializedState">The memory region the model's state should be serialized into.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Serialize(byte* serializedState)
{
_serialize(serializedState + _stateHeaderBytes);
}
/// <summary>
/// Resets the model to one of its initial states.
/// </summary>
internal void Reset()
{
fixed (byte* state = ConstructionState)
{
Deserialize(state);
foreach (var obj in _serializedObjects.OfType<IInitializable>())
obj.Initialize();
_restrictRanges();
}
}
/// <summary>
/// Computes an initial state of the model.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ExecuteInitialStep()
{
foreach (var fault in Faults)
fault.Reset();
foreach (var obj in _serializedObjects.OfType<IInitializable>())
obj.Initialize();
_restrictRanges();
}
/// <summary>
/// Updates the state of the model by executing a single step.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ExecuteStep()
{
foreach (var fault in Faults)
fault.Reset();
foreach (var component in RootComponents)
component.Update();
_restrictRanges();
}
/// <summary>
/// Computes the initial states of the model, storing the computed <paramref name="transitions" />.
/// </summary>
/// <param name="transitions">The set the computed transitions should be stored in.</param>
internal void ComputeInitialStates(TransitionSet transitions)
{
_choiceResolver.PrepareNextState();
fixed (byte* state = ConstructionState)
{
while (_choiceResolver.PrepareNextPath())
{
Deserialize(state);
ExecuteInitialStep();
transitions.Add(this);
}
}
}
/// <summary>
/// Computes the successor states for <paramref name="sourceState" />, storing the computed <paramref name="transitions" />.
/// </summary>
/// <param name="transitions">The set the computed transitions should be stored in.</param>
/// <param name="sourceState">The source state the next states should be computed for.</param>
internal void ComputeSuccessorStates(TransitionSet transitions, byte* sourceState)
{
_choiceResolver.PrepareNextState();
while (_choiceResolver.PrepareNextPath())
{
Deserialize(sourceState);
ExecuteStep();
transitions.Add(this);
}
}
/// <summary>
/// Generates the replay information for the <paramref name="trace" />.
/// </summary>
/// <param name="trace">The trace the replay information should be generated for.</param>
/// <param name="endsWithException">Indicates whether the trace ends with an exception being thrown.</param>
internal int[][] GenerateReplayInformation(byte[][] trace, bool endsWithException)
{
var info = new int[trace.Length - 1][];
var targetState = stackalloc byte[StateVectorSize];
// We have to generate the replay info for all transitions
for (var i = 0; i < trace.Length - 1; ++i)
{
_choiceResolver.Clear();
_choiceResolver.PrepareNextState();
// Try all transitions until we find the one that leads to the desired state
while (_choiceResolver.PrepareNextPath())
{
fixed (byte* sourceState = trace[i])
Deserialize(sourceState);
try
{
if (i == 0)
ExecuteInitialStep();
else
ExecuteStep();
}
catch (Exception)
{
Requires.That(endsWithException, "Unexpected exception.");
Requires.That(i == trace.Length - 2, "Unexpected exception.");
info[i] = _choiceResolver.GetChoices().ToArray();
break;
}
NotifyFaultActivations();
Serialize(targetState);
// Compare the target states; if they match, we've found the correct transition
var areEqual = true;
for (var j = 0; j < StateVectorSize; ++j)
areEqual &= targetState[j] == trace[i + 1][j];
if (!areEqual)
continue;
info[i] = _choiceResolver.GetChoices().ToArray();
break;
}
Requires.That(info[i] != null, $"Unable to generate replay information for step {i} of {trace.Length}.");
}
return info;
}
/// <summary>
/// Replays the model step starting at the serialized <paramref name="state" /> using the given
/// <paramref name="replayInformation" />.
/// </summary>
/// <param name="state">The serialized state that the replay starts from.</param>
/// <param name="replayInformation">The replay information required to compute the target state.</param>
/// <param name="initializationStep">Indicates whether the initialization step should be replayed.</param>
internal void Replay(byte* state, int[] replayInformation, bool initializationStep)
{
Requires.NotNull(replayInformation, nameof(replayInformation));
_choiceResolver.Clear();
_choiceResolver.PrepareNextState();
_choiceResolver.SetChoices(replayInformation);
Deserialize(state);
if (initializationStep)
ExecuteInitialStep();
else
ExecuteStep();
NotifyFaultActivations();
}
/// <summary>
/// Notifies all activated faults of their activation. Returns <c>false</c> to indicate that no notifications were necessary.
/// </summary>
internal bool NotifyFaultActivations()
{
if (ActivationSensitiveFaults.Length == 0)
return false;
var notificationsSent = false;
foreach (var fault in ActivationSensitiveFaults)
{
if (fault.IsActivated)
{
fault.OnActivated();
notificationsSent = true;
}
}
return notificationsSent;
}
/// <summary>
/// Gets the choices that were made to generate the last transitions.
/// </summary>
internal int[] GetLastChoices()
{
return _choiceResolver.GetChoices().ToArray();
}
/// <summary>
/// Disposes the object, releasing all managed and unmanaged resources.
/// </summary>
/// <param name="disposing">If true, indicates that the object is disposed; otherwise, the object is finalized.</param>
protected override void OnDisposing(bool disposing)
{
if (!disposing)
return;
_choiceResolver.SafeDispose();
Objects.OfType<IDisposable>().SafeDisposeAll();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAdGroupAssetServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetAdGroupAssetRequestObject()
{
moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAdGroupAssetRequest request = new GetAdGroupAssetRequest
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AdGroupAsset expectedResponse = new gagvr::AdGroupAsset
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetAdGroupAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupAssetServiceClient client = new AdGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupAsset response = client.GetAdGroupAsset(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupAssetRequestObjectAsync()
{
moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAdGroupAssetRequest request = new GetAdGroupAssetRequest
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AdGroupAsset expectedResponse = new gagvr::AdGroupAsset
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetAdGroupAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupAssetServiceClient client = new AdGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupAsset responseCallSettings = await client.GetAdGroupAssetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroupAsset responseCancellationToken = await client.GetAdGroupAssetAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAdGroupAsset()
{
moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAdGroupAssetRequest request = new GetAdGroupAssetRequest
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AdGroupAsset expectedResponse = new gagvr::AdGroupAsset
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetAdGroupAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupAssetServiceClient client = new AdGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupAsset response = client.GetAdGroupAsset(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupAssetAsync()
{
moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAdGroupAssetRequest request = new GetAdGroupAssetRequest
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AdGroupAsset expectedResponse = new gagvr::AdGroupAsset
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetAdGroupAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupAssetServiceClient client = new AdGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupAsset responseCallSettings = await client.GetAdGroupAssetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroupAsset responseCancellationToken = await client.GetAdGroupAssetAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAdGroupAssetResourceNames()
{
moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAdGroupAssetRequest request = new GetAdGroupAssetRequest
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AdGroupAsset expectedResponse = new gagvr::AdGroupAsset
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetAdGroupAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupAssetServiceClient client = new AdGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupAsset response = client.GetAdGroupAsset(request.ResourceNameAsAdGroupAssetName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupAssetResourceNamesAsync()
{
moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAdGroupAssetRequest request = new GetAdGroupAssetRequest
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AdGroupAsset expectedResponse = new gagvr::AdGroupAsset
{
ResourceNameAsAdGroupAssetName = gagvr::AdGroupAssetName.FromCustomerAdGroupAssetFieldType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetAdGroupAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupAssetServiceClient client = new AdGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupAsset responseCallSettings = await client.GetAdGroupAssetAsync(request.ResourceNameAsAdGroupAssetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroupAsset responseCancellationToken = await client.GetAdGroupAssetAsync(request.ResourceNameAsAdGroupAssetName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAdGroupAssetsRequestObject()
{
moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupAssetsRequest request = new MutateAdGroupAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupAssetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateAdGroupAssetsResponse expectedResponse = new MutateAdGroupAssetsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateAdGroupAssetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateAdGroupAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupAssetServiceClient client = new AdGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupAssetsResponse response = client.MutateAdGroupAssets(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAdGroupAssetsRequestObjectAsync()
{
moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupAssetsRequest request = new MutateAdGroupAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupAssetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateAdGroupAssetsResponse expectedResponse = new MutateAdGroupAssetsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateAdGroupAssetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateAdGroupAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupAssetServiceClient client = new AdGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupAssetsResponse responseCallSettings = await client.MutateAdGroupAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAdGroupAssetsResponse responseCancellationToken = await client.MutateAdGroupAssetsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAdGroupAssets()
{
moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupAssetsRequest request = new MutateAdGroupAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupAssetOperation(),
},
};
MutateAdGroupAssetsResponse expectedResponse = new MutateAdGroupAssetsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateAdGroupAssetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateAdGroupAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupAssetServiceClient client = new AdGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupAssetsResponse response = client.MutateAdGroupAssets(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAdGroupAssetsAsync()
{
moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AdGroupAssetService.AdGroupAssetServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupAssetsRequest request = new MutateAdGroupAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupAssetOperation(),
},
};
MutateAdGroupAssetsResponse expectedResponse = new MutateAdGroupAssetsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateAdGroupAssetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateAdGroupAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupAssetServiceClient client = new AdGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupAssetsResponse responseCallSettings = await client.MutateAdGroupAssetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAdGroupAssetsResponse responseCancellationToken = await client.MutateAdGroupAssetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
namespace Alachisoft.NCache.Common.DataStructures
{
public class BinaryPriorityQueue : IPriorityQueue, ICollection, ICloneable, IList
{
protected ArrayList InnerList = new ArrayList();
protected IComparer Comparer;
#region contructors
public BinaryPriorityQueue() : this(System.Collections.Comparer.Default)
{}
public BinaryPriorityQueue(IComparer c)
{
Comparer = c;
}
public BinaryPriorityQueue(int C) : this(System.Collections.Comparer.Default,C)
{}
public BinaryPriorityQueue(IComparer c, int Capacity)
{
Comparer = c;
InnerList.Capacity = Capacity;
}
protected BinaryPriorityQueue(ArrayList Core, IComparer Comp, bool Copy)
{
if(Copy)
InnerList = Core.Clone() as ArrayList;
else
InnerList = Core;
Comparer = Comp;
}
#endregion
protected void SwitchElements(int i, int j)
{
object h = InnerList[i];
InnerList[i] = InnerList[j];
InnerList[j] = h;
}
protected virtual int OnCompare(int i, int j)
{
return Comparer.Compare(InnerList[i],InnerList[j]);
}
#region public methods
/// <summary>
/// Push an object onto the PQ
/// </summary>
/// <param name="O">The new object</param>
/// <returns>The index in the list where the object is _now_. This will change when objects are taken from or put onto the PQ.</returns>
public int Push(object O)
{
int p = InnerList.Count,p2;
InnerList.Add(O); // E[p] = O
do
{
if(p==0)
break;
p2 = (p-1)/2;
if(OnCompare(p,p2)<0)
{
SwitchElements(p,p2);
p = p2;
}
else
break;
}while(true);
return p;
}
/// <summary>
/// Get the smallest object and remove it.
/// </summary>
/// <returns>The smallest object</returns>
public object Pop()
{
object result = InnerList[0];
int p = 0,p1,p2,pn;
InnerList[0] = InnerList[InnerList.Count-1];
InnerList.RemoveAt(InnerList.Count-1);
do
{
pn = p;
p1 = 2*p+1;
p2 = 2*p+2;
if(InnerList.Count>p1 && OnCompare(p,p1)>0)
p = p1;
if(InnerList.Count>p2 && OnCompare(p,p2)>0)
p = p2;
if(p==pn)
break;
SwitchElements(p,pn);
}while(true);
return result;
}
/// <summary>
/// Notify the PQ that the object at position i has changed
/// and the PQ needs to restore order.
/// Since you dont have access to any indexes (except by using the
/// explicit IList.this) you should not call this function without knowing exactly
/// what you do.
/// </summary>
/// <param name="i">The index of the changed object.</param>
public void Update(int i)
{
int p = i,pn;
int p1,p2;
do
{
if(p==0)
break;
p2 = (p-1)/2;
if(OnCompare(p,p2)<0)
{
SwitchElements(p,p2);
p = p2;
}
else
break;
}while(true);
if(p<i)
return;
do
{
pn = p;
p1 = 2*p+1;
p2 = 2*p+2;
if(InnerList.Count>p1 && OnCompare(p,p1)>0)
p = p1;
if(InnerList.Count>p2 && OnCompare(p,p2)>0)
p = p2;
if(p==pn)
break;
SwitchElements(p,pn);
}while(true);
}
/// <summary>
/// Get the smallest object without removing it.
/// </summary>
/// <returns>The smallest object</returns>
public object Peek()
{
if(InnerList.Count>0)
return InnerList[0];
return null;
}
public bool Contains(object value)
{
return InnerList.Contains(value);
}
public void Clear()
{
InnerList.Clear();
}
public int Count
{
get
{
return InnerList.Count;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return InnerList.GetEnumerator();
}
public void CopyTo(Array array, int index)
{
InnerList.CopyTo(array,index);
}
public object Clone()
{
return new BinaryPriorityQueue(InnerList,Comparer,true);
}
public bool IsSynchronized
{
get
{
return InnerList.IsSynchronized;
}
}
public object SyncRoot
{
get
{
return this;
}
}
#endregion
#region explicit implementation
bool IList.IsReadOnly
{
get
{
return false;
}
}
object IList.this[int index]
{
get
{
return InnerList[index];
}
set
{
InnerList[index] = value;
Update(index);
}
}
int IList.Add(object o)
{
return Push(o);
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException();
}
void IList.Insert(int index, object value)
{
throw new NotSupportedException();
}
void IList.Remove(object value)
{
throw new NotSupportedException();
}
int IList.IndexOf(object value)
{
throw new NotSupportedException();
}
bool IList.IsFixedSize
{
get
{
return false;
}
}
public static BinaryPriorityQueue Syncronized(BinaryPriorityQueue P)
{
return new BinaryPriorityQueue(ArrayList.Synchronized(P.InnerList),P.Comparer,false);
}
public static BinaryPriorityQueue ReadOnly(BinaryPriorityQueue P)
{
return new BinaryPriorityQueue(ArrayList.ReadOnly(P.InnerList),P.Comparer,false);
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.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 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
{
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public sealed class LogManager
{
private static readonly LogFactory globalFactory = new LogFactory();
#if !NET_CF && !SILVERLIGHT && !MONO
/// <summary>
/// Initializes static members of the LogManager class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static LogManager()
{
try
{
SetupTerminationEvents();
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Error setting up termiation events: {0}", exception);
}
}
#endif
/// <summary>
/// Prevents a default instance of the LogManager class from being created.
/// </summary>
private LogManager()
{
}
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged
{
add { globalFactory.ConfigurationChanged += value; }
remove { globalFactory.ConfigurationChanged -= value; }
}
#if !NET_CF && !SILVERLIGHT
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded
{
add { globalFactory.ConfigurationReloaded += value; }
remove { globalFactory.ConfigurationReloaded -= value; }
}
#endif
/// <summary>
/// Gets or sets a value indicating whether NLog should throw exceptions.
/// By default exceptions are not thrown under any circumstances.
/// </summary>
public static bool ThrowExceptions
{
get { return globalFactory.ThrowExceptions; }
set { globalFactory.ThrowExceptions = value; }
}
/// <summary>
/// Gets or sets the current logging configuration.
/// </summary>
public static LoggingConfiguration Configuration
{
get { return globalFactory.Configuration; }
set { globalFactory.Configuration = value; }
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public static LogLevel GlobalThreshold
{
get { return globalFactory.GlobalThreshold; }
set { globalFactory.GlobalThreshold = value; }
}
#if !NET_CF
/// <summary>
/// Gets the logger named after the currently-being-initialized class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
#if SILVERLIGHT
StackFrame frame = new StackTrace().GetFrame(1);
#else
StackFrame frame = new StackFrame(1, false);
#endif
return globalFactory.GetLogger(frame.GetMethod().DeclaringType.FullName);
}
/// <summary>
/// Gets the logger named after the currently-being-initialized class.
/// </summary>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger(Type loggerType)
{
#if SILVERLIGHT
StackFrame frame = new StackTrace().GetFrame(1);
#else
StackFrame frame = new StackFrame(1, false);
#endif
return globalFactory.GetLogger(frame.GetMethod().DeclaringType.FullName, loggerType);
}
#endif
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger which discards all log messages.</returns>
public static Logger CreateNullLogger()
{
return globalFactory.CreateNullLogger();
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
public static Logger GetLogger(string name)
{
return globalFactory.GetLogger(name);
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
public static Logger GetLogger(string name, Type loggerType)
{
return globalFactory.GetLogger(name, loggerType);
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger.
/// and recalculates their target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public static void ReconfigExistingLoggers()
{
globalFactory.ReconfigExistingLoggers();
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public static void Flush()
{
globalFactory.Flush();
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(TimeSpan timeout)
{
globalFactory.Flush(timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(int timeoutMilliseconds)
{
globalFactory.Flush(timeoutMilliseconds);
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public static void Flush(AsyncContinuation asyncContinuation)
{
globalFactory.Flush(asyncContinuation);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
globalFactory.Flush(asyncContinuation, timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
globalFactory.Flush(asyncContinuation, timeoutMilliseconds);
}
/// <summary>Decreases the log enable counter and if it reaches -1
/// the logs are disabled.</summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
/// <returns>An object that iplements IDisposable whose Dispose() method
/// reenables logging. To be used with C# <c>using ()</c> statement.</returns>
public static IDisposable DisableLogging()
{
return globalFactory.DisableLogging();
}
/// <summary>Increases the log enable counter and if it reaches 0 the logs are disabled.</summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static void EnableLogging()
{
globalFactory.EnableLogging();
}
/// <summary>
/// Returns <see langword="true" /> if logging is currently enabled.
/// </summary>
/// <returns>A value of <see langword="true" /> if logging is currently enabled,
/// <see langword="false"/> otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static bool IsLoggingEnabled()
{
return globalFactory.IsLoggingEnabled();
}
#if !NET_CF && !SILVERLIGHT && !MONO
private static void SetupTerminationEvents()
{
AppDomain.CurrentDomain.ProcessExit += TurnOffLogging;
AppDomain.CurrentDomain.DomainUnload += TurnOffLogging;
}
private static void TurnOffLogging(object sender, EventArgs args)
{
// reset logging configuration to null
// this causes old configuration (if any) to be closed.
InternalLogger.Info("Shutting down logging...");
Configuration = null;
InternalLogger.Info("Logger has been shut down.");
}
#endif
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// NotificationResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Notify.V1.Service
{
public class NotificationResource : Resource
{
public sealed class PriorityEnum : StringEnum
{
private PriorityEnum(string value) : base(value) {}
public PriorityEnum() {}
public static implicit operator PriorityEnum(string value)
{
return new PriorityEnum(value);
}
public static readonly PriorityEnum High = new PriorityEnum("high");
public static readonly PriorityEnum Low = new PriorityEnum("low");
}
private static Request BuildCreateRequest(CreateNotificationOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Notify,
"/v1/Services/" + options.PathServiceSid + "/Notifications",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Notification parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Notification </returns>
public static NotificationResource Create(CreateNotificationOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Notification parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Notification </returns>
public static async System.Threading.Tasks.Task<NotificationResource> CreateAsync(CreateNotificationOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="identity"> The `identity` value that identifies the new resource's User </param>
/// <param name="tag"> A tag that selects the Bindings to notify </param>
/// <param name="body"> The notification body text </param>
/// <param name="priority"> The priority of the notification </param>
/// <param name="ttl"> How long, in seconds, the notification is valid </param>
/// <param name="title"> The notification title </param>
/// <param name="sound"> The name of the sound to be played for the notification </param>
/// <param name="action"> The actions to display for the notification </param>
/// <param name="data"> The custom key-value pairs of the notification's payload </param>
/// <param name="apn"> The APNS-specific payload that overrides corresponding attributes in a generic payload for APNS
/// Bindings </param>
/// <param name="gcm"> The GCM-specific payload that overrides corresponding attributes in generic payload for GCM
/// Bindings </param>
/// <param name="sms"> The SMS-specific payload that overrides corresponding attributes in generic payload for SMS
/// Bindings </param>
/// <param name="facebookMessenger"> Deprecated </param>
/// <param name="fcm"> The FCM-specific payload that overrides corresponding attributes in generic payload for FCM
/// Bindings </param>
/// <param name="segment"> A Segment to notify </param>
/// <param name="alexa"> Deprecated </param>
/// <param name="toBinding"> The destination address specified as a JSON string </param>
/// <param name="deliveryCallbackUrl"> URL to send webhooks </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Notification </returns>
public static NotificationResource Create(string pathServiceSid,
List<string> identity = null,
List<string> tag = null,
string body = null,
NotificationResource.PriorityEnum priority = null,
int? ttl = null,
string title = null,
string sound = null,
string action = null,
object data = null,
object apn = null,
object gcm = null,
object sms = null,
object facebookMessenger = null,
object fcm = null,
List<string> segment = null,
object alexa = null,
List<string> toBinding = null,
string deliveryCallbackUrl = null,
ITwilioRestClient client = null)
{
var options = new CreateNotificationOptions(pathServiceSid){Identity = identity, Tag = tag, Body = body, Priority = priority, Ttl = ttl, Title = title, Sound = sound, Action = action, Data = data, Apn = apn, Gcm = gcm, Sms = sms, FacebookMessenger = facebookMessenger, Fcm = fcm, Segment = segment, Alexa = alexa, ToBinding = toBinding, DeliveryCallbackUrl = deliveryCallbackUrl};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="identity"> The `identity` value that identifies the new resource's User </param>
/// <param name="tag"> A tag that selects the Bindings to notify </param>
/// <param name="body"> The notification body text </param>
/// <param name="priority"> The priority of the notification </param>
/// <param name="ttl"> How long, in seconds, the notification is valid </param>
/// <param name="title"> The notification title </param>
/// <param name="sound"> The name of the sound to be played for the notification </param>
/// <param name="action"> The actions to display for the notification </param>
/// <param name="data"> The custom key-value pairs of the notification's payload </param>
/// <param name="apn"> The APNS-specific payload that overrides corresponding attributes in a generic payload for APNS
/// Bindings </param>
/// <param name="gcm"> The GCM-specific payload that overrides corresponding attributes in generic payload for GCM
/// Bindings </param>
/// <param name="sms"> The SMS-specific payload that overrides corresponding attributes in generic payload for SMS
/// Bindings </param>
/// <param name="facebookMessenger"> Deprecated </param>
/// <param name="fcm"> The FCM-specific payload that overrides corresponding attributes in generic payload for FCM
/// Bindings </param>
/// <param name="segment"> A Segment to notify </param>
/// <param name="alexa"> Deprecated </param>
/// <param name="toBinding"> The destination address specified as a JSON string </param>
/// <param name="deliveryCallbackUrl"> URL to send webhooks </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Notification </returns>
public static async System.Threading.Tasks.Task<NotificationResource> CreateAsync(string pathServiceSid,
List<string> identity = null,
List<string> tag = null,
string body = null,
NotificationResource.PriorityEnum priority = null,
int? ttl = null,
string title = null,
string sound = null,
string action = null,
object data = null,
object apn = null,
object gcm = null,
object sms = null,
object facebookMessenger = null,
object fcm = null,
List<string> segment = null,
object alexa = null,
List<string> toBinding = null,
string deliveryCallbackUrl = null,
ITwilioRestClient client = null)
{
var options = new CreateNotificationOptions(pathServiceSid){Identity = identity, Tag = tag, Body = body, Priority = priority, Ttl = ttl, Title = title, Sound = sound, Action = action, Data = data, Apn = apn, Gcm = gcm, Sms = sms, FacebookMessenger = facebookMessenger, Fcm = fcm, Segment = segment, Alexa = alexa, ToBinding = toBinding, DeliveryCallbackUrl = deliveryCallbackUrl};
return await CreateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a NotificationResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> NotificationResource object represented by the provided JSON </returns>
public static NotificationResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<NotificationResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Service that the resource is associated with
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The list of identity values of the Users to notify
/// </summary>
[JsonProperty("identities")]
public List<string> Identities { get; private set; }
/// <summary>
/// The tags that select the Bindings to notify
/// </summary>
[JsonProperty("tags")]
public List<string> Tags { get; private set; }
/// <summary>
/// The list of Segments to notify
/// </summary>
[JsonProperty("segments")]
public List<string> Segments { get; private set; }
/// <summary>
/// The priority of the notification
/// </summary>
[JsonProperty("priority")]
[JsonConverter(typeof(StringEnumConverter))]
public NotificationResource.PriorityEnum Priority { get; private set; }
/// <summary>
/// How long, in seconds, the notification is valid
/// </summary>
[JsonProperty("ttl")]
public int? Ttl { get; private set; }
/// <summary>
/// The notification title
/// </summary>
[JsonProperty("title")]
public string Title { get; private set; }
/// <summary>
/// The notification body text
/// </summary>
[JsonProperty("body")]
public string Body { get; private set; }
/// <summary>
/// The name of the sound to be played for the notification
/// </summary>
[JsonProperty("sound")]
public string Sound { get; private set; }
/// <summary>
/// The actions to display for the notification
/// </summary>
[JsonProperty("action")]
public string Action { get; private set; }
/// <summary>
/// The custom key-value pairs of the notification's payload
/// </summary>
[JsonProperty("data")]
public object Data { get; private set; }
/// <summary>
/// The APNS-specific payload that overrides corresponding attributes in a generic payload for APNS Bindings
/// </summary>
[JsonProperty("apn")]
public object Apn { get; private set; }
/// <summary>
/// The GCM-specific payload that overrides corresponding attributes in generic payload for GCM Bindings
/// </summary>
[JsonProperty("gcm")]
public object Gcm { get; private set; }
/// <summary>
/// The FCM-specific payload that overrides corresponding attributes in generic payload for FCM Bindings
/// </summary>
[JsonProperty("fcm")]
public object Fcm { get; private set; }
/// <summary>
/// The SMS-specific payload that overrides corresponding attributes in generic payload for SMS Bindings
/// </summary>
[JsonProperty("sms")]
public object Sms { get; private set; }
/// <summary>
/// Deprecated
/// </summary>
[JsonProperty("facebook_messenger")]
public object FacebookMessenger { get; private set; }
/// <summary>
/// Deprecated
/// </summary>
[JsonProperty("alexa")]
public object Alexa { get; private set; }
private NotificationResource()
{
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
internal static class WebSocketHelper
{
internal const int OperationNotStarted = 0;
internal const int OperationFinished = 1;
internal const string SecWebSocketKey = "Sec-WebSocket-Key";
internal const string SecWebSocketVersion = "Sec-WebSocket-Version";
internal const string SecWebSocketProtocol = "Sec-WebSocket-Protocol";
internal const string SecWebSocketAccept = "Sec-WebSocket-Accept";
internal const string MaxPendingConnectionsString = "MaxPendingConnections";
internal const string WebSocketTransportSettingsString = "WebSocketTransportSettings";
internal const string CloseOperation = "CloseOperation";
internal const string SendOperation = "SendOperation";
internal const string ReceiveOperation = "ReceiveOperation";
internal static readonly char[] ProtocolSeparators = new char[] { ',' };
private const string SchemeWs = "ws";
private const string SchemeWss = "wss";
private static readonly HashSet<char> s_InvalidSeparatorSet = new HashSet<char>(new char[] { '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', ' ' });
internal static int GetReceiveBufferSize(long maxReceivedMessageSize)
{
int effectiveMaxReceiveBufferSize = maxReceivedMessageSize <= WebSocketDefaults.BufferSize ? (int)maxReceivedMessageSize : WebSocketDefaults.BufferSize;
return Math.Max(WebSocketDefaults.MinReceiveBufferSize, effectiveMaxReceiveBufferSize);
}
internal static bool UseWebSocketTransport(WebSocketTransportUsage transportUsage, bool isContractDuplex)
{
return transportUsage == WebSocketTransportUsage.Always
|| (transportUsage == WebSocketTransportUsage.WhenDuplex && isContractDuplex);
}
internal static bool IsWebSocketUri(Uri uri)
{
return uri != null &&
(WebSocketHelper.SchemeWs.Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase) ||
WebSocketHelper.SchemeWss.Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase));
}
internal static Uri NormalizeHttpSchemeWithWsScheme(Uri uri)
{
Fx.Assert(uri != null, "RemoteAddress.Uri should not be null.");
if (IsWebSocketUri(uri))
{
return uri;
}
UriBuilder builder = new UriBuilder(uri);
switch (uri.Scheme.ToLowerInvariant())
{
case UriEx.UriSchemeHttp:
builder.Scheme = SchemeWs;
break;
case UriEx.UriSchemeHttps:
builder.Scheme = SchemeWss;
break;
default:
break;
}
return builder.Uri;
}
internal static bool IsSubProtocolInvalid(string protocol, out string invalidChar)
{
Fx.Assert(protocol != null, "protocol should not be null");
char[] chars = protocol.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
char ch = chars[i];
if (ch < 0x21 || ch > 0x7e)
{
invalidChar = string.Format(CultureInfo.InvariantCulture, "[{0}]", (int)ch);
return true;
}
if (s_InvalidSeparatorSet.Contains(ch))
{
invalidChar = ch.ToString();
return true;
}
}
invalidChar = null;
return false;
}
internal static WebSocketTransportSettings GetRuntimeWebSocketSettings(WebSocketTransportSettings settings)
{
WebSocketTransportSettings runtimeSettings = settings.Clone();
return runtimeSettings;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.WrapExceptionsRule,
Justification = "The exceptions thrown here are already wrapped.")]
internal static void ThrowCorrectException(Exception ex)
{
throw ConvertAndTraceException(ex);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.WrapExceptionsRule,
Justification = "The exceptions thrown here are already wrapped.")]
internal static void ThrowCorrectException(Exception ex, TimeSpan timeout, string operation)
{
throw ConvertAndTraceException(ex, timeout, operation);
}
internal static Exception ConvertAndTraceException(Exception ex)
{
return ConvertAndTraceException(
ex,
TimeSpan.MinValue, // this is a dummy since operation type is null, so the timespan value won't be used
null);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability103:ThrowWrappedExceptionsRule",
Justification = "The exceptions wrapped here will be thrown out later.")]
internal static Exception ConvertAndTraceException(Exception ex, TimeSpan timeout, string operation)
{
ObjectDisposedException objectDisposedException = ex as ObjectDisposedException;
if (objectDisposedException != null)
{
CommunicationObjectAbortedException communicationObjectAbortedException = new CommunicationObjectAbortedException(ex.Message, ex);
FxTrace.Exception.AsWarning(communicationObjectAbortedException);
return communicationObjectAbortedException;
}
AggregateException aggregationException = ex as AggregateException;
if (aggregationException != null)
{
Exception exception = FxTrace.Exception.AsError<OperationCanceledException>(aggregationException);
OperationCanceledException operationCanceledException = exception as OperationCanceledException;
if (operationCanceledException != null)
{
TimeoutException timeoutException = GetTimeoutException(exception, timeout, operation);
FxTrace.Exception.AsWarning(timeoutException);
return timeoutException;
}
else
{
Exception communicationException = ConvertAggregateExceptionToCommunicationException(aggregationException);
if (communicationException is CommunicationObjectAbortedException)
{
FxTrace.Exception.AsWarning(communicationException);
return communicationException;
}
else
{
return FxTrace.Exception.AsError(communicationException);
}
}
}
return FxTrace.Exception.AsError(ex);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability103",
Justification = "The exceptions will be wrapped by the callers.")]
internal static Exception ConvertAggregateExceptionToCommunicationException(AggregateException ex)
{
Exception exception = FxTrace.Exception.AsError<Exception>(ex);
ObjectDisposedException objectDisposedException = exception as ObjectDisposedException;
if (objectDisposedException != null)
{
return new CommunicationObjectAbortedException(exception.Message, exception);
}
return new CommunicationException(exception.Message, exception);
}
internal static void ThrowExceptionOnTaskFailure(Task task, TimeSpan timeout, string operation)
{
if (task.IsFaulted)
{
throw FxTrace.Exception.AsError<CommunicationException>(task.Exception);
}
if (task.IsCanceled)
{
throw FxTrace.Exception.AsError(GetTimeoutException(null, timeout, operation));
}
}
// TODO: Move to correct place alphabetically, it's here temporariliy to make editting easier
internal static Exception CreateExceptionOnTaskFailure(Task task, TimeSpan timeout, string operation)
{
if (task.IsFaulted)
{
return FxTrace.Exception.AsError<CommunicationException>(task.Exception);
}
if (task.IsCanceled)
{
throw FxTrace.Exception.AsError(GetTimeoutException(null, timeout, operation));
}
return null;
}
internal static TimeoutException GetTimeoutException(Exception innerException, TimeSpan timeout, string operation)
{
string errorMsg = string.Empty;
if (operation != null)
{
switch (operation)
{
case WebSocketHelper.CloseOperation:
errorMsg = SR.Format(SR.CloseTimedOut, timeout);
break;
case WebSocketHelper.SendOperation:
errorMsg = SR.Format(SR.WebSocketSendTimedOut, timeout);
break;
case WebSocketHelper.ReceiveOperation:
errorMsg = SR.Format(SR.WebSocketReceiveTimedOut, timeout);
break;
default:
errorMsg = SR.Format(SR.WebSocketOperationTimedOut, operation, timeout);
break;
}
}
return innerException == null ? new TimeoutException(errorMsg) : new TimeoutException(errorMsg, innerException);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A quaternion of type long.
/// </summary>
[Serializable]
[DataContract]
[StructLayout(LayoutKind.Sequential)]
public struct lquat : IReadOnlyList<long>, IEquatable<lquat>
{
#region Fields
/// <summary>
/// x-component
/// </summary>
[DataMember]
public long x;
/// <summary>
/// y-component
/// </summary>
[DataMember]
public long y;
/// <summary>
/// z-component
/// </summary>
[DataMember]
public long z;
/// <summary>
/// w-component
/// </summary>
[DataMember]
public long w;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public lquat(long x, long y, long z, long w)
{
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/// <summary>
/// all-same-value constructor
/// </summary>
public lquat(long v)
{
this.x = v;
this.y = v;
this.z = v;
this.w = v;
}
/// <summary>
/// copy constructor
/// </summary>
public lquat(lquat q)
{
this.x = q.x;
this.y = q.y;
this.z = q.z;
this.w = q.w;
}
/// <summary>
/// vector-and-scalar constructor (CAUTION: not angle-axis, use FromAngleAxis instead)
/// </summary>
public lquat(lvec3 v, long s)
{
this.x = v.x;
this.y = v.y;
this.z = v.z;
this.w = s;
}
#endregion
#region Implicit Operators
/// <summary>
/// Implicitly converts this to a decquat.
/// </summary>
public static implicit operator decquat(lquat v) => new decquat((decimal)v.x, (decimal)v.y, (decimal)v.z, (decimal)v.w);
#endregion
#region Explicit Operators
/// <summary>
/// Explicitly converts this to a ivec4.
/// </summary>
public static explicit operator ivec4(lquat v) => new ivec4((int)v.x, (int)v.y, (int)v.z, (int)v.w);
/// <summary>
/// Explicitly converts this to a iquat.
/// </summary>
public static explicit operator iquat(lquat v) => new iquat((int)v.x, (int)v.y, (int)v.z, (int)v.w);
/// <summary>
/// Explicitly converts this to a uvec4.
/// </summary>
public static explicit operator uvec4(lquat v) => new uvec4((uint)v.x, (uint)v.y, (uint)v.z, (uint)v.w);
/// <summary>
/// Explicitly converts this to a uquat.
/// </summary>
public static explicit operator uquat(lquat v) => new uquat((uint)v.x, (uint)v.y, (uint)v.z, (uint)v.w);
/// <summary>
/// Explicitly converts this to a vec4.
/// </summary>
public static explicit operator vec4(lquat v) => new vec4((float)v.x, (float)v.y, (float)v.z, (float)v.w);
/// <summary>
/// Explicitly converts this to a quat.
/// </summary>
public static explicit operator quat(lquat v) => new quat((float)v.x, (float)v.y, (float)v.z, (float)v.w);
/// <summary>
/// Explicitly converts this to a hvec4.
/// </summary>
public static explicit operator hvec4(lquat v) => new hvec4((Half)v.x, (Half)v.y, (Half)v.z, (Half)v.w);
/// <summary>
/// Explicitly converts this to a hquat.
/// </summary>
public static explicit operator hquat(lquat v) => new hquat((Half)v.x, (Half)v.y, (Half)v.z, (Half)v.w);
/// <summary>
/// Explicitly converts this to a dvec4.
/// </summary>
public static explicit operator dvec4(lquat v) => new dvec4((double)v.x, (double)v.y, (double)v.z, (double)v.w);
/// <summary>
/// Explicitly converts this to a dquat.
/// </summary>
public static explicit operator dquat(lquat v) => new dquat((double)v.x, (double)v.y, (double)v.z, (double)v.w);
/// <summary>
/// Explicitly converts this to a decvec4.
/// </summary>
public static explicit operator decvec4(lquat v) => new decvec4((decimal)v.x, (decimal)v.y, (decimal)v.z, (decimal)v.w);
/// <summary>
/// Explicitly converts this to a cvec4.
/// </summary>
public static explicit operator cvec4(lquat v) => new cvec4((Complex)v.x, (Complex)v.y, (Complex)v.z, (Complex)v.w);
/// <summary>
/// Explicitly converts this to a cquat.
/// </summary>
public static explicit operator cquat(lquat v) => new cquat((Complex)v.x, (Complex)v.y, (Complex)v.z, (Complex)v.w);
/// <summary>
/// Explicitly converts this to a lvec4.
/// </summary>
public static explicit operator lvec4(lquat v) => new lvec4((long)v.x, (long)v.y, (long)v.z, (long)v.w);
/// <summary>
/// Explicitly converts this to a bvec4.
/// </summary>
public static explicit operator bvec4(lquat v) => new bvec4(v.x != 0, v.y != 0, v.z != 0, v.w != 0);
/// <summary>
/// Explicitly converts this to a bquat.
/// </summary>
public static explicit operator bquat(lquat v) => new bquat(v.x != 0, v.y != 0, v.z != 0, v.w != 0);
#endregion
#region Indexer
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public long this[int index]
{
get
{
switch (index)
{
case 0: return x;
case 1: return y;
case 2: return z;
case 3: return w;
default: throw new ArgumentOutOfRangeException("index");
}
}
set
{
switch (index)
{
case 0: x = value; break;
case 1: y = value; break;
case 2: z = value; break;
case 3: w = value; break;
default: throw new ArgumentOutOfRangeException("index");
}
}
}
#endregion
#region Properties
/// <summary>
/// Returns an array with all values
/// </summary>
public long[] Values => new[] { x, y, z, w };
/// <summary>
/// Returns the number of components (4).
/// </summary>
public int Count => 4;
/// <summary>
/// Returns the euclidean length of this quaternion.
/// </summary>
public double Length => (double)Math.Sqrt(((x*x + y*y) + (z*z + w*w)));
/// <summary>
/// Returns the squared euclidean length of this quaternion.
/// </summary>
public long LengthSqr => ((x*x + y*y) + (z*z + w*w));
/// <summary>
/// Returns the conjugated quaternion
/// </summary>
public lquat Conjugate => new lquat(-x, -y, -z, w);
/// <summary>
/// Returns the inverse quaternion
/// </summary>
public lquat Inverse => Conjugate / LengthSqr;
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero quaternion
/// </summary>
public static lquat Zero { get; } = new lquat(0, 0, 0, 0);
/// <summary>
/// Predefined all-ones quaternion
/// </summary>
public static lquat Ones { get; } = new lquat(1, 1, 1, 1);
/// <summary>
/// Predefined identity quaternion
/// </summary>
public static lquat Identity { get; } = new lquat(0, 0, 0, 1);
/// <summary>
/// Predefined unit-X quaternion
/// </summary>
public static lquat UnitX { get; } = new lquat(1, 0, 0, 0);
/// <summary>
/// Predefined unit-Y quaternion
/// </summary>
public static lquat UnitY { get; } = new lquat(0, 1, 0, 0);
/// <summary>
/// Predefined unit-Z quaternion
/// </summary>
public static lquat UnitZ { get; } = new lquat(0, 0, 1, 0);
/// <summary>
/// Predefined unit-W quaternion
/// </summary>
public static lquat UnitW { get; } = new lquat(0, 0, 0, 1);
/// <summary>
/// Predefined all-MaxValue quaternion
/// </summary>
public static lquat MaxValue { get; } = new lquat(long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue);
/// <summary>
/// Predefined all-MinValue quaternion
/// </summary>
public static lquat MinValue { get; } = new lquat(long.MinValue, long.MinValue, long.MinValue, long.MinValue);
#endregion
#region Operators
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator==(lquat lhs, lquat rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator!=(lquat lhs, lquat rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns proper multiplication of two quaternions.
/// </summary>
public static lquat operator*(lquat p, lquat q) => new lquat(p.w * q.x + p.x * q.w + p.y * q.z - p.z * q.y, p.w * q.y + p.y * q.w + p.z * q.x - p.x * q.z, p.w * q.z + p.z * q.w + p.x * q.y - p.y * q.x, p.w * q.w - p.x * q.x - p.y * q.y - p.z * q.z);
/// <summary>
/// Returns a vector rotated by the quaternion.
/// </summary>
public static lvec3 operator*(lquat q, lvec3 v)
{
var qv = new lvec3(q.x, q.y, q.z);
var uv = lvec3.Cross(qv, v);
var uuv = lvec3.Cross(qv, uv);
return v + ((uv * q.w) + uuv) * 2;
}
/// <summary>
/// Returns a vector rotated by the quaternion (preserves v.w).
/// </summary>
public static lvec4 operator*(lquat q, lvec4 v) => new lvec4(q * new lvec3(v), v.w);
/// <summary>
/// Returns a vector rotated by the inverted quaternion.
/// </summary>
public static lvec3 operator*(lvec3 v, lquat q) => q.Inverse * v;
/// <summary>
/// Returns a vector rotated by the inverted quaternion (preserves v.w).
/// </summary>
public static lvec4 operator*(lvec4 v, lquat q) => q.Inverse * v;
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
public IEnumerator<long> GetEnumerator()
{
yield return x;
yield return y;
yield return z;
yield return w;
}
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Returns a string representation of this quaternion using ', ' as a seperator.
/// </summary>
public override string ToString() => ToString(", ");
/// <summary>
/// Returns a string representation of this quaternion using a provided seperator.
/// </summary>
public string ToString(string sep) => ((x + sep + y) + sep + (z + sep + w));
/// <summary>
/// Returns a string representation of this quaternion using a provided seperator and a format provider for each component.
/// </summary>
public string ToString(string sep, IFormatProvider provider) => ((x.ToString(provider) + sep + y.ToString(provider)) + sep + (z.ToString(provider) + sep + w.ToString(provider)));
/// <summary>
/// Returns a string representation of this quaternion using a provided seperator and a format for each component.
/// </summary>
public string ToString(string sep, string format) => ((x.ToString(format) + sep + y.ToString(format)) + sep + (z.ToString(format) + sep + w.ToString(format)));
/// <summary>
/// Returns a string representation of this quaternion using a provided seperator and a format and format provider for each component.
/// </summary>
public string ToString(string sep, string format, IFormatProvider provider) => ((x.ToString(format, provider) + sep + y.ToString(format, provider)) + sep + (z.ToString(format, provider) + sep + w.ToString(format, provider)));
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(lquat rhs) => ((x.Equals(rhs.x) && y.Equals(rhs.y)) && (z.Equals(rhs.z) && w.Equals(rhs.w)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is lquat && Equals((lquat) obj);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((x.GetHashCode()) * 397) ^ y.GetHashCode()) * 397) ^ z.GetHashCode()) * 397) ^ w.GetHashCode();
}
}
#endregion
#region Static Functions
/// <summary>
/// Converts the string representation of the quaternion into a quaternion representation (using ', ' as a separator).
/// </summary>
public static lquat Parse(string s) => Parse(s, ", ");
/// <summary>
/// Converts the string representation of the quaternion into a quaternion representation (using a designated separator).
/// </summary>
public static lquat Parse(string s, string sep)
{
var kvp = s.Split(new[] { sep }, StringSplitOptions.None);
if (kvp.Length != 4) throw new FormatException("input has not exactly 4 parts");
return new lquat(long.Parse(kvp[0].Trim()), long.Parse(kvp[1].Trim()), long.Parse(kvp[2].Trim()), long.Parse(kvp[3].Trim()));
}
/// <summary>
/// Converts the string representation of the quaternion into a quaternion representation (using a designated separator and a type provider).
/// </summary>
public static lquat Parse(string s, string sep, IFormatProvider provider)
{
var kvp = s.Split(new[] { sep }, StringSplitOptions.None);
if (kvp.Length != 4) throw new FormatException("input has not exactly 4 parts");
return new lquat(long.Parse(kvp[0].Trim(), provider), long.Parse(kvp[1].Trim(), provider), long.Parse(kvp[2].Trim(), provider), long.Parse(kvp[3].Trim(), provider));
}
/// <summary>
/// Converts the string representation of the quaternion into a quaternion representation (using a designated separator and a number style).
/// </summary>
public static lquat Parse(string s, string sep, NumberStyles style)
{
var kvp = s.Split(new[] { sep }, StringSplitOptions.None);
if (kvp.Length != 4) throw new FormatException("input has not exactly 4 parts");
return new lquat(long.Parse(kvp[0].Trim(), style), long.Parse(kvp[1].Trim(), style), long.Parse(kvp[2].Trim(), style), long.Parse(kvp[3].Trim(), style));
}
/// <summary>
/// Converts the string representation of the quaternion into a quaternion representation (using a designated separator and a number style and a format provider).
/// </summary>
public static lquat Parse(string s, string sep, NumberStyles style, IFormatProvider provider)
{
var kvp = s.Split(new[] { sep }, StringSplitOptions.None);
if (kvp.Length != 4) throw new FormatException("input has not exactly 4 parts");
return new lquat(long.Parse(kvp[0].Trim(), style, provider), long.Parse(kvp[1].Trim(), style, provider), long.Parse(kvp[2].Trim(), style, provider), long.Parse(kvp[3].Trim(), style, provider));
}
/// <summary>
/// Tries to convert the string representation of the quaternion into a quaternion representation (using ', ' as a separator), returns false if string was invalid.
/// </summary>
public static bool TryParse(string s, out lquat result) => TryParse(s, ", ", out result);
/// <summary>
/// Tries to convert the string representation of the quaternion into a quaternion representation (using a designated separator), returns false if string was invalid.
/// </summary>
public static bool TryParse(string s, string sep, out lquat result)
{
result = Zero;
if (string.IsNullOrEmpty(s)) return false;
var kvp = s.Split(new[] { sep }, StringSplitOptions.None);
if (kvp.Length != 4) return false;
long x = 0, y = 0, z = 0, w = 0;
var ok = ((long.TryParse(kvp[0].Trim(), out x) && long.TryParse(kvp[1].Trim(), out y)) && (long.TryParse(kvp[2].Trim(), out z) && long.TryParse(kvp[3].Trim(), out w)));
result = ok ? new lquat(x, y, z, w) : Zero;
return ok;
}
/// <summary>
/// Tries to convert the string representation of the quaternion into a quaternion representation (using a designated separator and a number style and a format provider), returns false if string was invalid.
/// </summary>
public static bool TryParse(string s, string sep, NumberStyles style, IFormatProvider provider, out lquat result)
{
result = Zero;
if (string.IsNullOrEmpty(s)) return false;
var kvp = s.Split(new[] { sep }, StringSplitOptions.None);
if (kvp.Length != 4) return false;
long x = 0, y = 0, z = 0, w = 0;
var ok = ((long.TryParse(kvp[0].Trim(), style, provider, out x) && long.TryParse(kvp[1].Trim(), style, provider, out y)) && (long.TryParse(kvp[2].Trim(), style, provider, out z) && long.TryParse(kvp[3].Trim(), style, provider, out w)));
result = ok ? new lquat(x, y, z, w) : Zero;
return ok;
}
/// <summary>
/// Returns the inner product (dot product, scalar product) of the two quaternions.
/// </summary>
public static long Dot(lquat lhs, lquat rhs) => ((lhs.x * rhs.x + lhs.y * rhs.y) + (lhs.z * rhs.z + lhs.w * rhs.w));
/// <summary>
/// Returns the cross product between two quaternions.
/// </summary>
public static lquat Cross(lquat q1, lquat q2) => new lquat(q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y, q1.w * q2.y + q1.y * q2.w + q1.z * q2.x - q1.x * q2.z, q1.w * q2.z + q1.z * q2.w + q1.x * q2.y - q1.y * q2.x, q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z);
#endregion
#region Component-Wise Static Functions
/// <summary>
/// Returns a bvec4 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bvec4 Equal(lquat lhs, lquat rhs) => new bvec4(lhs.x == rhs.x, lhs.y == rhs.y, lhs.z == rhs.z, lhs.w == rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bvec4 Equal(lquat lhs, long rhs) => new bvec4(lhs.x == rhs, lhs.y == rhs, lhs.z == rhs, lhs.w == rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bvec4 Equal(long lhs, lquat rhs) => new bvec4(lhs == rhs.x, lhs == rhs.y, lhs == rhs.z, lhs == rhs.w);
/// <summary>
/// Returns a bvec from the application of Equal (lhs == rhs).
/// </summary>
public static bvec4 Equal(long lhs, long rhs) => new bvec4(lhs == rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bvec4 NotEqual(lquat lhs, lquat rhs) => new bvec4(lhs.x != rhs.x, lhs.y != rhs.y, lhs.z != rhs.z, lhs.w != rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bvec4 NotEqual(lquat lhs, long rhs) => new bvec4(lhs.x != rhs, lhs.y != rhs, lhs.z != rhs, lhs.w != rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bvec4 NotEqual(long lhs, lquat rhs) => new bvec4(lhs != rhs.x, lhs != rhs.y, lhs != rhs.z, lhs != rhs.w);
/// <summary>
/// Returns a bvec from the application of NotEqual (lhs != rhs).
/// </summary>
public static bvec4 NotEqual(long lhs, long rhs) => new bvec4(lhs != rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec4 GreaterThan(lquat lhs, lquat rhs) => new bvec4(lhs.x > rhs.x, lhs.y > rhs.y, lhs.z > rhs.z, lhs.w > rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec4 GreaterThan(lquat lhs, long rhs) => new bvec4(lhs.x > rhs, lhs.y > rhs, lhs.z > rhs, lhs.w > rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec4 GreaterThan(long lhs, lquat rhs) => new bvec4(lhs > rhs.x, lhs > rhs.y, lhs > rhs.z, lhs > rhs.w);
/// <summary>
/// Returns a bvec from the application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec4 GreaterThan(long lhs, long rhs) => new bvec4(lhs > rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec4 GreaterThanEqual(lquat lhs, lquat rhs) => new bvec4(lhs.x >= rhs.x, lhs.y >= rhs.y, lhs.z >= rhs.z, lhs.w >= rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec4 GreaterThanEqual(lquat lhs, long rhs) => new bvec4(lhs.x >= rhs, lhs.y >= rhs, lhs.z >= rhs, lhs.w >= rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec4 GreaterThanEqual(long lhs, lquat rhs) => new bvec4(lhs >= rhs.x, lhs >= rhs.y, lhs >= rhs.z, lhs >= rhs.w);
/// <summary>
/// Returns a bvec from the application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec4 GreaterThanEqual(long lhs, long rhs) => new bvec4(lhs >= rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bvec4 LesserThan(lquat lhs, lquat rhs) => new bvec4(lhs.x < rhs.x, lhs.y < rhs.y, lhs.z < rhs.z, lhs.w < rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bvec4 LesserThan(lquat lhs, long rhs) => new bvec4(lhs.x < rhs, lhs.y < rhs, lhs.z < rhs, lhs.w < rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bvec4 LesserThan(long lhs, lquat rhs) => new bvec4(lhs < rhs.x, lhs < rhs.y, lhs < rhs.z, lhs < rhs.w);
/// <summary>
/// Returns a bvec from the application of LesserThan (lhs < rhs).
/// </summary>
public static bvec4 LesserThan(long lhs, long rhs) => new bvec4(lhs < rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec4 LesserThanEqual(lquat lhs, lquat rhs) => new bvec4(lhs.x <= rhs.x, lhs.y <= rhs.y, lhs.z <= rhs.z, lhs.w <= rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec4 LesserThanEqual(lquat lhs, long rhs) => new bvec4(lhs.x <= rhs, lhs.y <= rhs, lhs.z <= rhs, lhs.w <= rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec4 LesserThanEqual(long lhs, lquat rhs) => new bvec4(lhs <= rhs.x, lhs <= rhs.y, lhs <= rhs.z, lhs <= rhs.w);
/// <summary>
/// Returns a bvec from the application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec4 LesserThanEqual(long lhs, long rhs) => new bvec4(lhs <= rhs);
/// <summary>
/// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static lquat Lerp(lquat min, lquat max, lquat a) => new lquat(min.x * (1-a.x) + max.x * a.x, min.y * (1-a.y) + max.y * a.y, min.z * (1-a.z) + max.z * a.z, min.w * (1-a.w) + max.w * a.w);
/// <summary>
/// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static lquat Lerp(lquat min, lquat max, long a) => new lquat(min.x * (1-a) + max.x * a, min.y * (1-a) + max.y * a, min.z * (1-a) + max.z * a, min.w * (1-a) + max.w * a);
/// <summary>
/// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static lquat Lerp(lquat min, long max, lquat a) => new lquat(min.x * (1-a.x) + max * a.x, min.y * (1-a.y) + max * a.y, min.z * (1-a.z) + max * a.z, min.w * (1-a.w) + max * a.w);
/// <summary>
/// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static lquat Lerp(lquat min, long max, long a) => new lquat(min.x * (1-a) + max * a, min.y * (1-a) + max * a, min.z * (1-a) + max * a, min.w * (1-a) + max * a);
/// <summary>
/// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static lquat Lerp(long min, lquat max, lquat a) => new lquat(min * (1-a.x) + max.x * a.x, min * (1-a.y) + max.y * a.y, min * (1-a.z) + max.z * a.z, min * (1-a.w) + max.w * a.w);
/// <summary>
/// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static lquat Lerp(long min, lquat max, long a) => new lquat(min * (1-a) + max.x * a, min * (1-a) + max.y * a, min * (1-a) + max.z * a, min * (1-a) + max.w * a);
/// <summary>
/// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static lquat Lerp(long min, long max, lquat a) => new lquat(min * (1-a.x) + max * a.x, min * (1-a.y) + max * a.y, min * (1-a.z) + max * a.z, min * (1-a.w) + max * a.w);
/// <summary>
/// Returns a lquat from the application of Lerp (min * (1-a) + max * a).
/// </summary>
public static lquat Lerp(long min, long max, long a) => new lquat(min * (1-a) + max * a);
#endregion
#region Component-Wise Operator Overloads
/// <summary>
/// Returns a bvec4 from component-wise application of operator< (lhs < rhs).
/// </summary>
public static bvec4 operator<(lquat lhs, lquat rhs) => new bvec4(lhs.x < rhs.x, lhs.y < rhs.y, lhs.z < rhs.z, lhs.w < rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of operator< (lhs < rhs).
/// </summary>
public static bvec4 operator<(lquat lhs, long rhs) => new bvec4(lhs.x < rhs, lhs.y < rhs, lhs.z < rhs, lhs.w < rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of operator< (lhs < rhs).
/// </summary>
public static bvec4 operator<(long lhs, lquat rhs) => new bvec4(lhs < rhs.x, lhs < rhs.y, lhs < rhs.z, lhs < rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of operator<= (lhs <= rhs).
/// </summary>
public static bvec4 operator<=(lquat lhs, lquat rhs) => new bvec4(lhs.x <= rhs.x, lhs.y <= rhs.y, lhs.z <= rhs.z, lhs.w <= rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of operator<= (lhs <= rhs).
/// </summary>
public static bvec4 operator<=(lquat lhs, long rhs) => new bvec4(lhs.x <= rhs, lhs.y <= rhs, lhs.z <= rhs, lhs.w <= rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of operator<= (lhs <= rhs).
/// </summary>
public static bvec4 operator<=(long lhs, lquat rhs) => new bvec4(lhs <= rhs.x, lhs <= rhs.y, lhs <= rhs.z, lhs <= rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of operator> (lhs > rhs).
/// </summary>
public static bvec4 operator>(lquat lhs, lquat rhs) => new bvec4(lhs.x > rhs.x, lhs.y > rhs.y, lhs.z > rhs.z, lhs.w > rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of operator> (lhs > rhs).
/// </summary>
public static bvec4 operator>(lquat lhs, long rhs) => new bvec4(lhs.x > rhs, lhs.y > rhs, lhs.z > rhs, lhs.w > rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of operator> (lhs > rhs).
/// </summary>
public static bvec4 operator>(long lhs, lquat rhs) => new bvec4(lhs > rhs.x, lhs > rhs.y, lhs > rhs.z, lhs > rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of operator>= (lhs >= rhs).
/// </summary>
public static bvec4 operator>=(lquat lhs, lquat rhs) => new bvec4(lhs.x >= rhs.x, lhs.y >= rhs.y, lhs.z >= rhs.z, lhs.w >= rhs.w);
/// <summary>
/// Returns a bvec4 from component-wise application of operator>= (lhs >= rhs).
/// </summary>
public static bvec4 operator>=(lquat lhs, long rhs) => new bvec4(lhs.x >= rhs, lhs.y >= rhs, lhs.z >= rhs, lhs.w >= rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of operator>= (lhs >= rhs).
/// </summary>
public static bvec4 operator>=(long lhs, lquat rhs) => new bvec4(lhs >= rhs.x, lhs >= rhs.y, lhs >= rhs.z, lhs >= rhs.w);
/// <summary>
/// Returns a lquat from component-wise application of operator+ (identity).
/// </summary>
public static lquat operator+(lquat v) => v;
/// <summary>
/// Returns a lquat from component-wise application of operator- (-v).
/// </summary>
public static lquat operator-(lquat v) => new lquat(-v.x, -v.y, -v.z, -v.w);
/// <summary>
/// Returns a lquat from component-wise application of operator+ (lhs + rhs).
/// </summary>
public static lquat operator+(lquat lhs, lquat rhs) => new lquat(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w);
/// <summary>
/// Returns a lquat from component-wise application of operator+ (lhs + rhs).
/// </summary>
public static lquat operator+(lquat lhs, long rhs) => new lquat(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs, lhs.w + rhs);
/// <summary>
/// Returns a lquat from component-wise application of operator+ (lhs + rhs).
/// </summary>
public static lquat operator+(long lhs, lquat rhs) => new lquat(lhs + rhs.x, lhs + rhs.y, lhs + rhs.z, lhs + rhs.w);
/// <summary>
/// Returns a lquat from component-wise application of operator- (lhs - rhs).
/// </summary>
public static lquat operator-(lquat lhs, lquat rhs) => new lquat(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w);
/// <summary>
/// Returns a lquat from component-wise application of operator- (lhs - rhs).
/// </summary>
public static lquat operator-(lquat lhs, long rhs) => new lquat(lhs.x - rhs, lhs.y - rhs, lhs.z - rhs, lhs.w - rhs);
/// <summary>
/// Returns a lquat from component-wise application of operator- (lhs - rhs).
/// </summary>
public static lquat operator-(long lhs, lquat rhs) => new lquat(lhs - rhs.x, lhs - rhs.y, lhs - rhs.z, lhs - rhs.w);
/// <summary>
/// Returns a lquat from component-wise application of operator* (lhs * rhs).
/// </summary>
public static lquat operator*(lquat lhs, long rhs) => new lquat(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs);
/// <summary>
/// Returns a lquat from component-wise application of operator* (lhs * rhs).
/// </summary>
public static lquat operator*(long lhs, lquat rhs) => new lquat(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z, lhs * rhs.w);
/// <summary>
/// Returns a lquat from component-wise application of operator/ (lhs / rhs).
/// </summary>
public static lquat operator/(lquat lhs, long rhs) => new lquat(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs);
#endregion
}
}
| |
using System;
using RestSharp;
using TwitchCSharp.Enums;
using TwitchCSharp.Helpers;
using TwitchCSharp.Models;
namespace TwitchCSharp.Clients
{
public class TwitchAuthenticatedClient : TwitchReadOnlyClient, ITwitchClient
{
private readonly string username;
public TwitchAuthenticatedClient(string clientId, string oauth) : base(clientId)
{
// Include Authorization header with every request
restClient.AddDefaultHeader("Authorization", String.Format("OAuth {0}", oauth));
// automatically fetch user name
var user = this.GetMyUser();
if (user == null || String.IsNullOrWhiteSpace(user.Name))
{
throw new TwitchException("Couldn't get the user name!");
}
this.username = user.Name;
}
public Channel GetMyChannel()
{
var request = GetRequest("channel", Method.GET);
var response = restClient.Execute<Channel>(request);
return response.Data;
}
// more details than GetUser(myname)
public User GetMyUser()
{
var request = GetRequest("user", Method.GET);
var response = restClient.Execute<User>(request);
return response.Data;
}
public TwitchList<Stream> GetFollowedStreams(PagingInfo pagingInfo = null)
{
var request = GetRequest("streams/followed", Method.GET);
TwitchHelper.AddPaging(request, pagingInfo);
var response = restClient.Execute<TwitchList<Stream>>(request);
return response.Data;
}
public TwitchList<Video> GetFollowedVideos(PagingInfo pagingInfo = null)
{
var request = GetRequest("videos/followed", Method.GET);
TwitchHelper.AddPaging(request, pagingInfo);
var response = restClient.Execute<TwitchList<Video>>(request);
return response.Data;
}
public StreamResult GetMyStream()
{
return GetStream(username);
}
public TwitchList<Block> GetBlocks()
{
var request = GetRequest("users/{user}/blocks", Method.GET);
request.AddUrlSegment("user", username);
var response = restClient.Execute<TwitchList<Block>>(request);
return response.Data;
}
public TwitchResponse Block(string target)
{
var request = GetRequest("users/{user}/blocks/{target}", Method.PUT);
request.AddUrlSegment("user", username);
request.AddUrlSegment("target", target);
var response = restClient.Execute<TwitchResponse>(request);
return response.Data;
}
public TwitchResponse Unblock(string target)
{
var request = GetRequest("users/{user}/blocks/{target}", Method.DELETE);
request.AddUrlSegment("user", username);
request.AddUrlSegment("target", target);
var response = restClient.Execute<TwitchResponse>(request);
return response.Data;
}
public TwitchList<User> GetChannelEditors()
{
var request = GetRequest("channels/{channel}/editors", Method.GET);
request.AddUrlSegment("channel", username);
var response = restClient.Execute<TwitchList<User>>(request);
return response.Data;
}
public Channel Update(string status = null, string game = null, string delay = null)
{
var request = GetRequest("channels/{channel}", Method.PUT);
request.AddUrlSegment("channel", username);
request.RequestFormat = DataFormat.Json;
request.AddBody(new { channel = new { status, game, delay } });
var response = restClient.Execute<Channel>(request);
return response.Data;
}
public Channel SetTitle(string title)
{
return Update(title);
}
public Channel SetGame(string game)
{
return Update(null, game);
}
// only for partnered channels
public Channel SetDelay(string delay)
{
return Update(null, null, delay);
}
public User ResetStreamKey()
{
var request = GetRequest("channels/{channel}/stream_key", Method.DELETE);
request.AddUrlSegment("channel", username);
var response = restClient.Execute<User>(request);
return response.Data;
}
// Length of commercial break in seconds. Default value is 30. Valid values are 30, 60, 90, 120, 150, and 180. You can only trigger a commercial once every 8 minutes.
public TwitchResponse TriggerCommercial(int length)
{
var request = GetRequest("channels/{channel}/commercial", Method.POST);
request.AddUrlSegment("channel", username);
request.AddParameter("length", length);
var response = restClient.Execute<TwitchResponse>(request);
return response.Data;
}
public FollowedChannel Follow(string target, bool notifications = false)
{
var request = GetRequest("users/{user}/follows/channels/{target}", Method.PUT);
request.AddUrlSegment("user", username);
request.AddUrlSegment("target", target);
request.AddParameter("notifications", notifications);
var response = restClient.Execute<FollowedChannel>(request);
return response.Data;
}
public TwitchResponse Unfollow(string target)
{
var request = GetRequest("users/{user}/follows/channels/{target}", Method.DELETE);
request.AddUrlSegment("user", username);
request.AddUrlSegment("target", target);
var response = restClient.Execute<TwitchResponse>(request);
return response.Data;
}
public TwitchList<Subscription> GetSubscribers(PagingInfo pagingInfo = null, SortDirection sortDirection = SortDirection.asc)
{
var request = GetRequest("channels/{channel}/subscriptions", Method.GET);
request.AddUrlSegment("channel", username);
TwitchHelper.AddPaging(request, pagingInfo);
request.AddParameter("direction", sortDirection);
var response = restClient.Execute<TwitchList<Subscription>>(request);
return response.Data;
}
// someone who subscribed your channel
public Subscription GetSubscriber(string user)
{
var request = GetRequest("channels/{channel}/subscriptions/{user}", Method.GET);
request.AddUrlSegment("channel", username);
request.AddUrlSegment("user", user);
var response = restClient.Execute<Subscription>(request);
return response.Data;
}
//may return true if request failed
public bool IsSubscriber(string user)
{
int state = GetSubscriber(user).Status;
return state != 404 && state != 422;
}
// a channel you subscribed
public Subscription GetSubscribedChannel(string channel)
{
var request = GetRequest("users/{user}/subscriptions/{channel}", Method.GET);
request.AddUrlSegment("user", username);
request.AddUrlSegment("channel", channel);
var response = restClient.Execute<Subscription>(request);
return response.Data;
}
public bool IsSubscribedToChannel(string channel)
{
return GetSubscribedChannel(channel).Status != 404;
}
// has the channel a subscription programm?
public bool CanSubscribeToChannel(string channel)
{
return GetSubscribedChannel(channel).Status != 422;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
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.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Printing;
using System.IO;
using System.Xml;
using fyiReporting.RDL;
using fyiReporting.RdlViewer;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// RdlReader is a application for displaying reports based on RDL.
/// </summary>
internal class MDIChild : Form
{
public delegate void RdlChangeHandler(object sender, EventArgs e);
public event RdlChangeHandler OnSelectionChanged;
public event RdlChangeHandler OnSelectionMoved;
public event RdlChangeHandler OnReportItemInserted;
public event RdlChangeHandler OnDesignTabChanged;
public event DesignCtl.OpenSubreportEventHandler OnOpenSubreport;
public event DesignCtl.HeightEventHandler OnHeightChanged;
private fyiReporting.RdlDesign.RdlEditPreview rdlDesigner;
string _SourceFile;
TabPage _Tab; // TabPage for this MDI Child
public MDIChild(int width, int height)
{
this.rdlDesigner = new fyiReporting.RdlDesign.RdlEditPreview();
this.SuspendLayout();
//
// rdlDesigner
//
this.rdlDesigner.Dock = System.Windows.Forms.DockStyle.Fill;
this.rdlDesigner.Location = new System.Drawing.Point(0, 0);
this.rdlDesigner.Name = "rdlDesigner";
this.rdlDesigner.Size = new System.Drawing.Size(width, height);
this.rdlDesigner.TabIndex = 0;
// register event for RDL changed.
rdlDesigner.OnRdlChanged += new RdlEditPreview.RdlChangeHandler(rdlDesigner_RdlChanged);
rdlDesigner.OnHeightChanged += new DesignCtl.HeightEventHandler(rdlDesigner_HeightChanged);
rdlDesigner.OnSelectionChanged += new RdlEditPreview.RdlChangeHandler(rdlDesigner_SelectionChanged);
rdlDesigner.OnSelectionMoved += new RdlEditPreview.RdlChangeHandler(rdlDesigner_SelectionMoved);
rdlDesigner.OnReportItemInserted += new RdlEditPreview.RdlChangeHandler(rdlDesigner_ReportItemInserted);
rdlDesigner.OnDesignTabChanged += new RdlEditPreview.RdlChangeHandler(rdlDesigner_DesignTabChanged);
rdlDesigner.OnOpenSubreport += new DesignCtl.OpenSubreportEventHandler(rdlDesigner_OpenSubreport);
//
// MDIChild
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(width, height);
this.Controls.Add(this.rdlDesigner);
this.Name = "";
this.Text = "";
this.Closing += new System.ComponentModel.CancelEventHandler(this.MDIChild_Closing);
this.ResumeLayout(false);
}
internal TabPage Tab
{
get { return _Tab; }
set { _Tab = value; }
}
public RdlEditPreview Editor
{
get
{
return rdlDesigner.CanEdit? rdlDesigner: null; // only return when it can edit
}
}
public RdlEditPreview RdlEditor
{
get
{
return rdlDesigner; // always return
}
}
public void ShowEditLines(bool bShow)
{
rdlDesigner.ShowEditLines(bShow);
}
internal void ShowPreviewWaitDialog(bool bShow)
{
rdlDesigner.ShowPreviewWaitDialog(bShow);
}
internal bool ShowReportItemOutline
{
get { return rdlDesigner.ShowReportItemOutline; }
set { rdlDesigner.ShowReportItemOutline = value; }
}
public string CurrentInsert
{
get {return rdlDesigner.CurrentInsert; }
set
{
rdlDesigner.CurrentInsert = value;
}
}
public int CurrentLine
{
get {return rdlDesigner.CurrentLine; }
}
public int CurrentCh
{
get {return rdlDesigner.CurrentCh; }
}
internal string DesignTab
{
get {return rdlDesigner.DesignTab;}
set { rdlDesigner.DesignTab = value; }
}
internal DesignXmlDraw DrawCtl
{
get {return rdlDesigner.DrawCtl;}
}
public XmlDocument ReportDocument
{
get {return rdlDesigner.ReportDocument;}
}
internal void SetFocus()
{
rdlDesigner.SetFocus();
}
public StyleInfo SelectedStyle
{
get {return rdlDesigner.SelectedStyle;}
}
public string SelectionName
{
get {return rdlDesigner.SelectionName;}
}
public PointF SelectionPosition
{
get {return rdlDesigner.SelectionPosition;}
}
public SizeF SelectionSize
{
get {return rdlDesigner.SelectionSize;}
}
public void ApplyStyleToSelected(string name, string v)
{
rdlDesigner.ApplyStyleToSelected(name, v);
}
public bool FileSave()
{
string file = SourceFile;
if (file == "" || file == null) // if no file name then do SaveAs
{
return FileSaveAs();
}
string rdl = GetRdlText();
return FileSave(file, rdl);
}
private bool FileSave(string file, string rdl)
{
StreamWriter writer=null;
bool bOK=true;
try
{
writer = new StreamWriter(file);
writer.Write(rdl);
// editRDL.ClearUndo();
// editRDL.Modified = false;
// SetTitle();
// statusBar.Text = "Saved " + curFileName;
}
catch (Exception ae)
{
bOK=false;
MessageBox.Show(ae.Message + "\r\n" + ae.StackTrace);
// statusBar.Text = "Save of file '" + curFileName + "' failed";
}
finally
{
writer.Close();
}
if (bOK)
this.Modified=false;
return bOK;
}
public bool Export(string type)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Export to " + type.ToUpper();
switch (type.ToLower())
{
case "csv":
sfd.Filter = "CSV file (*.csv)|*.csv|All files (*.*)|*.*";
break;
case "xml":
sfd.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
break;
case "pdf":
sfd.Filter = "PDF file (*.pdf)|*.pdf|All files (*.*)|*.*";
break;
case "tif": case "tiff":
sfd.Filter = "TIF file (*.tif, *.tiff)|*.tiff;*.tif|All files (*.*)|*.*";
break;
case "rtf":
sfd.Filter = "RTF file (*.rtf)|*.rtf|All files (*.*)|*.*";
break;
case "xlsx": case "excel":
type = "xlsx";
sfd.Filter = "Excel file (*.xlsx)|*.xlsx|All files (*.*)|*.*";
break;
case "html":
case "htm":
sfd.Filter = "Web Page (*.html, *.htm)|*.html;*.htm|All files (*.*)|*.*";
break;
case "mhtml":
case "mht":
sfd.Filter = "MHT (*.mht)|*.mhtml;*.mht|All files (*.*)|*.*";
break;
default:
throw new Exception("Only HTML, MHT, XML, CSV, RTF, Excel, TIF and PDF are allowed as Export types.");
}
sfd.FilterIndex = 1;
if (SourceFile != null)
sfd.FileName = Path.GetFileNameWithoutExtension(SourceFile) + "." + type;
else
sfd.FileName = "*." + type;
try
{
if (sfd.ShowDialog(this) != DialogResult.OK)
return false;
// save the report in the requested rendered format
bool rc = true;
// tif can be either in color or black and white; ask user what they want
if (type == "tif" || type == "tiff")
{
DialogResult dr = MessageBox.Show(this, "Do you want to display colors in TIF?", "Export", MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.No)
type = "tifbw";
else if (dr == DialogResult.Cancel)
return false;
}
try { SaveAs(sfd.FileName, type); }
catch (Exception ex)
{
MessageBox.Show(this,
ex.Message, "Export Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
rc = false;
}
return rc;
}
finally
{
sfd.Dispose();
}
}
public bool FileSaveAs()
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "RDL files (*.rdl)|*.rdl|All files (*.*)|*.*";
sfd.FilterIndex = 1;
string file = SourceFile;
sfd.FileName = file == null? "*.rdl": file;
try
{
if (sfd.ShowDialog(this) != DialogResult.OK)
return false;
// User wants to save!
string rdl = GetRdlText();
if (FileSave(sfd.FileName, rdl))
{ // Save was successful
Text = sfd.FileName;
Tab.Text = Path.GetFileName(sfd.FileName);
_SourceFile = sfd.FileName;
Tab.ToolTipText = sfd.FileName;
return true;
}
}
finally
{
sfd.Dispose();
}
return false;
}
public string GetRdlText()
{
return this.rdlDesigner.GetRdlText();
}
public bool Modified
{
get {return rdlDesigner.Modified;}
set
{
rdlDesigner.Modified = value;
SetTitle();
}
}
/// <summary>
/// The RDL file that should be displayed.
/// </summary>
public string SourceFile
{
get {return _SourceFile;}
set
{
_SourceFile = value;
string rdl = GetRdlSource();
this.rdlDesigner.SetRdlText(rdl == null? "": rdl);
}
}
public string SourceRdl
{
get {return this.rdlDesigner.GetRdlText();}
set {this.rdlDesigner.SetRdlText(value);}
}
private string GetRdlSource()
{
StreamReader fs=null;
string prog=null;
try
{
fs = new StreamReader(_SourceFile);
prog = fs.ReadToEnd();
}
finally
{
if (fs != null)
fs.Close();
}
return prog;
}
/// <summary>
/// Number of pages in the report.
/// </summary>
public int PageCount
{
get {return this.rdlDesigner.PageCount;}
}
/// <summary>
/// Current page in view on report
/// </summary>
public int PageCurrent
{
get {return this.rdlDesigner.PageCurrent;}
}
/// <summary>
/// Page height of the report.
/// </summary>
public float PageHeight
{
get {return this.rdlDesigner.PageHeight;}
}
/// <summary>
/// Turns the Selection Tool on in report preview
/// </summary>
public bool SelectionTool
{
get
{
return this.rdlDesigner.SelectionTool;
}
set
{
this.rdlDesigner.SelectionTool = value;
}
}
/// <summary>
/// Page width of the report.
/// </summary>
public float PageWidth
{
get {return this.rdlDesigner.PageWidth;}
}
/// <summary>
/// Zoom
/// </summary>
public float Zoom
{
get {return this.rdlDesigner.Zoom;}
set {this.rdlDesigner.Zoom = value;}
}
/// <summary>
/// ZoomMode
/// </summary>
public ZoomEnum ZoomMode
{
get {return this.rdlDesigner.ZoomMode;}
set {this.rdlDesigner.ZoomMode = value;}
}
/// <summary>
/// Print the report.
/// </summary>
public void Print(PrintDocument pd)
{
this.rdlDesigner.Print(pd);
}
public void SaveAs(string filename, string ext)
{
rdlDesigner.SaveAs(filename, ext);
}
private void MDIChild_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!OkToClose())
{
e.Cancel = true;
return;
}
if (Tab == null)
return;
Control ctl = Tab.Parent;
ctl.Controls.Remove(Tab);
Tab.Tag = null; // this is the Tab reference to this
Tab = null;
}
public bool OkToClose()
{
if (!this.Modified)
return true;
DialogResult r =
MessageBox.Show(this, String.Format("Do you want to save changes you made to '{0}'?",
_SourceFile==null?"Untitled":Path.GetFileName(_SourceFile)),
"fyiReporting Designer",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button3);
bool bOK = true;
if (r == DialogResult.Cancel)
bOK = false;
else if (r == DialogResult.Yes)
{
if (!FileSave())
bOK = false;
}
return bOK;
}
private void rdlDesigner_RdlChanged(object sender, System.EventArgs e)
{
SetTitle();
}
private void rdlDesigner_HeightChanged(object sender, HeightEventArgs e)
{
if (OnHeightChanged != null)
OnHeightChanged(this, e);
}
private void rdlDesigner_SelectionChanged(object sender, System.EventArgs e)
{
if (OnSelectionChanged != null)
OnSelectionChanged(this, e);
}
private void rdlDesigner_DesignTabChanged(object sender, System.EventArgs e)
{
if (OnDesignTabChanged != null)
OnDesignTabChanged(this, e);
}
private void rdlDesigner_ReportItemInserted(object sender, System.EventArgs e)
{
if (OnReportItemInserted != null)
OnReportItemInserted(this, e);
}
private void rdlDesigner_SelectionMoved(object sender, System.EventArgs e)
{
if (OnSelectionMoved != null)
OnSelectionMoved(this, e);
}
private void rdlDesigner_OpenSubreport(object sender, SubReportEventArgs e)
{
if (OnOpenSubreport != null)
{
OnOpenSubreport(this, e);
}
}
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MDIChild));
//
// MDIChild
//
this.AutoScaleMode = AutoScaleMode.None;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MDIChild";
}
private void SetTitle()
{
string title = this.Text;
if (title.Length < 1)
return;
char m = title[title.Length-1];
if (this.Modified)
{
if (m != '*')
title = title + "*";
}
else if (m == '*')
title = title.Substring(0, title.Length-1);
if (title != this.Text)
this.Text = title;
return;
}
public fyiReporting.RdlViewer.RdlViewer Viewer
{
get {return rdlDesigner.Viewer;}
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class AggregateTests
{
private const int ResultFuncModifier = 17;
public static IEnumerable<object[]> AggregateExceptionData(int[] counts)
{
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>()))
{
Labeled<ParallelQuery<int>> query = (Labeled<ParallelQuery<int>>)results[0];
if (query.ToString().StartsWith("Partitioner"))
{
yield return new object[] { Labeled.Label(query.ToString(), Partitioner.Create(UnorderedSources.GetRangeArray(0, (int)results[1]), false).AsParallel()), results[1] };
}
else if (query.ToString().StartsWith("Enumerable.Range"))
{
yield return new object[] { Labeled.Label(query.ToString(), new StrictPartitioner<int>(Partitioner.Create(Enumerable.Range(0, (int)results[1]), EnumerablePartitionerOptions.None), (int)results[1]).AsParallel()), results[1] };
}
else
{
yield return results;
}
}
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
if (count == 0)
{
Assert.Throws<InvalidOperationException>(() => query.Aggregate((x, y) => x + y));
}
else
{
// The operation will overflow for long-running sizes, but that's okay:
// The helper is overflowing too!
Assert.Equal(Functions.SumRange(0, count), query.Aggregate((x, y) => x + y));
}
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Sum(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Seed(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count), query.Aggregate(0, (x, y) => x + y));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Seed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Sum_Seed(labeled, count);
}
[Theory]
[MemberData("Ranges", 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Seed(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
ParallelQuery<int> query = labeled.Item;
// The operation will overflow for long-running sizes, but that's okay:
// The helper is overflowing too!
Assert.Equal(Functions.ProductRange(start, count), query.Aggregate(1L, (x, y) => x * y));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Seed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
Aggregate_Product_Seed(labeled, count, start);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Seed(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Enumerable.Range(0, count), query.Aggregate((IList<int>)new List<int>(), (l, x) => l.AddToCopy(x)).OrderBy(x => x));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Seed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Collection_Seed(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Result(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, query.Aggregate(0, (x, y) => x + y, result => result + ResultFuncModifier));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Result_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Sum_Result(labeled, count);
}
[Theory]
[MemberData("Ranges", 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Result(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.ProductRange(start, count) + ResultFuncModifier, query.Aggregate(1L, (x, y) => x * y, result => result + ResultFuncModifier));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Results_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
Aggregate_Product_Result(labeled, count, start);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Results(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Enumerable.Range(0, count), query.Aggregate((IList<int>)new List<int>(), (l, x) => l.AddToCopy(x), l => l.OrderBy(x => x)));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Results_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Collection_Results(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Accumulator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int actual = query.Aggregate(
0,
(accumulator, x) => accumulator + x,
(left, right) => left + right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Accumulator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Sum_Accumulator(labeled, count);
}
[Theory]
[MemberData("Ranges", 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Accumulator(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
ParallelQuery<int> query = labeled.Item;
long actual = query.Aggregate(
1L,
(accumulator, x) => accumulator * x,
(left, right) => left * right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.ProductRange(start, count) + ResultFuncModifier, actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Accumulator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
Aggregate_Product_Accumulator(labeled, count, start);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Accumulator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IList<int> actual = query.Aggregate(
(IList<int>)new List<int>(),
(accumulator, x) => accumulator.AddToCopy(x),
(left, right) => left.ConcatCopy(right),
result => result.OrderBy(x => x).ToList());
Assert.Equal(Enumerable.Range(0, count), actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Accumulator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Collection_Accumulator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_SeedFunction(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int actual = query.Aggregate(
() => 0,
(accumulator, x) => accumulator + x,
(left, right) => left + right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_SeedFunction_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Sum_SeedFunction(labeled, count);
}
[Theory]
[MemberData("Ranges", 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_SeedFunction(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
ParallelQuery<int> query = labeled.Item;
long actual = query.Aggregate(
() => 1L,
(accumulator, x) => accumulator * x,
(left, right) => left * right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.ProductRange(start, count) + ResultFuncModifier, actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_SeedFunction_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
Aggregate_Product_SeedFunction(labeled, count, start);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_SeedFunction(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IList<int> actual = query.Aggregate(
() => (IList<int>)new List<int>(),
(accumulator, x) => accumulator.AddToCopy(x),
(left, right) => left.ConcatCopy(right),
result => result.OrderBy(x => x).ToList());
Assert.Equal(Enumerable.Range(0, count), actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_SeedFunction_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Collection_SeedFunction(labeled, count);
}
[Fact]
public static void Aggregate_InvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Aggregate((i, j) => i));
// All other invocations return the seed value.
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j));
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j, i => i));
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j, (i, j) => i + j, i => i));
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(() => -1, (i, j) => i + j, (i, j) => i + j, i => i));
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate((i, j) => i));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate(0, (i, j) => i));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate(0, (i, j) => i, i => i));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate(0, (i, j) => i, (i, j) => i, i => i));
}
[Theory]
[MemberData("AggregateExceptionData", (object)(new int[] { 2 }))]
public static void Aggregate_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate((i, j) => { throw new DeliberateTestException(); }));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => { throw new DeliberateTestException(); }));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => { throw new DeliberateTestException(); }, i => i));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(0, (i, j) => i, i => { throw new DeliberateTestException(); }));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => { throw new DeliberateTestException(); }, (i, j) => i, i => i));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(0, (i, j) => i, (i, j) => i, i => { throw new DeliberateTestException(); }));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(() => { throw new DeliberateTestException(); }, (i, j) => i, (i, j) => i, i => i));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(() => 0, (i, j) => { throw new DeliberateTestException(); }, (i, j) => i, i => i));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(() => 0, (i, j) => i, (i, j) => i, i => { throw new DeliberateTestException(); }));
if (Environment.ProcessorCount >= 2)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => i, (i, j) => { throw new DeliberateTestException(); }, i => i));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(() => 0, (i, j) => i, (i, j) => { throw new DeliberateTestException(); }, i => i));
}
}
[Fact]
public static void Aggregate_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate((i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, null, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(0, (i, j) => i, null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, null, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, (i, j) => i, null, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(0, (i, j) => i, (i, j) => i, null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(null, (i, j) => i, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(() => 0, null, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(() => 0, (i, j) => i, null, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(() => 0, (i, j) => i, (i, j) => i, null));
}
}
internal static class ListHelper
{
// System.Collections.Immutable.ImmutableList wasn't available.
public static IList<int> AddToCopy(this IList<int> collection, int element)
{
collection = new List<int>(collection);
collection.Add(element);
return collection;
}
public static IList<int> ConcatCopy(this IList<int> left, IList<int> right)
{
List<int> results = new List<int>(left);
results.AddRange(right);
return results;
}
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Thrift.Transport
{
// ReSharper disable once InconsistentNaming
public class TBufferedTransport : TLayeredTransport
{
private readonly int DesiredBufferSize;
private readonly Client.TMemoryBufferTransport ReadBuffer;
private readonly Client.TMemoryBufferTransport WriteBuffer;
private bool IsDisposed;
public class Factory : TTransportFactory
{
public override TTransport GetTransport(TTransport trans)
{
return new TBufferedTransport(trans);
}
}
//TODO: should support only specified input transport?
public TBufferedTransport(TTransport transport, int bufSize = 1024)
: base(transport)
{
if (bufSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufSize), "Buffer size must be a positive number.");
}
DesiredBufferSize = bufSize;
WriteBuffer = new Client.TMemoryBufferTransport(InnerTransport.Configuration, bufSize);
ReadBuffer = new Client.TMemoryBufferTransport(InnerTransport.Configuration, bufSize);
Debug.Assert(DesiredBufferSize == ReadBuffer.Capacity);
Debug.Assert(DesiredBufferSize == WriteBuffer.Capacity);
}
public TTransport UnderlyingTransport
{
get
{
CheckNotDisposed();
return InnerTransport;
}
}
public override bool IsOpen => !IsDisposed && InnerTransport.IsOpen;
public override async Task OpenAsync(CancellationToken cancellationToken)
{
CheckNotDisposed();
await InnerTransport.OpenAsync(cancellationToken);
}
public override void Close()
{
CheckNotDisposed();
InnerTransport.Close();
}
public override async ValueTask<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
{
CheckNotDisposed();
ValidateBufferArgs(buffer, offset, length);
if (!IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
// do we have something buffered?
var count = ReadBuffer.Length - ReadBuffer.Position;
if (count > 0)
{
return await ReadBuffer.ReadAsync(buffer, offset, length, cancellationToken);
}
// does the request even fit into the buffer?
// Note we test for >= instead of > to avoid nonsense buffering
if (length >= ReadBuffer.Capacity)
{
return await InnerTransport.ReadAsync(buffer, offset, length, cancellationToken);
}
// buffer a new chunk of bytes from the underlying transport
ReadBuffer.Length = ReadBuffer.Capacity;
ReadBuffer.TryGetBuffer(out ArraySegment<byte> bufSegment);
ReadBuffer.Length = await InnerTransport.ReadAsync(bufSegment.Array, 0, bufSegment.Count, cancellationToken);
ReadBuffer.Position = 0;
// deliver the bytes
return await ReadBuffer.ReadAsync(buffer, offset, length, cancellationToken);
}
public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
{
CheckNotDisposed();
ValidateBufferArgs(buffer, offset, length);
if (!IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
// enough space left in buffer?
var free = WriteBuffer.Capacity - WriteBuffer.Length;
if (length > free)
{
WriteBuffer.TryGetBuffer(out ArraySegment<byte> bufSegment);
await InnerTransport.WriteAsync(bufSegment.Array, 0, bufSegment.Count, cancellationToken);
WriteBuffer.SetLength(0);
}
// do the data even fit into the buffer?
// Note we test for < instead of <= to avoid nonsense buffering
if (length < WriteBuffer.Capacity)
{
await WriteBuffer.WriteAsync(buffer, offset, length, cancellationToken);
return;
}
// write thru
await InnerTransport.WriteAsync(buffer, offset, length, cancellationToken);
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
CheckNotDisposed();
if (!IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
if (WriteBuffer.Length > 0)
{
WriteBuffer.TryGetBuffer(out ArraySegment<byte> bufSegment);
await InnerTransport.WriteAsync(bufSegment.Array, 0, bufSegment.Count, cancellationToken);
WriteBuffer.SetLength(0);
}
await InnerTransport.FlushAsync(cancellationToken);
}
public override void CheckReadBytesAvailable(long numBytes)
{
var buffered = ReadBuffer.Length - ReadBuffer.Position;
if (buffered < numBytes)
{
numBytes -= buffered;
InnerTransport.CheckReadBytesAvailable(numBytes);
}
}
private void CheckNotDisposed()
{
if (IsDisposed)
{
throw new ObjectDisposedException(nameof(InnerTransport));
}
}
// IDisposable
protected override void Dispose(bool disposing)
{
if (!IsDisposed)
{
if (disposing)
{
ReadBuffer?.Dispose();
WriteBuffer?.Dispose();
InnerTransport?.Dispose();
}
}
IsDisposed = true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.IO
{
/// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
internal sealed partial class UnixFileSystem : FileSystem
{
public override int MaxPath { get { return Interop.Sys.MaxPath; } }
public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } }
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);
}
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
// Note: we could consider using sendfile here, but it isn't part of the POSIX spec, and
// has varying degrees of support on different systems.
// The destination path may just be a directory into which the file should be copied.
// If it is, append the filename from the source onto the destination directory
if (DirectoryExists(destFullPath))
{
destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
}
// Copy the contents of the file from the source to the destination, creating the destination in the process
const int bufferSize = FileStream.DefaultBufferSize;
const bool useAsync = false;
using (Stream src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync))
using (Stream dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
{
src.CopyTo(dst);
}
// Now copy over relevant read/write/execute permissions from the source to the destination
// Use Stat (not LStat) since permissions for symbolic links are meaninless and defer to permissions on the target
Interop.Sys.FileStatus status;
Interop.CheckIo(Interop.Sys.Stat(sourceFullPath, out status), sourceFullPath);
int newMode = status.Mode & (int)Interop.Sys.Permissions.Mask;
Interop.CheckIo(Interop.Sys.ChMod(destFullPath, newMode), destFullPath);
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
// The desired behavior for Move(source, dest) is to not overwrite the destination file
// if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,
// link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move
// as a Creation and Deletion instead of a Rename and thus differ from Windows.
if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EXDEV) // rename fails across devices / mount points
{
CopyFile(sourceFullPath, destFullPath, overwrite: false);
}
else if (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(destFullPath))) // The parent directory of destFile can't be found
{
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
throw Interop.GetExceptionForIoErrno(errorInfo, destFullPath, isDirectory: true);
}
else
{
throw Interop.GetExceptionForIoErrno(errorInfo);
}
}
DeleteFile(sourceFullPath);
}
public override void DeleteFile(string fullPath)
{
if (Interop.Sys.Unlink(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// ENOENT means it already doesn't exist; nop
if (errorInfo.Error != Interop.Error.ENOENT)
{
if (errorInfo.Error == Interop.Error.EISDIR)
errorInfo = Interop.Error.EACCES.Info();
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);
}
}
}
public override void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
{
length--;
}
// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
}
// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
{
return;
}
// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
Stack<string> stackDir = new Stack<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
string dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
{
stackDir.Push(dir);
}
else
{
somepathexists = true;
}
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
{
i--;
}
i--;
}
}
int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
string root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
return;
}
// Create all the directories
int result = 0;
Interop.ErrorInfo firstError = default(Interop.ErrorInfo);
string errorString = fullPath;
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
if (name.Length >= MaxDirectoryPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.S_IRWXU);
if (result < 0 && firstError.Error == 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errorInfo.Error != Interop.Error.EEXIST)
{
firstError = errorInfo;
}
else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errorInfo;
errorString = name;
}
}
}
// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError.Error != 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
}
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES: // match Win32 exception
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno);
default:
throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true);
}
}
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
if (!DirectoryExists(fullPath))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
RemoveDirectoryInternal(fullPath, recursive, throwOnTopLevelDirectoryNotFound: true);
}
private void RemoveDirectoryInternal(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
Exception firstException = null;
if (recursive)
{
try
{
foreach (string item in EnumeratePaths(fullPath, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
{
if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
{
try
{
if (DirectoryExists(item))
{
RemoveDirectoryInternal(item, recursive, throwOnTopLevelDirectoryNotFound: false);
}
else
{
DeleteFile(item);
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
}
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
if (firstException != null)
{
throw firstException;
}
}
if (Interop.Sys.RmDir(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES:
case Interop.Error.EPERM:
case Interop.Error.EROFS:
case Interop.Error.EISDIR:
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // match Win32 exception
case Interop.Error.ENOENT:
if (!throwOnTopLevelDirectoryNotFound)
{
return;
}
goto default;
default:
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath, isDirectory: true);
}
}
}
public override bool DirectoryExists(string fullPath)
{
Interop.ErrorInfo ignored;
return DirectoryExists(fullPath, out ignored);
}
private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo)
{
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo);
}
public override bool FileExists(string fullPath)
{
Interop.ErrorInfo ignored;
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFREG, out ignored);
}
private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo)
{
Interop.Sys.FileStatus fileinfo;
errorInfo = default(Interop.ErrorInfo);
int result = Interop.Sys.Stat(fullPath, out fileinfo);
if (result < 0)
{
errorInfo = Interop.Sys.GetLastErrorInfo();
return false;
}
return (fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == fileType;
}
public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Files:
return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new FileInfo(path, null));
case SearchTarget.Directories:
return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new DirectoryInfo(path, null));
default:
return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?
(FileSystemInfo)new DirectoryInfo(path, null) :
(FileSystemInfo)new FileInfo(path, null));
}
}
private sealed class FileSystemEnumerable<T> : IEnumerable<T>
{
private readonly PathPair _initialDirectory;
private readonly string _searchPattern;
private readonly SearchOption _searchOption;
private readonly bool _includeFiles;
private readonly bool _includeDirectories;
private readonly Func<string, bool, T> _translateResult;
private IEnumerator<T> _firstEnumerator;
internal FileSystemEnumerable(
string userPath, string searchPattern,
SearchOption searchOption, SearchTarget searchTarget,
Func<string, bool, T> translateResult)
{
// Basic validation of the input path
if (userPath == null)
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrWhiteSpace(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
// Validate and normalize the search pattern. If after doing so it's empty,
// matching Win32 behavior we can skip all additional validation and effectively
// return an empty enumerable.
searchPattern = NormalizeSearchPattern(searchPattern);
if (searchPattern.Length > 0)
{
PathHelpers.CheckSearchPattern(searchPattern);
PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);
// If the search pattern contains any paths, make sure we factor those into
// the user path, and then trim them off.
int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (lastSlash >= 0)
{
if (lastSlash >= 1)
{
userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));
}
searchPattern = searchPattern.Substring(lastSlash + 1);
}
string fullPath = Path.GetFullPath(userPath);
// Store everything for the enumerator
_initialDirectory = new PathPair(userPath, fullPath);
_searchPattern = searchPattern;
_searchOption = searchOption;
_includeFiles = (searchTarget & SearchTarget.Files) != 0;
_includeDirectories = (searchTarget & SearchTarget.Directories) != 0;
_translateResult = translateResult;
}
// Open the first enumerator so that any errors are propagated synchronously.
_firstEnumerator = Enumerate();
}
public IEnumerator<T> GetEnumerator()
{
return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private IEnumerator<T> Enumerate()
{
return Enumerate(
_initialDirectory.FullPath != null ?
OpenDirectory(_initialDirectory.FullPath) :
null);
}
private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle)
{
if (dirHandle == null)
{
// Empty search
yield break;
}
Debug.Assert(!dirHandle.IsInvalid);
Debug.Assert(!dirHandle.IsClosed);
// Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories
// Lazily-initialized only if we find subdirectories that will be explored.
Stack<PathPair> toExplore = null;
PathPair dirPath = _initialDirectory;
while (dirHandle != null)
{
try
{
// Read each entry from the enumerator
Interop.Sys.DirectoryEntry dirent;
while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0)
{
// Get from the dir entry whether the entry is a file or directory.
// We classify everything as a file unless we know it to be a directory.
bool isDir;
if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR)
{
// We know it's a directory.
isDir = true;
}
else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN)
{
// It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
// If we can't (e.g.symlink to a file, broken symlink, etc.), we'll just treat it as a file.
Interop.ErrorInfo errnoIgnored;
isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored);
}
else
{
// Otherwise, treat it as a file. This includes regular files, FIFOs, etc.
isDir = false;
}
// Yield the result if the user has asked for it. In the case of directories,
// always explore it by pushing it onto the stack, regardless of whether
// we're returning directories.
if (isDir)
{
if (!ShouldIgnoreDirectory(dirent.InodeName))
{
string userPath = null;
if (_searchOption == SearchOption.AllDirectories)
{
if (toExplore == null)
{
toExplore = new Stack<PathPair>();
}
userPath = Path.Combine(dirPath.UserPath, dirent.InodeName);
toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName)));
}
if (_includeDirectories &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true);
}
}
}
else if (_includeFiles &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false);
}
}
}
finally
{
// Close the directory enumerator
dirHandle.Dispose();
dirHandle = null;
}
if (toExplore != null && toExplore.Count > 0)
{
// Open the next directory.
dirPath = toExplore.Pop();
dirHandle = OpenDirectory(dirPath.FullPath);
}
}
}
private static string NormalizeSearchPattern(string searchPattern)
{
if (searchPattern == "." || searchPattern == "*.*")
{
searchPattern = "*";
}
else if (PathHelpers.EndsInDirectorySeparator(searchPattern))
{
searchPattern += "*";
}
return searchPattern;
}
private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath)
{
Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath);
if (handle.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true);
}
return handle;
}
}
/// <summary>Determines whether the specified directory name should be ignored.</summary>
/// <param name="name">The name to evaluate.</param>
/// <returns>true if the name is "." or ".."; otherwise, false.</returns>
private static bool ShouldIgnoreDirectory(string name)
{
return name == "." || name == "..";
}
public override string GetCurrentDirectory()
{
return Interop.Sys.GetCwd();
}
public override void SetCurrentDirectory(string fullPath)
{
Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath);
}
public override FileAttributes GetAttributes(string fullPath)
{
return new FileInfo(fullPath, null).Attributes;
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
new FileInfo(fullPath, null).Attributes = attributes;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return new FileInfo(fullPath, null).CreationTime;
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.CreationTime = time;
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return new FileInfo(fullPath, null).LastAccessTime;
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastAccessTime = time;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return new FileInfo(fullPath, null).LastWriteTime;
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastWriteTime = time;
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Search
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// IndexersOperations operations.
/// </summary>
public partial interface IIndexersOperations
{
/// <summary>
/// Resets the change tracking state associated with an Azure Search
/// indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Reset-Indexer" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to reset.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> ResetWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Runs an Azure Search indexer on-demand.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Run-Indexer" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to run.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> RunWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new Azure Search indexer or updates an indexer if it
/// already exists.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Create-Indexer" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to create or update.
/// </param>
/// <param name='indexer'>
/// The definition of the indexer to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='accessCondition'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Indexer>> CreateOrUpdateWithHttpMessagesAsync(string indexerName, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an Azure Search indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Delete-Indexer" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='accessCondition'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieves an indexer definition from Azure Search.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Get-Indexer" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Indexer>> GetWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all indexers available for an Azure Search service.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/List-Indexers" />
/// </summary>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IndexerListResult>> ListWithHttpMessagesAsync(SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new Azure Search indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Create-Indexer" />
/// </summary>
/// <param name='indexer'>
/// The definition of the indexer to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Indexer>> CreateWithHttpMessagesAsync(Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the current status and execution history of an indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Get-Indexer-Status" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer for which to retrieve status.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IndexerExecutionInfo>> GetStatusWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Wireless.V1
{
/// <summary>
/// Fetch a Command instance from your account.
/// </summary>
public class FetchCommandOptions : IOptions<CommandResource>
{
/// <summary>
/// The SID that identifies the resource to fetch
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchCommandOptions
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
public FetchCommandOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Retrieve a list of Commands from your account.
/// </summary>
public class ReadCommandOptions : ReadOptions<CommandResource>
{
/// <summary>
/// The sid or unique_name of the Sim resources to read
/// </summary>
public string Sim { get; set; }
/// <summary>
/// The status of the resources to read
/// </summary>
public CommandResource.StatusEnum Status { get; set; }
/// <summary>
/// Only return Commands with this direction value
/// </summary>
public CommandResource.DirectionEnum Direction { get; set; }
/// <summary>
/// Only return Commands with this transport value
/// </summary>
public CommandResource.TransportEnum Transport { get; set; }
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Sim != null)
{
p.Add(new KeyValuePair<string, string>("Sim", Sim));
}
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
if (Direction != null)
{
p.Add(new KeyValuePair<string, string>("Direction", Direction.ToString()));
}
if (Transport != null)
{
p.Add(new KeyValuePair<string, string>("Transport", Transport.ToString()));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// Send a Command to a Sim.
/// </summary>
public class CreateCommandOptions : IOptions<CommandResource>
{
/// <summary>
/// The message body of the Command or a Base64 encoded byte string in binary mode
/// </summary>
public string Command { get; }
/// <summary>
/// The sid or unique_name of the SIM to send the Command to
/// </summary>
public string Sim { get; set; }
/// <summary>
/// The HTTP method we use to call callback_url
/// </summary>
public Twilio.Http.HttpMethod CallbackMethod { get; set; }
/// <summary>
/// he URL we call when the Command has finished sending
/// </summary>
public Uri CallbackUrl { get; set; }
/// <summary>
/// The mode to use when sending the SMS message
/// </summary>
public CommandResource.CommandModeEnum CommandMode { get; set; }
/// <summary>
/// Whether to include the SID of the command in the message body
/// </summary>
public string IncludeSid { get; set; }
/// <summary>
/// Whether to request delivery receipt from the recipient
/// </summary>
public bool? DeliveryReceiptRequested { get; set; }
/// <summary>
/// Construct a new CreateCommandOptions
/// </summary>
/// <param name="command"> The message body of the Command or a Base64 encoded byte string in binary mode </param>
public CreateCommandOptions(string command)
{
Command = command;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Command != null)
{
p.Add(new KeyValuePair<string, string>("Command", Command));
}
if (Sim != null)
{
p.Add(new KeyValuePair<string, string>("Sim", Sim));
}
if (CallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("CallbackMethod", CallbackMethod.ToString()));
}
if (CallbackUrl != null)
{
p.Add(new KeyValuePair<string, string>("CallbackUrl", Serializers.Url(CallbackUrl)));
}
if (CommandMode != null)
{
p.Add(new KeyValuePair<string, string>("CommandMode", CommandMode.ToString()));
}
if (IncludeSid != null)
{
p.Add(new KeyValuePair<string, string>("IncludeSid", IncludeSid));
}
if (DeliveryReceiptRequested != null)
{
p.Add(new KeyValuePair<string, string>("DeliveryReceiptRequested", DeliveryReceiptRequested.Value.ToString().ToLower()));
}
return p;
}
}
/// <summary>
/// Delete a Command instance from your account.
/// </summary>
public class DeleteCommandOptions : IOptions<CommandResource>
{
/// <summary>
/// The SID that identifies the resource to delete
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteCommandOptions
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to delete </param>
public DeleteCommandOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
}
| |
// Copyright (c) 2016 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using Bugsnag.Payload;
using IniParser.Model;
using LfMerge.Core.Actions;
using LfMerge.Core.Actions.Infrastructure;
using LfMerge.Core.LanguageForge.Config;
using LfMerge.Core.LanguageForge.Model;
using LfMerge.Core.Logging;
using LfMerge.Core.MongoConnector;
using LfMerge.Core.Settings;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using Moq;
using Exception = System.Exception;
namespace LfMerge.Core.Tests
{
public class ProcessingStateFactoryDouble: IProcessingStateDeserialize
{
public ProcessingStateDouble State { get; set; }
private LfMergeSettings Settings { get; set; }
public ProcessingStateFactoryDouble(LfMergeSettings settings)
{
Settings = settings;
}
#region IProcessingStateDeserialize implementation
public ProcessingState Deserialize(string projectCode)
{
if (State == null)
State = new ProcessingStateDouble(projectCode, Settings);
return State;
}
#endregion
}
public class ProcessingStateDouble: ProcessingState
{
public List<ProcessingState.SendReceiveStates> SavedStates;
public ProcessingStateDouble(string projectCode, LfMergeSettings settings): base(projectCode, settings)
{
SavedStates = new List<ProcessingState.SendReceiveStates>();
}
protected override void SetProperty<T>(ref T property, T value)
{
property = value;
if (SavedStates.Count == 0 || SavedStates[SavedStates.Count - 1] != SRState)
SavedStates.Add(SRState);
}
public void ResetSavedStates()
{
SavedStates.Clear();
}
}
public class LanguageForgeProjectAccessor: LanguageForgeProject
{
protected LanguageForgeProjectAccessor(): base(null)
{
}
public static void Reset()
{
LanguageForgeProject.DisposeProjectCache();
}
}
public class LfMergeSettingsDouble: LfMergeSettings
{
static LfMergeSettingsDouble()
{
ConfigDir = Path.GetRandomFileName();
}
public LfMergeSettingsDouble(string replacementBaseDir)
{
var replacementConfig = new IniData(ParsedConfig);
replacementConfig.Global["BaseDir"] = replacementBaseDir;
Initialize(replacementConfig);
CommitWhenDone = false;
VerboseProgress = true;
PhpSourcePath = Path.Combine(TestEnvironment.FindGitRepoRoot(), "data", "php", "src");
}
public override IniData ParseFiles(string defaultConfig, string globalConfigFilename)
{
// Hide the console warning about "no global configuration file found" because we're doing that on purpose
var savedStdout = Console.Out;
Console.SetOut(TextWriter.Null);
IniData result = base.ParseFiles(defaultConfig, globalConfigFilename);
Console.SetOut(savedStdout);
return result;
}
}
public class MongoConnectionDouble: IMongoConnection
{
public static void Initialize()
{
// Just as with MongoConnection.Initialize(), we need to set up BSON serialization conventions
// so that the "fake" connection can deserialize the sample JSON identically to how the real DB does it.
Console.WriteLine("Initializing FAKE Mongo connection...");
// Serialize Boolean values permissively
BsonSerializer.RegisterSerializationProvider(new BooleanSerializationProvider());
// Use CamelCaseName conversions between Mongo and our mapping classes
var pack = new ConventionPack();
pack.Add(new CamelCaseElementNameConvention());
ConventionRegistry.Register(
"My Custom Conventions",
pack,
t => t.FullName.StartsWith("LfMerge."));
// Register class mappings before opening first connection
new MongoRegistrarForLfConfig().RegisterClassMappings();
}
private readonly Dictionary<string, LfInputSystemRecord> _storedInputSystems = new Dictionary<string, LfInputSystemRecord>();
private readonly Dictionary<Guid, LfLexEntry> _storedLfLexEntries = new Dictionary<Guid, LfLexEntry>();
private readonly Dictionary<string, LfOptionList> _storedLfOptionLists = new Dictionary<string, LfOptionList>();
private Dictionary<string, LfConfigFieldBase> _storedCustomFieldConfig = new Dictionary<string, LfConfigFieldBase>();
private Dictionary<string, DateTime?> _storedLastSyncDate = new Dictionary<string, DateTime?>();
// Used in mocking SetLastSyncDate
private MongoProjectRecordFactoryDouble _projectRecordFactory = null;
public void Reset()
{
_storedInputSystems.Clear();
_storedLfLexEntries.Clear();
_storedLfOptionLists.Clear();
_storedCustomFieldConfig.Clear();
}
public void RegisterProjectRecordFactory(MongoProjectRecordFactoryDouble projectRecordFactory)
{
_projectRecordFactory = projectRecordFactory;
}
public long LexEntryCount(ILfProject project) { return _storedLfLexEntries.LongCount(); }
public static TObj DeepCopy<TObj>(TObj orig)
{
// Take advantage of BSON serialization to clone any object
// This allows this test double to act a bit more like a "real" Mongo database: it no longer holds
// onto references to the objects that the test code added. Instead, it clones them. So if we change
// fields of those objects *after* adding them to Mongo, those changes should NOT be reflected in Mongo.
BsonDocument bson = orig.ToBsonDocument();
return BsonSerializer.Deserialize<TObj>(bson);
}
public Dictionary<string, LfInputSystemRecord> GetInputSystems(ILfProject project)
{
return _storedInputSystems;
}
public bool SetInputSystems(ILfProject project, Dictionary<string, LfInputSystemRecord> inputSystems,
List<string> vernacularWss, List<string> analysisWss, List<string> pronunciationWss)
{
foreach (var ws in inputSystems.Keys)
_storedInputSystems[ws] = inputSystems[ws];
if (project.IsInitialClone)
{
// TODO: Update field input systems too?
}
return true;
}
public bool SetCustomFieldConfig(ILfProject project, Dictionary<string, LfConfigFieldBase> lfCustomFieldList)
{
if (lfCustomFieldList == null)
_storedCustomFieldConfig = new Dictionary<string, LfConfigFieldBase>();
else
// _storedCustomFieldConfig = lfCustomFieldList; // This would assign a reference; we want to clone instead, in case unit tests further modify this dict
_storedCustomFieldConfig = new Dictionary<string, LfConfigFieldBase>(lfCustomFieldList); // Cloning better simulates writing to Mongo
return true;
}
public Dictionary<string, LfConfigFieldBase> GetCustomFieldConfig(ILfProject project)
{
return _storedCustomFieldConfig;
}
public void UpdateMockLfLexEntry(BsonDocument mockData)
{
LfLexEntry data = BsonSerializer.Deserialize<LfLexEntry>(mockData);
UpdateMockLfLexEntry(data);
}
public void UpdateMockLfLexEntry(LfLexEntry mockData)
{
Guid guid = mockData.Guid ?? Guid.Empty;
_storedLfLexEntries[guid] = DeepCopy(mockData);
}
public void UpdateMockOptionList(BsonDocument mockData)
{
LfOptionList data = BsonSerializer.Deserialize<LfOptionList>(mockData);
UpdateMockOptionList(data);
}
public void UpdateMockOptionList(LfOptionList mockData)
{
string listCode = mockData.Code ?? string.Empty;
_storedLfOptionLists[listCode] = DeepCopy(mockData);
}
public IEnumerable<LfLexEntry> GetLfLexEntries()
{
return new List<LfLexEntry>(_storedLfLexEntries.Values.Select(entry => DeepCopy(entry)));
}
public LfLexEntry GetLfLexEntryByGuid(Guid key)
{
LfLexEntry result;
if (_storedLfLexEntries.TryGetValue(key, out result))
return result;
return null;
}
public IEnumerable<LfOptionList> GetLfOptionLists()
{
return new List<LfOptionList>(_storedLfOptionLists.Values.Select(entry => DeepCopy(entry)));
}
public IEnumerable<TDocument> GetRecords<TDocument>(ILfProject project, string collectionName, Expression<Func<TDocument, bool>> filter)
{
return GetRecords<TDocument>(project, collectionName).Where(filter.Compile());
}
public IEnumerable<TDocument> GetRecords<TDocument>(ILfProject project, string collectionName)
{
switch (collectionName)
{
case MagicStrings.LfCollectionNameForLexicon:
return (IEnumerable<TDocument>)GetLfLexEntries();
case MagicStrings.LfCollectionNameForOptionLists:
return (IEnumerable<TDocument>)GetLfOptionLists();
default:
List<TDocument> empty = new List<TDocument>();
return empty.AsEnumerable();
}
}
public Dictionary<Guid, DateTime> GetAllModifiedDatesForEntries(ILfProject project)
{
return _storedLfLexEntries.ToDictionary(kv => kv.Key, kv => kv.Value.AuthorInfo.ModifiedDate);
}
public LfOptionList GetLfOptionListByCode(ILfProject project, string listCode)
{
LfOptionList result;
if (!_storedLfOptionLists.TryGetValue(listCode, out result))
result = null;
return result;
}
public IMongoDatabase GetProjectDatabase(ILfProject project)
{
var mockDb = new Mock<IMongoDatabase>(); // SO much easier than implementing the 9 public methods for a manual stub of IMongoDatabase!
// TODO: Add appropriate mock functions if needed
return mockDb as IMongoDatabase;
}
public IMongoDatabase GetMainDatabase()
{
var mockDb = new Mock<IMongoDatabase>(); // SO much easier than implementing the 9 public methods for a manual stub of IMongoDatabase!
// TODO: Add appropriate mock functions if needed
return mockDb as IMongoDatabase;
}
public bool UpdateRecord(ILfProject project, LfLexEntry data)
{
_storedLfLexEntries[data.Guid ?? Guid.Empty] = DeepCopy(data);
return true;
}
public bool UpdateRecord(ILfProject project, LfOptionList data, string listCode)
{
_storedLfOptionLists[listCode ?? string.Empty] = DeepCopy(data);
return true;
}
public bool RemoveRecord(ILfProject project, Guid guid)
{
_storedLfLexEntries.Remove(guid);
return true;
}
public bool SetLastSyncedDate(ILfProject project, DateTime? newSyncedDate)
{
_storedLastSyncDate[project.ProjectCode] = newSyncedDate;
// Also update on the fake project record, since EnsureCloneAction looks at the project record to check its initial-clone logic
if (_projectRecordFactory != null)
{
MongoProjectRecord projectRecord = _projectRecordFactory.Create(project);
projectRecord.LastSyncedDate = newSyncedDate;
}
return true;
}
public DateTime? GetLastSyncedDate(ILfProject project)
{
DateTime? result = null;
if (_storedLastSyncDate.TryGetValue(project.ProjectCode, out result))
return result;
return null;
}
public IEnumerable<LfComment> GetComments(ILfProject project)
{
yield break;
}
public Dictionary<MongoDB.Bson.ObjectId, Guid> GetGuidsByObjectIdForCollection(ILfProject project, string collectionName)
{
return new Dictionary<MongoDB.Bson.ObjectId, Guid>();
}
public void UpdateComments(ILfProject project, List<LfComment> comments)
{
;
}
public void UpdateReplies(ILfProject project, List<Tuple<string, List<LfCommentReply>>> repliesFromFWWithCommentGuids)
{
;
}
public void UpdateCommentStatuses(ILfProject project, List<KeyValuePair<string, Tuple<string, string>>> statusChanges)
{
;
}
public void SetCommentReplyGuids(ILfProject project, IDictionary<string,Guid> uniqIdToGuidMappings)
{
// No-op. TODO: Implement something that stores a simple comment-replies data structure so we can unit test.
}
public void SetCommentGuids(ILfProject project, IDictionary<string,Guid> commentIdToGuidMappings)
{
// No-op. TODO: Implement something that stores a simple comments dictionary so we can unit test.
}
}
public class MongoProjectRecordFactoryDouble: MongoProjectRecordFactory
{
// Memoize the project records for each project so that we're returning the same one each time, to better simulate the Mongo DB.
private Dictionary<string, MongoProjectRecord> _projectRecords;
public MongoProjectRecordFactoryDouble(IMongoConnection connection) : base(connection)
{
_projectRecords = new Dictionary<string, MongoProjectRecord>();
var testDouble = connection as MongoConnectionDouble;
if (testDouble != null)
{
testDouble.RegisterProjectRecordFactory(this);
}
}
public override MongoProjectRecord Create(ILfProject project)
{
var sampleConfig = BsonSerializer.Deserialize<LfProjectConfig>(SampleData.jsonConfigData);
// TODO: Could we use a Mock to do this instead?
MongoProjectRecord record;
if (_projectRecords.TryGetValue(project.ProjectCode, out record))
{
return record;
}
else
{
record = new MongoProjectRecord {
Id = new ObjectId(),
InputSystems = new Dictionary<string, LfInputSystemRecord>() {
{"en", new LfInputSystemRecord {
Abbreviation = "Eng",
Tag = "en",
LanguageName = "English",
IsRightToLeft = false } },
{"fr", new LfInputSystemRecord {
// this should probably be a three-letter abbreviation like Fre,
// but since our test data has the two letter abbreviation for this ws
// we have to stick with it so that we don't introduce an unwanted
// change.
Abbreviation = "fr",
Tag = "fr",
LanguageName = "French",
IsRightToLeft = false } },
},
InterfaceLanguageCode = "en",
LanguageCode = "fr",
ProjectCode = project.ProjectCode,
ProjectName = project.ProjectCode,
SendReceiveProjectIdentifier = project.ProjectCode,
Config = sampleConfig
};
_projectRecords.Add(project.ProjectCode, record);
return record;
}
}
}
class LanguageDepotProjectDouble: ILanguageDepotProject
{
#region ILanguageDepotProject implementation
public void Initialize(string lfProjectCode)
{
Identifier = lfProjectCode;
}
public string Identifier { get; set; }
public string Repository { get; set; }
#endregion
}
class ChorusHelperDouble: ChorusHelper
{
public override string GetSyncUri(ILfProject project)
{
var server = LanguageDepotMock.Server;
return server != null && server.IsStarted ? server.Url : LanguageDepotMock.ProjectFolderPath;
}
}
class EnsureCloneActionDouble: EnsureCloneAction
{
private readonly bool _projectExists;
private readonly bool _throwAuthorizationException;
public EnsureCloneActionDouble(LfMergeSettings settings, ILogger logger,
MongoProjectRecordFactory projectRecordFactory, IMongoConnection connection,
bool projectExists = true, bool throwAuthorizationException = true):
base(settings, logger, projectRecordFactory, connection)
{
_projectExists = projectExists;
_throwAuthorizationException = throwAuthorizationException;
}
protected override bool CloneRepo(ILfProject project, string projectFolderPath,
out string cloneResult)
{
if (_projectExists)
{
Directory.CreateDirectory(projectFolderPath);
Directory.CreateDirectory(Path.Combine(projectFolderPath, ".hg"));
File.WriteAllText(Path.Combine(projectFolderPath, ".hg", "hgrc"), "blablabla");
cloneResult = string.Format("Clone success: new clone created on branch '' in folder {0}",
projectFolderPath);
return true;
}
if (_throwAuthorizationException)
throw new Chorus.VcsDrivers.Mercurial.RepositoryAuthorizationException();
throw new Exception("Just some arbitrary exception");
}
}
class EnsureCloneActionDoubleMockingInitialTransfer: EnsureCloneActionDouble
{
// This mock object will be used in the EnsureClone_RunsInitialClone series of tests
internal bool InitialCloneWasRun { get; set; }
public EnsureCloneActionDoubleMockingInitialTransfer(LfMergeSettings settings, ILogger logger,
MongoProjectRecordFactory projectRecordFactory, IMongoConnection connection, bool projectExists = true):
base(settings, logger, projectRecordFactory, connection, projectExists)
{
InitialCloneWasRun = false;
}
protected override void InitialTransferToMongoAfterClone(ILfProject project)
{
InitialCloneWasRun = true;
}
}
class EnsureCloneActionDoubleMockErrorCondition : EnsureCloneAction
{
private string _cloneResult;
public EnsureCloneActionDoubleMockErrorCondition(LfMergeSettings settings, ILogger logger,
MongoProjectRecordFactory projectRecordFactory, IMongoConnection connection,
string cloneResult):
base(settings, logger, projectRecordFactory, connection)
{
_cloneResult = cloneResult;
}
protected override bool CloneRepo(ILfProject project, string projectFolderPath, out string cloneResult)
{
cloneResult = _cloneResult;
return true;
}
}
class ExceptionLoggingDouble : ExceptionLogging
{
private List<Report> _exceptions = new List<Report>();
private ExceptionLoggingDouble() : base("unit-test", "foo", ".")
{
}
protected override void OnBeforeNotify(Report report)
{
_exceptions.Add(report);
}
public List<Report> Exceptions
{
get { return _exceptions; }
}
public static ExceptionLoggingDouble Initialize()
{
var exceptionLoggingDouble = new ExceptionLoggingDouble();
Client = exceptionLoggingDouble;
return exceptionLoggingDouble;
}
}
}
| |
/*
* 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.Reflection;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework
{
/// <summary>
/// Represents an item in a task inventory
/// </summary>
public class TaskInventoryItem : ICloneable
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// XXX This should really be factored out into some constants class.
/// </summary>
private const uint FULL_MASK_PERMISSIONS_GENERAL = 2147483647;
private UUID _assetID = UUID.Zero;
private uint _baseMask = FULL_MASK_PERMISSIONS_GENERAL;
private uint _creationDate = 0;
private UUID _creatorID = UUID.Zero;
private string _creatorData = String.Empty;
private string _description = String.Empty;
private uint _everyoneMask = FULL_MASK_PERMISSIONS_GENERAL;
private uint _flags = 0;
private UUID _groupID = UUID.Zero;
private uint _groupMask = FULL_MASK_PERMISSIONS_GENERAL;
private int _invType = 0;
private UUID _itemID = UUID.Zero;
private UUID _lastOwnerID = UUID.Zero;
private UUID _rezzerID = UUID.Zero;
private string _name = String.Empty;
private uint _nextOwnerMask = FULL_MASK_PERMISSIONS_GENERAL;
private UUID _ownerID = UUID.Zero;
private uint _ownerMask = FULL_MASK_PERMISSIONS_GENERAL;
private UUID _parentID = UUID.Zero; //parent folder id
private UUID _parentPartID = UUID.Zero; // SceneObjectPart this is inside
private UUID _permsGranter;
private int _permsMask;
private int _type = 0;
private UUID _oldID;
private UUID _loadedID = UUID.Zero;
private bool _ownerChanged = false;
public UUID AssetID {
get {
return _assetID;
}
set {
_assetID = value;
}
}
public uint BasePermissions {
get {
return _baseMask;
}
set {
_baseMask = value;
}
}
public uint CreationDate {
get {
return _creationDate;
}
set {
_creationDate = value;
}
}
public UUID CreatorID {
get {
return _creatorID;
}
set {
_creatorID = value;
}
}
public string CreatorData // = <profile url>;<name>
{
get { return _creatorData; }
set { _creatorData = value; }
}
/// <summary>
/// Used by the DB layer to retrieve / store the entire user identification.
/// The identification can either be a simple UUID or a string of the form
/// uuid[;profile_url[;name]]
/// </summary>
public string CreatorIdentification
{
get
{
if (!string.IsNullOrEmpty(_creatorData))
return _creatorID.ToString() + ';' + _creatorData;
else
return _creatorID.ToString();
}
set
{
if ((value == null) || (value != null && value == string.Empty))
{
_creatorData = string.Empty;
return;
}
if (!value.Contains(";")) // plain UUID
{
UUID uuid = UUID.Zero;
UUID.TryParse(value, out uuid);
_creatorID = uuid;
}
else // <uuid>[;<endpoint>[;name]]
{
string name = "Unknown User";
string[] parts = value.Split(';');
if (parts.Length >= 1)
{
UUID uuid = UUID.Zero;
UUID.TryParse(parts[0], out uuid);
_creatorID = uuid;
}
if (parts.Length >= 2)
_creatorData = parts[1];
if (parts.Length >= 3)
name = parts[2];
_creatorData += ';' + name;
}
}
}
public string Description {
get {
return _description;
}
set {
_description = value;
}
}
public uint EveryonePermissions {
get {
return _everyoneMask;
}
set {
_everyoneMask = value;
}
}
public uint Flags {
get {
return _flags;
}
set {
_flags = value;
}
}
public UUID GroupID {
get {
return _groupID;
}
set {
_groupID = value;
}
}
public uint GroupPermissions {
get {
return _groupMask;
}
set {
_groupMask = value;
}
}
public int InvType {
get {
return _invType;
}
set {
_invType = value;
}
}
public UUID ItemID {
get {
return _itemID;
}
set {
_itemID = value;
}
}
public UUID OldItemID {
get {
return _oldID;
}
set {
_oldID = value;
}
}
public UUID LoadedItemID {
get {
return _loadedID;
}
set {
_loadedID = value;
}
}
public UUID LastOwnerID {
get {
return _lastOwnerID;
}
set {
_lastOwnerID = value;
}
}
public UUID RezzerID
{
get {
return _rezzerID;
}
set {
_rezzerID = value;
}
}
public string Name {
get {
return _name;
}
set {
_name = value;
}
}
public uint NextPermissions {
get {
return _nextOwnerMask;
}
set {
_nextOwnerMask = value;
}
}
public UUID OwnerID {
get {
return _ownerID;
}
set {
_ownerID = value;
}
}
public uint CurrentPermissions {
get {
return _ownerMask;
}
set {
_ownerMask = value;
}
}
public UUID ParentID {
get {
return _parentID;
}
set {
_parentID = value;
}
}
public UUID ParentPartID {
get {
return _parentPartID;
}
set {
_parentPartID = value;
}
}
public UUID PermsGranter {
get {
return _permsGranter;
}
set {
_permsGranter = value;
}
}
public int PermsMask {
get {
return _permsMask;
}
set {
_permsMask = value;
}
}
public int Type {
get {
return _type;
}
set {
_type = value;
}
}
public bool OwnerChanged
{
get
{
return _ownerChanged;
}
set
{
_ownerChanged = value;
// m_log.DebugFormat(
// "[TASK INVENTORY ITEM]: Owner changed set {0} for {1} {2} owned by {3}",
// _ownerChanged, Name, ItemID, OwnerID);
}
}
/// <summary>
/// This used ONLY during copy. It can't be relied on at other times!
/// </summary>
/// <remarks>
/// For true script running status, use IEntityInventory.TryGetScriptInstanceRunning() for now.
/// </remarks>
public bool ScriptRunning { get; set; }
// See ICloneable
#region ICloneable Members
public Object Clone()
{
return MemberwiseClone();
}
#endregion
/// <summary>
/// Reset the UUIDs for this item.
/// </summary>
/// <param name="partID">The new part ID to which this item belongs</param>
public void ResetIDs(UUID partID)
{
LoadedItemID = OldItemID;
OldItemID = ItemID;
ItemID = UUID.Random();
ParentPartID = partID;
ParentID = partID;
}
public TaskInventoryItem()
{
ScriptRunning = true;
CreationDate = (uint)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Search
{
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 Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ServicesOperations operations.
/// </summary>
internal partial class ServicesOperations : IServiceOperations<SearchManagementClient>, IServicesOperations
{
/// <summary>
/// Initializes a new instance of the ServicesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ServicesOperations(SearchManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the SearchManagementClient
/// </summary>
public SearchManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates a Search service in the given resource group. If the
/// Search service already exists, all properties will be updated with the
/// given values.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription.
/// </param>
/// <param name='serviceName'>
/// The name of the Search service to create or update.
/// </param>
/// <param name='parameters'>
/// The properties to set or update on the Search service.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SearchServiceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, SearchServiceCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{serviceName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", Uri.EscapeDataString(serviceName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_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);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// 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();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SearchServiceResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<SearchServiceResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<SearchServiceResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a Search service in the given resource group, along with its
/// associated resources.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription.
/// </param>
/// <param name='serviceName'>
/// The name of the Search service to delete.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{serviceName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", Uri.EscapeDataString(serviceName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_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);
}
}
// Serialize Request
string _requestContent = null;
// 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();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 404 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_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>
/// Returns a list of all Search services in the given resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SearchServiceListResult>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_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);
}
}
// Serialize Request
string _requestContent = null;
// 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();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SearchServiceListResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<SearchServiceListResult>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace FakeItEasy.Specs
{
using System;
using FakeItEasy.Configuration;
using FakeItEasy.Tests.TestHelpers;
using FluentAssertions;
using Xbehave;
using Xunit;
public static class ArgumentMatchingSpecs
{
public interface IFoo
{
int Bar(int a);
int Bar(int a, string b);
int Bar(int a, string b, bool c);
int Bar(int a, string b, bool c, object d);
}
[Scenario]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(10)]
public static void WithAnyArguments(int argument, IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 1 parameter is configured to return a value when called with any arguments"
.x(() => A.CallTo(() => fake.Bar(0))
.WithAnyArguments()
.Returns(42));
$"When the method is called with argument {argument}"
.x(() => result = fake.Bar(argument));
"Then it returns the configured value"
.x(() => result.Should().Be(42));
}
[Scenario]
public static void WhenArgumentsMatchWith1ArgSuccess(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 1 parameter is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0))
.WhenArgumentsMatch(args => args.Get<int>(0) % 2 == 0)
.Returns(42));
"When the method is called with an argument that satisfies the predicate"
.x(() => result = fake.Bar(4));
"Then it returns the configured value"
.x(() => result.Should().Be(42));
}
[Scenario]
public static void WhenArgumentsMatchWith1ArgFailure(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 1 parameter is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0))
.WhenArgumentsMatch(args => args.Get<int>(0) % 2 == 0)
.Returns(42));
"When the method is called with an argument that doesn't satisfy the predicate"
.x(() => result = fake.Bar(3));
"Then it returns the default value"
.x(() => result.Should().Be(0));
}
[Scenario]
public static void WhenArgumentsMatchWith2ArgsSuccess(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 2 parameters is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0, string.Empty))
.WhenArgumentsMatch(args => args.Get<int>(0) % 2 == 0 && args.Get<string>(1)?.Length < 3)
.Returns(42));
"When the method is called with arguments that satisfy the predicate"
.x(() => result = fake.Bar(4, "x"));
"Then it returns the configured value"
.x(() => result.Should().Be(42));
}
[Scenario]
public static void WhenArgumentsMatchWith2ArgsFailure(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 2 parameters is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0, string.Empty))
.WhenArgumentsMatch(args => args.Get<int>(0) % 2 == 0 && args.Get<string>(1)?.Length < 3)
.Returns(42));
"When the method is called with arguments that don't satisfy the predicate"
.x(() => result = fake.Bar(3, "hello"));
"Then it returns the default value"
.x(() => result.Should().Be(0));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith1ArgSuccess(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 1 parameter is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0))
.WhenArgumentsMatch((int a) => a % 2 == 0)
.Returns(42));
"When the method is called with an argument that satisfies the predicate"
.x(() => result = fake.Bar(4));
"Then it returns the configured value"
.x(() => result.Should().Be(42));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith1ArgFailure(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 1 parameter is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0))
.WhenArgumentsMatch((int a) => a % 2 == 0)
.Returns(42));
"When the method is called with an argument that doesn't satisfy the predicate"
.x(() => result = fake.Bar(3));
"Then it returns the default value"
.x(() => result.Should().Be(0));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith1ArgWrongSignature(IFoo fake, Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 1 parameter is configured with an arguments predicate with an incompatible signature"
.x(() => exception = Record.Exception(
() => A.CallTo(() => fake.Bar(0))
.WhenArgumentsMatch((long a) => true)
.Returns(42)));
"When the method is called"
.x(() => exception = Record.Exception(() => fake.Bar(3)));
"Then it throws a FakeConfigurationException that describes the problem"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.WithMessage("The faked method has the signature (System.Int32), but when arguments match was used with (System.Int64)."));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith2ArgsSuccess(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 2 parameters is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0, string.Empty))
.WhenArgumentsMatch((int a, string b) => a % 2 == 0 && b.Length < 3)
.Returns(42));
"When the method is called with arguments that satisfy the predicate"
.x(() => result = fake.Bar(4, "x"));
"Then it returns the configured value"
.x(() => result.Should().Be(42));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith2ArgsFailure(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 2 parameters is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0, string.Empty))
.WhenArgumentsMatch((int a, string b) => a % 2 == 0 && b.Length < 3)
.Returns(42));
"When the method is called with arguments that don't satisfy the predicate"
.x(() => result = fake.Bar(3, "hello"));
"Then it returns the default value"
.x(() => result.Should().Be(0));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith2ArgsWrongSignature(IFoo fake, Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 2 parameters is configured with an arguments predicate with an incompatible signature"
.x(() => exception = Record.Exception(
() => A.CallTo(() => fake.Bar(0, string.Empty))
.WhenArgumentsMatch((long a, DateTime b) => true)
.Returns(42)));
"When the method is called"
.x(() => exception = Record.Exception(() => fake.Bar(3, "hello")));
"Then it throws a FakeConfigurationException that describes the problem"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.WithMessage("The faked method has the signature (System.Int32, System.String), but when arguments match was used with (System.Int64, System.DateTime)."));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith3ArgsSuccess(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 3 parameters is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0, string.Empty, false))
.WhenArgumentsMatch((int a, string b, bool c) => a % 2 == 0 && b.Length < 3 && c)
.Returns(42));
"When the method is called with arguments that satisfy the predicate"
.x(() => result = fake.Bar(4, "x", true));
"Then it returns the configured value"
.x(() => result.Should().Be(42));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith3ArgsFailure(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 3 parameters is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0, string.Empty, false))
.WhenArgumentsMatch((int a, string b, bool c) => a % 2 == 0 && b.Length < 3 && c)
.Returns(42));
"When the method is called with arguments that don't satisfy the predicate"
.x(() => result = fake.Bar(3, "hello", false));
"Then it returns the default value"
.x(() => result.Should().Be(0));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith3ArgsWrongSignature(IFoo fake, Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 3 parameters is configured with an arguments predicate with an incompatible signature"
.x(() => exception = Record.Exception(
() => A.CallTo(() => fake.Bar(0, string.Empty, false))
.WhenArgumentsMatch((long a, DateTime b, Type c) => true)
.Returns(42)));
"When the method is called"
.x(() => exception = Record.Exception(() => fake.Bar(3, "hello", true)));
"Then it throws a FakeConfigurationException that describes the problem"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.WithMessage("The faked method has the signature (System.Int32, System.String, System.Boolean), but when arguments match was used with (System.Int64, System.DateTime, System.Type)."));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith4ArgsSuccess(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 4 parameters is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0, string.Empty, false, new object()))
.WhenArgumentsMatch((int a, string b, bool c, object d) => a % 2 == 0 && b.Length < 3 && c && d is not null)
.Returns(42));
"When the method is called with arguments that satisfy the predicate"
.x(() => result = fake.Bar(4, "x", true, new object()));
"Then it returns the configured value"
.x(() => result.Should().Be(42));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith4ArgsFailure(IFoo fake, int result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 4 parameters is configured to return a value when the arguments match a predicate"
.x(() => A.CallTo(() => fake.Bar(0, string.Empty, false, new object()))
.WhenArgumentsMatch((int a, string b, bool c, object d) => a % 2 == 0 && b.Length < 3 && c && d is not null)
.Returns(42));
"When the method is called with arguments that don't satisfy the predicate"
.x(() => result = fake.Bar(3, "hello", false, new object()));
"Then it returns the default value"
.x(() => result.Should().Be(0));
}
[Scenario]
public static void StronglyTypedWhenArgumentsMatchWith4ArgsWrongSignature(IFoo fake, Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And a fake method with 4 parameters is configured with an arguments predicate with an incompatible signature"
.x(() => exception = Record.Exception(
() => A.CallTo(() => fake.Bar(0, string.Empty, false, new object()))
.WhenArgumentsMatch((long a, DateTime b, Type c, char d) => true)
.Returns(42)));
"When the method is called"
.x(() => exception = Record.Exception(() => fake.Bar(3, "hello", true, new object())));
"Then it throws a FakeConfigurationException that describes the problem"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.WithMessage("The faked method has the signature (System.Int32, System.String, System.Boolean, System.Object), but when arguments match was used with (System.Int64, System.DateTime, System.Type, System.Char)."));
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Globalization;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// TextMessageWriter writes constraint descriptions and messages
/// in displayable form as a text stream. It tailors the display
/// of individual message components to form the standard message
/// format of NUnit assertion failure messages.
/// </summary>
public class TextMessageWriter : MessageWriter
{
#region Message Formats and Constants
private static readonly int DEFAULT_LINE_LENGTH = 78;
// Prefixes used in all failure messages. All must be the same
// length, which is held in the PrefixLength field. Should not
// contain any tabs or newline characters.
/// <summary>
/// Prefix used for the expected value line of a message
/// </summary>
public static readonly string Pfx_Expected = " Expected: ";
/// <summary>
/// Prefix used for the actual value line of a message
/// </summary>
public static readonly string Pfx_Actual = " But was: ";
/// <summary>
/// Length of a message prefix
/// </summary>
public static readonly int PrefixLength = Pfx_Expected.Length;
private static readonly string Fmt_Connector = " {0} ";
private static readonly string Fmt_Predicate = "{0} ";
//private static readonly string Fmt_Label = "{0}";
private static readonly string Fmt_Modifier = ", {0}";
private static readonly string Fmt_Null = "null";
private static readonly string Fmt_EmptyString = "<string.Empty>";
private static readonly string Fmt_EmptyCollection = "<empty>";
private static readonly string Fmt_String = "\"{0}\"";
private static readonly string Fmt_Char = "'{0}'";
private static readonly string Fmt_DateTime = "yyyy-MM-dd HH:mm:ss.fff";
private static readonly string Fmt_ValueType = "{0}";
private static readonly string Fmt_Default = "<{0}>";
#endregion
private int maxLineLength = DEFAULT_LINE_LENGTH;
#region Constructors
/// <summary>
/// Construct a TextMessageWriter
/// </summary>
public TextMessageWriter() { }
/// <summary>
/// Construct a TextMessageWriter, specifying a user message
/// and optional formatting arguments.
/// </summary>
/// <param name="userMessage"></param>
/// <param name="args"></param>
public TextMessageWriter(string userMessage, params object[] args)
{
if ( userMessage != null && userMessage != string.Empty)
this.WriteMessageLine(userMessage, args);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the maximum line length for this writer
/// </summary>
public override int MaxLineLength
{
get { return maxLineLength; }
set { maxLineLength = value; }
}
#endregion
#region Public Methods - High Level
/// <summary>
/// Method to write single line message with optional args, usually
/// written to precede the general failure message, at a givel
/// indentation level.
/// </summary>
/// <param name="level">The indentation level of the message</param>
/// <param name="message">The message to be written</param>
/// <param name="args">Any arguments used in formatting the message</param>
public override void WriteMessageLine(int level, string message, params object[] args)
{
if (message != null)
{
while (level-- >= 0) Write(" ");
if (args != null && args.Length > 0)
message = string.Format(message, args);
WriteLine(message);
}
}
/// <summary>
/// Display Expected and Actual lines for a constraint. This
/// is called by MessageWriter's default implementation of
/// WriteMessageTo and provides the generic two-line display.
/// </summary>
/// <param name="constraint">The constraint that failed</param>
public override void DisplayDifferences(Constraint constraint)
{
WriteExpectedLine(constraint);
WriteActualLine(constraint);
}
/// <summary>
/// Display Expected and Actual lines for given values. This
/// method may be called by constraints that need more control over
/// the display of actual and expected values than is provided
/// by the default implementation.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value causing the failure</param>
public override void DisplayDifferences(object expected, object actual)
{
WriteExpectedLine(expected);
WriteActualLine(actual);
}
/// <summary>
/// Display Expected and Actual lines for given values, including
/// a tolerance value on the expected line.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value causing the failure</param>
/// <param name="tolerance">The tolerance within which the test was made</param>
public override void DisplayDifferences(object expected, object actual, Tolerance tolerance)
{
WriteExpectedLine(expected, tolerance);
WriteActualLine(actual);
}
/// <summary>
/// Display the expected and actual string values on separate lines.
/// If the mismatch parameter is >=0, an additional line is displayed
/// line containing a caret that points to the mismatch point.
/// </summary>
/// <param name="expected">The expected string value</param>
/// <param name="actual">The actual string value</param>
/// <param name="mismatch">The point at which the strings don't match or -1</param>
/// <param name="ignoreCase">If true, case is ignored in string comparisons</param>
/// <param name="clipping">If true, clip the strings to fit the max line length</param>
public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping)
{
// Maximum string we can display without truncating
int maxDisplayLength = MaxLineLength
- PrefixLength // Allow for prefix
- 2; // 2 quotation marks
if ( clipping )
MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch);
expected = MsgUtils.EscapeControlChars(expected);
actual = MsgUtils.EscapeControlChars(actual);
// The mismatch position may have changed due to clipping or white space conversion
mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase);
Write( Pfx_Expected );
WriteExpectedValue( expected );
if ( ignoreCase )
WriteModifier( "ignoring case" );
WriteLine();
WriteActualLine( actual );
//DisplayDifferences(expected, actual);
if (mismatch >= 0)
WriteCaretLine(mismatch);
}
#endregion
#region Public Methods - Low Level
/// <summary>
/// Writes the text for a connector.
/// </summary>
/// <param name="connector">The connector.</param>
public override void WriteConnector(string connector)
{
Write(Fmt_Connector, connector);
}
/// <summary>
/// Writes the text for a predicate.
/// </summary>
/// <param name="predicate">The predicate.</param>
public override void WritePredicate(string predicate)
{
Write(Fmt_Predicate, predicate);
}
//public override void WriteLabel(string label)
//{
// Write(Fmt_Label, label);
//}
/// <summary>
/// Write the text for a modifier.
/// </summary>
/// <param name="modifier">The modifier.</param>
public override void WriteModifier(string modifier)
{
Write(Fmt_Modifier, modifier);
}
/// <summary>
/// Writes the text for an expected value.
/// </summary>
/// <param name="expected">The expected value.</param>
public override void WriteExpectedValue(object expected)
{
WriteValue(expected);
}
/// <summary>
/// Writes the text for an actual value.
/// </summary>
/// <param name="actual">The actual value.</param>
public override void WriteActualValue(object actual)
{
WriteValue(actual);
}
/// <summary>
/// Writes the text for a generalized value.
/// </summary>
/// <param name="val">The value.</param>
public override void WriteValue(object val)
{
if (val == null)
Write(Fmt_Null);
else if (val.GetType().IsArray)
WriteArray((Array)val);
else if (val is ICollection)
WriteCollectionElements((ICollection)val, 0, 10);
else if (val is string)
WriteString((string)val);
else if (val is char)
WriteChar((char)val);
else if (val is double)
WriteDouble((double)val);
else if (val is float)
WriteFloat((float)val);
else if (val is decimal)
WriteDecimal((decimal)val);
else if (val is DateTime)
WriteDateTime((DateTime)val);
else if (val.GetType().IsValueType)
Write(Fmt_ValueType, val);
else
Write(Fmt_Default, val);
}
/// <summary>
/// Writes the text for a collection value,
/// starting at a particular point, to a max length
/// </summary>
/// <param name="collection">The collection containing elements to write.</param>
/// <param name="start">The starting point of the elements to write</param>
/// <param name="max">The maximum number of elements to write</param>
public override void WriteCollectionElements(ICollection collection, int start, int max)
{
if ( collection.Count == 0 )
{
Write(Fmt_EmptyCollection);
return;
}
int count = 0;
int index = 0;
Write("< ");
foreach (object obj in collection)
{
if ( index++ >= start )
{
if (count > 0)
Write(", ");
WriteValue(obj);
if ( ++count >= max )
break;
}
}
if ( index < collection.Count )
Write("...");
Write(" >");
}
private void WriteArray(Array array)
{
if ( array.Length == 0 )
{
Write( Fmt_EmptyCollection );
return;
}
int rank = array.Rank;
int[] products = new int[rank];
for (int product = 1, r = rank; --r >= 0; )
products[r] = product *= array.GetLength(r);
int count = 0;
foreach (object obj in array)
{
if (count > 0)
Write(", ");
bool startSegment = false;
for (int r = 0; r < rank; r++)
{
startSegment = startSegment || count % products[r] == 0;
if (startSegment) Write("< ");
}
WriteValue(obj);
++count;
bool nextSegment = false;
for (int r = 0; r < rank; r++)
{
nextSegment = nextSegment || count % products[r] == 0;
if (nextSegment) Write(" >");
}
}
}
private void WriteString(string s)
{
if (s == string.Empty)
Write(Fmt_EmptyString);
else
Write(Fmt_String, s);
}
private void WriteChar(char c)
{
Write(Fmt_Char, c);
}
private void WriteDouble(double d)
{
if (double.IsNaN(d) || double.IsInfinity(d))
Write(d);
else
{
string s = d.ToString("G17", CultureInfo.InvariantCulture);
if (s.IndexOf('.') > 0)
Write(s + "d");
else
Write(s + ".0d");
}
}
private void WriteFloat(float f)
{
if (float.IsNaN(f) || float.IsInfinity(f))
Write(f);
else
{
string s = f.ToString("G9", CultureInfo.InvariantCulture);
if (s.IndexOf('.') > 0)
Write(s + "f");
else
Write(s + ".0f");
}
}
private void WriteDecimal(Decimal d)
{
Write(d.ToString("G29", CultureInfo.InvariantCulture) + "m");
}
private void WriteDateTime(DateTime dt)
{
Write(dt.ToString(Fmt_DateTime, CultureInfo.InvariantCulture));
}
#endregion
#region Helper Methods
/// <summary>
/// Write the generic 'Expected' line for a constraint
/// </summary>
/// <param name="constraint">The constraint that failed</param>
private void WriteExpectedLine(Constraint constraint)
{
Write(Pfx_Expected);
constraint.WriteDescriptionTo(this);
WriteLine();
}
/// <summary>
/// Write the generic 'Expected' line for a given value
/// </summary>
/// <param name="expected">The expected value</param>
private void WriteExpectedLine(object expected)
{
WriteExpectedLine(expected, null);
}
/// <summary>
/// Write the generic 'Expected' line for a given value
/// and tolerance.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="tolerance">The tolerance within which the test was made</param>
private void WriteExpectedLine(object expected, Tolerance tolerance)
{
Write(Pfx_Expected);
WriteExpectedValue(expected);
if (tolerance != null && !tolerance.IsEmpty)
{
WriteConnector("+/-");
WriteExpectedValue(tolerance.Value);
}
WriteLine();
}
/// <summary>
/// Write the generic 'Actual' line for a constraint
/// </summary>
/// <param name="constraint">The constraint for which the actual value is to be written</param>
private void WriteActualLine(Constraint constraint)
{
Write(Pfx_Actual);
constraint.WriteActualValueTo(this);
WriteLine();
}
/// <summary>
/// Write the generic 'Actual' line for a given value
/// </summary>
/// <param name="actual">The actual value causing a failure</param>
private void WriteActualLine(object actual)
{
Write(Pfx_Actual);
WriteActualValue(actual);
WriteLine();
}
private void WriteCaretLine(int mismatch)
{
// We subtract 2 for the initial 2 blanks and add back 1 for the initial quote
WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1));
}
#endregion
}
}
| |
using RefactoringEssentials.CSharp.Diagnostics;
using Xunit;
namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
public class FunctionNeverReturnsTests : CSharpDiagnosticTestBase
{
[Fact]
public void TestEnd()
{
var input = @"
class TestClass
{
void TestMethod ()
{
int i = 1;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestReturn()
{
var input = @"
class TestClass
{
void TestMethod ()
{
return;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestThrow()
{
var input = @"
class TestClass
{
void TestMethod ()
{
throw new System.NotImplementedException();
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestNeverReturns()
{
var input = @"
class TestClass
{
void $TestMethod$ ()
{
while (true) ;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestIfWithoutElse()
{
var input = @"
class TestClass
{
string TestMethod (int x)
{
if (x <= 0) return ""Hi"";
return ""_"" + TestMethod(x - 1);
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestRecursive()
{
var input = @"
class TestClass
{
void $TestMethod$ ()
{
TestMethod ();
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestRecursiveWithThis()
{
var input = @"
class TestClass
{
void $TestMethod$ ()
{
this.TestMethod();
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestNonRecursive()
{
var input = @"
class TestClass
{
void TestMethod ()
{
TestMethod (0);
}
void TestMethod (int i)
{
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestVirtualNonRecursive()
{
var input = @"
class Base
{
public Base parent;
public virtual string Result {
get { return parent.Result; }
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestOverrideNonRecursive()
{
var input = @"
class Base
{
public Base anotherInstance;
public override int GetHashCode() {
return anotherInstance.GetHashCode();
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestNonRecursiveProperty()
{
var input = @"
class TestClass
{
int foo;
int Foo
{
get { return foo; }
set
{
if (Foo != value)
foo = value;
}
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestNonRecursivePropertyWithPassingPropertyName()
{
var input = @"
class TestClass
{
private int TryProperty(string propertyName)
{
}
private void SetProperty(string propertyName, int newValue)
{
}
int Foo
{
get { return TryProperty(nameof(Foo)); }
set
{
SetProperty(nameof(Foo), value);
}
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestGetterNeverReturns()
{
var input = @"
class TestClass
{
int TestProperty
{
$get$ {
while (true) ;
}
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestRecursiveGetter()
{
var input = @"
class TestClass
{
int TestProperty
{
$get$ {
return TestProperty;
}
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestRecursiveSetter()
{
var input = @"
class TestClass
{
int TestProperty
{
$set$ {
TestProperty = value;
}
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestAutoProperty()
{
var input = @"
class TestClass
{
int TestProperty
{
get;
set;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestMethodGroupNeverReturns()
{
var input = @"
class TestClass
{
int $TestMethod$()
{
return TestMethod();
}
int TestMethod(object o)
{
return TestMethod();
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestIncrementProperty()
{
var input = @"
class TestClass
{
int TestProperty
{
$get$ { return TestProperty++; }
$set$ { TestProperty++; }
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestLambdaNeverReturns()
{
var input = @"
class TestClass
{
void TestMethod()
{
System.Action action = () $=>$ { while (true) ; };
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestDelegateNeverReturns()
{
var input = @"
class TestClass
{
void TestMethod()
{
System.Action action = $delegate$() { while (true) ; };
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void YieldBreak()
{
var input = @"
class TestClass
{
System.Collections.Generic.IEnumerable<string> TestMethod ()
{
yield break;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestDisable()
{
var input = @"
class TestClass
{
#pragma warning disable " + CSharpDiagnosticIDs.FunctionNeverReturnsAnalyzerID + @"
void TestMethod ()
{
while (true) ;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestBug254()
{
//https://github.com/icsharpcode/NRefactory/issues/254
var input = @"
class TestClass
{
int state = 0;
bool Foo()
{
return state < 10;
}
void TestMethod()
{
if (Foo()) {
++state;
TestMethod ();
}
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestSwitch()
{
//https://github.com/icsharpcode/NRefactory/issues/254
var input = @"
class TestClass
{
int foo;
void TestMethod()
{
switch (foo) {
case 0: TestMethod();
}
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestSwitchWithDefault()
{
//https://github.com/icsharpcode/NRefactory/issues/254
var input = @"
class TestClass
{
int foo;
void $TestMethod$()
{
switch (foo) {
case 0: case 1: TestMethod();
default: TestMethod();
}
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestSwitchValue()
{
//https://github.com/icsharpcode/NRefactory/issues/254
var input = @"
class TestClass
{
int foo;
int $TestMethod$()
{
switch (TestMethod()) {
case 0: return 0;
}
return 1;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestSwitchDefault_CaseReturns()
{
var input = @"
class TestClass
{
void TestSwitch(int i)
{
switch (i)
{
case 1:
return;
default:
break;
}
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestLinqFrom()
{
//https://github.com/icsharpcode/NRefactory/issues/254
var input = @"
using System.Linq;
using System.Collections.Generic;
class TestClass
{
IEnumerable<int> $TestMethod$()
{
return from y in TestMethod() select y;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestWrongLinqContexts()
{
//https://github.com/icsharpcode/NRefactory/issues/254
var input = @"
using System.Linq;
using System.Collections.Generic;
class TestClass
{
IEnumerable<int> TestMethod()
{
return from y in Enumerable.Empty<int>()
from z in TestMethod()
select y;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestForeach()
{
//https://bugzilla.xamarin.com/show_bug.cgi?id=14732
var input = @"
using System.Linq;
class TestClass
{
void TestMethod()
{
foreach (var x in new int[0])
TestMethod();
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestNoExecutionFor()
{
var input = @"
using System.Linq;
class TestClass
{
void TestMethod()
{
for (int i = 0; i < 0; ++i)
TestMethod ();
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestNullCoalescing()
{
//https://bugzilla.xamarin.com/show_bug.cgi?id=14732
var input = @"
using System.Linq;
class TestClass
{
TestClass parent;
int? value;
int TestMethod()
{
return value ?? parent.TestMethod();
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestPropertyGetterInSetter()
{
Analyze<FunctionNeverReturnsAnalyzer>(@"using System;
class TestClass
{
int a;
int Foo {
get { return 1; }
set { a = Foo; }
}
}");
}
[Fact]
public void TestRecursiveFunctionBug()
{
Analyze<FunctionNeverReturnsAnalyzer>(@"using System;
class TestClass
{
bool Foo (int i)
{
return i < 0 || Foo (i - 1);
}
}");
}
/// <summary>
/// Bug 17769 - Incorrect "method never returns" warning
/// </summary>
[Fact]
public void TestBug17769()
{
Analyze<FunctionNeverReturnsAnalyzer>(@"
using System.Linq;
class A
{
A[] list = new A[0];
public bool Test ()
{
return list.Any (t => t.Test ());
}
}
");
}
[Fact]
public void TestSelfUnregisteringEvent()
{
var input = @"
using System;
class TestClass
{
public event EventHandler SomeEvent;
void OnSomeEvent(object o, EventArgs e)
{
((TestClass) o).SomeEvent -= OnSomeEvent;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestConditionalExpression()
{
var input = @"
using System;
class TestClass
{
TestClass another;
int Test(bool recursive)
{
return recursive ? another.Test(true) : 0;
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
[Fact]
public void TestConditionalAccessExpression()
{
var input = @"
using System;
class TestClass
{
TestClass another;
void Test()
{
another?.Test();
}
}";
Analyze<FunctionNeverReturnsAnalyzer>(input);
}
}
}
| |
using System;
using System.Collections;
using ILPathways.Business;
namespace ILPathways.Utilities
{
/// <summary>
/// Class for formatting a custom menu
/// </summary>
[Serializable]
public class CustomMenu {
/// <summary>
/// Menu identifier
/// </summary>
public string MenuId
{
get { return _menuId; }
set { _menuId = value; }
}
///<exclude/>
private string _menuId = "";
/// <summary>
/// Menu name
/// </summary>
public string MenuName
{
get { return _menuName; }
set { _menuName = value; }
}
///<exclude/>
private string _menuName = "";
/// <summary>
/// Menu Title
/// </summary>
public string MenuTitle {
get { return _menuTitle; }
set { _menuTitle = value; }
}
///<exclude/>
private string _menuTitle = "";
/// <summary>
/// Set to true to show title for menu
/// </summary>
public bool ShowMenuTitle
{
get { return _showMenuTitle; }
set { _showMenuTitle = value; }
}
///<exclude/>
private bool _showMenuTitle = true;
/// <summary>
/// Main URL for the Menu
/// </summary>
public string MenuLink{
get { return _menuLink; }
set { _menuLink = value; }
}
///<exclude/>
private string _menuLink= "";
/// <summary>
/// The parent channel or menu for the current custom menu list
/// </summary>
public string ParentMenu {
get { return _parentMenu; }
set { _parentMenu = value; }
}
///<exclude/>
private string _parentMenu="";
/// <summary>
/// Indicate if the full url is the menu name
/// True - use url
/// False - use parent channel name
/// </summary>
public bool UsingUrlAsMenuName
{
get { return _usingUrlAsMenuName; }
set { _usingUrlAsMenuName = value; }
}
///<exclude/>
private bool _usingUrlAsMenuName = false;
/// <summary>
/// Get/Set for _addRemoveMenuItem - true means add a remove menu item at bottom of menu
/// </summary>
public bool AddRemoveMenuItem
{
get { return _addRemoveMenuItem; }
set { _addRemoveMenuItem = value; }
}
///<exclude/>
private bool _addRemoveMenuItem = true;
/// <summary>
/// Menu Collection
/// </summary>
public ArrayList MenuItems{
get { return _menuItems; }
set { _menuItems = value; }
}
///<exclude/>
private ArrayList _menuItems = new ArrayList();
/// <summary>
/// Training Menu Collection - NOT USED - set to private
/// </summary>
private ArrayList TrainingMenuList{
get { return _trainMenuList; }
set { _trainMenuList = value; }
}
///<exclude/>
private ArrayList _trainMenuList = new ArrayList();
/// <summary>
/// Occupation ID
/// </summary>
public string OccId{
get { return _occId; }
set { _occId = value; }
}
///<exclude/>
private string _occId = "";
/// <summary>
/// Job/Career area id
/// </summary>
public string JobId{
get { return _jobId; }
set { _jobId = value; }
}
///<exclude/>
private string _jobId = "";
/// <summary>
/// Program id
/// </summary>
public string ProgId{
get { return _progId; }
set { _progId = value; }
}
///<exclude/>
private string _progId = "";
/// <summary>
/// MenuTag - used to determine if menu item should be styled as the "current" item (by checking against Request Parameter)
/// </summary>
public string MenuTag
{
get { return _menuTag; }
set { _menuTag = value; }
}
///<exclude/>
private string _menuTag = "";
///<exclude/>
private string _menuTitleStyle = "leftRailNavItem2";
private string _menuTitleStyleImg = "leftRailNavItem2Img";
private string _menuStyle2 = "leftRailNavItem3";
private string _menuStyle2Img = "leftRailNavItem3Img";
/// <summary>
/// Default constructor
/// </summary>
public CustomMenu() {
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Appends the custom menu to a passed ArrayList
/// </summary>
/// <param name="list">ArrayList to contain the custom menu</param>
/// <param name="itemCntr">Counter used to tag the menu items</param>
/// <returns>Updated ArrayList</returns>
public int AppendMenu(ArrayList list, int itemCntr) {
DataItem menuItem = new DataItem();
try {
//Add title
itemCntr ++;
DataItem titleItem = new DataItem();
titleItem.Title = this.MenuTitle;
titleItem.Url = this.MenuLink;
titleItem.param1 = _menuTitleStyle;
titleItem.param2 = _menuTitleStyleImg;
titleItem.param4 = "nav" + itemCntr.ToString();
titleItem.param3 = "NavDisabled";
list.Add(titleItem);
System.Collections.IEnumerator myEnumerator = this.MenuItems.GetEnumerator();
while ( myEnumerator.MoveNext() ) {
menuItem = myEnumerator.Current as DataItem;
itemCntr ++;
DataItem dataItem = new DataItem();
dataItem.Title = menuItem.Title;
if (menuItem.Url == "#") {
dataItem.Url = menuItem.Url;
dataItem.OnClick = menuItem.OnClick;
} else {
dataItem.Url = menuItem.Url;
dataItem.OnClick = "";
}
dataItem.param1 = _menuStyle2;
dataItem.param2 = _menuStyle2Img;
dataItem.param4 = "nav"+itemCntr.ToString();
dataItem.param3 = "NavDisabled";
list.Add(dataItem);
} // while
} catch (Exception ex) {
LoggingHelper.LogError("CustomMenu.AppendMenu:"+ex.Message);
}
return itemCntr;
} //
/// <summary>
/// Format the menu as a list
/// </summary>
/// <returns></returns>
public string AsList() {
string menuList="";
DataItem menuItem = new DataItem();
try {
//Add title
menuList += FormatMenuItem( this.MenuTitle,this.MenuLink, _menuTitleStyle);
System.Collections.IEnumerator myEnumerator = this.MenuItems.GetEnumerator();
while ( myEnumerator.MoveNext() )
{
menuItem = myEnumerator.Current as DataItem;
menuList += FormatMenuItem( menuItem, _menuStyle2);
} // while
} catch (Exception ex) {
LoggingHelper.LogError("CustomMenu.AsList:"+ex.Message);
}
return menuList;
} //
private string FormatMenuItem(string display, string url, string style) {
return "<br><a href='" + url + "' class='" + style + "' >" + display + "</a>";
} //
private string FormatMenuItem(DataItem menuItem, string style)
{
string item = "";
string onClick = "";
if ( menuItem.Url == "#" )
{
if (menuItem.OnClick.Length > 0)
onClick = "onclick=\"" + menuItem.OnClick + "\"";
}
return "<br><a href='" + menuItem.Url + onClick + "' class='" + style + "' >" + menuItem.Title + "</a>";
} //
}
}
| |
using System;
using System.Runtime.Serialization;
using Hammock.Model;
using Newtonsoft.Json;
namespace TweetSharp
{
/*
<list>
<id>2029636</id>
<name>firemen</name>
<full_name>@twitterapidocs/firemen</full_name>
<slug>firemen</slug>
<subscriber_count>0</subscriber_count>
<member_count>0</member_count>
<uri>/twitterapidocs/firemen</uri>
<mode>public</mode>
<user/>
</list>
*/
#if !SILVERLIGHT
/// <summary>
/// Represents a user-curated list of Twitter members,
/// that other users can subscribe to and see the aggregated
/// list of member tweets in a dedicated timeline.
/// </summary>
[Serializable]
#endif
#if !Smartphone && !NET20
[DataContract]
#endif
[JsonObject(MemberSerialization.OptIn)]
public class TwitterList : PropertyChangedBase, ITwitterModel
{
private long _id;
private string _name;
private string _fullName;
private string _slug;
private string _description;
private int _subscriberCount;
private int _memberCount;
private string _uri;
private string _mode;
private TwitterUser _user;
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the ID of the list.
/// </summary>
/// <value>The list ID.</value>
[DataMember]
#endif
public virtual long Id
{
get { return _id; }
set
{
if (_id == value)
{
return;
}
_id = value;
OnPropertyChanged("Id");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the descriptive name of the list.
/// </summary>
/// <value>The name.</value>
[DataMember]
#endif
public virtual string Name
{
get { return _name; }
set
{
if (_name == value)
{
return;
}
_name = value;
OnPropertyChanged("Name");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the full name of the list including the list owner.
/// </summary>
/// <value>The full name of the list.</value>
[DataMember]
#endif
public virtual string FullName
{
get { return _fullName; }
set
{
if (_fullName == value)
{
return;
}
_fullName = value;
OnPropertyChanged("FullName");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the user-supplied list description.
/// </summary>
/// <value>The list description.</value>
[DataMember]
#endif
public virtual string Description
{
get { return _description; }
set
{
if (_description == value)
{
return;
}
_description = value;
OnPropertyChanged("Description");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the list URL slug.
/// </summary>
/// <value>The list slug.</value>
[DataMember]
#endif
public virtual string Slug
{
get { return _slug; }
set
{
if (_slug == value)
{
return;
}
_slug = value;
OnPropertyChanged("Slug");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the subscriber count.
/// A subscriber follows the list's updates.
/// </summary>
/// <value>The subscriber count.</value>
[DataMember]
#endif
public virtual int SubscriberCount
{
get { return _subscriberCount; }
set
{
if (_subscriberCount == value)
{
return;
}
_subscriberCount = value;
OnPropertyChanged("SubscriberCount");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the member count.
/// A member's updates appear in the list.
/// </summary>
/// <value>The member count.</value>
[DataMember]
#endif
public virtual int MemberCount
{
get { return _memberCount; }
set
{
if (_memberCount == value)
{
return;
}
_memberCount = value;
OnPropertyChanged("MemberCount");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the URI of the list.
/// </summary>
/// <value>The URI of the list.</value>
[DataMember]
#endif
public virtual string Uri
{
get { return _uri; }
set
{
if (_uri == value)
{
return;
}
_uri = value;
OnPropertyChanged("Uri");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the mode.
/// The list can be "public", visible to everyone,
/// or "private", visible only to the authenticating user.
/// </summary>
/// <value>The mode.</value>
[DataMember]
#endif
public virtual string Mode
{
get { return _mode; }
set
{
if (_mode == value)
{
return;
}
_mode = value;
OnPropertyChanged("Mode");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the user who created the list.
/// </summary>
/// <value>The user.</value>
[DataMember]
#endif
public virtual TwitterUser User
{
get { return _user; }
set
{
if (_user == value)
{
return;
}
_user = value;
OnPropertyChanged("User");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string RawSource { get; set; }
}
}
| |
// Deflater.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace GameAnalyticsSDK.Net.Utilities.Zip.Compression
{
/// <summary>
/// This is the Deflater class. The deflater class compresses input
/// with the deflate algorithm described in RFC 1951. It has several
/// compression levels and three different strategies described below.
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of deflate and setInput.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class Deflater
{
/// <summary>
/// The best and slowest compression level. This tries to find very
/// long and distant string repetitions.
/// </summary>
public static int BEST_COMPRESSION = 9;
/// <summary>
/// The worst but fastest compression level.
/// </summary>
public static int BEST_SPEED = 1;
/// <summary>
/// The default compression level.
/// </summary>
public static int DEFAULT_COMPRESSION = -1;
/// <summary>
/// This level won't compress at all but output uncompressed blocks.
/// </summary>
public static int NO_COMPRESSION = 0;
/// <summary>
/// The compression method. This is the only method supported so far.
/// There is no need to use this constant at all.
/// </summary>
public static int DEFLATED = 8;
/*
* The Deflater can do the following state transitions:
*
* (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---.
* / | (2) (5) |
* / v (5) |
* (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3)
* \ | (3) | ,-------'
* | | | (3) /
* v v (5) v v
* (1) -> BUSY_STATE ----> FINISHING_STATE
* | (6)
* v
* FINISHED_STATE
* \_____________________________________/
* | (7)
* v
* CLOSED_STATE
*
* (1) If we should produce a header we start in INIT_STATE, otherwise
* we start in BUSY_STATE.
* (2) A dictionary may be set only when we are in INIT_STATE, then
* we change the state as indicated.
* (3) Whether a dictionary is set or not, on the first call of deflate
* we change to BUSY_STATE.
* (4) -- intentionally left blank -- :)
* (5) FINISHING_STATE is entered, when flush() is called to indicate that
* there is no more INPUT. There are also states indicating, that
* the header wasn't written yet.
* (6) FINISHED_STATE is entered, when everything has been flushed to the
* internal pending output buffer.
* (7) At any time (7)
*
*/
private static int IS_SETDICT = 0x01;
private static int IS_FLUSHING = 0x04;
private static int IS_FINISHING = 0x08;
private static int INIT_STATE = 0x00;
private static int SETDICT_STATE = 0x01;
// private static int INIT_FINISHING_STATE = 0x08;
// private static int SETDICT_FINISHING_STATE = 0x09;
private static int BUSY_STATE = 0x10;
private static int FLUSHING_STATE = 0x14;
private static int FINISHING_STATE = 0x1c;
private static int FINISHED_STATE = 0x1e;
private static int CLOSED_STATE = 0x7f;
/// <summary>
/// Compression level.
/// </summary>
private int level;
/// <summary>
/// If true no Zlib/RFC1950 headers or footers are generated
/// </summary>
private bool noZlibHeaderOrFooter;
/// <summary>
/// The current state.
/// </summary>
private int state;
/// <summary>
/// The total bytes of output written.
/// </summary>
private long totalOut;
/// <summary>
/// The pending output.
/// </summary>
private DeflaterPending pending;
/// <summary>
/// The deflater engine.
/// </summary>
private DeflaterEngine engine;
/// <summary>
/// Creates a new deflater with default compression level.
/// </summary>
public Deflater() : this(DEFAULT_COMPRESSION, false)
{
}
/// <summary>
/// Creates a new deflater with given compression level.
/// </summary>
/// <param name="lvl">
/// the compression level, a value between NO_COMPRESSION
/// and BEST_COMPRESSION, or DEFAULT_COMPRESSION.
/// </param>
/// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
public Deflater(int lvl) : this(lvl, false)
{
}
/// <summary>
/// Creates a new deflater with given compression level.
/// </summary>
/// <param name="level">
/// the compression level, a value between NO_COMPRESSION
/// and BEST_COMPRESSION.
/// </param>
/// <param name="noZlibHeaderOrFooter">
/// true, if we should suppress the Zlib/RFC1950 header at the
/// beginning and the adler checksum at the end of the output. This is
/// useful for the GZIP/PKZIP formats.
/// </param>
/// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
public Deflater(int level, bool noZlibHeaderOrFooter)
{
if (level == DEFAULT_COMPRESSION) {
level = 6;
} else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) {
throw new ArgumentOutOfRangeException("level");
}
pending = new DeflaterPending();
engine = new DeflaterEngine(pending);
this.noZlibHeaderOrFooter = noZlibHeaderOrFooter;
SetStrategy(DeflateStrategy.Default);
SetLevel(level);
Reset();
}
/// <summary>
/// Resets the deflater. The deflater acts afterwards as if it was
/// just created with the same compression level and strategy as it
/// had before.
/// </summary>
public void Reset()
{
state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE);
totalOut = 0;
pending.Reset();
engine.Reset();
}
/// <summary>
/// Gets the current adler checksum of the data that was processed so far.
/// </summary>
public int Adler {
get {
return engine.Adler;
}
}
/// <summary>
/// Gets the number of input bytes processed so far.
/// </summary>
public int TotalIn {
get {
return engine.TotalIn;
}
}
/// <summary>
/// Gets the number of output bytes so far.
/// </summary>
public long TotalOut {
get {
return totalOut;
}
}
/// <summary>
/// Flushes the current input block. Further calls to deflate() will
/// produce enough output to inflate everything in the current input
/// block. This is not part of Sun's JDK so I have made it package
/// private. It is used by DeflaterOutputStream to implement
/// flush().
/// </summary>
public void Flush()
{
state |= IS_FLUSHING;
}
/// <summary>
/// Finishes the deflater with the current input block. It is an error
/// to give more input after this method was called. This method must
/// be called to force all bytes to be flushed.
/// </summary>
public void Finish()
{
state |= IS_FLUSHING | IS_FINISHING;
}
/// <summary>
/// Returns true if the stream was finished and no more output bytes
/// are available.
/// </summary>
public bool IsFinished {
get {
return state == FINISHED_STATE && pending.IsFlushed;
}
}
/// <summary>
/// Returns true, if the input buffer is empty.
/// You should then call setInput().
/// NOTE: This method can also return true when the stream
/// was finished.
/// </summary>
public bool IsNeedingInput {
get {
return engine.NeedsInput();
}
}
/// <summary>
/// Sets the data which should be compressed next. This should be only
/// called when needsInput indicates that more input is needed.
/// If you call setInput when needsInput() returns false, the
/// previous input that is still pending will be thrown away.
/// The given byte array should not be changed, before needsInput() returns
/// true again.
/// This call is equivalent to <code>setInput(input, 0, input.length)</code>.
/// </summary>
/// <param name="input">
/// the buffer containing the input data.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if the buffer was finished() or ended().
/// </exception>
public void SetInput(byte[] input)
{
SetInput(input, 0, input.Length);
}
/// <summary>
/// Sets the data which should be compressed next. This should be
/// only called when needsInput indicates that more input is needed.
/// The given byte array should not be changed, before needsInput() returns
/// true again.
/// </summary>
/// <param name="input">
/// the buffer containing the input data.
/// </param>
/// <param name="off">
/// the start of the data.
/// </param>
/// <param name="len">
/// the length of the data.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if the buffer was finished() or ended() or if previous input is still pending.
/// </exception>
public void SetInput(byte[] input, int off, int len)
{
if ((state & IS_FINISHING) != 0) {
throw new InvalidOperationException("finish()/end() already called");
}
engine.SetInput(input, off, len);
}
/// <summary>
/// Sets the compression level. There is no guarantee of the exact
/// position of the change, but if you call this when needsInput is
/// true the change of compression level will occur somewhere near
/// before the end of the so far given input.
/// </summary>
/// <param name="lvl">
/// the new compression level.
/// </param>
public void SetLevel(int lvl)
{
if (lvl == DEFAULT_COMPRESSION) {
lvl = 6;
} else if (lvl < NO_COMPRESSION || lvl > BEST_COMPRESSION) {
throw new ArgumentOutOfRangeException("lvl");
}
if (level != lvl) {
level = lvl;
engine.SetLevel(lvl);
}
}
/// <summary>
/// Get current compression level
/// </summary>
/// <returns>Returns the current compression level</returns>
public int GetLevel() {
return level;
}
/// <summary>
/// Sets the compression strategy. Strategy is one of
/// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact
/// position where the strategy is changed, the same as for
/// setLevel() applies.
/// </summary>
/// <param name="strategy">
/// The new compression strategy.
/// </param>
public void SetStrategy(DeflateStrategy strategy)
{
engine.Strategy = strategy;
}
/// <summary>
/// Deflates the current input block with to the given array.
/// </summary>
/// <param name="output">
/// The buffer where compressed data is stored
/// </param>
/// <returns>
/// The number of compressed bytes added to the output, or 0 if either
/// needsInput() or finished() returns true or length is zero.
/// </returns>
public int Deflate(byte[] output)
{
return Deflate(output, 0, output.Length);
}
/// <summary>
/// Deflates the current input block to the given array.
/// </summary>
/// <param name="output">
/// Buffer to store the compressed data.
/// </param>
/// <param name="offset">
/// Offset into the output array.
/// </param>
/// <param name="length">
/// The maximum number of bytes that may be stored.
/// </param>
/// <returns>
/// The number of compressed bytes added to the output, or 0 if either
/// needsInput() or finished() returns true or length is zero.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// If end() was previously called.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// If offset and/or length don't match the array length.
/// </exception>
public int Deflate(byte[] output, int offset, int length)
{
int origLength = length;
if (state == CLOSED_STATE) {
throw new InvalidOperationException("Deflater closed");
}
if (state < BUSY_STATE) {
/* output header */
int header = (DEFLATED +
((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8;
int level_flags = (level - 1) >> 1;
if (level_flags < 0 || level_flags > 3) {
level_flags = 3;
}
header |= level_flags << 6;
if ((state & IS_SETDICT) != 0) {
/* Dictionary was set */
header |= DeflaterConstants.PRESET_DICT;
}
header += 31 - (header % 31);
pending.WriteShortMSB(header);
if ((state & IS_SETDICT) != 0) {
int chksum = engine.Adler;
engine.ResetAdler();
pending.WriteShortMSB(chksum >> 16);
pending.WriteShortMSB(chksum & 0xffff);
}
state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING));
}
for (;;) {
int count = pending.Flush(output, offset, length);
offset += count;
totalOut += count;
length -= count;
if (length == 0 || state == FINISHED_STATE) {
break;
}
if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) {
if (state == BUSY_STATE) {
/* We need more input now */
return origLength - length;
} else if (state == FLUSHING_STATE) {
if (level != NO_COMPRESSION) {
/* We have to supply some lookahead. 8 bit lookahead
* is needed by the zlib inflater, and we must fill
* the next byte, so that all bits are flushed.
*/
int neededbits = 8 + ((-pending.BitCount) & 7);
while (neededbits > 0) {
/* write a static tree block consisting solely of
* an EOF:
*/
pending.WriteBits(2, 10);
neededbits -= 10;
}
}
state = BUSY_STATE;
} else if (state == FINISHING_STATE) {
pending.AlignToByte();
// Compressed data is complete. Write footer information if required.
if (!noZlibHeaderOrFooter) {
int adler = engine.Adler;
pending.WriteShortMSB(adler >> 16);
pending.WriteShortMSB(adler & 0xffff);
}
state = FINISHED_STATE;
}
}
}
return origLength - length;
}
/// <summary>
/// Sets the dictionary which should be used in the deflate process.
/// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>.
/// </summary>
/// <param name="dict">
/// the dictionary.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if setInput () or deflate () were already called or another dictionary was already set.
/// </exception>
public void SetDictionary(byte[] dict)
{
SetDictionary(dict, 0, dict.Length);
}
/// <summary>
/// Sets the dictionary which should be used in the deflate process.
/// The dictionary is a byte array containing strings that are
/// likely to occur in the data which should be compressed. The
/// dictionary is not stored in the compressed output, only a
/// checksum. To decompress the output you need to supply the same
/// dictionary again.
/// </summary>
/// <param name="dict">
/// The dictionary data
/// </param>
/// <param name="offset">
/// An offset into the dictionary.
/// </param>
/// <param name="length">
/// The length of the dictionary data to use
/// </param>
/// <exception cref="System.InvalidOperationException">
/// If setInput () or deflate () were already called or another dictionary was already set.
/// </exception>
public void SetDictionary(byte[] dict, int offset, int length)
{
if (state != INIT_STATE) {
throw new InvalidOperationException();
}
state = SETDICT_STATE;
engine.SetDictionary(dict, offset, length);
}
}
}
| |
// 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.Windows.Media.Media3D.Viewport3DVisual.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.Windows.Media.Media3D
{
sealed public partial class Viewport3DVisual : System.Windows.Media.Visual, System.Windows.Media.Composition.DUCE.IResource, MS.Internal.IVisual3DContainer
{
#region Methods and constructors
public System.Windows.Media.HitTestResult HitTest(System.Windows.Point point)
{
return default(System.Windows.Media.HitTestResult);
}
public void HitTest(System.Windows.Media.HitTestFilterCallback filterCallback, System.Windows.Media.HitTestResultCallback resultCallback, System.Windows.Media.HitTestParameters hitTestParameters)
{
}
protected override System.Windows.Media.GeometryHitTestResult HitTestCore(System.Windows.Media.GeometryHitTestParameters hitTestParameters)
{
return default(System.Windows.Media.GeometryHitTestResult);
}
void MS.Internal.IVisual3DContainer.AddChild(Visual3D child)
{
}
Visual3D MS.Internal.IVisual3DContainer.GetChild(int index)
{
return default(Visual3D);
}
int MS.Internal.IVisual3DContainer.GetChildrenCount()
{
return default(int);
}
void MS.Internal.IVisual3DContainer.RemoveChild(Visual3D child)
{
}
void MS.Internal.IVisual3DContainer.VerifyAPIReadOnly(System.Windows.DependencyObject other)
{
}
void MS.Internal.IVisual3DContainer.VerifyAPIReadOnly()
{
}
void MS.Internal.IVisual3DContainer.VerifyAPIReadWrite()
{
}
void MS.Internal.IVisual3DContainer.VerifyAPIReadWrite(System.Windows.DependencyObject other)
{
}
int System.Windows.Media.Composition.DUCE.IResource.GetChannelCount()
{
return default(int);
}
public Viewport3DVisual()
{
}
#endregion
#region Properties and indexers
public System.Windows.Media.Effects.BitmapEffect BitmapEffect
{
get
{
return default(System.Windows.Media.Effects.BitmapEffect);
}
set
{
}
}
public System.Windows.Media.Effects.BitmapEffectInput BitmapEffectInput
{
get
{
return default(System.Windows.Media.Effects.BitmapEffectInput);
}
set
{
}
}
public Camera Camera
{
get
{
return default(Camera);
}
set
{
}
}
public Visual3DCollection Children
{
get
{
return default(Visual3DCollection);
}
}
public System.Windows.Media.Geometry Clip
{
get
{
return default(System.Windows.Media.Geometry);
}
set
{
}
}
public System.Windows.Rect ContentBounds
{
get
{
return default(System.Windows.Rect);
}
}
public System.Windows.Rect DescendantBounds
{
get
{
return default(System.Windows.Rect);
}
}
public System.Windows.Vector Offset
{
get
{
return default(System.Windows.Vector);
}
set
{
}
}
public double Opacity
{
get
{
return default(double);
}
set
{
}
}
public System.Windows.Media.Brush OpacityMask
{
get
{
return default(System.Windows.Media.Brush);
}
set
{
}
}
public System.Windows.DependencyObject Parent
{
get
{
return default(System.Windows.DependencyObject);
}
}
public System.Windows.Media.Transform Transform
{
get
{
return default(System.Windows.Media.Transform);
}
set
{
}
}
public System.Windows.Rect Viewport
{
get
{
return default(System.Windows.Rect);
}
set
{
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty CameraProperty;
public readonly static System.Windows.DependencyProperty ViewportProperty;
#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.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.Diagnostics.Tests
{
public class ProcessWaitingTests : ProcessTestBase
{
[Fact]
public void MultipleProcesses_StartAllKillAllWaitAll()
{
const int Iters = 10;
Process[] processes = Enumerable.Range(0, Iters).Select(_ => CreateProcessLong()).ToArray();
foreach (Process p in processes) p.Start();
foreach (Process p in processes) p.Kill();
foreach (Process p in processes) Assert.True(p.WaitForExit(WaitInMS));
}
[Fact]
public void MultipleProcesses_SerialStartKillWait()
{
const int Iters = 10;
for (int i = 0; i < Iters; i++)
{
Process p = CreateProcessLong();
p.Start();
p.Kill();
p.WaitForExit(WaitInMS);
}
}
[Fact]
public void MultipleProcesses_ParallelStartKillWait()
{
const int Tasks = 4, ItersPerTask = 10;
Action work = () =>
{
for (int i = 0; i < ItersPerTask; i++)
{
Process p = CreateProcessLong();
p.Start();
p.Kill();
p.WaitForExit(WaitInMS);
}
};
Task.WaitAll(Enumerable.Range(0, Tasks).Select(_ => Task.Run(work)).ToArray());
}
[Theory]
[InlineData(0)] // poll
[InlineData(10)] // real timeout
public void CurrentProcess_WaitNeverCompletes(int milliseconds)
{
Assert.False(Process.GetCurrentProcess().WaitForExit(milliseconds));
}
[Fact]
public void SingleProcess_TryWaitMultipleTimesBeforeCompleting()
{
Process p = CreateProcessLong();
p.Start();
// Verify we can try to wait for the process to exit multiple times
Assert.False(p.WaitForExit(0));
Assert.False(p.WaitForExit(0));
// Then wait until it exits and concurrently kill it.
// There's a race condition here, in that we really want to test
// killing it while we're waiting, but we could end up killing it
// before hand, in which case we're simply not testing exactly
// what we wanted to test, but everything should still work.
Task.Delay(10).ContinueWith(_ => p.Kill());
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.WaitForExit(0));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task SingleProcess_WaitAfterExited(bool addHandlerBeforeStart)
{
Process p = CreateProcessLong();
p.EnableRaisingEvents = true;
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
if (addHandlerBeforeStart)
{
p.Exited += delegate { tcs.SetResult(true); };
}
p.Start();
if (!addHandlerBeforeStart)
{
p.Exited += delegate { tcs.SetResult(true); };
}
p.Kill();
Assert.True(await tcs.Task);
Assert.True(p.WaitForExit(0));
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Issue https://github.com/dotnet/corefx/issues/18210")]
[InlineData(0)]
[InlineData(1)]
[InlineData(127)]
public async Task SingleProcess_EnableRaisingEvents_CorrectExitCode(int exitCode)
{
using (Process p = RemoteInvoke(exitCodeStr => int.Parse(exitCodeStr), exitCode.ToString(), new RemoteInvokeOptions { Start = false }).Process)
{
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
p.EnableRaisingEvents = true;
p.Exited += delegate { tcs.SetResult(true); };
p.Start();
Assert.True(await tcs.Task);
Assert.Equal(exitCode, p.ExitCode);
}
}
[Fact]
public void SingleProcess_CopiesShareExitInformation()
{
Process p = CreateProcessLong();
p.Start();
Process[] copies = Enumerable.Range(0, 3).Select(_ => Process.GetProcessById(p.Id)).ToArray();
Assert.False(p.WaitForExit(0));
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
foreach (Process copy in copies)
{
Assert.True(copy.WaitForExit(0));
}
}
[Fact]
public void WaitForPeerProcess()
{
Process child1 = CreateProcessLong();
child1.Start();
Process child2 = CreateProcess(peerId =>
{
Process peer = Process.GetProcessById(int.Parse(peerId));
Console.WriteLine("Signal");
Assert.True(peer.WaitForExit(WaitInMS));
return SuccessExitCode;
}, child1.Id.ToString());
child2.StartInfo.RedirectStandardOutput = true;
child2.Start();
char[] output = new char[6];
child2.StandardOutput.Read(output, 0, output.Length);
Assert.Equal("Signal", new string(output)); // wait for the signal before killing the peer
child1.Kill();
Assert.True(child1.WaitForExit(WaitInMS));
Assert.True(child2.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, child2.ExitCode);
}
[Fact]
[ActiveIssue(15844, TestPlatforms.AnyUnix)]
public void WaitChain()
{
Process root = CreateProcess(() =>
{
Process child1 = CreateProcess(() =>
{
Process child2 = CreateProcess(() =>
{
Process child3 = CreateProcess(() => SuccessExitCode);
child3.Start();
Assert.True(child3.WaitForExit(WaitInMS));
return child3.ExitCode;
});
child2.Start();
Assert.True(child2.WaitForExit(WaitInMS));
return child2.ExitCode;
});
child1.Start();
Assert.True(child1.WaitForExit(WaitInMS));
return child1.ExitCode;
});
root.Start();
Assert.True(root.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, root.ExitCode);
}
[Fact]
public void WaitForSelfTerminatingChild()
{
Process child = CreateProcess(() =>
{
Process.GetCurrentProcess().Kill();
throw new ShouldNotBeInvokedException();
});
child.Start();
Assert.True(child.WaitForExit(WaitInMS));
Assert.NotEqual(SuccessExitCode, child.ExitCode);
}
[Fact]
public void WaitForInputIdle_NotDirected_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.WaitForInputIdle());
}
[Fact]
public void WaitForExit_NotDirected_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.WaitForExit());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using OrchardCore.ContentManagement.Display.Models;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
namespace OrchardCore.ContentManagement.Display.ContentDisplay
{
/// <summary>
/// Any concrete implementation of this class can provide shapes for any content item which has a specific Part.
/// </summary>
/// <typeparam name="TPart"></typeparam>
public abstract class ContentPartDisplayDriver<TPart> : DisplayDriverBase, IContentPartDisplayDriver where TPart : ContentPart, new()
{
private const string DisplayToken = "_Display";
private const string DisplaySeparator = "_Display__";
private ContentTypePartDefinition _typePartDefinition;
public override ShapeResult Factory(string shapeType, Func<IBuildShapeContext, ValueTask<IShape>> shapeBuilder, Func<IShape, Task> initializeAsync)
{
// e.g., HtmlBodyPart.Summary, HtmlBodyPart-BlogPost, BagPart-LandingPage-Services
// context.Shape is the ContentItem shape, we need to alter the part shape
var result = base.Factory(shapeType, shapeBuilder, initializeAsync).Prefix(Prefix);
if (_typePartDefinition != null)
{
// The stereotype is used when not displaying for a specific content type. We don't use [Stereotype] and [ContentType] at
// the same time in an alternate because a content type is always of one stereotype.
var stereotype = "";
var settings = _typePartDefinition.ContentTypeDefinition?.GetSettings<ContentTypeSettings>();
if (settings != null)
{
stereotype = settings.Stereotype;
}
if (!String.IsNullOrEmpty(stereotype) && !String.Equals("Content", stereotype, StringComparison.OrdinalIgnoreCase))
{
stereotype += "__";
}
var partName = _typePartDefinition.Name;
var partType = _typePartDefinition.PartDefinition.Name;
var contentType = _typePartDefinition.ContentTypeDefinition.Name;
var editorPartType = GetEditorShapeType(_typePartDefinition);
var displayMode = _typePartDefinition.DisplayMode();
var hasDisplayMode = !String.IsNullOrEmpty(displayMode);
// If the shape type and the field type only differ by the display mode
if (hasDisplayMode && shapeType == partType + DisplaySeparator + displayMode)
{
// Preserve the shape name regardless its differentiator
result.Name(partName);
}
if (partType == shapeType || editorPartType == shapeType)
{
// HtmlBodyPart, Services
result.Differentiator(partName);
}
else
{
// ListPart-ListPartFeed
result.Differentiator($"{partName}-{shapeType}");
}
result.Displaying(ctx =>
{
string[] displayTypes;
if (editorPartType == shapeType)
{
displayTypes = new[] { "_" + ctx.Shape.Metadata.DisplayType };
}
else
{
displayTypes = new[] { "", "_" + ctx.Shape.Metadata.DisplayType };
// [ShapeType]_[DisplayType], e.g. HtmlBodyPart.Summary, BagPart.Summary, ListPartFeed.Summary
ctx.Shape.Metadata.Alternates.Add($"{shapeType}_{ctx.Shape.Metadata.DisplayType}");
}
if (shapeType == partType || shapeType == editorPartType)
{
foreach (var displayType in displayTypes)
{
// [ContentType]_[DisplayType]__[PartType], e.g. Blog-HtmlBodyPart, LandingPage-BagPart
ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partType}");
if (!String.IsNullOrEmpty(stereotype))
{
// [Stereotype]__[DisplayType]__[PartType], e.g. Widget-ContentsMetadata
ctx.Shape.Metadata.Alternates.Add($"{stereotype}{displayType}__{partType}");
}
}
if (partType != partName)
{
foreach (var displayType in displayTypes)
{
// [ContentType]_[DisplayType]__[PartName], e.g. LandingPage-Services
ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partName}");
if (!String.IsNullOrEmpty(stereotype))
{
// [Stereotype]_[DisplayType]__[PartName], e.g. LandingPage-Services
ctx.Shape.Metadata.Alternates.Add($"{stereotype}{displayType}__{partName}");
}
}
}
}
else
{
if (hasDisplayMode)
{
// [PartType]_[DisplayType]__[DisplayMode]_Display, e.g. HtmlBodyPart-MyDisplayMode.Display.Summary
ctx.Shape.Metadata.Alternates.Add($"{partType}_{ctx.Shape.Metadata.DisplayType}__{displayMode}{DisplayToken}");
}
var lastAlternatesOfNamedPart = new List<string>();
for (var i = 0; i < displayTypes.Length; i++)
{
var displayType = displayTypes[i];
if (hasDisplayMode)
{
shapeType = $"{partType}__{displayMode}";
if (displayType == "")
{
displayType = DisplayToken;
}
else
{
shapeType += DisplayToken;
}
}
// [ContentType]_[DisplayType]__[PartType]__[ShapeType], e.g. Blog-ListPart-ListPartFeed
ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partType}__{shapeType}");
if (!String.IsNullOrEmpty(stereotype))
{
// [Stereotype]_[DisplayType]__[PartType]__[ShapeType], e.g. Blog-ListPart-ListPartFeed
ctx.Shape.Metadata.Alternates.Add($"{stereotype}{displayType}__{partType}__{shapeType}");
}
if (partType != partName)
{
// [ContentType]_[DisplayType]__[PartName]__[ShapeType], e.g. LandingPage-Services-BagPartSummary
lastAlternatesOfNamedPart.Add($"{contentType}{displayType}__{partName}__{shapeType}");
if (!String.IsNullOrEmpty(stereotype))
{
// [Stereotype]_[DisplayType]__[PartName]__[ShapeType], e.g. LandingPage-Services-BagPartSummary
lastAlternatesOfNamedPart.Add($"{stereotype}{displayType}__{partName}__{shapeType}");
}
}
}
ctx.Shape.Metadata.Alternates.AddRange(lastAlternatesOfNamedPart);
}
});
}
return result;
}
async Task<IDisplayResult> IContentPartDisplayDriver.BuildDisplayAsync(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, BuildDisplayContext context)
{
var part = contentPart as TPart;
if (part == null)
{
return null;
}
using (BuildPrefix(typePartDefinition, context.HtmlFieldPrefix))
{
_typePartDefinition = typePartDefinition;
var buildDisplayContext = new BuildPartDisplayContext(typePartDefinition, context);
var result = await DisplayAsync(part, buildDisplayContext);
_typePartDefinition = null;
return result;
}
}
async Task<IDisplayResult> IContentPartDisplayDriver.BuildEditorAsync(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, BuildEditorContext context)
{
var part = contentPart as TPart;
if (part == null)
{
return null;
}
using (BuildPrefix(typePartDefinition, context.HtmlFieldPrefix))
{
_typePartDefinition = typePartDefinition;
var buildEditorContext = new BuildPartEditorContext(typePartDefinition, context);
var result = await EditAsync(part, buildEditorContext);
_typePartDefinition = null;
return result;
}
}
async Task<IDisplayResult> IContentPartDisplayDriver.UpdateEditorAsync(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, UpdateEditorContext context)
{
var part = contentPart as TPart;
if (part == null)
{
return null;
}
using (BuildPrefix(typePartDefinition, context.HtmlFieldPrefix))
{
var updateEditorContext = new UpdatePartEditorContext(typePartDefinition, context);
var result = await UpdateAsync(part, context.Updater, updateEditorContext);
part.ContentItem.Apply(typePartDefinition.Name, part);
return result;
}
}
public virtual Task<IDisplayResult> DisplayAsync(TPart part, BuildPartDisplayContext context)
{
return Task.FromResult(Display(part, context));
}
public virtual IDisplayResult Display(TPart part, BuildPartDisplayContext context)
{
return Display(part);
}
public virtual IDisplayResult Display(TPart part)
{
return null;
}
public virtual Task<IDisplayResult> EditAsync(TPart part, BuildPartEditorContext context)
{
return Task.FromResult(Edit(part, context));
}
public virtual IDisplayResult Edit(TPart part, BuildPartEditorContext context)
{
return Edit(part);
}
public virtual IDisplayResult Edit(TPart part)
{
return null;
}
public virtual Task<IDisplayResult> UpdateAsync(TPart part, IUpdateModel updater, UpdatePartEditorContext context)
{
return UpdateAsync(part, context);
}
public virtual Task<IDisplayResult> UpdateAsync(TPart part, UpdatePartEditorContext context)
{
return UpdateAsync(part, context.Updater);
}
public virtual Task<IDisplayResult> UpdateAsync(TPart part, IUpdateModel updater)
{
return Task.FromResult<IDisplayResult>(null);
}
protected string GetEditorShapeType(string shapeType, ContentTypePartDefinition typePartDefinition)
{
var editor = typePartDefinition.Editor();
return !String.IsNullOrEmpty(editor)
? shapeType + "__" + editor
: shapeType;
}
protected string GetEditorShapeType(string shapeType, BuildPartEditorContext context)
{
return GetEditorShapeType(shapeType, context.TypePartDefinition);
}
protected string GetEditorShapeType(ContentTypePartDefinition typePartDefinition)
{
return GetEditorShapeType(typeof(TPart).Name + "_Edit", typePartDefinition);
}
protected string GetEditorShapeType(BuildPartEditorContext context)
{
return GetEditorShapeType(context.TypePartDefinition);
}
protected string GetDisplayShapeType(string shapeType, BuildPartDisplayContext context)
{
var displayMode = context.TypePartDefinition.DisplayMode();
return !String.IsNullOrEmpty(displayMode)
? shapeType + DisplaySeparator + displayMode
: shapeType;
}
protected string GetDisplayShapeType(BuildPartDisplayContext context)
{
return GetDisplayShapeType(typeof(TPart).Name, context);
}
private TempPrefix BuildPrefix(ContentTypePartDefinition typePartDefinition, string htmlFieldPrefix)
{
var tempPrefix = new TempPrefix(this, Prefix);
Prefix = typePartDefinition.Name;
if (!String.IsNullOrEmpty(htmlFieldPrefix))
{
Prefix = htmlFieldPrefix + "." + Prefix;
}
return tempPrefix;
}
/// <summary>
/// Restores the previous prefix automatically
/// </summary>
private class TempPrefix : IDisposable
{
private readonly ContentPartDisplayDriver<TPart> _driver;
private readonly string _originalPrefix;
public TempPrefix(ContentPartDisplayDriver<TPart> driver, string originalPrefix)
{
_driver = driver;
_originalPrefix = originalPrefix;
}
public void Dispose()
{
_driver.Prefix = _originalPrefix;
}
}
}
}
| |
// $begin{copyright}
//
// This file is part of WebSharper
//
// Copyright (c) 2008-2018 IntelliFactory
//
// 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.
//
// $end{copyright}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSharper.Testing;
using static WebSharper.JavaScript.Pervasives;
namespace WebSharper.CSharp.Tests
{
[JavaScript, Test("C# Arithmetic")]
class Arithmetic : TestCategory
{
[Test]
public void LiteralWithUnderscore()
{
Equal(1_024, 1024);
}
[Test]
public void Int32()
{
int x = 22;
Equal(+x, 22, "Unary plus");
Equal(-x, -22, "Unary minus");
Equal(x + 3, 25, "Addition");
Equal(x - 4, 18, "Subtraction");
Equal(x * 3, 66, "Multiplication");
Equal(x / 5, 4, "Division");
Equal(x % 5, 2, "Modulus");
Equal(x | 13, 31, "Bitwise or");
Equal(x & 13, 4, "Bitwise or");
Equal(x ^ 13, 27, "Bitwise or");
Equal(x >> 2, 5, "Shift right");
Equal(x << 2, 88, "Shift left");
IsTrue(x == 22, "Equality");
IsFalse(x == 23, "Equality");
IsTrue(x != 23, "Inequality");
IsFalse(x != 22, "Inequality");
IsTrue(x < 25, "Less than");
IsFalse(x < 22, "Less than");
IsTrue(x > 12, "Greater than");
IsFalse(x > 22, "Greater than");
IsTrue(x <= 26, "Less than or equal");
IsTrue(x <= 22, "Less than or equal");
IsTrue(x >= 14, "Greater than or equal");
IsTrue(x >= 22, "Greater than or equal");
}
[Test]
public void Long()
{
long x = 22;
Equal(+x, 22, "Unary plus");
Equal(-x, -22, "Unary minus");
Equal(x + 3, 25, "Addition");
Equal(x - 4, 18, "Subtraction");
Equal(x * 3, 66, "Multiplication");
Equal(x / 5, 4, "Division");
Equal(x % 5, 2, "Modulus");
Equal(x | 13, 31, "Bitwise or");
Equal(x & 13, 4, "Bitwise or");
Equal(x ^ 13, 27, "Bitwise or");
Equal(x >> 2, 5, "Shift right");
Equal(x << 2, 88, "Shift left");
IsTrue(x == 22, "Equality");
IsFalse(x == 23, "Equality");
IsTrue(x != 23, "Inequality");
IsFalse(x != 22, "Inequality");
IsTrue(x < 25, "Less than");
IsFalse(x < 22, "Less than");
IsTrue(x > 12, "Greater than");
IsFalse(x > 22, "Greater than");
IsTrue(x <= 26, "Less than or equal");
IsTrue(x <= 22, "Less than or equal");
IsTrue(x >= 14, "Greater than or equal");
IsTrue(x >= 22, "Greater than or equal");
}
[Test]
public void Double()
{
double x = 22.3;
Equal(+x, 22.3, "Unary plus");
Equal(-x, -22.3, "Unary minus");
ApproxEqual(x + 3.1, 25.4, "Addition");
ApproxEqual(x - 4.2, 18.1, "Subtraction");
ApproxEqual(x * 3.1, 69.13, "Multiplication");
ApproxEqual(x / 5.1, 4.372549, "Division");
ApproxEqual(x % 5.1, 1.9, "Modulus");
IsTrue(x == 22.3, "Equality");
IsFalse(x == 23, "Equality");
IsTrue(x != 23, "Inequality");
IsFalse(x != 22.3, "Inequality");
IsTrue(x < 25, "Less than");
IsFalse(x < 22.3, "Less than");
IsTrue(x > 12, "Greater than");
IsFalse(x > 22.3, "Greater than");
IsTrue(x <= 26, "Less than or equal");
IsTrue(x <= 22.3, "Less than or equal");
IsTrue(x >= 14, "Greater than or equal");
IsTrue(x >= 22.3, "Greater than or equal");
}
[Test]
public void Float()
{
float x = 22.3f;
Equal(+x, 22.3f, "Unary plus");
Equal(-x, -22.3f, "Unary minus");
ApproxEqual(x + 3.1f, 25.4f, "Addition");
ApproxEqual(x - 4.2f, 18.1f, "Subtraction");
ApproxEqual(x * 3.1f, 69.13f, "Multiplication");
ApproxEqual(x / 5.1f, 4.372549f, "Division");
ApproxEqual(x % 5.1f, 1.9f, "Modulus");
IsTrue(x == 22.3f, "Equality");
IsFalse(x == 23, "Equality");
IsTrue(x != 23, "Inequality");
IsFalse(x != 22.3f, "Inequality");
IsTrue(x < 25, "Less than");
IsFalse(x < 22.3f, "Less than");
IsTrue(x > 12, "Greater than");
IsFalse(x > 22.3f, "Greater than");
IsTrue(x <= 26, "Less than or equal");
IsTrue(x <= 22.3f, "Less than or equal");
IsTrue(x >= 14, "Greater than or equal");
IsTrue(x >= 22.3f, "Greater than or equal");
}
[Test]
public void Char()
{
Equal('a' + 2, 'c', "Addition");
Equal('c' - 2, 'a', "Subtraction");
IsTrue('a' == 'a', "Equality");
IsFalse('a' == 'c', "Equality");
IsFalse('a' != 'a', "Inequality");
IsTrue('a' != 'c', "Inequality");
IsTrue('a' < 'c', "Less than");
IsFalse('c' < 'c', "Less than");
IsTrue('c' > 'a', "Greater than");
IsFalse('c' > 'c', "Greater than");
IsTrue('a' <= 'c', "Less than or equal");
IsTrue('c' <= 'c', "Less than or equal");
IsTrue('c' >= 'a', "Greater than or equal");
IsTrue('c' >= 'c', "Greater than or equal");
}
[Test]
public void String()
{
Equal("foo" + "bar", "foobar", "Concatenation");
IsTrue("foo" == "foo", "Equality");
IsTrue("foo" != "bar", "Inequality");
Equal("foo" + 1, "foo1");
Equal(1 + "foo", "1foo");
}
[Test]
public void NullableAbsorbing()
{
int? x = 1;
int? y = null;
int? z = x + y;
IsTrue(z == null);
}
[Test]
public void CompareTo()
{
Equal((3).CompareTo(5), -1);
Equal((4).CompareTo(4), 0);
Equal((5).CompareTo(3), 1);
Equal((3.0).CompareTo(5.0), -1);
}
[Test]
public void NumEquals()
{
IsTrue((3).Equals(3));
IsTrue((3).Equals((object)3));
IsFalse((3).Equals("3"));
IsFalse((3).Equals((object)"3"));
}
[Test]
public void Bool()
{
IsTrue(true.Equals(true));
IsTrue(true.Equals((object)true));
IsTrue(true == true);
IsTrue(true != false);
IsTrue(true.GetHashCode() == true.GetHashCode());
IsTrue(true.GetHashCode() != false.GetHashCode());
Equal(true.CompareTo(false), 1);
Equal(bool.TrueString, "true");
Equal(bool.FalseString, "false");
Equal(true.ToString(), "true");
Equal(false.ToString(), "false");
IsTrue(bool.Parse("true") && bool.Parse("True"));
IsTrue(!bool.Parse("false") && !bool.Parse("False"));
}
[Test]
public void TimeSpanTest()
{
var t = TimeSpan.FromHours(1);
IsTrue(t == +t);
Equal((-t).Hours, -1);
Equal((t + t).Hours, 2);
Equal(t - t, TimeSpan.Zero);
IsTrue(t == +t);
IsTrue(t != -t);
IsTrue(t + t > t);
IsTrue(t < t + t);
IsTrue(t + t >= t);
IsTrue(t <= t + t);
}
[Test]
public void DateTimeTest()
{
var d = new System.DateTime(2017, 11, 14);
var d2 = new System.DateTime(2017, 11, 15);
var t = TimeSpan.FromHours(1);
Equal((d2 - d).Days, 1);
IsTrue(d == d + TimeSpan.Zero);
IsTrue(d != d2);
IsTrue(d + t > d);
IsTrue(d - t < d);
IsTrue(d + t >= d);
IsTrue(d <= d + t);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using ExpectedObjects.Chain.Links;
using ExpectedObjects.Strategies;
namespace ExpectedObjects
{
static class ObjectExtensions
{
internal static string ToUsefulString(this object obj, bool verbose = false)
{
if (obj is IExpectedDescription)
return obj.ToString();
string str;
if (obj == null) return "[null]";
var description = obj as Description;
if (description != null)
if (description.Value != null)
return $"{description.Label} {ToUsefulString(description.Value, verbose)}";
else
return $"{description.Label}";
if (obj.GetType() == typeof(string))
{
str = (string) obj;
if (string.IsNullOrWhiteSpace(str))
return "String.Empty";
return "\"" + str.Replace("\n", "\\n") + "\"";
}
if (obj.GetType().GetTypeInfo().IsValueType) return obj.ToObjectString();
if (obj is IEnumerable)
{
var enumerable = ((IEnumerable) obj).Cast<object>();
return $"{obj.GetType().ToUsefulTypeName()}:{Environment.NewLine}{enumerable.EachToUsefulString(verbose)}";
}
str = verbose ? obj.ToObjectString() : obj.ToString();
if (str == null || str.Trim() == "")
return $"{obj.GetType()}:[]";
if (!verbose)
{
if (str.Contains(Environment.NewLine))
return $@"{obj.GetType().ToUsefulTypeName()}:[{str.Tab()}]";
if (obj.GetType().ToString() == str)
return obj.GetType().ToUsefulTypeName();
str = $"{obj.GetType().ToUsefulTypeName()}:[{str}]";
}
return str;
}
static string EachToUsefulString<T>(this IEnumerable<T> enumerable, bool verbose = false)
{
var sb = new StringBuilder();
sb.AppendLine("{");
sb.Append(string.Join($",{Environment.NewLine}",
enumerable.Select(x => ToUsefulString(x, verbose).Tab()).Take(10).ToArray()));
if (enumerable.Count() > 10)
if (enumerable.Count() > 11)
sb.AppendLine($",{Environment.NewLine} ...({enumerable.Count() - 10} more elements)");
else
sb.AppendLine($",{Environment.NewLine}" + enumerable.Last().ToUsefulString(verbose).Tab());
else sb.AppendLine();
sb.AppendLine("}");
return sb.ToString();
}
static string Tab(this string str)
{
if (string.IsNullOrEmpty(str)) return "";
var split = str.Split(new[] {$"{Environment.NewLine}"}, StringSplitOptions.None);
var sb = new StringBuilder();
sb.Append(" " + split[0]);
foreach (var part in split.Skip(1))
{
sb.AppendLine();
sb.Append(" " + part);
}
return sb.ToString();
}
}
static class ObjectStringExtensions
{
static int _indentLevel;
public static string ToObjectString(this object o)
{
var s = o as string;
if (s != null)
return $"\"{s}\"";
return GetCSharpString(o);
}
public static string ToUsefulTypeName(this Type type)
{
if (type.IsAnonymousType())
{
return "<Anonymous>";
}
if (type.GetTypeInfo().IsGenericType)
{
var arg = type.GetGenericArguments().First().ToUsefulTypeName();
return type.Name.Replace("`1", string.Format("<{0}>", arg));
}
return type.Name;
}
static string Prefix()
{
return new string(' ', _indentLevel * 2);
}
static StringBuilder CreateObject(this object o, Stack<object> visited = null)
{
var builder = new StringBuilder();
if (visited == null)
visited = new Stack<object>();
if (visited.Contains(o))
{
builder.Append("... ");
return builder;
}
visited.Push(o);
if (_indentLevel > 0) builder.Append("new ");
builder.Append($"{o.ToUsefulClassName()}{Environment.NewLine}{Prefix()}{{ ");
_indentLevel++;
_indentLevel++;
var l = new List<string>();
foreach (var fieldInfo in o.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
{
var value = fieldInfo.GetValue(o);
if (value != null)
l.Add($"{Prefix()}{fieldInfo.Name} = {value.GetCSharpString(visited)}");
}
foreach (var property in o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var value = property.GetValue(o, null);
if (value != null)
l.Add($"{Prefix()}{property.Name} = {value.GetCSharpString(visited)}");
}
if (l.Any())
{
builder.Append(Environment.NewLine);
builder.Append(string.Join($",{Environment.NewLine}", l));
}
_indentLevel -= 2;
builder.Append($"{Environment.NewLine}{Prefix()}}}");
visited.Pop();
return builder;
}
static string ToUsefulClassName(this object o)
{
var type = o.GetType();
return type.ToUsefulTypeName();
}
static string GetCSharpString(this object o, Stack<object> visited = null)
{
if (o == null) return "[null]";
if (o is string)
return $"\"{o}\"";
if (o is decimal)
return $"{o}m";
if (IsNumericType(o))
return $"{o}";
if (o is Boolean)
return $"{o}";
if (o is DateTime)
return $"DateTime.Parse(\"{o}\")";
if (o is DateTimeOffset)
return $"DateTimeOffset.Parse(\"{o}\")";
if (o is IEnumerable)
return $"new {o.ToUsefulClassName()} {{ {((IEnumerable) o).GetItems(visited)}}}";
if (IsExpression(o))
return o.ToString();
return $"{o.CreateObject(visited)}";
}
public static bool IsExpression(object instance)
{
return instance.GetType().GetTypeInfo().IsSubclassOf(typeof(Expression));
}
static string GetItems(this IEnumerable items, Stack<object> visited = null)
{
var itemStrings = string.Join(",", items.Cast<object>().Select(i => i.GetCSharpString(visited)));
return itemStrings;
}
static bool IsNumericType(this object o)
{
switch (Convert.GetTypeCode(o))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
default:
return false;
}
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections;
using System.Collections.Generic;
using MindTouch.Dream;
using MindTouch.Tasking;
using MindTouch.Xml;
namespace MindTouch.Deki.Services {
using Yield = IEnumerator<IYield>;
[DreamService("MindTouch ADO.NET Data Services Extension", "Copyright (c) 2006-2010 MindTouch Inc.",
Info = "http://developer.mindtouch.com/App_Catalog/ADONET",
SID = new string[] {
"sid://mindtouch.com/2008/02/ado.net",
"http://services.mindtouch.com/deki/draft/2008/02/ado.net"
}
)]
[DreamServiceConfig("service-uri", "string", "URI to an ADO.NET web service endpoint. (Example: http://astoria.sandbox.live.com/northwind/northwind.rse)")]
[DreamServiceConfig("username", "string?", "Username for ADO.NET data service")]
[DreamServiceConfig("password", "string?", "Password for ADO.NET data service")]
[DreamServiceBlueprint("deki/service-type", "extension")]
[DekiExtLibrary(
Label = "ADO.NET",
Namespace = "adonet",
Description = "This extension contains functions for displaying data from ADO.NET data services."
)]
[DekiExtLibraryFiles(Prefix = "MindTouch.Deki.Services.Resources", Filenames = new string[] { "sorttable.js" })]
public class AdoDotNetService : DekiExtService {
//--- Constants ---
private const string MISSING_FIELD_ERROR = "ADO.NET extension: missing configuration setting";
private const string METADATA_PATH = "$sys_GetEdmSchema";
private const double CACHE_TTL = 30;
//--- Fields ---
Plug _adoNetPlug = null;
Dictionary<string, XDoc> _cache = new Dictionary<string, XDoc>();
//--- Functions ---
[DekiExtFunction(Description = "Show results from an ADO.NET query as a table.", Transform = "pre")]
public XDoc Table(
[DekiExtParam("resource name with optional query logic. Example: Products[ProductName eq 'Chai']")] string resource,
[DekiExtParam("nested resources to expand (default: none)", true)] string expand,
[DekiExtParam("filter records by (default: return all records)", true)] string filter,
[DekiExtParam("order records by (default: none)", true)] string orderby,
[DekiExtParam("number of records to skip (default: 0)", true)] int? skip,
[DekiExtParam("number of records to return (default: 100)", true)] int? top,
[DekiExtParam("record columns to table columns mapping ({ Customer: { LastName: 'Last', FirstName: 'First' }, Order: { OrderID: 'ID'} }; default: all columns)", true)] Hashtable columns,
[DekiExtParam("URI to ADO.NET data service", true)] XUri dataservice
) {
XDoc schema;
XDoc adoNetRet = PerformQuery(dataservice, resource, expand, filter, orderby, skip ?? 0, top ?? 100, true, out schema);
XDoc result = new XDoc("html")
.Start("head")
.Start("script").Attr("type", "text/javascript").Attr("src", Files.At("sorttable.js")).End()
.Start("style").Attr("type", "text/css").Value(@".feedtable {
border:1px solid #999;
line-height:1.5em;
overflow:hidden;
width:100%;
}
.feedtable th {
background-color:#ddd;
border-bottom:1px solid #999;
font-size:14px;
}
.feedtable tr {
background-color:#FFFFFF;
}
.feedtable tr.feedroweven td {
background-color:#ededed;
}").End()
.End()
.Start("body");
if(adoNetRet.HasName("DataService")) {
foreach(XDoc resourceSet in adoNetRet.Elements) {
RenderOutput(result, resourceSet, schema, columns);
}
}
result.End();
return result;
}
[DekiExtFunction(Description = "Show single value from a query for a given column")]
public string Value(
[DekiExtParam("resource name with optional query logic. Example: Products[ProductName eq 'Chai']")] string resource,
[DekiExtParam("filter records by (default: return all records)", true)] string filter,
[DekiExtParam("record column")] string column,
[DekiExtParam("URI to ADO.NET data service", true)] XUri dataservice
) {
XDoc schema;
XDoc adoNetRet = PerformQuery(dataservice, resource, string.Empty, filter, string.Empty, 0, null, false, out schema);
return adoNetRet[string.Format(".//{0}", column)].AsText;
}
[DekiExtFunction(Description = "Show the values of a given column from a list of records")]
public ArrayList List(
[DekiExtParam("resource name with optional query logic. Example: Products[ProductName eq 'Chai']")] string resource,
[DekiExtParam("filter records by (default: return all records)", true)] string filter,
[DekiExtParam("order records by (default: none)", true)] string orderby,
[DekiExtParam("number of records to skip (default: 0)", true)] int? skip,
[DekiExtParam("number of records to return (default: 100)", true)] int? top,
[DekiExtParam("record column")] string column,
[DekiExtParam("URI to ADO.NET data service", true)] XUri dataservice
) {
XDoc schema;
XDoc adoNetRet = PerformQuery(dataservice, resource, string.Empty, filter, orderby, skip ?? 0, top ?? 100, false, out schema);
ArrayList ret = new ArrayList();
foreach (XDoc x in adoNetRet[string.Format(".//{0}", column)]) {
ret.Add(x.AsText);
}
return ret;
}
//--- Methods ---
private XDoc PerformQuery(XUri dataservice, string resource, string expand, string filter, string orderby, int? skip, int? top, bool fetchSchema, out XDoc schema) {
Plug p = _adoNetPlug;
if (dataservice != null) {
p = Plug.New(dataservice);
} else if (p == null) {
throw new ArgumentException("Missing field", "dataservice");
}
if (fetchSchema) {
schema = FetchSchema(p);
} else {
schema = null;
}
if (!string.IsNullOrEmpty(resource)) {
//HACKHACKHACK: +'s aren't treated the same way as '%20' when uri is decoded on the server side
string s = XUri.Encode(resource).Replace("+", "%20");
p = p.At(s);
}
if (!string.IsNullOrEmpty(expand)) {
p = p.With("$expand", expand);
}
if (!string.IsNullOrEmpty(filter)) {
p = p.With("$filter", filter);
}
if (!string.IsNullOrEmpty(orderby)) {
p = p.With("$orderby", orderby);
}
if (skip != null) {
p = p.With("$skip", skip.Value);
}
if (top != null) {
p = p.With("$top", top.Value);
}
XDoc ret = null;
string key = p.ToString();
lock (_cache) {
_cache.TryGetValue(key, out ret);
}
if (ret == null) {
ret = p.Get().ToDocument();
// add result to cache and start a clean-up timer
lock (_cache) {
_cache[key] = ret;
}
TaskTimer.New(TimeSpan.FromSeconds(CACHE_TTL), RemoveCachedEntry, key, TaskEnv.None);
}
return ret;
}
private XDoc RenderOutput(XDoc output, XDoc adoNetInput, XDoc schema, Hashtable columnFilter) {
KeyValuePair<string, string>[] columns;
List<string> refColumns;
string entityType = string.Empty;
//Discover entity type from collection
if (!adoNetInput.Elements.IsEmpty)
entityType = adoNetInput.Elements.Name;
if (!string.IsNullOrEmpty(entityType)) {
GetColumnsForEntityType(schema, entityType, out columns, out refColumns, columnFilter);
output = BuildTableHeader(output, columns);
foreach (XDoc resource in adoNetInput[entityType]) {
output.Start("tr");
foreach (KeyValuePair<string, string> c in columns) {
output.Start("td");
if (refColumns.Contains(c.Key)) {
//foreign key column
if (resource[c.Key]["@href"].IsEmpty) {
output = RenderOutput(output, resource[c.Key], schema, columnFilter);
} else {
// TODO (maxm): need to build a complete uri
output.Value(resource[c.Key]["@href"].AsText);
}
} else {
output.Value(resource[c.Key].AsText);
}
output.End();
}
output.End();//tr
}
output.End(); //table
}
return output;
}
private XDoc FetchSchema(Plug adoNetPlug) {
XDoc ret = null;
string key = adoNetPlug.At(METADATA_PATH).ToString();
lock (_cache) {
_cache.TryGetValue(key, out ret);
}
if (ret == null) {
string temp = adoNetPlug.At(METADATA_PATH).Get().AsTextReader().ReadToEnd();
//HACKHACKHACK to workaround ns issue
temp = temp.Replace("xmlns=\"http://schemas.microsoft.com/ado/2006/04/edm\"", "");
ret = XDocFactory.From(temp, MimeType.XML);
// add result to cache and start a clean-up timer
lock (_cache) {
_cache[key] = ret;
}
TaskTimer.New(TimeSpan.FromSeconds(CACHE_TTL), RemoveCachedEntry, key, TaskEnv.None);
}
//TODO: throw exception if schema is invalid somehow (or if the schema changed)
return ret;
}
private void GetColumnsForEntityType(XDoc schema, string entityType, out KeyValuePair<string, string>[] columns, out List<string> refColumns, Hashtable columnFilter) {
// Example: http://astoria.sandbox.live.com/northwind/northwind.rse/$sys_GetEdmSchema
XDoc entity = schema[string.Format("EntityType[@Name='{0}']", entityType)];
if (entity.IsEmpty) {
throw new ArgumentOutOfRangeException(string.Format("Could not resolve the EntityType for '{0}'", entityType));
}
Hashtable columnMapping = null;
if (columnFilter != null) {
columnMapping = columnFilter[entityType] as Hashtable;
}
List<KeyValuePair<string, string>> columnsList = new List<KeyValuePair<string, string>>();
refColumns = new List<string>();
foreach (XDoc column in entity["Property/@Name"]) {
string name = column.AsText;
string newName = name;
if (columnMapping != null) {
newName = columnMapping[name] as string;
}
if (name != null && newName != null) {
columnsList.Add(new KeyValuePair<string, string>(name, newName));
}
}
foreach (XDoc columnRef in entity["NavigationProperty/@Name"]) {
string name = columnRef.AsText;
string newName = name;
refColumns.Add(name);
if (columnMapping != null) {
newName = columnMapping[name] as string;
}
if (name != null && newName != null) {
columnsList.Add(new KeyValuePair<string, string>(name, newName));
}
}
columns = columnsList.ToArray();
}
private XDoc BuildTableHeader(XDoc doc, KeyValuePair<string, string>[] columns) {
doc.Start("table").Attr("border", 1).Attr("cellpadding", 0).Attr("cellspacing", 0).Attr("class", "feedtable sortable");
doc.Start("tr");
foreach (KeyValuePair<string, string> c in columns) {
doc.Start("th").Value(c.Value).End();//th
}
doc.End();//tr
return doc;
}
private void RemoveCachedEntry(TaskTimer timer) {
lock (_cache) {
_cache.Remove((string) timer.State);
}
}
protected override Yield Start(XDoc config, Result result) {
yield return Coroutine.Invoke(base.Start, config, new Result());
_adoNetPlug = Plug.New(config["service-uri"].AsUri);
if (_adoNetPlug != null) {
string u = config["username"].AsText;
string p = config["password"].AsText;
if (!string.IsNullOrEmpty(u) || !string.IsNullOrEmpty(p))
_adoNetPlug = _adoNetPlug.WithCredentials(u, p);
}
result.Return();
}
}
}
| |
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Sync;
using MediaBrowser.Model.Users;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Emby.ApiClient.Model;
namespace Emby.ApiClient.Data
{
public interface ILocalAssetManager
{
/// <summary>
/// Records the user action.
/// </summary>
/// <param name="action">The action.</param>
/// <returns>Task.</returns>
Task RecordUserAction(UserAction action);
/// <summary>
/// Deletes the specified action.
/// </summary>
/// <param name="action">The action.</param>
/// <returns>Task.</returns>
Task Delete(UserAction action);
/// <summary>
/// Deletes the specified item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>Task.</returns>
Task Delete(LocalItem item);
/// <summary>
/// Gets all user actions by serverId
/// </summary>
/// <param name="serverId"></param>
/// <returns></returns>
Task<IEnumerable<UserAction>> GetUserActions(string serverId);
/// <summary>
/// Adds the or update.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>Task.</returns>
Task AddOrUpdate(LocalItem item);
/// <summary>
/// Gets the files.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>Task<List<ItemFileInfo>>.</returns>
Task<List<ItemFileInfo>> GetFiles(LocalItem item);
/// <summary>
/// Deletes the specified file.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>Task.</returns>
Task DeleteFile(string path);
/// <summary>
/// Saves the subtitles.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="format">The format.</param>
/// <param name="item">The item.</param>
/// <param name="language">The language.</param>
/// <param name="isForced">if set to <c>true</c> [is forced].</param>
/// <returns>Task<System.String>.</returns>
Task<string> SaveSubtitles(Stream stream,
string format,
LocalItem item,
string language,
bool isForced);
/// <summary>
/// Saves the media.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="localItem">The local item.</param>
/// <param name="server">The server.</param>
/// <returns>Task.</returns>
Task SaveMedia(Stream stream, LocalItem localItem, ServerInfo server);
#if WINDOWS_UWP
/// <summary>
/// Saves the media.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="localItem">The local item.</param>
/// <param name="server">The server.</param>
/// <returns>Task.</returns>
Task SaveMedia(Windows.Storage.IStorageFile file, LocalItem localItem, ServerInfo server);
#endif
/// <summary>
/// Creates the local item.
/// </summary>
/// <param name="libraryItem">The library item.</param>
/// <param name="server">The server.</param>
/// <param name="syncJobItemId">The synchronize job item identifier.</param>
/// <param name="originalFileName">Name of the original file.</param>
/// <returns>LocalItem.</returns>
LocalItem CreateLocalItem(BaseItemDto libraryItem, ServerInfo server, string syncJobItemId, string originalFileName);
/// <summary>
/// Gets the local item.
/// </summary>
/// <param name="localId">The local identifier.</param>
/// <returns>Task<LocalItem>.</returns>
Task<LocalItem> GetLocalItem(string localId);
/// <summary>
/// Gets the local item.
/// </summary>
/// <param name="serverId">The server identifier.</param>
/// <param name="itemId">The item identifier.</param>
/// <returns>Task<LocalItem>.</returns>
Task<LocalItem> GetLocalItem(string serverId, string itemId);
/// <summary>
/// Files the exists.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>Task<System.Boolean>.</returns>
Task<bool> FileExists(string path);
/// <summary>
/// Gets the server item ids.
/// </summary>
/// <param name="serverId">The server identifier.</param>
/// <returns>Task<List<System.String>>.</returns>
Task<List<string>> GetServerItemIds(string serverId);
/// <summary>
/// Gets the file stream.
/// </summary>
/// <param name="info">The information.</param>
/// <returns>Task<Stream>.</returns>
Task<Stream> GetFileStream(StreamInfo info);
/// <summary>
/// Gets the file stream.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>Task<Stream>.</returns>
Task<Stream> GetFileStream(string path);
/// <summary>
/// Saves the offline user.
/// </summary>
/// <param name="user">The user.</param>
/// <returns>Task.</returns>
Task SaveOfflineUser(UserDto user);
/// <summary>
/// Deletes the offline user.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>Task.</returns>
Task DeleteOfflineUser(string id);
/// <summary>
/// Saves the user image.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="stream">The stream.</param>
/// <returns>Task.</returns>
Task SaveImage(UserDto user, Stream stream);
/// <summary>
/// Gets the user image.
/// </summary>
/// <param name="user">The user.</param>
/// <returns>Task<Stream>.</returns>
Task<Stream> GetImage(UserDto user);
/// <summary>
/// Deletes the user image.
/// </summary>
/// <param name="user">The user.</param>
/// <returns>Task.</returns>
Task DeleteImage(UserDto user);
/// <summary>
/// Determines whether the specified user has image.
/// </summary>
/// <param name="user">The user.</param>
Task<bool> HasImage(UserDto user);
/// <summary>
/// Saves the item image.
/// </summary>
/// <param name="serverId">The server identifier.</param>
/// <param name="itemId">The item identifier.</param>
/// <param name="imageId">The image identifier.</param>
/// <param name="stream">The stream.</param>
/// <returns>Task.</returns>
Task SaveImage(string serverId, string itemId, string imageId, Stream stream);
/// <summary>
/// Determines whether the specified server identifier has image.
/// </summary>
/// <param name="serverId">The server identifier.</param>
/// <param name="itemId">The item identifier.</param>
/// <param name="imageId">The image identifier.</param>
Task<bool> HasImage(string serverId, string itemId, string imageId);
/// <summary>
/// Gets the image.
/// </summary>
/// <param name="serverId">The server identifier.</param>
/// <param name="itemId">The item identifier.</param>
/// <param name="imageId">The image identifier.</param>
/// <returns>Task<Stream>.</returns>
Task<Stream> GetImage(string serverId, string itemId, string imageId);
/// <summary>
/// Determines whether the specified item has image.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="imageId">The image identifier.</param>
Task<bool> HasImage(BaseItemDto item, string imageId);
/// <summary>
/// Gets the image.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="imageId">The image identifier.</param>
/// <returns>Task<Stream>.</returns>
Task<Stream> GetImage(BaseItemDto item, string imageId);
/// <summary>
/// Gets the views.
/// </summary>
/// <param name="serverId">The server identifier.</param>
/// <param name="userId">The user identifier.</param>
/// <returns>Task<List<BaseItemDto>>.</returns>
Task<List<BaseItemDto>> GetViews(string serverId, string userId);
/// <summary>
/// Gets the items.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="parentItem">The parent item.</param>
/// <returns>Task<List<BaseItemDto>>.</returns>
Task<List<BaseItemDto>> GetItems(UserDto user, BaseItemDto parentItem);
/// <summary>
/// Gets the user.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>Task<UserDto>.</returns>
Task<UserDto> GetUser(string id);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Invio.Xunit;
using Xunit;
namespace Invio.Immutable {
[UnitTest]
public sealed class ListPropertyHandlerTests : EnumerablePropertyHandlerTestsBase {
private static ISet<PropertyInfo> properties { get; }
private static Random random { get; }
static ListPropertyHandlerTests() {
var parent = typeof(FakeImmutable);
properties = ImmutableHashSet.Create(
parent.GetProperty(nameof(FakeImmutable.Array)),
parent.GetProperty(nameof(FakeImmutable.Enumerable)),
parent.GetProperty(nameof(FakeImmutable.List)),
parent.GetProperty(nameof(FakeImmutable.Collection))
);
random = new Random();
}
public static IEnumerable<object[]> MatchingMemberData {
get {
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", "bar" },
new string[] { "foo", "bar" }
};
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", null },
new string[] { "foo", null }
};
yield return new object[] {
nameof(FakeImmutable.Enumerable),
ImmutableList.Create<object>(String.Empty, 45m, DateTime.MinValue),
new object[] { String.Empty, 45m, DateTime.MinValue }
};
yield return new object[] {
nameof(FakeImmutable.List),
new List<string> { "12345", "Hello, World", "Bananas" },
ImmutableList.Create<string>("12345", "Hello, World", "Bananas" )
};
var guid = Guid.NewGuid();
yield return new object[] {
nameof(FakeImmutable.Collection),
new List<Guid> { Guid.Empty, guid },
ImmutableList.Create(Guid.Empty, guid)
};
}
}
[Theory]
[MemberData(nameof(MatchingMemberData))]
public void GetPropertyValueHashCode_Matches(
String propertyName,
IEnumerable leftPropertyValue,
IEnumerable rightPropertyValue) {
// Arrange
var handler = this.CreateHandler(propertyName);
var leftFake = this.NextFake().SetPropertyValue(propertyName, leftPropertyValue);
var rightFake = this.NextFake().SetPropertyValue(propertyName, rightPropertyValue);
// Act
var leftHashCode = handler.GetPropertyValueHashCode(leftFake);
var rightHashCode = handler.GetPropertyValueHashCode(rightFake);
// Assert
Assert.Equal(leftHashCode, rightHashCode);
}
[Theory]
[MemberData(nameof(MatchingMemberData))]
public void ArePropertyValuesEqual_Matches(
String propertyName,
IEnumerable leftPropertyValue,
IEnumerable rightPropertyValue) {
// Arrange
var handler = this.CreateHandler(propertyName);
var leftFake = this.NextFake().SetPropertyValue(propertyName, leftPropertyValue);
var rightFake = this.NextFake().SetPropertyValue(propertyName, rightPropertyValue);
// Act
var areEqual = handler.ArePropertyValuesEqual(leftFake, rightFake);
// Assert
Assert.True(areEqual);
}
public static IEnumerable<object[]> ArePropertyValuesEqual_MismatchedValues_MemberData {
get {
// Case of 'foo' differs
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", "bar" },
new string[] { "FOO", "bar" }
};
// null vs. "foo"
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { null, "bar" },
new string[] { "foo", "bar" }
};
// DateTime.MinValue vs. null
yield return new object[] {
nameof(FakeImmutable.Enumerable),
ImmutableList.Create<object>(String.Empty, 45m, DateTime.MinValue),
new object[] { String.Empty, 45m, null }
};
// 12345 => 54321
yield return new object[] {
nameof(FakeImmutable.List),
new List<string> { "12345", "Hello, World", "Bananas" },
ImmutableList.Create<string>("54321", "Hello, World", "Bananas" )
};
// Distinct Guids
yield return new object[] {
nameof(FakeImmutable.Collection),
new List<Guid> { Guid.Empty, Guid.NewGuid() },
ImmutableList.Create(Guid.Empty, Guid.NewGuid())
};
}
}
[Theory]
[MemberData(nameof(ArePropertyValuesEqual_MismatchedValues_MemberData))]
public void ArePropertyValuesEqual_MismatchedValues(
String propertyName,
IEnumerable leftPropertyValue,
IEnumerable rightPropertyValue) {
// Arrange
var handler = this.CreateHandler(propertyName);
var leftFake = this.NextFake().SetPropertyValue(propertyName, leftPropertyValue);
var rightFake = this.NextFake().SetPropertyValue(propertyName, rightPropertyValue);
// Act
var areEqual = handler.ArePropertyValuesEqual(leftFake, rightFake);
// Assert
Assert.False(areEqual);
}
public static IEnumerable<object[]> ArePropertyValuesEqual_MismatchedOrder_MemberData {
get {
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", "bar" },
new string[] { "bar", "foo" }
};
yield return new object[] {
nameof(FakeImmutable.Enumerable),
ImmutableList.Create<object>(String.Empty, DateTime.MinValue, 45m),
new object[] { String.Empty, 45m, DateTime.MinValue }
};
yield return new object[] {
nameof(FakeImmutable.List),
new List<string> { "12345", "Hello, World", "Bananas" },
ImmutableList.Create<string>("Bananas", "12345", "Hello, World")
};
var guid = Guid.NewGuid();
yield return new object[] {
nameof(FakeImmutable.Collection),
new List<Guid> { Guid.Empty, guid },
ImmutableList.Create(guid, Guid.Empty)
};
}
}
[Theory]
[MemberData(nameof(ArePropertyValuesEqual_MismatchedOrder_MemberData))]
public void ArePropertyValuesEqual_MismatchedOrder(
String propertyName,
IEnumerable leftPropertyValue,
IEnumerable rightPropertyValue) {
// Arrange
var handler = this.CreateHandler(propertyName);
var leftFake = this.NextFake().SetPropertyValue(propertyName, leftPropertyValue);
var rightFake = this.NextFake().SetPropertyValue(propertyName, rightPropertyValue);
// Act
var areEqual = handler.ArePropertyValuesEqual(leftFake, rightFake);
// Assert
Assert.False(areEqual);
}
public static IEnumerable<object[]> ArePropertyValuesEqual_MismatchedSize_MemberData {
get {
// Jagged on left
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", "bar", "biz" },
new string[] { "foo", "bar" }
};
// Jagged on right
yield return new object[] {
nameof(FakeImmutable.Enumerable),
ImmutableList.Create<object>(String.Empty, 45m, DateTime.MinValue),
new object[] { String.Empty, 45m, DateTime.MinValue, new object() }
};
// Trailing duplicate on left
yield return new object[] {
nameof(FakeImmutable.List),
new List<string> { "12345", "Hello, World", "Bananas", "Bananas" },
ImmutableList.Create<string>("12345", "Hello, World", "Bananas" )
};
// Leading duplicate on right
var guid = Guid.NewGuid();
yield return new object[] {
nameof(FakeImmutable.Collection),
new List<Guid> { Guid.Empty, guid },
ImmutableList.Create(Guid.Empty, Guid.Empty, guid)
};
}
}
[Theory]
[MemberData(nameof(ArePropertyValuesEqual_MismatchedSize_MemberData))]
public void ArePropertyValuesEqual_MismatchedSize(
String propertyName,
IEnumerable leftPropertyValue,
IEnumerable rightPropertyValue) {
// Arrange
var handler = this.CreateHandler(propertyName);
var leftFake = this.NextFake().SetPropertyValue(propertyName, leftPropertyValue);
var rightFake = this.NextFake().SetPropertyValue(propertyName, rightPropertyValue);
// Act
var areEqual = handler.ArePropertyValuesEqual(leftFake, rightFake);
// Assert
Assert.False(areEqual);
}
protected override PropertyInfo NextValidPropertyInfo() {
return
properties
.Skip(random.Next(0, properties.Count))
.First();
}
protected override object NextParent() {
return this.NextFake();
}
private FakeImmutable NextFake() {
return new FakeImmutable(
new object[] { new object() },
ImmutableHashSet.Create(DateTime.UtcNow),
ImmutableList.Create(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()),
new HashSet<Guid> { Guid.NewGuid() }
);
}
private IPropertyHandler CreateHandler(string propertyName) {
return this.CreateHandler(typeof(FakeImmutable).GetProperty(propertyName));
}
protected override IPropertyHandler CreateHandler(PropertyInfo property) {
return new ListPropertyHandler(property);
}
private sealed class FakeImmutable : ImmutableBase<FakeImmutable> {
public object[] Array { get; }
public IEnumerable Enumerable { get; }
public IList<string> List { get; }
public ICollection<Guid> Collection { get; }
public FakeImmutable(
object[] array = default(object[]),
IEnumerable enumerable = default(IEnumerable),
IList<string> list = default(IList<string>),
ICollection<Guid> collection = default(ICollection<Guid>)) {
this.Array = array;
this.Enumerable = enumerable;
this.List = list;
this.Collection = collection;
}
public FakeImmutable SetPropertyValue(String propertyName, object propertyValue) {
return this.SetPropertyValueImpl(propertyName, propertyValue);
}
}
}
}
| |
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Apache.NMS;
using Common.Logging;
using Spring.Collections;
using Spring.Util;
using IQueue=Apache.NMS.IQueue;
namespace Spring.Messaging.Nms.Connections
{
/// <summary>
/// Wrapper for Session that caches producers and registers itself as available
/// to the session cache when being closed. Generally used for testing purposes or
/// if need to get at the wrapped Session object via the TargetSession property (for
/// vendor specific methods).
/// </summary>
/// <author>Juergen Hoeller</author>
/// <author>Mark Pollack</author>
public class CachedSession : IDecoratorSession
{
private static readonly ILog Log = LogManager.GetLogger(typeof(CachedSession));
private readonly ISession target;
private readonly List<ISession> sessionList;
private readonly int sessionCacheSize;
private readonly Dictionary<IDestination, IMessageProducer> cachedProducers = new Dictionary<IDestination, IMessageProducer>();
private readonly Dictionary<ConsumerCacheKey, IMessageConsumer> cachedConsumers = new Dictionary<ConsumerCacheKey, IMessageConsumer>();
private IMessageProducer cachedUnspecifiedDestinationMessageProducer;
private readonly bool shouldCacheProducers;
private readonly bool shouldCacheConsumers;
private bool transactionOpen = false;
private readonly CachingConnectionFactory ccf;
/// <summary>
/// Initializes a new instance of the <see cref="CachedSession"/> class.
/// </summary>
/// <param name="targetSession">The target session.</param>
/// <param name="sessionList">The session list.</param>
/// <param name="ccf">The CachingConnectionFactory.</param>
public CachedSession(
ISession targetSession,
List<ISession> sessionList,
CachingConnectionFactory ccf)
{
target = targetSession;
this.sessionList = sessionList;
sessionCacheSize = ccf.SessionCacheSize;
shouldCacheProducers = ccf.CacheProducers;
shouldCacheConsumers = ccf.CacheConsumers;
this.ccf = ccf;
}
/// <summary>
/// Gets the target, for testing purposes.
/// </summary>
/// <value>The target.</value>
public ISession TargetSession => target;
/// <summary>
/// Creates the producer, potentially returning a cached instance.
/// </summary>
/// <returns>A message producer, potentially cached.</returns>
public IMessageProducer CreateProducer()
{
if (shouldCacheProducers)
{
if (cachedUnspecifiedDestinationMessageProducer != null)
{
if (Log.IsDebugEnabled)
{
Log.Debug("Found cached MessageProducer for unspecified destination");
}
}
else
{
if (Log.IsDebugEnabled)
{
Log.Debug("Creating cached MessageProducer for unspecified destination");
}
cachedUnspecifiedDestinationMessageProducer = target.CreateProducer();
}
transactionOpen = true;
return new CachedMessageProducer(cachedUnspecifiedDestinationMessageProducer);
}
else
{
return target.CreateProducer();
}
}
/// <summary>
/// Creates the producer, potentially returning a cached instance.
/// </summary>
/// <param name="destination">The destination.</param>
/// <returns>A message producer.</returns>
public IMessageProducer CreateProducer(IDestination destination)
{
AssertUtils.ArgumentNotNull(destination,"destination");
if (shouldCacheProducers)
{
if (cachedProducers.TryGetValue(destination, out var producer))
{
if (Log.IsDebugEnabled)
{
Log.Debug("Found cached MessageProducer for destination [" + destination + "]");
}
}
else
{
producer = target.CreateProducer(destination);
if (Log.IsDebugEnabled)
{
Log.Debug("Creating cached MessageProducer for destination [" + destination + "]");
}
cachedProducers[destination] = producer;
}
transactionOpen = true;
return new CachedMessageProducer(producer);
}
else
{
return target.CreateProducer(destination);
}
}
/// <summary>
/// If have not yet reached session cache size, cache the session, otherwise
/// dispose of all cached message producers and close the session.
/// </summary>
public void Close()
{
if (ccf.IsActive)
{
//don't pass the call to the underlying target.
lock (sessionList)
{
if (sessionList.Count < sessionCacheSize)
{
LogicalClose();
// Remain open in the session list.
return;
}
}
}
// If we get here, we're supposed to shut down.
PhysicalClose();
}
private void LogicalClose()
{
// Preserve rollback-on-close semantics.
if (transactionOpen && target.Transacted)
{
transactionOpen = false;
target.Rollback();
}
// Physically close durable subscribers at time of Session close call.
var toRemove = new List<ConsumerCacheKey>();
foreach (var dictionaryEntry in cachedConsumers)
{
ConsumerCacheKey key = dictionaryEntry.Key;
if (key.Subscription != null)
{
dictionaryEntry.Value.Close();
toRemove.Add(key);
}
}
foreach (ConsumerCacheKey key in toRemove)
{
cachedConsumers.Remove(key);
}
// Allow for multiple close calls...
if (!sessionList.Contains(this))
{
if (Log.IsDebugEnabled)
{
Log.Debug("Returning cached Session: " + target);
}
sessionList.Add(this); //add to end of linked list.
}
}
private void PhysicalClose()
{
if (Log.IsDebugEnabled)
{
Log.Debug("Closing cached Session: " + target);
}
// Explicitly close all MessageProducers and MessageConsumers that
// this Session happens to cache...
try
{
foreach (var entry in cachedProducers)
{
entry.Value.Close();
}
foreach (var entry in cachedConsumers)
{
entry.Value.Close();
}
}
finally
{
// Now actually close the Session.
target.Close();
}
}
/// <summary>
/// Creates the consumer, potentially returning a cached instance.
/// </summary>
/// <param name="destination">The destination.</param>
/// <returns>A message consumer</returns>
public IMessageConsumer CreateConsumer(IDestination destination)
{
return CreateConsumer(destination, null, false, null);
}
/// <summary>
/// Creates the consumer, potentially returning a cached instance.
/// </summary>
/// <param name="destination">The destination.</param>
/// <param name="selector">The selector.</param>
/// <returns>A message consumer</returns>
public IMessageConsumer CreateConsumer(IDestination destination, string selector)
{
return CreateConsumer(destination, selector, false, null);
}
/// <summary>
/// Creates the consumer, potentially returning a cached instance.
/// </summary>
/// <param name="destination">The destination.</param>
/// <param name="selector">The selector.</param>
/// <param name="noLocal">if set to <c>true</c> [no local].</param>
/// <returns>A message consumer.</returns>
public IMessageConsumer CreateConsumer(IDestination destination, string selector, bool noLocal)
{
return CreateConsumer(destination, selector, noLocal, null);
}
/// <summary>
/// Creates the durable consumer, potentially returning a cached instance.
/// </summary>
/// <param name="destination">The destination.</param>
/// <param name="subscription">The name of the durable subscription.</param>
/// <param name="selector">The selector.</param>
/// <param name="noLocal">if set to <c>true</c> [no local].</param>
/// <returns>A message consumer</returns>
public IMessageConsumer CreateDurableConsumer(ITopic destination, string subscription, string selector, bool noLocal)
{
transactionOpen = true;
if (shouldCacheConsumers)
{
return GetCachedConsumer(destination, selector, noLocal, subscription);
}
else
{
return target.CreateDurableConsumer(destination, subscription, selector, noLocal);
}
}
/// <summary>
/// Deletes the durable consumer.
/// </summary>
/// <param name="durableSubscriptionName">The name of the durable subscription.</param>
public void DeleteDurableConsumer(string durableSubscriptionName)
{
if (shouldCacheConsumers)
{
throw new InvalidOperationException("Deleting of durable consumers is not supported when caching of consumers is enabled");
}
target.DeleteDurableConsumer(durableSubscriptionName);
}
/// <summary>
/// Creates the consumer.
/// </summary>
/// <param name="destination">The destination.</param>
/// <param name="selector">The selector.</param>
/// <param name="noLocal">if set to <c>true</c> [no local].</param>
/// <param name="durableSubscriptionName">The durable subscription name.</param>
/// <returns></returns>
protected IMessageConsumer CreateConsumer(IDestination destination, string selector, bool noLocal, string durableSubscriptionName)
{
transactionOpen = true;
if (shouldCacheConsumers)
{
return GetCachedConsumer(destination, selector, noLocal, durableSubscriptionName);
}
else
{
return target.CreateConsumer(destination, selector, noLocal);
}
}
private IMessageConsumer GetCachedConsumer(IDestination destination, string selector, bool noLocal, string durableSubscriptionName)
{
var cacheKey = new ConsumerCacheKey(destination, selector, noLocal, durableSubscriptionName);
if (cachedConsumers.TryGetValue(cacheKey, out var consumer))
{
if (Log.IsDebugEnabled)
{
Log.Debug("Found cached NMS MessageConsumer for destination [" + destination + "]: " + consumer);
}
}
else
{
if (destination is ITopic topic)
{
consumer = (durableSubscriptionName != null
? target.CreateDurableConsumer(topic, durableSubscriptionName, selector, noLocal)
: target.CreateConsumer(topic, selector, noLocal));
}
else
{
consumer = target.CreateConsumer(destination, selector);
}
if (Log.IsDebugEnabled)
{
Log.Debug("Creating cached NMS MessageConsumer for destination [" + destination + "]: " + consumer);
}
cachedConsumers[cacheKey] = consumer;
}
return new CachedMessageConsumer(consumer);
}
/// <summary>
/// Gets the queue.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public IQueue GetQueue(string name)
{
transactionOpen = true;
return target.GetQueue(name);
}
/// <summary>
/// Gets the topic.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public ITopic GetTopic(string name)
{
transactionOpen = true;
return target.GetTopic(name);
}
/// <summary>
/// Creates the temporary queue.
/// </summary>
/// <returns></returns>
public ITemporaryQueue CreateTemporaryQueue()
{
transactionOpen = true;
return target.CreateTemporaryQueue();
}
/// <summary>
/// Creates the temporary topic.
/// </summary>
/// <returns></returns>
public ITemporaryTopic CreateTemporaryTopic()
{
transactionOpen = true;
return target.CreateTemporaryTopic();
}
/// <summary>
/// Deletes the destination.
/// </summary>
/// <param name="destination">The destination.</param>
public void DeleteDestination(IDestination destination)
{
transactionOpen = true;
target.DeleteDestination(destination);
}
/// <summary>
/// Creates the message.
/// </summary>
/// <returns></returns>
public IMessage CreateMessage()
{
transactionOpen = true;
return target.CreateMessage();
}
/// <summary>
/// Creates the text message.
/// </summary>
/// <returns></returns>
public ITextMessage CreateTextMessage()
{
transactionOpen = true;
return target.CreateTextMessage();
}
/// <summary>
/// Creates the text message.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public ITextMessage CreateTextMessage(string text)
{
transactionOpen = true;
return target.CreateTextMessage(text);
}
/// <summary>
/// Creates the map message.
/// </summary>
/// <returns></returns>
public IMapMessage CreateMapMessage()
{
transactionOpen = true;
return target.CreateMapMessage();
}
/// <summary>
/// Creates the object message.
/// </summary>
/// <param name="body">The body.</param>
/// <returns></returns>
public IObjectMessage CreateObjectMessage(object body)
{
transactionOpen = true;
return target.CreateObjectMessage(body);
}
/// <summary>
/// Creates the bytes message.
/// </summary>
/// <returns></returns>
public IBytesMessage CreateBytesMessage()
{
transactionOpen = true;
return target.CreateBytesMessage();
}
/// <summary>
/// Creates the bytes message.
/// </summary>
/// <param name="body">The body.</param>
/// <returns></returns>
public IBytesMessage CreateBytesMessage(byte[] body)
{
transactionOpen = true;
return target.CreateBytesMessage(body);
}
/// <summary>
/// Creates the stream message.
/// </summary>
/// <returns></returns>
public IStreamMessage CreateStreamMessage()
{
transactionOpen = true;
return target.CreateStreamMessage();
}
/// <summary>
/// Commits this instance.
/// </summary>
public void Commit()
{
transactionOpen = false;
target.Commit();
}
/// <summary>
/// Stops all Message delivery in this session and restarts it again with the oldest unacknowledged message. Messages that were delivered
/// but not acknowledged should have their redelivered property set. This is an optional method that may not by implemented by all NMS
/// providers, if not implemented an Exception will be thrown. Message redelivery is not requried to be performed in the original
/// order. It is not valid to call this method on a Transacted Session.
/// </summary>
public void Recover()
{
transactionOpen = true;
target.Recover();
}
/// <summary>
/// Rollbacks this instance.
/// </summary>
public void Rollback()
{
transactionOpen = false;
target.Rollback();
}
/// <summary>
/// A Delegate that is called each time a Message is dispatched to allow the client to do
/// any necessary transformations on the received message before it is delivered.
/// The Session instance sets the delegate on each Consumer it creates.
/// </summary>
/// <value></value>
public ConsumerTransformerDelegate ConsumerTransformer
{
get => target.ConsumerTransformer;
set => target.ConsumerTransformer = value;
}
/// <summary>
/// A delegate that is called each time a Message is sent from this Producer which allows
/// the application to perform any needed transformations on the Message before it is sent.
/// The Session instance sets the delegate on each Producer it creates.
/// </summary>
/// <value></value>
public ProducerTransformerDelegate ProducerTransformer
{
get => target.ProducerTransformer;
set => target.ProducerTransformer = value;
}
/// <summary>
/// Gets or sets the request timeout.
/// </summary>
/// <value>The request timeout.</value>
public TimeSpan RequestTimeout
{
get => target.RequestTimeout;
set => target.RequestTimeout = value;
}
/// <summary>
/// Gets a value indicating whether this <see cref="CachedSession"/> is transacted.
/// </summary>
/// <value><c>true</c> if transacted; otherwise, <c>false</c>.</value>
public bool Transacted
{
get
{
transactionOpen = true;
return target.Transacted;
}
}
/// <summary>
/// Gets the acknowledgement mode.
/// </summary>
/// <value>The acknowledgement mode.</value>
public AcknowledgementMode AcknowledgementMode
{
get
{
transactionOpen = true;
return target.AcknowledgementMode;
}
}
/// <summary>
/// Occurs, when a transaction is started.
/// </summary>
public event SessionTxEventDelegate TransactionStartedListener
{
add => target.TransactionStartedListener += value;
remove => target.TransactionStartedListener -= value;
}
/// <summary>
/// Occurs, when a transaction is commited.
/// </summary>
public event SessionTxEventDelegate TransactionCommittedListener
{
add => target.TransactionCommittedListener += value;
remove => target.TransactionCommittedListener -= value;
}
/// <summary>
/// Occurs, when a transaction is rolled back.
/// </summary>
public event SessionTxEventDelegate TransactionRolledBackListener
{
add => target.TransactionRolledBackListener += value;
remove => target.TransactionRolledBackListener -= value;
}
/// <summary>
/// Call dispose on the target.
/// </summary>
public void Dispose()
{
transactionOpen = true;
target.Dispose();
}
/// <summary>
/// Creates the queue browser with a specified selector
/// </summary>
/// <param name="queue">The queue.</param>
/// <param name="selector">The selector.</param>
/// <returns>The Queue browser</returns>
public IQueueBrowser CreateBrowser(IQueue queue, string selector)
{
transactionOpen = true;
return target.CreateBrowser(queue, selector);
}
/// <summary>
/// Creates the queue browser.
/// </summary>
/// <param name="queue">The queue.</param>
/// <returns>The Queue browser</returns>
public IQueueBrowser CreateBrowser(IQueue queue)
{
transactionOpen = true;
return target.CreateBrowser(queue);
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return "Cached NMS Session: " + target;
}
}
internal class ConsumerCacheKey
{
private readonly IDestination destination;
private readonly string selector;
private readonly bool noLocal;
private readonly string subscription;
public ConsumerCacheKey(IDestination destination, string selector, bool noLocal, string subscription)
{
this.destination = destination;
this.selector = selector;
this.noLocal = noLocal;
this.subscription = subscription;
}
public string Subscription => subscription;
protected bool Equals(ConsumerCacheKey consumerCacheKey)
{
if (consumerCacheKey == null) return false;
if (!Equals(destination, consumerCacheKey.destination)) return false;
if (!ObjectUtils.NullSafeEquals(selector, consumerCacheKey.selector)) return false;
if (!Equals(noLocal, consumerCacheKey.noLocal)) return false;
if (!ObjectUtils.NullSafeEquals(subscription, consumerCacheKey.subscription)) return false;
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
return Equals(obj as ConsumerCacheKey);
}
public override int GetHashCode()
{
return destination.GetHashCode();
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using WOSI.Utilities;
using WOSI.CallButler.Data;
using Controls;
namespace CallButler.Manager.Controls
{
public partial class ExtensionContactControl : UserControl
{
private string numberType;
private CallButlerDataset.ExtensionContactNumbersDataTable _extContactTable;
private CallButlerDataset.ExtensionsRow extension;
private WOSI.CallButler.Data.CallButlerDataset.ExtensionsDataTable extensions;
private bool enableCallBlast;
private bool enableCallIPPhone = true;
/*public event EventHandler<ExtensionContactEventArgs> OnContactNumberChanged;
public event EventHandler<ExtensionContactEventArgs> OnPriorityChanged;
public event EventHandler<ExtensionContactEventArgs> OnTimezoneChanged;
public event EventHandler<ExtensionContactEventArgs> OnTimeoutChanged;
public event EventHandler<ExtensionContactEventArgs> OnScheduleChanged;
public event EventHandler<ExtensionContactEventArgs> OnAddContactItem;
public event EventHandler<ExtensionContactEventArgs> OnExtensionHoursCheckChanged;
public event EventHandler<ExtensionContactEventArgs> OnDeleteContactItem;*/
public ExtensionContactControl()
{
InitializeComponent();
}
public void LoadData(WOSI.CallButler.Data.CallButlerDataset.ExtensionsDataTable extensions, CallButlerDataset.ExtensionsRow extension, CallButlerDataset.ExtensionContactNumbersDataTable extensionContactTable)
{
this.extensions = extensions;
this.extension = extension;
ExtensionContactTable = extensionContactTable;
pnlFlow.Controls.Clear();
// Create our voicemail shape
VoicemailDiagramShape vds = new VoicemailDiagramShape();
vds.Dock = DockStyle.Top;
pnlFlow.Controls.Add(vds);
WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow[] contactRows = (WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow[])ExtensionContactTable.Select("ExtensionID = '" + extension.ExtensionID + "'", "Priority ASC");
foreach (WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow contactRow in contactRows)
{
AddContactControl(extensions, contactRow, false);
}
cbCallBlast.Checked = extension.UseCallBlast;
UpdateCallBlast();
}
public string NumberTypeName
{
get
{
return numberType;
}
set
{
numberType = value;
}
}
public bool EnableCallIPPhone
{
get
{
return enableCallIPPhone;
}
set
{
enableCallIPPhone = value;
}
}
public bool EnableCallBlast
{
get
{
return enableCallBlast;
}
set
{
enableCallBlast = value;
lblCallBlast.Visible = enableCallBlast;
cbCallBlast.Visible = enableCallBlast;
}
}
public WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersDataTable ExtensionContactTable
{
get
{
return _extContactTable;
}
private set
{
_extContactTable = value;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
AddContactItem();
}
private void AddContactControl(WOSI.CallButler.Data.CallButlerDataset.ExtensionsDataTable extensions, WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow contactRow, bool scrollIntoView)
{
// Create our contact number shape
FindMeNumberDiagramShape fmd = new FindMeNumberDiagramShape(extensions, contactRow);
fmd.Dock = DockStyle.Top;
fmd.NumberType = numberType;
fmd.UsingCallBlast = cbCallBlast.Checked;
fmd.EnableCallIPPhone = enableCallIPPhone;
fmd.Visible = false;
fmd.DeletePressed += new EventHandler(fmd_DeletePressed);
fmd.MoveDownPressed += new EventHandler(fmd_MoveDownPressed);
fmd.MoveUpPressed += new EventHandler(fmd_MoveUpPressed);
fmd.SizeChanged += new EventHandler(fmd_SizeChanged);
pnlFlow.Controls.Add(fmd);
pnlFlow.Controls.SetChildIndex(fmd, 1);
fmd.Visible = true;
if (scrollIntoView)
{
fmd.Expanded = true;
//pnlFlow.ScrollControlIntoView(fmd);
//pnlFlow.AutoScrollPosition = new Point(pnlFlow.AutoScrollPosition.X, fmd.Top);
}
}
void fmd_SizeChanged(object sender, EventArgs e)
{
pnlFlow.ScrollControlIntoView((FindMeNumberDiagramShape)sender);
}
void fmd_MoveUpPressed(object sender, EventArgs e)
{
ChangePriority((FindMeNumberDiagramShape)sender, -1);
}
void fmd_MoveDownPressed(object sender, EventArgs e)
{
ChangePriority((FindMeNumberDiagramShape)sender, 1);
}
void fmd_DeletePressed(object sender, EventArgs e)
{
DeleteContactItem((FindMeNumberDiagramShape)sender);
}
private void ChangePriority(FindMeNumberDiagramShape fmd, short prChange)
{
WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow contactRow = fmd.ContactRow;
short oldPriority = contactRow.Priority;
// Increase the priority of the current contactRow. Zero is highest priority.
contactRow.Priority += prChange;
// Get all or our contacts in order of priority
WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow[] contactRows = (WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow[])ExtensionContactTable.Select("ExtensionID = '" + extension.ExtensionID + "'", "Priority ASC");
foreach (WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow contact in contactRows)
{
if (contact != contactRow && contact.Priority >= contactRow.Priority)
{
contact.Priority = oldPriority;
break;
}
}
UpdatePriorityNumbers();
int childIndex = pnlFlow.Controls.GetChildIndex(fmd);
if ((prChange > 0 && childIndex > 1) || (prChange < 0 && childIndex < pnlFlow.Controls.Count))
{
childIndex -= prChange;
pnlFlow.Controls.SetChildIndex(fmd, childIndex);
}
}
private void AddContactItem()
{
// Update our current contact numbers priority and return the highest priority number
short priorityNumber = UpdatePriorityNumbers();
WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow contactRow = ExtensionContactTable.NewExtensionContactNumbersRow();
contactRow.ExtensionContactNumberID = Guid.NewGuid();
contactRow.ExtensionID = extension.ExtensionID;
contactRow.Priority = priorityNumber;
contactRow.Timeout = 20;
ExtensionContactTable.AddExtensionContactNumbersRow(contactRow);
AddContactControl(extensions, contactRow, true);
}
private void DeleteContactItem(FindMeNumberDiagramShape fmd)
{
WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow contactRow = fmd.ContactRow;
Guid extensionId = contactRow.ExtensionID;
Guid extContactId = contactRow.ExtensionContactNumberID;
contactRow.Delete();
pnlFlow.Controls.Remove(fmd);
}
private short UpdatePriorityNumbers()
{
// Get all or our contacts in order of priority
WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow[] contactRows = (WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow[])ExtensionContactTable.Select("ExtensionID = '" + extension.ExtensionID + "'", "Priority ASC");
short priorityIndex = 0;
foreach (WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow contactRow in contactRows)
{
contactRow.Priority = priorityIndex;
priorityIndex++;
}
return priorityIndex;
}
private void lblCallBlast_Click(object sender, EventArgs e)
{
cbCallBlast.Checked = !cbCallBlast.Checked;
}
private void cbCallBlast_CheckedChanged(object sender, EventArgs e)
{
extension.UseCallBlast = cbCallBlast.Checked;
UpdateCallBlast();
}
private void UpdateCallBlast()
{
foreach (Control control in pnlFlow.Controls)
{
if (control is FindMeNumberDiagramShape)
{
((FindMeNumberDiagramShape)control).UsingCallBlast = cbCallBlast.Checked;
}
}
}
}
/*public class ExtensionContactEventArgs : System.EventArgs
{
public CallButlerDataset.ExtensionContactNumbersRow ContactRow;
public ExtensionContactEventArgs(CallButlerDataset.ExtensionContactNumbersRow contactRow)
{
this.ContactRow = contactRow;
}
}*/
}
| |
#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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using System.Runtime.Serialization;
using System.Text;
#if !(NET20 || NET35)
using System.Threading.Tasks;
#endif
using System.Xml;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests
{
[TestFixture]
public class JsonConvertTest : TestFixtureBase
{
[Test]
public void DefaultSettings()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } });
StringAssert.AreEqual(@"{
""test"": [
1,
2,
3
]
}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
public class NameTableTestClass
{
public string Value { get; set; }
}
public class NameTableTestClassConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
reader.Read();
reader.Read();
JsonTextReader jsonTextReader = (JsonTextReader)reader;
Assert.IsNotNull(jsonTextReader.NameTable);
string s = serializer.Deserialize<string>(reader);
Assert.AreEqual("hi", s);
Assert.IsNotNull(jsonTextReader.NameTable);
NameTableTestClass o = new NameTableTestClass
{
Value = s
};
return o;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(NameTableTestClass);
}
}
[Test]
public void NameTableTest()
{
StringReader sr = new StringReader("{'property':'hi'}");
JsonTextReader jsonTextReader = new JsonTextReader(sr);
Assert.IsNull(jsonTextReader.NameTable);
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new NameTableTestClassConverter());
NameTableTestClass o = serializer.Deserialize<NameTableTestClass>(jsonTextReader);
Assert.IsNull(jsonTextReader.NameTable);
Assert.AreEqual("hi", o.Value);
}
[Test]
public void DefaultSettings_Example()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
Employee e = new Employee
{
FirstName = "Eric",
LastName = "Example",
BirthDate = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc),
Department = "IT",
JobTitle = "Web Dude"
};
string json = JsonConvert.SerializeObject(e);
// {
// "firstName": "Eric",
// "lastName": "Example",
// "birthDate": "1980-04-20T00:00:00Z",
// "department": "IT",
// "jobTitle": "Web Dude"
// }
StringAssert.AreEqual(@"{
""firstName"": ""Eric"",
""lastName"": ""Example"",
""birthDate"": ""1980-04-20T00:00:00Z"",
""department"": ""IT"",
""jobTitle"": ""Web Dude""
}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Override()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } }, new JsonSerializerSettings
{
Formatting = Formatting.None
});
Assert.AreEqual(@"{""test"":[1,2,3]}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Override_JsonConverterOrder()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
Converters = { new IsoDateTimeConverter { DateTimeFormat = "yyyy" } }
};
string json = JsonConvert.SerializeObject(new[] { new DateTime(2000, 12, 12, 4, 2, 4, DateTimeKind.Utc) }, new JsonSerializerSettings
{
Formatting = Formatting.None,
Converters =
{
// should take precedence
new JavaScriptDateTimeConverter(),
new IsoDateTimeConverter { DateTimeFormat = "dd" }
}
});
Assert.AreEqual(@"[new Date(976593724000)]", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Create()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
IList<int> l = new List<int> { 1, 2, 3 };
StringWriter sw = new StringWriter();
JsonSerializer serializer = JsonSerializer.CreateDefault();
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
sw = new StringWriter();
serializer.Formatting = Formatting.None;
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
sw = new StringWriter();
serializer = new JsonSerializer();
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
sw = new StringWriter();
serializer = JsonSerializer.Create();
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_CreateWithSettings()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
IList<int> l = new List<int> { 1, 2, 3 };
StringWriter sw = new StringWriter();
JsonSerializer serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
{
Converters = { new IntConverter() }
});
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
2,
4,
6
]", sw.ToString());
sw = new StringWriter();
serializer.Converters.Clear();
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
sw = new StringWriter();
serializer = JsonSerializer.Create(new JsonSerializerSettings { Formatting = Formatting.Indented });
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
public class IntConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
int i = (int)value;
writer.WriteValue(i * 2);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(int);
}
}
[Test]
public void DeserializeObject_EmptyString()
{
object result = JsonConvert.DeserializeObject(string.Empty);
Assert.IsNull(result);
}
[Test]
public void DeserializeObject_Integer()
{
object result = JsonConvert.DeserializeObject("1");
Assert.AreEqual(1L, result);
}
[Test]
public void DeserializeObject_Integer_EmptyString()
{
int? value = JsonConvert.DeserializeObject<int?>("");
Assert.IsNull(value);
}
[Test]
public void DeserializeObject_Decimal_EmptyString()
{
decimal? value = JsonConvert.DeserializeObject<decimal?>("");
Assert.IsNull(value);
}
[Test]
public void DeserializeObject_DateTime_EmptyString()
{
DateTime? value = JsonConvert.DeserializeObject<DateTime?>("");
Assert.IsNull(value);
}
[Test]
public void EscapeJavaScriptString()
{
string result;
result = JavaScriptUtils.ToEscapedJavaScriptString("How now brown cow?", '"', true);
Assert.AreEqual(@"""How now brown cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How now 'brown' cow?", '"', true);
Assert.AreEqual(@"""How now 'brown' cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How now <brown> cow?", '"', true);
Assert.AreEqual(@"""How now <brown> cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How \r\nnow brown cow?", '"', true);
Assert.AreEqual(@"""How \r\nnow brown cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007", '"', true);
Assert.AreEqual(@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007""", result);
result =
JavaScriptUtils.ToEscapedJavaScriptString("\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013", '"', true);
Assert.AreEqual(@"""\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013""", result);
result =
JavaScriptUtils.ToEscapedJavaScriptString(
"\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f ", '"', true);
Assert.AreEqual(@"""\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f """, result);
result =
JavaScriptUtils.ToEscapedJavaScriptString(
"!\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]", '"', true);
Assert.AreEqual(@"""!\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("^_`abcdefghijklmnopqrstuvwxyz{|}~", '"', true);
Assert.AreEqual(@"""^_`abcdefghijklmnopqrstuvwxyz{|}~""", result);
string data =
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
string expected =
@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""";
result = JavaScriptUtils.ToEscapedJavaScriptString(data, '"', true);
Assert.AreEqual(expected, result);
result = JavaScriptUtils.ToEscapedJavaScriptString("Fred's cat.", '\'', true);
Assert.AreEqual(result, @"'Fred\'s cat.'");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are you gentlemen?"" said Cats.", '"', true);
Assert.AreEqual(result, @"""\""How are you gentlemen?\"" said Cats.""");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are' you gentlemen?"" said Cats.", '"', true);
Assert.AreEqual(result, @"""\""How are' you gentlemen?\"" said Cats.""");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"Fred's ""cat"".", '\'', true);
Assert.AreEqual(result, @"'Fred\'s ""cat"".'");
result = JavaScriptUtils.ToEscapedJavaScriptString("\u001farray\u003caddress", '"', true);
Assert.AreEqual(result, @"""\u001farray<address""");
}
[Test]
public void EscapeJavaScriptString_UnicodeLinefeeds()
{
string result;
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u0085' + "after", '"', true);
Assert.AreEqual(@"""before\u0085after""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2028' + "after", '"', true);
Assert.AreEqual(@"""before\u2028after""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2029' + "after", '"', true);
Assert.AreEqual(@"""before\u2029after""", result);
}
[Test]
public void ToStringInvalid()
{
ExceptionAssert.Throws<ArgumentException>(() => { JsonConvert.ToString(new Version(1, 0)); }, "Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.");
}
[Test]
public void GuidToString()
{
Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
string json = JsonConvert.ToString(guid);
Assert.AreEqual(@"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""", json);
}
[Test]
public void EnumToString()
{
string json = JsonConvert.ToString(StringComparison.CurrentCultureIgnoreCase);
Assert.AreEqual("1", json);
}
[Test]
public void ObjectToString()
{
object value;
value = 1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = 1.1;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = 1.1m;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = (float)1.1;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = (short)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (long)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (byte)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (uint)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (ushort)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (sbyte)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (ulong)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""1970-01-01T00:00:00Z""", JsonConvert.ToString(value));
value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""\/Date(0)\/""", JsonConvert.ToString((DateTime)value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind));
#if !NET20
value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""1970-01-01T00:00:00+00:00""", JsonConvert.ToString(value));
value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""\/Date(0+0000)\/""", JsonConvert.ToString((DateTimeOffset)value, DateFormatHandling.MicrosoftDateFormat));
#endif
value = null;
Assert.AreEqual("null", JsonConvert.ToString(value));
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
value = DBNull.Value;
Assert.AreEqual("null", JsonConvert.ToString(value));
#endif
value = "I am a string";
Assert.AreEqual(@"""I am a string""", JsonConvert.ToString(value));
value = true;
Assert.AreEqual("true", JsonConvert.ToString(value));
value = 'c';
Assert.AreEqual(@"""c""", JsonConvert.ToString(value));
}
[Test]
public void TestInvalidStrings()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string orig = @"this is a string ""that has quotes"" ";
string serialized = JsonConvert.SerializeObject(orig);
// *** Make string invalid by stripping \" \"
serialized = serialized.Replace(@"\""", "\"");
JsonConvert.DeserializeObject<string>(serialized);
}, "Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19.");
}
[Test]
public void DeserializeValueObjects()
{
int i = JsonConvert.DeserializeObject<int>("1");
Assert.AreEqual(1, i);
#if !NET20
DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""\/Date(-59011455539000+0000)\/""");
Assert.AreEqual(new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)), d);
#endif
bool b = JsonConvert.DeserializeObject<bool>("true");
Assert.AreEqual(true, b);
object n = JsonConvert.DeserializeObject<object>("null");
Assert.AreEqual(null, n);
object u = JsonConvert.DeserializeObject<object>("undefined");
Assert.AreEqual(null, u);
}
[Test]
public void FloatToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0));
Assert.AreEqual("1.0", JsonConvert.ToString(1d));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1d));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001));
Assert.AreEqual(JsonConvert.PositiveInfinity, JsonConvert.ToString(Double.PositiveInfinity));
Assert.AreEqual(JsonConvert.NegativeInfinity, JsonConvert.ToString(Double.NegativeInfinity));
Assert.AreEqual(JsonConvert.NaN, JsonConvert.ToString(Double.NaN));
}
[Test]
public void DecimalToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1m));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11m));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111m));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111m));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111m));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111m));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1m));
Assert.AreEqual("1.0", JsonConvert.ToString(1m));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01m));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001m));
Assert.AreEqual("79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MaxValue));
Assert.AreEqual("-79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MinValue));
}
[Test]
public void StringEscaping()
{
string v = "It's a good day\r\n\"sunshine\"";
string json = JsonConvert.ToString(v);
Assert.AreEqual(@"""It's a good day\r\n\""sunshine\""""", json);
}
[Test]
public void ToStringStringEscapeHandling()
{
string v = "<b>hi " + '\u20AC' + "</b>";
string json = JsonConvert.ToString(v, '"');
Assert.AreEqual(@"""<b>hi " + '\u20AC' + @"</b>""", json);
json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeHtml);
Assert.AreEqual(@"""\u003cb\u003ehi " + '\u20AC' + @"\u003c/b\u003e""", json);
json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeNonAscii);
Assert.AreEqual(@"""<b>hi \u20ac</b>""", json);
}
[Test]
public void WriteDateTime()
{
DateTimeResult result = null;
result = TestDateTime("DateTime Max", DateTime.MaxValue);
Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateRoundtrip);
Assert.AreEqual("9999-12-31T23:59:59.9999999" + GetOffset(DateTime.MaxValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateUnspecified);
Assert.AreEqual("9999-12-31T23:59:59.9999999Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(253402300799999" + GetOffset(DateTime.MaxValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUtc);
DateTime year2000local = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local);
string localToUtcDate = year2000local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local", year2000local);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + @")\/", result.MsDateUtc);
DateTime millisecondsLocal = new DateTime(2000, 1, 1, 1, 1, 1, 999, DateTimeKind.Local);
localToUtcDate = millisecondsLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local with milliseconds", millisecondsLocal);
Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01.999", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + @")\/", result.MsDateUtc);
DateTime ticksLocal = new DateTime(634663873826822481, DateTimeKind.Local);
localToUtcDate = ticksLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local with ticks", ticksLocal);
Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2012-03-03T16:03:02.6822481", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + @")\/", result.MsDateUtc);
DateTime year2000Unspecified = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified);
result = TestDateTime("DateTime Unspecified", year2000Unspecified);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000Unspecified, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified.ToLocalTime()) + @")\/", result.MsDateUtc);
DateTime year2000Utc = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string utcTolocalDate = year2000Utc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");
result = TestDateTime("DateTime Utc", year2000Utc);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateRoundtrip);
Assert.AreEqual(utcTolocalDate + GetOffset(year2000Utc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(946688461000" + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(year2000Utc, DateTimeKind.Unspecified)) + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateUtc);
DateTime unixEpoc = new DateTime(621355968000000000, DateTimeKind.Utc);
utcTolocalDate = unixEpoc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");
result = TestDateTime("DateTime Unix Epoc", unixEpoc);
Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateRoundtrip);
Assert.AreEqual(utcTolocalDate + GetOffset(unixEpoc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("1970-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(0)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(0" + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(unixEpoc, DateTimeKind.Unspecified)) + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(0)\/", result.MsDateUtc);
result = TestDateTime("DateTime Min", DateTime.MinValue);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(DateTime.MinValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(DateTime.MinValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);
result = TestDateTime("DateTime Default", default(DateTime));
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(default(DateTime), DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(default(DateTime), DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);
#if !NET20
result = TestDateTime("DateTimeOffset TimeSpan Zero", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
Assert.AreEqual("2000-01-01T01:01:01+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946688461000+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 1 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1)));
Assert.AreEqual("2000-01-01T01:01:01+01:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946684861000+0100)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 1.5 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1.5)));
Assert.AreEqual("2000-01-01T01:01:01+01:30", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946683061000+0130)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 13 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)));
Assert.AreEqual("2000-01-01T01:01:01+13:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946641661000+1300)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan with ticks", new DateTimeOffset(634663873826822481, TimeSpan.Zero));
Assert.AreEqual("2012-03-03T16:03:02.6822481+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(1330790582682+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Min", DateTimeOffset.MinValue);
Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Max", DateTimeOffset.MaxValue);
Assert.AreEqual("9999-12-31T23:59:59.9999999+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(253402300799999+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Default", default(DateTimeOffset));
Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
#endif
}
public class DateTimeResult
{
public string IsoDateRoundtrip { get; set; }
public string IsoDateLocal { get; set; }
public string IsoDateUnspecified { get; set; }
public string IsoDateUtc { get; set; }
public string MsDateRoundtrip { get; set; }
public string MsDateLocal { get; set; }
public string MsDateUnspecified { get; set; }
public string MsDateUtc { get; set; }
}
private DateTimeResult TestDateTime<T>(string name, T value)
{
Console.WriteLine(name);
DateTimeResult result = new DateTimeResult();
result.IsoDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
if (value is DateTime)
{
result.IsoDateLocal = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Local);
result.IsoDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Unspecified);
result.IsoDateUtc = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Utc);
}
result.MsDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind);
if (value is DateTime)
{
result.MsDateLocal = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Local);
result.MsDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Unspecified);
result.MsDateUtc = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Utc);
}
TestDateTimeFormat(value, new IsoDateTimeConverter());
#if !NETFX_CORE
if (value is DateTime)
{
Console.WriteLine(XmlConvert.ToString((DateTime)(object)value, XmlDateTimeSerializationMode.RoundtripKind));
}
else
{
Console.WriteLine(XmlConvert.ToString((DateTimeOffset)(object)value));
}
#endif
#if !NET20
MemoryStream ms = new MemoryStream();
DataContractSerializer s = new DataContractSerializer(typeof(T));
s.WriteObject(ms, value);
string json = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
Console.WriteLine(json);
#endif
Console.WriteLine();
return result;
}
private static string TestDateTimeFormat<T>(T value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
string date = null;
if (value is DateTime)
{
date = JsonConvert.ToString((DateTime)(object)value, format, timeZoneHandling);
}
else
{
#if !NET20
date = JsonConvert.ToString((DateTimeOffset)(object)value, format);
#endif
}
Console.WriteLine(format.ToString("g") + "-" + timeZoneHandling.ToString("g") + ": " + date);
if (timeZoneHandling == DateTimeZoneHandling.RoundtripKind)
{
T parsed = JsonConvert.DeserializeObject<T>(date);
try
{
Assert.AreEqual(value, parsed);
}
catch (Exception)
{
long valueTicks = GetTicks(value);
long parsedTicks = GetTicks(parsed);
valueTicks = (valueTicks / 10000) * 10000;
Assert.AreEqual(valueTicks, parsedTicks);
}
}
return date.Trim('"');
}
private static void TestDateTimeFormat<T>(T value, JsonConverter converter)
{
string date = Write(value, converter);
Console.WriteLine(converter.GetType().Name + ": " + date);
T parsed = Read<T>(date, converter);
try
{
Assert.AreEqual(value, parsed);
}
catch (Exception)
{
// JavaScript ticks aren't as precise, recheck after rounding
long valueTicks = GetTicks(value);
long parsedTicks = GetTicks(parsed);
valueTicks = (valueTicks / 10000) * 10000;
Assert.AreEqual(valueTicks, parsedTicks);
}
}
public static long GetTicks(object value)
{
return (value is DateTime) ? ((DateTime)value).Ticks : ((DateTimeOffset)value).Ticks;
}
public static string Write(object value, JsonConverter converter)
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
converter.WriteJson(writer, value, null);
writer.Flush();
return sw.ToString();
}
public static T Read<T>(string text, JsonConverter converter)
{
JsonTextReader reader = new JsonTextReader(new StringReader(text));
reader.ReadAsString();
return (T)converter.ReadJson(reader, typeof(T), null, null);
}
#if !(NET20 || NET35 || PORTABLE40)
[Test]
public void Async()
{
Task<string> task = null;
#pragma warning disable 612,618
task = JsonConvert.SerializeObjectAsync(42);
#pragma warning restore 612,618
task.Wait();
Assert.AreEqual("42", task.Result);
#pragma warning disable 612,618
task = JsonConvert.SerializeObjectAsync(new[] { 1, 2, 3, 4, 5 }, Formatting.Indented);
#pragma warning restore 612,618
task.Wait();
StringAssert.AreEqual(@"[
1,
2,
3,
4,
5
]", task.Result);
#pragma warning disable 612,618
task = JsonConvert.SerializeObjectAsync(DateTime.MaxValue, Formatting.None, new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});
#pragma warning restore 612,618
task.Wait();
Assert.AreEqual(@"""\/Date(253402300799999)\/""", task.Result);
#pragma warning disable 612,618
var taskObject = JsonConvert.DeserializeObjectAsync("[]");
#pragma warning restore 612,618
taskObject.Wait();
CollectionAssert.AreEquivalent(new JArray(), (JArray)taskObject.Result);
#pragma warning disable 612,618
Task<object> taskVersionArray = JsonConvert.DeserializeObjectAsync("['2.0']", typeof(Version[]), new JsonSerializerSettings
{
Converters = { new VersionConverter() }
});
#pragma warning restore 612,618
taskVersionArray.Wait();
Version[] versionArray = (Version[])taskVersionArray.Result;
Assert.AreEqual(1, versionArray.Length);
Assert.AreEqual(2, versionArray[0].Major);
#pragma warning disable 612,618
Task<int> taskInt = JsonConvert.DeserializeObjectAsync<int>("5");
#pragma warning restore 612,618
taskInt.Wait();
Assert.AreEqual(5, taskInt.Result);
#pragma warning disable 612,618
var taskVersion = JsonConvert.DeserializeObjectAsync<Version>("'2.0'", new JsonSerializerSettings
{
Converters = { new VersionConverter() }
});
#pragma warning restore 612,618
taskVersion.Wait();
Assert.AreEqual(2, taskVersion.Result.Major);
Movie p = new Movie();
p.Name = "Existing,";
#pragma warning disable 612,618
Task taskVoid = JsonConvert.PopulateObjectAsync("{'Name':'Appended'}", p, new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new StringAppenderConverter() }
});
#pragma warning restore 612,618
taskVoid.Wait();
Assert.AreEqual("Existing,Appended", p.Name);
}
#endif
[Test]
public void SerializeObjectDateTimeZoneHandling()
{
string json = JsonConvert.SerializeObject(
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
});
Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json);
}
[Test]
public void DeserializeObject()
{
string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys
Assert.AreEqual("Bad Boys", m.Name);
}
#if !NET20
[Test]
public void TestJsonDateTimeOffsetRoundtrip()
{
var now = DateTimeOffset.Now;
var dict = new Dictionary<string, object> { { "foo", now } };
var settings = new JsonSerializerSettings();
settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
settings.DateParseHandling = DateParseHandling.DateTimeOffset;
settings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
var json = JsonConvert.SerializeObject(dict, settings);
Console.WriteLine(json);
var newDict = new Dictionary<string, object>();
JsonConvert.PopulateObject(json, newDict, settings);
var date = newDict["foo"];
Assert.AreEqual(date, now);
}
[Test]
public void MaximumDateTimeOffsetLength()
{
DateTimeOffset dt = new DateTimeOffset(2000, 12, 31, 20, 59, 59, new TimeSpan(0, 11, 33, 0, 0));
dt = dt.AddTicks(9999999);
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(dt);
writer.Flush();
Console.WriteLine(sw.ToString());
Console.WriteLine(sw.ToString().Length);
}
#endif
[Test]
public void MaximumDateTimeLength()
{
DateTime dt = new DateTime(2000, 12, 31, 20, 59, 59, DateTimeKind.Local);
dt = dt.AddTicks(9999999);
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(dt);
writer.Flush();
Console.WriteLine(sw.ToString());
Console.WriteLine(sw.ToString().Length);
}
[Test]
public void MaximumDateTimeMicrosoftDateFormatLength()
{
DateTime dt = DateTime.MaxValue;
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
writer.WriteValue(dt);
writer.Flush();
Console.WriteLine(sw.ToString());
Console.WriteLine(sw.ToString().Length);
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
[Test]
public void IntegerLengthOverflows()
{
// Maximum javascript number length (in characters) is 380
JObject o = JObject.Parse(@"{""biginteger"":" + new String('9', 380) + "}");
JValue v = (JValue)o["biginteger"];
Assert.AreEqual(JTokenType.Integer, v.Type);
Assert.AreEqual(typeof(BigInteger), v.Value.GetType());
Assert.AreEqual(BigInteger.Parse(new String('9', 380)), (BigInteger)v.Value);
ExceptionAssert.Throws<JsonReaderException>(() => JObject.Parse(@"{""biginteger"":" + new String('9', 381) + "}"), "JSON integer " + new String('9', 381) + " is too large to parse. Path 'biginteger', line 1, position 395.");
}
#endif
[Test]
public void ParseIsoDate()
{
StringReader sr = new StringReader(@"""2014-02-14T14:25:02-13:00""");
JsonReader jsonReader = new JsonTextReader(sr);
Assert.IsTrue(jsonReader.Read());
Assert.AreEqual(typeof(DateTime), jsonReader.ValueType);
}
//[Test]
public void StackOverflowTest()
{
StringBuilder sb = new StringBuilder();
int depth = 900;
for (int i = 0; i < depth; i++)
{
sb.Append("{'A':");
}
// invalid json
sb.Append("{***}");
for (int i = 0; i < depth; i++)
{
sb.Append("}");
}
string json = sb.ToString();
JsonSerializer serializer = new JsonSerializer() { };
serializer.Deserialize<Nest>(new JsonTextReader(new StringReader(json)));
}
public class Nest
{
public Nest A { get; set; }
}
[Test]
public void ParametersPassedToJsonConverterConstructor()
{
ClobberMyProperties clobber = new ClobberMyProperties { One = "Red", Two = "Green", Three = "Yellow", Four = "Black" };
string json = JsonConvert.SerializeObject(clobber);
Assert.AreEqual("{\"One\":\"Uno-1-Red\",\"Two\":\"Dos-2-Green\",\"Three\":\"Tres-1337-Yellow\",\"Four\":\"Black\"}", json);
}
public class ClobberMyProperties
{
[JsonConverter(typeof(ClobberingJsonConverter), "Uno", 1)]
public string One { get; set; }
[JsonConverter(typeof(ClobberingJsonConverter), "Dos", 2)]
public string Two { get; set; }
[JsonConverter(typeof(ClobberingJsonConverter), "Tres")]
public string Three { get; set; }
public string Four { get; set; }
}
public class ClobberingJsonConverter : JsonConverter
{
public string ClobberValueString { get; private set; }
public int ClobberValueInt { get; private set; }
public ClobberingJsonConverter(string clobberValueString, int clobberValueInt)
{
ClobberValueString = clobberValueString;
ClobberValueInt = clobberValueInt;
}
public ClobberingJsonConverter(string clobberValueString)
: this(clobberValueString, 1337)
{
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(ClobberValueString + "-" + ClobberValueInt.ToString() + "-" + value.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
}
[Test]
public void WrongParametersPassedToJsonConvertConstructorShouldThrow()
{
IncorrectJsonConvertParameters value = new IncorrectJsonConvertParameters { One = "Boom" };
ExceptionAssert.Throws<JsonException>(() => { JsonConvert.SerializeObject(value); });
}
public class IncorrectJsonConvertParameters
{
/// <summary>
/// We deliberately use the wrong number/type of arguments for ClobberingJsonConverter to ensure an
/// exception is thrown.
/// </summary>
[JsonConverter(typeof(ClobberingJsonConverter), "Uno", "Blammo")]
public string One { get; set; }
}
[Test]
public void CustomDoubleRounding()
{
var measurements = new Measurements
{
Loads = new List<double> { 23283.567554707258, 23224.849899771067, 23062.5, 22846.272519910868, 22594.281246368635 },
Positions = new List<double> { 57.724227689317019, 60.440934405753069, 63.444192925248643, 66.813119113482557, 70.4496501404433 },
Gain = 12345.67895111213
};
string json = JsonConvert.SerializeObject(measurements);
Assert.AreEqual("{\"Positions\":[57.72,60.44,63.44,66.81,70.45],\"Loads\":[23284.0,23225.0,23062.0,22846.0,22594.0],\"Gain\":12345.679}", json);
}
public class Measurements
{
[JsonProperty(ItemConverterType = typeof(RoundingJsonConverter))]
public List<double> Positions { get; set; }
[JsonProperty(ItemConverterType = typeof(RoundingJsonConverter), ItemConverterParameters = new object[] { 0, MidpointRounding.ToEven })]
public List<double> Loads { get; set; }
[JsonConverter(typeof(RoundingJsonConverter), 4)]
public double Gain { get; set; }
}
public class RoundingJsonConverter : JsonConverter
{
int _precision;
MidpointRounding _rounding;
public RoundingJsonConverter()
: this(2)
{
}
public RoundingJsonConverter(int precision)
: this(precision, MidpointRounding.AwayFromZero)
{
}
public RoundingJsonConverter(int precision, MidpointRounding rounding)
{
_precision = precision;
_rounding = rounding;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(double);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(Math.Round((double)value, _precision, _rounding));
}
}
}
}
| |
using System;
using DevExpress.CodeRush.Core;
namespace CR_XkeysEngine
{
/// <summary>
/// Represents a keystroke in the IDE.
/// </summary>
public class Shortcut: ShortcutBase, IShortcut, ICloneable
{
#region private fields...
private bool _RightSide;
private bool _KeyDownIsRepeated;
private int _OriginalKeyState;
#endregion
// constructors...
#region Shortcut
public Shortcut()
{
}
#endregion
#region Shortcut(KeyPressedEventArgs e)
public Shortcut(KeyPressedEventArgs e)
{
Assign(e);
}
#endregion
// public overridden methods...
#region Equals
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj.GetType() != typeof(Shortcut))
return false;
Shortcut lShortcut = (Shortcut)obj;
bool lResult = false;
lResult = (lShortcut._Alt == _Alt) &&
(lShortcut._Ctrl == _Ctrl) &&
(lShortcut._Shift == _Shift) &&
(lShortcut._KeyCode == _KeyCode) &&
(lShortcut._Extended == _Extended);
if (OptXkeysShortcuts.SeparateAltKeys)
lResult = lResult && (lShortcut._RightSide == _RightSide);
if (lShortcut._KeyDownIsRepeated)
return lResult && (CompareKeyState(lShortcut._OriginalKeyState, _KeyState));
return lResult && (CompareKeyState(lShortcut._KeyState, _KeyState));
}
#endregion
#region GetHashCode
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
#region CompareKeyState(int first, int second)
bool CompareKeyState(int first, int second)
{
//return first == second;
uint mask = 0xE100FFF0;
return (first & mask) == (second & mask);
}
#endregion
// public methods...
#region Assign(KeyPressedEventArgs e)
public void Assign(KeyPressedEventArgs e)
{
_Alt = e.AltKeyDown;
_Shift = e.ShiftKeyDown;
_Ctrl = e.CtrlKeyDown;
//_RightSide = (e.VirtualKey != e.VirtualKeyLeftRight);
_RightSide = e.RAltPressed;
_Extended = e.ExtendedKey;
_KeyDownIsRepeated = e.KeyDownIsRepeated;
_KeyState = e.KeyState;
_OriginalKeyState = e.OriginalKeyState;
_KeyCode = e.KeyCode;
}
#endregion
#region Clear
public void Clear()
{
_Alt = false;
_Shift = false;
_Ctrl = false;
_RightSide = false; // For right-alt combinations....
_Extended = false;
_KeyState = 0;
_KeyCode = 0;
}
#endregion
#region Clone
public Shortcut Clone()
{
Shortcut lResult = new Shortcut();
lResult._Alt = this._Alt;
lResult._Shift = this._Shift;
lResult._Ctrl = this._Ctrl;
lResult._RightSide = this._RightSide;
lResult._Extended = this._Extended;
lResult._KeyState = this._KeyState;
lResult._KeyCode = this._KeyCode;
return lResult;
}
#endregion
#region Matches
/// <summary>
/// Returns true if aShortcut matches this shortcut.
/// </summary>
public bool Matches(Shortcut sc)
{
bool lResult = false;
lResult = (sc._KeyCode == _KeyCode) &&
(sc._Alt == _Alt) &&
(sc._Ctrl == _Ctrl) &&
(sc._Shift == _Shift) &&
(sc._Extended == _Extended) &&
(sc._RightSide == _RightSide);
if (sc._KeyDownIsRepeated)
return lResult && (sc._OriginalKeyState == _KeyState);
return lResult && (sc._KeyState == _KeyState);
}
#endregion
#region Load
public void Load(DecoupledStorage storage, string section, string prefix)
{
_KeyState = storage.ReadInt32(section, prefix + "KeyState");
_KeyCode = storage.ReadInt32(section, prefix + "KeyCode");
_Ctrl = storage.ReadBoolean(section, prefix + "Ctrl");
_Shift = storage.ReadBoolean(section, prefix + "Shift");
_Alt = storage.ReadBoolean(section, prefix + "Alt");
_RightSide = storage.ReadBoolean(section, prefix + "RightSide");
_Extended = storage.ReadBoolean(section, prefix + "Extended");
}
#endregion
#region Save
public void Save(DecoupledStorage storage, string section, string prefix)
{
storage.WriteInt32(section, prefix + "KeyState", _KeyState);
storage.WriteInt32(section, prefix + "KeyCode", _KeyCode);
storage.WriteBoolean(section, prefix + "Ctrl", _Ctrl);
storage.WriteBoolean(section, prefix + "Shift", _Shift);
storage.WriteBoolean(section, prefix + "Alt", _Alt);
storage.WriteBoolean(section, prefix + "RightSide", _RightSide);
storage.WriteBoolean(section, prefix + "Extended", _Extended);
}
#endregion
// public properties...
#region Assigned
/// <summary>
/// Returns true if this shortcut has been assigned a valid value.
/// </summary>
public bool Assigned
{
get
{
return (_KeyState != 0 || _KeyCode != 0);
}
}
#endregion
#region DisplayName
public string DisplayName
{
get
{
string lResult = CodeRush.Key.GetName(_KeyState, _KeyCode, _Ctrl, _Shift, _Alt);
if (_RightSide && _Alt)
lResult = lResult + " (Right Alt)";
return lResult;
}
}
#endregion
#region VisualStudioBindingName
public string VisualStudioBindingName
{
get
{
string lResult = CodeRush.Key.GetVisualStudioBindingName(_KeyState, _KeyCode, _Ctrl, _Shift, _Alt);
if (_RightSide && _Alt)
lResult = lResult + " (Right Alt)";
return lResult;
}
}
#endregion
#region RightSide
public bool RightSide
{
get
{
return _RightSide;
}
set
{
if (_RightSide == value)
return;
_RightSide = value;
OnChanged();
}
}
#endregion
#region KeyDownIsRepeated
public bool KeyDownIsRepeated
{
get
{
return _KeyDownIsRepeated;
}
set
{
if (_KeyDownIsRepeated == value)
return;
_KeyDownIsRepeated = value;
OnChanged();
}
}
#endregion
#region OriginalKeyState
public int OriginalKeyState
{
get
{
return _OriginalKeyState;
}
set
{
if (_OriginalKeyState == value)
return;
_OriginalKeyState = value;
OnChanged();
}
}
#endregion
// ICloneable methods...
#region ICloneable.Clone
object ICloneable.Clone()
{
return Clone();
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Utility;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Threading;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Media;
using System.Windows.Input;
using System.Windows.Controls.Primitives;
using System.Windows.Shapes;
using System;
// Disable CS3001: Warning as Error: not CLS-compliant
#pragma warning disable 3001
namespace System.Windows.Controls
{
/// <summary>
/// Control that implements a selectable item inside a ListBox.
/// </summary>
[DefaultEvent("Selected")]
public class ListBoxItem : ContentControl
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// Default DependencyObject constructor
/// </summary>
public ListBoxItem() : base()
{
}
static ListBoxItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ListBoxItem), new FrameworkPropertyMetadata(typeof(ListBoxItem)));
_dType = DependencyObjectType.FromSystemTypeInternal(typeof(ListBoxItem));
KeyboardNavigation.DirectionalNavigationProperty.OverrideMetadata(typeof(ListBoxItem), new FrameworkPropertyMetadata(KeyboardNavigationMode.Once));
KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(ListBoxItem), new FrameworkPropertyMetadata(KeyboardNavigationMode.Local));
IsEnabledProperty.OverrideMetadata(typeof(ListBoxItem), new UIPropertyMetadata(new PropertyChangedCallback(OnVisualStatePropertyChanged)));
IsMouseOverPropertyKey.OverrideMetadata(typeof(ListBoxItem), new UIPropertyMetadata(new PropertyChangedCallback(OnVisualStatePropertyChanged)));
Selector.IsSelectionActivePropertyKey.OverrideMetadata(typeof(ListBoxItem), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnVisualStatePropertyChanged)));
AutomationProperties.IsOffscreenBehaviorProperty.OverrideMetadata(typeof(ListBoxItem), new FrameworkPropertyMetadata(IsOffscreenBehavior.FromClip));
}
#endregion
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
/// <summary>
/// Indicates whether this ListBoxItem is selected.
/// </summary>
public static readonly DependencyProperty IsSelectedProperty =
Selector.IsSelectedProperty.AddOwner(typeof(ListBoxItem),
new FrameworkPropertyMetadata(BooleanBoxes.FalseBox,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal,
new PropertyChangedCallback(OnIsSelectedChanged)));
/// <summary>
/// Indicates whether this ListBoxItem is selected.
/// </summary>
[Bindable(true), Category("Appearance")]
public bool IsSelected
{
get { return (bool) GetValue(IsSelectedProperty); }
set { SetValue(IsSelectedProperty, BooleanBoxes.Box(value)); }
}
private static void OnIsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ListBoxItem listItem = d as ListBoxItem;
bool isSelected = (bool) e.NewValue;
Selector parentSelector = listItem.ParentSelector;
if (parentSelector != null)
{
parentSelector.RaiseIsSelectedChangedAutomationEvent(listItem, isSelected);
}
if (isSelected)
{
listItem.OnSelected(new RoutedEventArgs(Selector.SelectedEvent, listItem));
}
else
{
listItem.OnUnselected(new RoutedEventArgs(Selector.UnselectedEvent, listItem));
}
listItem.UpdateVisualState();
}
/// <summary>
/// Event indicating that the IsSelected property is now true.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnSelected(RoutedEventArgs e)
{
HandleIsSelectedChanged(true, e);
}
/// <summary>
/// Event indicating that the IsSelected property is now false.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnUnselected(RoutedEventArgs e)
{
HandleIsSelectedChanged(false, e);
}
private void HandleIsSelectedChanged(bool newValue, RoutedEventArgs e)
{
RaiseEvent(e);
}
#endregion
#region Events
/// <summary>
/// Raised when the item's IsSelected property becomes true.
/// </summary>
public static readonly RoutedEvent SelectedEvent = Selector.SelectedEvent.AddOwner(typeof(ListBoxItem));
/// <summary>
/// Raised when the item's IsSelected property becomes true.
/// </summary>
public event RoutedEventHandler Selected
{
add
{
AddHandler(SelectedEvent, value);
}
remove
{
RemoveHandler(SelectedEvent, value);
}
}
/// <summary>
/// Raised when the item's IsSelected property becomes false.
/// </summary>
public static readonly RoutedEvent UnselectedEvent = Selector.UnselectedEvent.AddOwner(typeof(ListBoxItem));
/// <summary>
/// Raised when the item's IsSelected property becomes false.
/// </summary>
public event RoutedEventHandler Unselected
{
add
{
AddHandler(UnselectedEvent, value);
}
remove
{
RemoveHandler(UnselectedEvent, value);
}
}
#endregion
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
internal override void ChangeVisualState(bool useTransitions)
{
// Change to the correct state in the Interaction group
if (!IsEnabled)
{
// [copied from SL code]
// If our child is a control then we depend on it displaying a proper "disabled" state. If it is not a control
// (ie TextBlock, Border, etc) then we will use our visuals to show a disabled state.
VisualStateManager.GoToState(this, Content is Control ? VisualStates.StateNormal : VisualStates.StateDisabled, useTransitions);
}
else if (IsMouseOver)
{
VisualStateManager.GoToState(this, VisualStates.StateMouseOver, useTransitions);
}
else
{
VisualStateManager.GoToState(this, VisualStates.StateNormal, useTransitions);
}
// Change to the correct state in the Selection group
if (IsSelected)
{
if (Selector.GetIsSelectionActive(this))
{
VisualStateManager.GoToState(this, VisualStates.StateSelected, useTransitions);
}
else
{
VisualStates.GoToState(this, useTransitions, VisualStates.StateSelectedUnfocused, VisualStates.StateSelected);
}
}
else
{
VisualStateManager.GoToState(this, VisualStates.StateUnselected, useTransitions);
}
if (IsKeyboardFocused)
{
VisualStateManager.GoToState(this, VisualStates.StateFocused, useTransitions);
}
else
{
VisualStateManager.GoToState(this, VisualStates.StateUnfocused, useTransitions);
}
base.ChangeVisualState(useTransitions);
}
/// <summary>
/// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>)
/// </summary>
protected override AutomationPeer OnCreateAutomationPeer()
{
return new ListBoxItemWrapperAutomationPeer(this);
}
/// <summary>
/// This is the method that responds to the MouseButtonEvent event.
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (!e.Handled)
{
//
e.Handled = true;
HandleMouseButtonDown(MouseButton.Left);
}
base.OnMouseLeftButtonDown(e);
}
/// <summary>
/// This is the method that responds to the MouseButtonEvent event.
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnMouseRightButtonDown(MouseButtonEventArgs e)
{
if (!e.Handled)
{
//
e.Handled = true;
HandleMouseButtonDown(MouseButton.Right);
}
base.OnMouseRightButtonDown(e);
}
private void HandleMouseButtonDown(MouseButton mouseButton)
{
if (Selector.UiGetIsSelectable(this) && Focus())
{
ListBox parent = ParentListBox;
if (parent != null)
{
parent.NotifyListItemClicked(this, mouseButton);
}
}
}
/// <summary>
/// Called when IsMouseOver changes on this element.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseEnter(MouseEventArgs e)
{
// abort any drag operation we have queued.
if (parentNotifyDraggedOperation != null)
{
parentNotifyDraggedOperation.Abort();
parentNotifyDraggedOperation = null;
}
if (IsMouseOver)
{
ListBox parent = ParentListBox;
if (parent != null && Mouse.LeftButton == MouseButtonState.Pressed)
{
parent.NotifyListItemMouseDragged(this);
}
}
base.OnMouseEnter(e);
}
/// <summary>
/// Called when IsMouseOver changes on this element.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseLeave(MouseEventArgs e)
{
// abort any drag operation we have queued.
if (parentNotifyDraggedOperation != null)
{
parentNotifyDraggedOperation.Abort();
parentNotifyDraggedOperation = null;
}
base.OnMouseLeave(e);
}
/// <summary>
/// Called when the visual parent of this element changes.
/// </summary>
/// <param name="oldParent"></param>
protected internal override void OnVisualParentChanged(DependencyObject oldParent)
{
ItemsControl oldItemsControl = null;
if (VisualTreeHelper.GetParent(this) == null)
{
if (IsKeyboardFocusWithin)
{
// This ListBoxItem had focus but was removed from the tree.
// The normal behavior is for focus to become null, but we would rather that
// focus go to the parent ListBox.
// Use the oldParent to get a reference to the ListBox that this ListBoxItem used to be in.
// The oldParent's ItemsOwner should be the ListBox.
oldItemsControl = ItemsControl.GetItemsOwner(oldParent);
}
}
base.OnVisualParentChanged(oldParent);
// If earlier, we decided to set focus to the old parent ListBox, do it here
// after calling base so that the state for IsKeyboardFocusWithin is updated correctly.
if (oldItemsControl != null)
{
oldItemsControl.Focus();
}
}
#endregion
//-------------------------------------------------------------------
//
// Implementation
//
//-------------------------------------------------------------------
#region Implementation
private ListBox ParentListBox
{
get
{
return ParentSelector as ListBox;
}
}
internal Selector ParentSelector
{
get
{
return ItemsControl.ItemsControlFromItemContainer(this) as Selector;
}
}
#endregion
#if OLD_AUTOMATION
// left here for reference only as it is still used by MonthCalendar
/// <summary>
/// DependencyProperty for SelectionContainer property.
/// </summary>
internal static readonly DependencyProperty SelectionContainerProperty
= DependencyProperty.RegisterAttached("SelectionContainer", typeof(UIElement), typeof(ListBoxItem),
new FrameworkPropertyMetadata((UIElement)null));
#endif
#region Private Fields
DispatcherOperation parentNotifyDraggedOperation = null;
#endregion
#region DTypeThemeStyleKey
// Returns the DependencyObjectType for the registered ThemeStyleKey's default
// value. Controls will override this method to return approriate types.
internal override DependencyObjectType DTypeThemeStyleKey
{
get { return _dType; }
}
private static DependencyObjectType _dType;
#endregion DTypeThemeStyleKey
}
}
| |
using J2N;
using Lucene.Net.Diagnostics;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BaseDirectoryWrapper = Lucene.Net.Store.BaseDirectoryWrapper;
using BinaryDocValuesField = Lucene.Net.Documents.BinaryDocValuesField;
using BytesRef = Lucene.Net.Util.BytesRef;
using Constants = Lucene.Net.Util.Constants;
using Directory = Lucene.Net.Store.Directory;
//using IndexOptions = Lucene.Net.Index.IndexOptions;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Lucene.Net.Documents.Document;
using DoubleDocValuesField = Lucene.Net.Documents.DoubleDocValuesField;
using Field = Lucene.Net.Documents.Field;
using FieldCache = Lucene.Net.Search.FieldCache;
using FieldType = Lucene.Net.Documents.FieldType;
using IBits = Lucene.Net.Util.IBits;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using Int32Field = Lucene.Net.Documents.Int32Field;
using Int64Field = Lucene.Net.Documents.Int64Field;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using NumericDocValuesField = Lucene.Net.Documents.NumericDocValuesField;
using NumericRangeQuery = Lucene.Net.Search.NumericRangeQuery;
using PhraseQuery = Lucene.Net.Search.PhraseQuery;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using ScoreDoc = Lucene.Net.Search.ScoreDoc;
using SingleDocValuesField = Lucene.Net.Documents.SingleDocValuesField;
using SortedDocValuesField = Lucene.Net.Documents.SortedDocValuesField;
using StringField = Lucene.Net.Documents.StringField;
using StringHelper = Lucene.Net.Util.StringHelper;
using TermQuery = Lucene.Net.Search.TermQuery;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = Lucene.Net.Documents.TextField;
using TopDocs = Lucene.Net.Search.TopDocs;
/*
Verify we can read the pre-4.0 file format, do searches
against it, and add documents to it.
*/
// don't use 3.x codec, its unrealistic since it means
// we won't even be running the actual code, only the impostor
// Sep codec cannot yet handle the offsets we add when changing indexes!
[SuppressCodecs("Lucene3x", "MockFixedIntBlock", "MockVariableIntBlock", "MockSep", "MockRandom", "Lucene40", "Lucene41", "Appending", "Lucene42", "Lucene45")]
[TestFixture]
public class TestBackwardsCompatibility3x : LuceneTestCase
{
// Uncomment these cases & run them on an older Lucene
// version, to generate an index to test backwards
// compatibility. Then, cd to build/test/index.cfs and
// run "zip index.<VERSION>.cfs.zip *"; cd to
// build/test/index.nocfs and run "zip
// index.<VERSION>.nocfs.zip *". Then move those 2 zip
// files to your trunk checkout and add them to the
// oldNames array.
/*
public void testCreateCFS() throws IOException {
createIndex("index.cfs", true, false);
}
public void testCreateNoCFS() throws IOException {
createIndex("index.nocfs", false, false);
}
*/
/*
// These are only needed for the special upgrade test to verify
// that also single-segment indexes are correctly upgraded by IndexUpgrader.
// You don't need them to be build for non-3.1 (the test is happy with just one
// "old" segment format, version is unimportant:
public void testCreateSingleSegmentCFS() throws IOException {
createIndex("index.singlesegment.cfs", true, true);
}
public void testCreateSingleSegmentNoCFS() throws IOException {
createIndex("index.singlesegment.nocfs", false, true);
}
*/
// LUCENENET specific to load resources for this type
internal const string CURRENT_RESOURCE_DIRECTORY = "Lucene.Net.Tests.Index.";
internal static readonly string[] oldNames = new string[] {
"30.cfs", "30.nocfs", "31.cfs", "31.nocfs", "32.cfs",
"32.nocfs", "34.cfs", "34.nocfs"
};
internal readonly string[] unsupportedNames = new string[] {
"19.cfs", "19.nocfs", "20.cfs", "20.nocfs", "21.cfs",
"21.nocfs", "22.cfs", "22.nocfs", "23.cfs", "23.nocfs",
"24.cfs", "24.nocfs", "29.cfs", "29.nocfs"
};
internal static readonly string[] oldSingleSegmentNames = new string[] {
"31.optimized.cfs", "31.optimized.nocfs"
};
internal static IDictionary<string, Directory> oldIndexDirs;
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
assertFalse("test infra is broken!", OldFormatImpersonationIsActive);
List<string> names = new List<string>(oldNames.Length + oldSingleSegmentNames.Length);
names.AddRange(oldNames);
names.AddRange(oldSingleSegmentNames);
oldIndexDirs = new Dictionary<string, Directory>();
foreach (string name in names)
{
DirectoryInfo dir = CreateTempDir(name);
using (Stream zipFileStream = this.GetType().FindAndGetManifestResourceStream("index." + name + ".zip"))
{
TestUtil.Unzip(zipFileStream, dir);
}
oldIndexDirs[name] = NewFSDirectory(dir);
}
}
[OneTimeTearDown]
public override void AfterClass()
{
foreach (Directory d in oldIndexDirs.Values)
{
d.Dispose();
}
oldIndexDirs = null;
base.AfterClass();
}
/// <summary>
/// this test checks that *only* IndexFormatTooOldExceptions are thrown when you open and operate on too old indexes! </summary>
[Test]
public virtual void TestUnsupportedOldIndexes()
{
for (int i = 0; i < unsupportedNames.Length; i++)
{
if (Verbose)
{
Console.WriteLine("TEST: index " + unsupportedNames[i]);
}
DirectoryInfo oldIndexDir = CreateTempDir(unsupportedNames[i]);
using (Stream dataFile = this.GetType().FindAndGetManifestResourceStream("unsupported." + unsupportedNames[i] + ".zip"))
{
TestUtil.Unzip(dataFile, oldIndexDir);
}
BaseDirectoryWrapper dir = NewFSDirectory(oldIndexDir);
// don't checkindex, these are intentionally not supported
dir.CheckIndexOnDispose = false;
IndexReader reader = null;
IndexWriter writer = null;
try
{
reader = DirectoryReader.Open(dir);
Assert.Fail("DirectoryReader.open should not pass for " + unsupportedNames[i]);
}
#pragma warning disable 168
catch (IndexFormatTooOldException e)
#pragma warning restore 168
{
// pass
}
finally
{
if (reader != null)
{
reader.Dispose();
}
reader = null;
}
try
{
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Assert.Fail("IndexWriter creation should not pass for " + unsupportedNames[i]);
}
catch (IndexFormatTooOldException e)
{
// pass
if (Verbose)
{
Console.WriteLine("TEST: got expected exc:");
Console.WriteLine(e.StackTrace);
}
// Make sure exc message includes a path=
Assert.IsTrue(e.Message.IndexOf("path=\"", StringComparison.Ordinal) != -1, "got exc message: " + e.Message);
}
finally
{
// we should fail to open IW, and so it should be null when we get here.
// However, if the test fails (i.e., IW did not fail on open), we need
// to close IW. However, if merges are run, IW may throw
// IndexFormatTooOldException, and we don't want to mask the Assert.Fail()
// above, so close without waiting for merges.
if (writer != null)
{
writer.Dispose(false);
}
writer = null;
}
StringBuilder bos = new StringBuilder();
CheckIndex checker = new CheckIndex(dir);
checker.InfoStream = new StringWriter(bos);
CheckIndex.Status indexStatus = checker.DoCheckIndex();
Assert.IsFalse(indexStatus.Clean);
checker.InfoStream.Flush();
Assert.IsTrue(bos.ToString().Contains(typeof(IndexFormatTooOldException).Name));
dir.Dispose();
}
}
[Test]
public virtual void TestFullyMergeOldIndex()
{
foreach (string name in oldNames)
{
if (Verbose)
{
Console.WriteLine("\nTEST: index=" + name);
}
Directory dir = NewDirectory(oldIndexDirs[name]);
IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
w.ForceMerge(1);
w.Dispose();
dir.Dispose();
}
}
[Test]
public virtual void TestAddOldIndexes()
{
foreach (string name in oldNames)
{
if (Verbose)
{
Console.WriteLine("\nTEST: old index " + name);
}
Directory targetDir = NewDirectory();
IndexWriter w = new IndexWriter(targetDir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
w.AddIndexes(oldIndexDirs[name]);
if (Verbose)
{
Console.WriteLine("\nTEST: done adding indices; now close");
}
w.Dispose();
targetDir.Dispose();
}
}
[Test]
public virtual void TestAddOldIndexesReader()
{
foreach (string name in oldNames)
{
IndexReader reader = DirectoryReader.Open(oldIndexDirs[name]);
Directory targetDir = NewDirectory();
IndexWriter w = new IndexWriter(targetDir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
w.AddIndexes(reader);
w.Dispose();
reader.Dispose();
targetDir.Dispose();
}
}
[Test]
public virtual void TestSearchOldIndex()
{
foreach (string name in oldNames)
{
SearchIndex(oldIndexDirs[name], name);
}
}
[Test]
public virtual void TestIndexOldIndexNoAdds()
{
foreach (string name in oldNames)
{
Directory dir = NewDirectory(oldIndexDirs[name]);
ChangeIndexNoAdds(Random, dir);
dir.Dispose();
}
}
[Test]
public virtual void TestIndexOldIndex()
{
foreach (string name in oldNames)
{
if (Verbose)
{
Console.WriteLine("TEST: oldName=" + name);
}
Directory dir = NewDirectory(oldIndexDirs[name]);
ChangeIndexWithAdds(Random, dir, name);
dir.Dispose();
}
}
/// @deprecated 3.x transition mechanism
[Obsolete("3.x transition mechanism")]
[Test]
public virtual void TestDeleteOldIndex()
{
foreach (string name in oldNames)
{
if (Verbose)
{
Console.WriteLine("TEST: oldName=" + name);
}
// Try one delete:
Directory dir = NewDirectory(oldIndexDirs[name]);
IndexReader ir = DirectoryReader.Open(dir);
Assert.AreEqual(35, ir.NumDocs);
ir.Dispose();
IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null));
iw.DeleteDocuments(new Term("id", "3"));
iw.Dispose();
ir = DirectoryReader.Open(dir);
Assert.AreEqual(34, ir.NumDocs);
ir.Dispose();
// Delete all but 1 document:
iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null));
for (int i = 0; i < 35; i++)
{
iw.DeleteDocuments(new Term("id", "" + i));
}
// Verify NRT reader takes:
ir = DirectoryReader.Open(iw, true);
iw.Dispose();
Assert.AreEqual(1, ir.NumDocs, "index " + name);
ir.Dispose();
// Verify non-NRT reader takes:
ir = DirectoryReader.Open(dir);
Assert.AreEqual(1, ir.NumDocs, "index " + name);
ir.Dispose();
dir.Dispose();
}
}
private void DoTestHits(ScoreDoc[] hits, int expectedCount, IndexReader reader)
{
int hitCount = hits.Length;
Assert.AreEqual(expectedCount, hitCount, "wrong number of hits");
for (int i = 0; i < hitCount; i++)
{
reader.Document(hits[i].Doc);
reader.GetTermVectors(hits[i].Doc);
}
}
public virtual void SearchIndex(Directory dir, string oldName)
{
//QueryParser parser = new QueryParser("contents", new MockAnalyzer(random));
//Query query = parser.parse("handle:1");
IndexReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
TestUtil.CheckIndex(dir);
// true if this is a 4.0+ index
bool is40Index = MultiFields.GetMergedFieldInfos(reader).FieldInfo("content5") != null;
IBits liveDocs = MultiFields.GetLiveDocs(reader);
for (int i = 0; i < 35; i++)
{
if (liveDocs.Get(i))
{
Document d = reader.Document(i);
IList<IIndexableField> fields = d.Fields;
bool isProxDoc = d.GetField("content3") == null;
if (isProxDoc)
{
int numFields = is40Index ? 7 : 5;
Assert.AreEqual(numFields, fields.Count);
IIndexableField f = d.GetField("id");
Assert.AreEqual("" + i, f.GetStringValue());
f = d.GetField("utf8");
Assert.AreEqual("Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", f.GetStringValue());
f = d.GetField("autf8");
Assert.AreEqual("Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", f.GetStringValue());
f = d.GetField("content2");
Assert.AreEqual("here is more content with aaa aaa aaa", f.GetStringValue());
f = d.GetField("fie\u2C77ld");
Assert.AreEqual("field with non-ascii name", f.GetStringValue());
}
Fields tfvFields = reader.GetTermVectors(i);
Assert.IsNotNull(tfvFields, "i=" + i);
Terms tfv = tfvFields.GetTerms("utf8");
Assert.IsNotNull(tfv, "docID=" + i + " index=" + oldName);
}
else
{
// Only ID 7 is deleted
Assert.AreEqual(7, i);
}
}
if (is40Index)
{
// check docvalues fields
NumericDocValues dvByte = MultiDocValues.GetNumericValues(reader, "dvByte");
BinaryDocValues dvBytesDerefFixed = MultiDocValues.GetBinaryValues(reader, "dvBytesDerefFixed");
BinaryDocValues dvBytesDerefVar = MultiDocValues.GetBinaryValues(reader, "dvBytesDerefVar");
SortedDocValues dvBytesSortedFixed = MultiDocValues.GetSortedValues(reader, "dvBytesSortedFixed");
SortedDocValues dvBytesSortedVar = MultiDocValues.GetSortedValues(reader, "dvBytesSortedVar");
BinaryDocValues dvBytesStraightFixed = MultiDocValues.GetBinaryValues(reader, "dvBytesStraightFixed");
BinaryDocValues dvBytesStraightVar = MultiDocValues.GetBinaryValues(reader, "dvBytesStraightVar");
NumericDocValues dvDouble = MultiDocValues.GetNumericValues(reader, "dvDouble");
NumericDocValues dvFloat = MultiDocValues.GetNumericValues(reader, "dvFloat");
NumericDocValues dvInt = MultiDocValues.GetNumericValues(reader, "dvInt");
NumericDocValues dvLong = MultiDocValues.GetNumericValues(reader, "dvLong");
NumericDocValues dvPacked = MultiDocValues.GetNumericValues(reader, "dvPacked");
NumericDocValues dvShort = MultiDocValues.GetNumericValues(reader, "dvShort");
for (int i = 0; i < 35; i++)
{
int id = Convert.ToInt32(reader.Document(i).Get("id"));
Assert.AreEqual(id, dvByte.Get(i));
sbyte[] bytes = new sbyte[] { (sbyte)((int)((uint)id >> 24)), (sbyte)((int)((uint)id >> 16)), (sbyte)((int)((uint)id >> 8)), (sbyte)id };
BytesRef expectedRef = new BytesRef((byte[])(Array)bytes);
BytesRef scratch = new BytesRef();
dvBytesDerefFixed.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
dvBytesDerefVar.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
dvBytesSortedFixed.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
dvBytesSortedVar.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
dvBytesStraightFixed.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
dvBytesStraightVar.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
Assert.AreEqual((double)id, J2N.BitConversion.Int64BitsToDouble(dvDouble.Get(i)), 0D);
Assert.AreEqual((float)id, J2N.BitConversion.Int32BitsToSingle((int)dvFloat.Get(i)), 0F);
Assert.AreEqual(id, dvInt.Get(i));
Assert.AreEqual(id, dvLong.Get(i));
Assert.AreEqual(id, dvPacked.Get(i));
Assert.AreEqual(id, dvShort.Get(i));
}
}
ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
// First document should be #21 since it's norm was
// increased:
Document d_ = searcher.IndexReader.Document(hits[0].Doc);
assertEquals("didn't get the right document first", "21", d_.Get("id"));
DoTestHits(hits, 34, searcher.IndexReader);
if (is40Index)
{
hits = searcher.Search(new TermQuery(new Term("content5", "aaa")), null, 1000).ScoreDocs;
DoTestHits(hits, 34, searcher.IndexReader);
hits = searcher.Search(new TermQuery(new Term("content6", "aaa")), null, 1000).ScoreDocs;
DoTestHits(hits, 34, searcher.IndexReader);
}
hits = searcher.Search(new TermQuery(new Term("utf8", "\u0000")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length);
hits = searcher.Search(new TermQuery(new Term("utf8", "Lu\uD834\uDD1Ece\uD834\uDD60ne")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length);
hits = searcher.Search(new TermQuery(new Term("utf8", "ab\ud917\udc17cd")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length);
reader.Dispose();
}
private int Compare(string name, string v)
{
int v0 = Convert.ToInt32(name.Substring(0, 2));
int v1 = Convert.ToInt32(v);
return v0 - v1;
}
public virtual void ChangeIndexWithAdds(Random random, Directory dir, string origOldName)
{
// open writer
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetOpenMode(OpenMode.APPEND));
// add 10 docs
for (int i = 0; i < 10; i++)
{
AddDoc(writer, 35 + i);
}
// make sure writer sees right total -- writer seems not to know about deletes in .del?
int expected;
if (Compare(origOldName, "24") < 0)
{
expected = 44;
}
else
{
expected = 45;
}
Assert.AreEqual(expected, writer.NumDocs, "wrong doc count");
writer.Dispose();
// make sure searching sees right # hits
IndexReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Document d = searcher.IndexReader.Document(hits[0].Doc);
assertEquals("wrong first document", "21", d.Get("id"));
DoTestHits(hits, 44, searcher.IndexReader);
reader.Dispose();
// fully merge
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetOpenMode(OpenMode.APPEND));
writer.ForceMerge(1);
writer.Dispose();
reader = DirectoryReader.Open(dir);
searcher = new IndexSearcher(reader);
hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(44, hits.Length, "wrong number of hits");
d = searcher.Doc(hits[0].Doc);
DoTestHits(hits, 44, searcher.IndexReader);
assertEquals("wrong first document", "21", d.Get("id"));
reader.Dispose();
}
public virtual void ChangeIndexNoAdds(Random random, Directory dir)
{
// make sure searching sees right # hits
DirectoryReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length, "wrong number of hits");
Document d = searcher.Doc(hits[0].Doc);
assertEquals("wrong first document", "21", d.Get("id"));
reader.Dispose();
// fully merge
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetOpenMode(OpenMode.APPEND));
writer.ForceMerge(1);
writer.Dispose();
reader = DirectoryReader.Open(dir);
searcher = new IndexSearcher(reader);
hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length, "wrong number of hits");
DoTestHits(hits, 34, searcher.IndexReader);
reader.Dispose();
}
public virtual DirectoryInfo CreateIndex(string dirName, bool doCFS, bool fullyMerged)
{
// we use a real directory name that is not cleaned up, because this method is only used to create backwards indexes:
DirectoryInfo indexDir = new DirectoryInfo(Path.Combine("/tmp/4x/", dirName));
TestUtil.Rm(indexDir);
Directory dir = NewFSDirectory(indexDir);
LogByteSizeMergePolicy mp = new LogByteSizeMergePolicy();
mp.NoCFSRatio = doCFS ? 1.0 : 0.0;
mp.MaxCFSSegmentSizeMB = double.PositiveInfinity;
// TODO: remove randomness
IndexWriterConfig conf = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetMaxBufferedDocs(10).SetMergePolicy(mp).SetUseCompoundFile(doCFS);
IndexWriter writer = new IndexWriter(dir, conf);
for (int i = 0; i < 35; i++)
{
AddDoc(writer, i);
}
Assert.AreEqual(35, writer.MaxDoc, "wrong doc count");
if (fullyMerged)
{
writer.ForceMerge(1);
}
writer.Dispose();
if (!fullyMerged)
{
// open fresh writer so we get no prx file in the added segment
mp = new LogByteSizeMergePolicy();
mp.NoCFSRatio = doCFS ? 1.0 : 0.0;
// TODO: remove randomness
conf = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetMaxBufferedDocs(10).SetMergePolicy(mp).SetUseCompoundFile(doCFS);
writer = new IndexWriter(dir, conf);
AddNoProxDoc(writer);
writer.Dispose();
writer = new IndexWriter(dir, conf.SetMergePolicy(doCFS ? NoMergePolicy.COMPOUND_FILES : NoMergePolicy.NO_COMPOUND_FILES));
Term searchTerm = new Term("id", "7");
writer.DeleteDocuments(searchTerm);
writer.Dispose();
}
dir.Dispose();
return indexDir;
}
private void AddDoc(IndexWriter writer, int id)
{
Document doc = new Document();
doc.Add(new TextField("content", "aaa", Field.Store.NO));
doc.Add(new StringField("id", Convert.ToString(id), Field.Store.YES));
FieldType customType2 = new FieldType(TextField.TYPE_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorPositions = true;
customType2.StoreTermVectorOffsets = true;
doc.Add(new Field("autf8", "Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", customType2));
doc.Add(new Field("utf8", "Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", customType2));
doc.Add(new Field("content2", "here is more content with aaa aaa aaa", customType2));
doc.Add(new Field("fie\u2C77ld", "field with non-ascii name", customType2));
// add numeric fields, to test if flex preserves encoding
doc.Add(new Int32Field("trieInt", id, Field.Store.NO));
doc.Add(new Int64Field("trieLong", (long)id, Field.Store.NO));
// add docvalues fields
doc.Add(new NumericDocValuesField("dvByte", (sbyte)id));
sbyte[] bytes = new sbyte[] { (sbyte)((int)((uint)id >> 24)), (sbyte)((int)((uint)id >> 16)), (sbyte)((int)((uint)id >> 8)), (sbyte)id };
BytesRef @ref = new BytesRef((byte[])(Array)bytes);
doc.Add(new BinaryDocValuesField("dvBytesDerefFixed", @ref));
doc.Add(new BinaryDocValuesField("dvBytesDerefVar", @ref));
doc.Add(new SortedDocValuesField("dvBytesSortedFixed", @ref));
doc.Add(new SortedDocValuesField("dvBytesSortedVar", @ref));
doc.Add(new BinaryDocValuesField("dvBytesStraightFixed", @ref));
doc.Add(new BinaryDocValuesField("dvBytesStraightVar", @ref));
doc.Add(new DoubleDocValuesField("dvDouble", (double)id));
doc.Add(new SingleDocValuesField("dvFloat", (float)id));
doc.Add(new NumericDocValuesField("dvInt", id));
doc.Add(new NumericDocValuesField("dvLong", id));
doc.Add(new NumericDocValuesField("dvPacked", id));
doc.Add(new NumericDocValuesField("dvShort", (short)id));
// a field with both offsets and term vectors for a cross-check
FieldType customType3 = new FieldType(TextField.TYPE_STORED);
customType3.StoreTermVectors = true;
customType3.StoreTermVectorPositions = true;
customType3.StoreTermVectorOffsets = true;
customType3.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
doc.Add(new Field("content5", "here is more content with aaa aaa aaa", customType3));
// a field that omits only positions
FieldType customType4 = new FieldType(TextField.TYPE_STORED);
customType4.StoreTermVectors = true;
customType4.StoreTermVectorPositions = false;
customType4.StoreTermVectorOffsets = true;
customType4.IndexOptions = IndexOptions.DOCS_AND_FREQS;
doc.Add(new Field("content6", "here is more content with aaa aaa aaa", customType4));
// TODO:
// index different norms types via similarity (we use a random one currently?!)
// remove any analyzer randomness, explicitly add payloads for certain fields.
writer.AddDocument(doc);
}
private void AddNoProxDoc(IndexWriter writer)
{
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_STORED);
customType.IndexOptions = IndexOptions.DOCS_ONLY;
Field f = new Field("content3", "aaa", customType);
doc.Add(f);
FieldType customType2 = new FieldType();
customType2.IsStored = true;
customType2.IndexOptions = IndexOptions.DOCS_ONLY;
f = new Field("content4", "aaa", customType2);
doc.Add(f);
writer.AddDocument(doc);
}
private int CountDocs(DocsEnum docs)
{
int count = 0;
while ((docs.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS)
{
count++;
}
return count;
}
// flex: test basics of TermsEnum api on non-flex index
[Test]
public virtual void TestNextIntoWrongField()
{
foreach (string name in oldNames)
{
Directory dir = oldIndexDirs[name];
IndexReader r = DirectoryReader.Open(dir);
TermsEnum terms = MultiFields.GetFields(r).GetTerms("content").GetEnumerator();
Assert.IsTrue(terms.MoveNext());
BytesRef t = terms.Term;
// content field only has term aaa:
Assert.AreEqual("aaa", t.Utf8ToString());
Assert.IsFalse(terms.MoveNext());
BytesRef aaaTerm = new BytesRef("aaa");
// should be found exactly
Assert.AreEqual(TermsEnum.SeekStatus.FOUND, terms.SeekCeil(aaaTerm));
Assert.AreEqual(35, CountDocs(TestUtil.Docs(Random, terms, null, null, 0)));
Assert.IsFalse(terms.MoveNext());
// should hit end of field
Assert.AreEqual(TermsEnum.SeekStatus.END, terms.SeekCeil(new BytesRef("bbb")));
Assert.IsFalse(terms.MoveNext());
// should seek to aaa
Assert.AreEqual(TermsEnum.SeekStatus.NOT_FOUND, terms.SeekCeil(new BytesRef("a")));
Assert.IsTrue(terms.Term.BytesEquals(aaaTerm));
Assert.AreEqual(35, CountDocs(TestUtil.Docs(Random, terms, null, null, 0)));
Assert.IsFalse(terms.MoveNext());
Assert.AreEqual(TermsEnum.SeekStatus.FOUND, terms.SeekCeil(aaaTerm));
Assert.AreEqual(35, CountDocs(TestUtil.Docs(Random, terms, null, null, 0)));
Assert.IsFalse(terms.MoveNext());
r.Dispose();
}
}
/// <summary>
/// Test that we didn't forget to bump the current Constants.LUCENE_MAIN_VERSION.
/// this is important so that we can determine which version of lucene wrote the segment.
/// </summary>
[Test]
public virtual void TestOldVersions()
{
// first create a little index with the current code and get the version
Directory currentDir = NewDirectory();
RandomIndexWriter riw = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, currentDir);
riw.AddDocument(new Document());
riw.Dispose();
DirectoryReader ir = DirectoryReader.Open(currentDir);
SegmentReader air = (SegmentReader)ir.Leaves[0].Reader;
string currentVersion = air.SegmentInfo.Info.Version;
Assert.IsNotNull(currentVersion); // only 3.0 segments can have a null version
ir.Dispose();
currentDir.Dispose();
IComparer<string> comparer = StringHelper.VersionComparer;
// now check all the old indexes, their version should be < the current version
foreach (string name in oldNames)
{
Directory dir = oldIndexDirs[name];
DirectoryReader r = DirectoryReader.Open(dir);
foreach (AtomicReaderContext context in r.Leaves)
{
air = (SegmentReader)context.Reader;
string oldVersion = air.SegmentInfo.Info.Version;
// TODO: does preflex codec actually set "3.0" here? this is safe to do I think.
// Assert.IsNotNull(oldVersion);
Assert.IsTrue(oldVersion == null || comparer.Compare(oldVersion, currentVersion) < 0, "current Constants.LUCENE_MAIN_VERSION is <= an old index: did you forget to bump it?!");
}
r.Dispose();
}
}
[Test]
public virtual void TestNumericFields()
{
foreach (string name in oldNames)
{
Directory dir = oldIndexDirs[name];
IndexReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
for (int id = 10; id < 15; id++)
{
ScoreDoc[] hits = searcher.Search(NumericRangeQuery.NewInt32Range("trieInt", 4, Convert.ToInt32(id), Convert.ToInt32(id), true, true), 100).ScoreDocs;
Assert.AreEqual(1, hits.Length, "wrong number of hits");
Document d = searcher.Doc(hits[0].Doc);
Assert.AreEqual(Convert.ToString(id), d.Get("id"));
hits = searcher.Search(NumericRangeQuery.NewInt64Range("trieLong", 4, Convert.ToInt64(id), Convert.ToInt64(id), true, true), 100).ScoreDocs;
Assert.AreEqual(1, hits.Length, "wrong number of hits");
d = searcher.Doc(hits[0].Doc);
Assert.AreEqual(Convert.ToString(id), d.Get("id"));
}
// check that also lower-precision fields are ok
ScoreDoc[] hits_ = searcher.Search(NumericRangeQuery.NewInt32Range("trieInt", 4, int.MinValue, int.MaxValue, false, false), 100).ScoreDocs;
Assert.AreEqual(34, hits_.Length, "wrong number of hits");
hits_ = searcher.Search(NumericRangeQuery.NewInt64Range("trieLong", 4, long.MinValue, long.MaxValue, false, false), 100).ScoreDocs;
Assert.AreEqual(34, hits_.Length, "wrong number of hits");
// check decoding into field cache
FieldCache.Int32s fci = FieldCache.DEFAULT.GetInt32s(SlowCompositeReaderWrapper.Wrap(searcher.IndexReader), "trieInt", false);
int maxDoc = searcher.IndexReader.MaxDoc;
for (int doc = 0; doc < maxDoc; doc++)
{
int val = fci.Get(doc);
Assert.IsTrue(val >= 0 && val < 35, "value in id bounds");
}
FieldCache.Int64s fcl = FieldCache.DEFAULT.GetInt64s(SlowCompositeReaderWrapper.Wrap(searcher.IndexReader), "trieLong", false);
for (int doc = 0; doc < maxDoc; doc++)
{
long val = fcl.Get(doc);
Assert.IsTrue(val >= 0L && val < 35L, "value in id bounds");
}
reader.Dispose();
}
}
private int CheckAllSegmentsUpgraded(Directory dir)
{
SegmentInfos infos = new SegmentInfos();
infos.Read(dir);
if (Verbose)
{
Console.WriteLine("checkAllSegmentsUpgraded: " + infos);
}
foreach (SegmentCommitInfo si in infos.Segments)
{
Assert.AreEqual(Constants.LUCENE_MAIN_VERSION, si.Info.Version);
}
return infos.Count;
}
private int GetNumberOfSegments(Directory dir)
{
SegmentInfos infos = new SegmentInfos();
infos.Read(dir);
return infos.Count;
}
[Test]
public virtual void TestUpgradeOldIndex()
{
List<string> names = new List<string>(oldNames.Length + oldSingleSegmentNames.Length);
names.AddRange(oldNames);
names.AddRange(oldSingleSegmentNames);
foreach (string name in names)
{
if (Verbose)
{
Console.WriteLine("testUpgradeOldIndex: index=" + name);
}
Directory dir = NewDirectory(oldIndexDirs[name]);
(new IndexUpgrader(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, null), false)).Upgrade();
CheckAllSegmentsUpgraded(dir);
dir.Dispose();
}
}
[Test]
public virtual void TestUpgradeOldSingleSegmentIndexWithAdditions()
{
foreach (string name in oldSingleSegmentNames)
{
if (Verbose)
{
Console.WriteLine("testUpgradeOldSingleSegmentIndexWithAdditions: index=" + name);
}
Directory dir = NewDirectory(oldIndexDirs[name]);
Assert.AreEqual(1, GetNumberOfSegments(dir), "Original index must be single segment");
// create a bunch of dummy segments
int id = 40;
RAMDirectory ramDir = new RAMDirectory();
for (int i = 0; i < 3; i++)
{
// only use Log- or TieredMergePolicy, to make document addition predictable and not suddenly merge:
MergePolicy mp = Random.NextBoolean() ? (MergePolicy)NewLogMergePolicy() : NewTieredMergePolicy();
IndexWriterConfig iwc = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetMergePolicy(mp);
IndexWriter w = new IndexWriter(ramDir, iwc);
// add few more docs:
for (int j = 0; j < RandomMultiplier * Random.Next(30); j++)
{
AddDoc(w, id++);
}
w.Dispose(false);
}
// add dummy segments (which are all in current
// version) to single segment index
MergePolicy mp_ = Random.NextBoolean() ? (MergePolicy)NewLogMergePolicy() : NewTieredMergePolicy();
IndexWriterConfig iwc_ = (new IndexWriterConfig(TEST_VERSION_CURRENT, null)).SetMergePolicy(mp_);
IndexWriter w_ = new IndexWriter(dir, iwc_);
w_.AddIndexes(ramDir);
w_.Dispose(false);
// determine count of segments in modified index
int origSegCount = GetNumberOfSegments(dir);
(new IndexUpgrader(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, null), false)).Upgrade();
int segCount = CheckAllSegmentsUpgraded(dir);
Assert.AreEqual(origSegCount, segCount, "Index must still contain the same number of segments, as only one segment was upgraded and nothing else merged");
dir.Dispose();
}
}
public const string SurrogatesIndexName = "index.36.surrogates.zip";
[Test]
public virtual void TestSurrogates()
{
DirectoryInfo oldIndexDir = CreateTempDir("surrogates");
using (Stream dataFile = this.GetType().FindAndGetManifestResourceStream(SurrogatesIndexName))
{
TestUtil.Unzip(dataFile, oldIndexDir);
}
Directory dir = NewFSDirectory(oldIndexDir);
// TODO: more tests
TestUtil.CheckIndex(dir);
dir.Dispose();
}
/*
* Index with negative positions (LUCENE-1542)
* Created with this code, using a 2.4.0 jar, then upgraded with 3.6 upgrader:
*
* public class CreateBogusIndexes {
* public static void main(String args[]) throws Exception {
* Directory d = FSDirectory.getDirectory("/tmp/bogus24");
* IndexWriter iw = new IndexWriter(d, new StandardAnalyzer());
* Document doc = new Document();
* Token brokenToken = new Token("broken", 0, 3);
* brokenToken.setPositionIncrement(0);
* Token okToken = new Token("ok", 0, 2);
* doc.Add(new Field("field1", new CannedTokenStream(brokenToken), Field.TermVector.NO));
* doc.Add(new Field("field2", new CannedTokenStream(brokenToken), Field.TermVector.WITH_POSITIONS));
* doc.Add(new Field("field3", new CannedTokenStream(brokenToken, okToken), Field.TermVector.NO));
* doc.Add(new Field("field4", new CannedTokenStream(brokenToken, okToken), Field.TermVector.WITH_POSITIONS));
* iw.AddDocument(doc);
* doc = new Document();
* doc.Add(new Field("field1", "just more text, not broken", Field.Store.NO, Field.Index.ANALYZED));
* doc.Add(new Field("field2", "just more text, not broken", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
* doc.Add(new Field("field3", "just more text, not broken", Field.Store.NO, Field.Index.ANALYZED));
* doc.Add(new Field("field4", "just more text, not broken", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
* iw.AddDocument(doc);
* iw.Dispose();
* d.Dispose();
* }
*
* static class CannedTokenStream extends TokenStream {
* private final Token[] tokens;
* private int upto = 0;
*
* CannedTokenStream(Token... tokens) {
* this.tokens = tokens;
* }
*
* @Override
* public Token next() {
* if (upto < tokens.Length) {
* return tokens[upto++];
* } else {
* return null;
* }
* }
* }
* }
*/
public const string Bogus24IndexName = "bogus24.upgraded.to.36.zip";
[Test]
public virtual void TestNegativePositions()
{
DirectoryInfo oldIndexDir = CreateTempDir("negatives");
using (Stream dataFile = this.GetType().FindAndGetManifestResourceStream(Bogus24IndexName))
{
TestUtil.Unzip(dataFile, oldIndexDir);
}
Directory dir = NewFSDirectory(oldIndexDir);
DirectoryReader ir = DirectoryReader.Open(dir);
IndexSearcher @is = new IndexSearcher(ir);
PhraseQuery pq = new PhraseQuery();
pq.Add(new Term("field3", "more"));
pq.Add(new Term("field3", "text"));
TopDocs td = @is.Search(pq, 10);
Assert.AreEqual(1, td.TotalHits);
AtomicReader wrapper = SlowCompositeReaderWrapper.Wrap(ir);
DocsAndPositionsEnum de = wrapper.GetTermPositionsEnum(new Term("field3", "broken"));
if (Debugging.AssertsEnabled) Debugging.Assert(de != null);
Assert.AreEqual(0, de.NextDoc());
Assert.AreEqual(0, de.NextPosition());
ir.Dispose();
TestUtil.CheckIndex(dir);
dir.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LiftedSubtractNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableByteTest(bool useInterpreter)
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableCharTest(bool useInterpreter)
{
char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableChar(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableLong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableSByteTest(bool useInterpreter)
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableSByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableULong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableUShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedSubtractNullableNumberTest(bool useInterpreter)
{
Number?[] values = new Number?[] { null, new Number(0), new Number(1), Number.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractNullableNumber(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Helpers
public static byte SubtractNullableByte(byte a, byte b)
{
return unchecked((byte)(a - b));
}
public static char SubtractNullableChar(char a, char b)
{
return unchecked((char)(a - b));
}
public static decimal SubtractNullableDecimal(decimal a, decimal b)
{
return (decimal)(a - b);
}
public static double SubtractNullableDouble(double a, double b)
{
return (double)(a - b);
}
public static float SubtractNullableFloat(float a, float b)
{
return (float)(a - b);
}
public static int SubtractNullableInt(int a, int b)
{
return unchecked((int)(a - b));
}
public static long SubtractNullableLong(long a, long b)
{
return unchecked((long)(a - b));
}
public static sbyte SubtractNullableSByte(sbyte a, sbyte b)
{
return unchecked((sbyte)(a - b));
}
public static short SubtractNullableShort(short a, short b)
{
return unchecked((short)(a - b));
}
public static uint SubtractNullableUInt(uint a, uint b)
{
return unchecked((uint)(a - b));
}
public static ulong SubtractNullableULong(ulong a, ulong b)
{
return unchecked((ulong)(a - b));
}
public static ushort SubtractNullableUShort(ushort a, ushort b)
{
return unchecked((ushort)(a - b));
}
#endregion
#region Test verifiers
private static void VerifySubtractNullableByte(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
Expression.Subtract(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableByte")));
Func<byte?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((byte?)(a - b)), f());
}
private static void VerifySubtractNullableChar(char? a, char? b, bool useInterpreter)
{
Expression<Func<char?>> e =
Expression.Lambda<Func<char?>>(
Expression.Subtract(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableChar")));
Func<char?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((char?)(a - b)), f());
}
private static void VerifySubtractNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Subtract(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableDecimal")));
Func<decimal?> f = e.Compile(useInterpreter);
decimal? expected = default(decimal);
try
{
expected = checked(a - b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifySubtractNullableDouble(double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Subtract(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableDouble")));
Func<double?> f = e.Compile(useInterpreter);
Assert.Equal(a - b, f());
}
private static void VerifySubtractNullableFloat(float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Subtract(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableFloat")));
Func<float?> f = e.Compile(useInterpreter);
Assert.Equal(a - b, f());
}
private static void VerifySubtractNullableInt(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Subtract(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableInt")));
Func<int?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a - b), f());
}
private static void VerifySubtractNullableLong(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Subtract(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableLong")));
Func<long?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a - b), f());
}
private static void VerifySubtractNullableSByte(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
Expression.Subtract(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableSByte")));
Func<sbyte?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((sbyte?)(a - b)), f());
}
private static void VerifySubtractNullableShort(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Subtract(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableShort")));
Func<short?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short?)(a - b)), f());
}
private static void VerifySubtractNullableUInt(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Subtract(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableUInt")));
Func<uint?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a - b), f());
}
private static void VerifySubtractNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Subtract(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableULong")));
Func<ulong?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a - b), f());
}
private static void VerifySubtractNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Subtract(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
typeof(LiftedSubtractNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractNullableUShort")));
Func<ushort?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort?)(a - b)), f());
}
private static void VerifySubtractNullableNumber(Number? a, Number? b, bool useInterpreter)
{
Expression<Func<Number?>> e =
Expression.Lambda<Func<Number?>>(
Expression.Subtract(
Expression.Constant(a, typeof(Number?)),
Expression.Constant(b, typeof(Number?))));
Assert.Equal(typeof(Number?), e.Body.Type);
Func<Number?> f = e.Compile(useInterpreter);
Number? expected = a - b;
Assert.Equal(expected, f());
}
#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.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
{
public delegate void OnIRCClientReadyDelegate(IRCClientView cv);
public class IRCClientView : IClientAPI, IClientCore, IClientIPEndpoint
{
public event OnIRCClientReadyDelegate OnIRCReady;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly TcpClient m_client;
private readonly Scene m_scene;
private UUID m_agentID = UUID.Random();
private string m_username;
private string m_nick;
private bool m_hasNick = false;
private bool m_hasUser = false;
private bool m_connected = true;
public IRCClientView(TcpClient client, Scene scene)
{
m_client = client;
m_scene = scene;
Watchdog.StartThread(InternalLoop, "IRCClientView", ThreadPriority.Normal, false);
}
private void SendServerCommand(string command)
{
SendCommand(":opensimircd " + command);
}
private void SendCommand(string command)
{
m_log.Info("[IRCd] Sending >>> " + command);
byte[] buf = Util.UTF8.GetBytes(command + "\r\n");
m_client.GetStream().BeginWrite(buf, 0, buf.Length, SendComplete, null);
}
private void SendComplete(IAsyncResult result)
{
m_log.Info("[IRCd] Send Complete.");
}
private string IrcRegionName
{
// I know &Channel is more technically correct, but people are used to seeing #Channel
// Dont shoot me!
get { return "#" + m_scene.RegionInfo.RegionName.Replace(" ", "-"); }
}
private void InternalLoop()
{
try
{
string strbuf = String.Empty;
while (m_connected && m_client.Connected)
{
byte[] buf = new byte[8]; // RFC1459 defines max message size as 512.
int count = m_client.GetStream().Read(buf, 0, buf.Length);
string line = Util.UTF8.GetString(buf, 0, count);
strbuf += line;
string message = ExtractMessage(strbuf);
if (message != null)
{
// Remove from buffer
strbuf = strbuf.Remove(0, message.Length);
m_log.Info("[IRCd] Recieving <<< " + message);
message = message.Trim();
// Extract command sequence
string command = ExtractCommand(message);
ProcessInMessage(message, command);
}
else
{
//m_log.Info("[IRCd] Recieved data, but not enough to make a message. BufLen is " + strbuf.Length +
// "[" + strbuf + "]");
if (strbuf.Length == 0)
{
m_connected = false;
m_log.Info("[IRCd] Buffer zero, closing...");
if (OnDisconnectUser != null)
OnDisconnectUser();
}
}
Thread.Sleep(0);
Watchdog.UpdateThread();
}
}
catch (IOException)
{
if (OnDisconnectUser != null)
OnDisconnectUser();
m_log.Warn("[IRCd] Disconnected client.");
}
catch (SocketException)
{
if (OnDisconnectUser != null)
OnDisconnectUser();
m_log.Warn("[IRCd] Disconnected client.");
}
Watchdog.RemoveThread();
}
private void ProcessInMessage(string message, string command)
{
m_log.Info("[IRCd] Processing [MSG:" + message + "] [COM:" + command + "]");
if (command != null)
{
switch (command)
{
case "ADMIN":
case "AWAY":
case "CONNECT":
case "DIE":
case "ERROR":
case "INFO":
case "INVITE":
case "ISON":
case "KICK":
case "KILL":
case "LINKS":
case "LUSERS":
case "OPER":
case "PART":
case "REHASH":
case "SERVICE":
case "SERVLIST":
case "SERVER":
case "SQUERY":
case "SQUIT":
case "STATS":
case "SUMMON":
case "TIME":
case "TRACE":
case "VERSION":
case "WALLOPS":
case "WHOIS":
case "WHOWAS":
SendServerCommand("421 " + command + " :Command unimplemented");
break;
// Connection Commands
case "PASS":
break; // Ignore for now. I want to implement authentication later however.
case "JOIN":
IRC_SendReplyJoin();
break;
case "MODE":
IRC_SendReplyModeChannel();
break;
case "USER":
IRC_ProcessUser(message);
IRC_Ready();
break;
case "USERHOST":
string[] userhostArgs = ExtractParameters(message);
if (userhostArgs[0] == ":" + m_nick)
{
SendServerCommand("302 :" + m_nick + "=+" + m_nick + "@" +
((IPEndPoint) m_client.Client.RemoteEndPoint).Address);
}
break;
case "NICK":
IRC_ProcessNick(message);
IRC_Ready();
break;
case "TOPIC":
IRC_SendReplyTopic();
break;
case "USERS":
IRC_SendReplyUsers();
break;
case "LIST":
break; // TODO
case "MOTD":
IRC_SendMOTD();
break;
case "NOTICE": // TODO
break;
case "WHO": // TODO
IRC_SendNamesReply();
IRC_SendWhoReply();
break;
case "PING":
IRC_ProcessPing(message);
break;
// Special case, ignore this completely.
case "PONG":
break;
case "QUIT":
if (OnDisconnectUser != null)
OnDisconnectUser();
break;
case "NAMES":
IRC_SendNamesReply();
break;
case "PRIVMSG":
IRC_ProcessPrivmsg(message);
break;
default:
SendServerCommand("421 " + command + " :Unknown command");
break;
}
}
}
private void IRC_Ready()
{
if (m_hasUser && m_hasNick)
{
SendServerCommand("001 " + m_nick + " :Welcome to OpenSimulator IRCd");
SendServerCommand("002 " + m_nick + " :Running OpenSimVersion");
SendServerCommand("003 " + m_nick + " :This server was created over 9000 years ago");
SendServerCommand("004 " + m_nick + " :opensimirc r1 aoOirw abeiIklmnoOpqrstv");
SendServerCommand("251 " + m_nick + " :There are 0 users and 0 services on 1 servers");
SendServerCommand("252 " + m_nick + " 0 :operators online");
SendServerCommand("253 " + m_nick + " 0 :unknown connections");
SendServerCommand("254 " + m_nick + " 1 :channels formed");
SendServerCommand("255 " + m_nick + " :I have 1 users, 0 services and 1 servers");
SendCommand(":" + m_nick + " MODE " + m_nick + " :+i");
SendCommand(":" + m_nick + " JOIN :" + IrcRegionName);
// Rename to 'Real Name'
SendCommand(":" + m_nick + " NICK :" + m_username.Replace(" ", ""));
m_nick = m_username.Replace(" ", "");
IRC_SendReplyJoin();
IRC_SendChannelPrivmsg("System", "Welcome to OpenSimulator.");
IRC_SendChannelPrivmsg("System", "You are in a maze of twisty little passages, all alike.");
IRC_SendChannelPrivmsg("System", "It is pitch black. You are likely to be eaten by a grue.");
if (OnIRCReady != null)
OnIRCReady(this);
}
}
private void IRC_SendReplyJoin()
{
IRC_SendReplyTopic();
IRC_SendNamesReply();
}
private void IRC_SendReplyModeChannel()
{
SendServerCommand("324 " + m_nick + " " + IrcRegionName + " +n");
//SendCommand(":" + IrcRegionName + " MODE +n");
}
private void IRC_ProcessUser(string message)
{
string[] userArgs = ExtractParameters(message);
// TODO: unused: string username = userArgs[0];
// TODO: unused: string hostname = userArgs[1];
// TODO: unused: string servername = userArgs[2];
string realname = userArgs[3].Replace(":", "");
m_username = realname;
m_hasUser = true;
}
private void IRC_ProcessNick(string message)
{
string[] nickArgs = ExtractParameters(message);
string nickname = nickArgs[0].Replace(":","");
m_nick = nickname;
m_hasNick = true;
}
private void IRC_ProcessPing(string message)
{
string[] pingArgs = ExtractParameters(message);
string pingHost = pingArgs[0];
SendCommand("PONG " + pingHost);
}
private void IRC_ProcessPrivmsg(string message)
{
string[] privmsgArgs = ExtractParameters(message);
if (privmsgArgs[0] == IrcRegionName)
{
if (OnChatFromClient != null)
{
OSChatMessage msg = new OSChatMessage();
msg.Sender = this;
msg.Channel = 0;
msg.From = this.Name;
msg.Message = privmsgArgs[1].Replace(":", "");
msg.Position = Vector3.Zero;
msg.Scene = m_scene;
msg.SenderObject = null;
msg.SenderUUID = this.AgentId;
msg.Type = ChatTypeEnum.Say;
OnChatFromClient(this, msg);
}
}
else
{
// Handle as an IM, later.
}
}
private void IRC_SendNamesReply()
{
EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>();
foreach (EntityBase user in users)
{
SendServerCommand("353 " + m_nick + " = " + IrcRegionName + " :" + user.Name.Replace(" ", ""));
}
SendServerCommand("366 " + IrcRegionName + " :End of /NAMES list");
}
private void IRC_SendWhoReply()
{
EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>();
foreach (EntityBase user in users)
{
/*SendServerCommand(String.Format("352 {0} {1} {2} {3} {4} {5} :0 {6}", IrcRegionName,
user.Name.Replace(" ", ""), "nohost.com", "opensimircd",
user.Name.Replace(" ", ""), 'H', user.Name));*/
SendServerCommand("352 " + m_nick + " " + IrcRegionName + " n=" + user.Name.Replace(" ", "") + " fakehost.com " + user.Name.Replace(" ", "") + " H " + ":0 " + user.Name);
//SendServerCommand("352 " + IrcRegionName + " " + user.Name.Replace(" ", "") + " nohost.com irc.opensimulator " + user.Name.Replace(" ", "") + " H " + ":0 " + user.Name);
}
SendServerCommand("315 " + m_nick + " " + IrcRegionName + " :End of /WHO list");
}
private void IRC_SendMOTD()
{
SendServerCommand("375 :- OpenSimulator Message of the day -");
SendServerCommand("372 :- Hiya!");
SendServerCommand("376 :End of /MOTD command");
}
private void IRC_SendReplyTopic()
{
SendServerCommand("332 " + IrcRegionName + " :OpenSimulator IRC Server");
}
private void IRC_SendReplyUsers()
{
EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>();
SendServerCommand("392 :UserID Terminal Host");
if (users.Length == 0)
{
SendServerCommand("395 :Nobody logged in");
return;
}
foreach (EntityBase user in users)
{
char[] nom = new char[8];
char[] term = "terminal_".ToCharArray();
char[] host = "hostname".ToCharArray();
string userName = user.Name.Replace(" ","");
for (int i = 0; i < nom.Length; i++)
{
if (userName.Length < i)
nom[i] = userName[i];
else
nom[i] = ' ';
}
SendServerCommand("393 :" + nom + " " + term + " " + host + "");
}
SendServerCommand("394 :End of users");
}
private static string ExtractMessage(string buffer)
{
int pos = buffer.IndexOf("\r\n");
if (pos == -1)
return null;
string command = buffer.Substring(0, pos + 2);
return command;
}
private static string ExtractCommand(string msg)
{
string[] msgs = msg.Split(' ');
if (msgs.Length < 2)
{
m_log.Warn("[IRCd] Dropped msg: " + msg);
return null;
}
if (msgs[0].StartsWith(":"))
return msgs[1];
return msgs[0];
}
private static string[] ExtractParameters(string msg)
{
string[] msgs = msg.Split(' ');
List<string> parms = new List<string>(msgs.Length);
bool foundCommand = false;
string command = ExtractCommand(msg);
for (int i=0;i<msgs.Length;i++)
{
if (msgs[i] == command)
{
foundCommand = true;
continue;
}
if (foundCommand != true)
continue;
if (i != 0 && msgs[i].StartsWith(":"))
{
List<string> tmp = new List<string>();
for (int j=i;j<msgs.Length;j++)
{
tmp.Add(msgs[j]);
}
parms.Add(string.Join(" ", tmp.ToArray()));
break;
}
parms.Add(msgs[i]);
}
return parms.ToArray();
}
#region Implementation of IClientAPI
public Vector3 StartPos
{
get { return new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 50); }
set { }
}
public bool TryGet<T>(out T iface)
{
iface = default(T);
return false;
}
public T Get<T>()
{
return default(T);
}
public UUID AgentId
{
get { return m_agentID; }
}
public void Disconnect(string reason)
{
IRC_SendChannelPrivmsg("System", "You have been eaten by a grue. (" + reason + ")");
m_connected = false;
m_client.Close();
}
public void Disconnect()
{
IRC_SendChannelPrivmsg("System", "You have been eaten by a grue.");
m_connected = false;
m_client.Close();
}
public UUID SessionId
{
get { return m_agentID; }
}
public UUID SecureSessionId
{
get { return m_agentID; }
}
public UUID ActiveGroupId
{
get { return UUID.Zero; }
}
public string ActiveGroupName
{
get { return "IRCd User"; }
}
public ulong ActiveGroupPowers
{
get { return 0; }
}
public ulong GetGroupPowers(UUID groupID)
{
return 0;
}
public bool IsGroupMember(UUID GroupID)
{
return false;
}
public string FirstName
{
get
{
string[] names = m_username.Split(' ');
return names[0];
}
}
public string LastName
{
get
{
string[] names = m_username.Split(' ');
if (names.Length > 1)
return names[1];
return names[0];
}
}
public IScene Scene
{
get { return m_scene; }
}
public int NextAnimationSequenceNumber
{
get { return 0; }
}
public string Name
{
get { return m_username; }
}
public bool IsActive
{
get { return true; }
set { if (!value) Disconnect("IsActive Disconnected?"); }
}
public bool IsLoggingOut
{
get { return false; }
set { }
}
public bool SendLogoutPacketWhenClosing
{
set { }
}
public uint CircuitCode
{
get { return (uint)Util.RandomClass.Next(0,int.MaxValue); }
}
public IPEndPoint RemoteEndPoint
{
get { return (IPEndPoint)m_client.Client.RemoteEndPoint; }
}
#pragma warning disable 67
public event GenericMessage OnGenericMessage;
public event ImprovedInstantMessage OnInstantMessage;
public event ChatMessage OnChatFromClient;
public event TextureRequest OnRequestTexture;
public event RezObject OnRezObject;
public event ModifyTerrain OnModifyTerrain;
public event BakeTerrain OnBakeTerrain;
public event EstateChangeInfo OnEstateChangeInfo;
public event SetAppearance OnSetAppearance;
public event AvatarNowWearing OnAvatarNowWearing;
public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv;
public event UUIDNameRequest OnDetachAttachmentIntoInv;
public event ObjectAttach OnObjectAttach;
public event ObjectDeselect OnObjectDetach;
public event ObjectDrop OnObjectDrop;
public event StartAnim OnStartAnim;
public event StopAnim OnStopAnim;
public event LinkObjects OnLinkObjects;
public event DelinkObjects OnDelinkObjects;
public event RequestMapBlocks OnRequestMapBlocks;
public event RequestMapName OnMapNameRequest;
public event TeleportLocationRequest OnTeleportLocationRequest;
public event DisconnectUser OnDisconnectUser;
public event RequestAvatarProperties OnRequestAvatarProperties;
public event SetAlwaysRun OnSetAlwaysRun;
public event TeleportLandmarkRequest OnTeleportLandmarkRequest;
public event DeRezObject OnDeRezObject;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall1 OnRequestWearables;
public event GenericCall1 OnCompleteMovementToRegion;
public event UpdateAgent OnPreAgentUpdate;
public event UpdateAgent OnAgentUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
public event AvatarPickerRequest OnAvatarPickerRequest;
public event Action<IClientAPI> OnRequestAvatarsData;
public event AddNewPrim OnAddPrim;
public event FetchInventory OnAgentDataUpdateRequest;
public event TeleportLocationRequest OnSetStartLocationRequest;
public event RequestGodlikePowers OnRequestGodlikePowers;
public event GodKickUser OnGodKickUser;
public event ObjectDuplicate OnObjectDuplicate;
public event ObjectDuplicateOnRay OnObjectDuplicateOnRay;
public event GrabObject OnGrabObject;
public event DeGrabObject OnDeGrabObject;
public event MoveObject OnGrabUpdate;
public event SpinStart OnSpinStart;
public event SpinObject OnSpinUpdate;
public event SpinStop OnSpinStop;
public event UpdateShape OnUpdatePrimShape;
public event ObjectExtraParams OnUpdateExtraParams;
public event ObjectRequest OnObjectRequest;
public event ObjectSelect OnObjectSelect;
public event ObjectDeselect OnObjectDeselect;
public event GenericCall7 OnObjectDescription;
public event GenericCall7 OnObjectName;
public event GenericCall7 OnObjectClickAction;
public event GenericCall7 OnObjectMaterial;
public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily;
public event UpdatePrimFlags OnUpdatePrimFlags;
public event UpdatePrimTexture OnUpdatePrimTexture;
public event UpdateVector OnUpdatePrimGroupPosition;
public event UpdateVector OnUpdatePrimSinglePosition;
public event UpdatePrimRotation OnUpdatePrimGroupRotation;
public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation;
public event UpdateVector OnUpdatePrimScale;
public event UpdateVector OnUpdatePrimGroupScale;
public event StatusChange OnChildAgentStatus;
public event GenericCall2 OnStopMovement;
public event Action<UUID> OnRemoveAvatar;
public event ObjectPermissions OnObjectPermissions;
public event CreateNewInventoryItem OnCreateNewInventoryItem;
public event LinkInventoryItem OnLinkInventoryItem;
public event CreateInventoryFolder OnCreateNewInventoryFolder;
public event UpdateInventoryFolder OnUpdateInventoryFolder;
public event MoveInventoryFolder OnMoveInventoryFolder;
public event FetchInventoryDescendents OnFetchInventoryDescendents;
public event PurgeInventoryDescendents OnPurgeInventoryDescendents;
public event FetchInventory OnFetchInventory;
public event RequestTaskInventory OnRequestTaskInventory;
public event UpdateInventoryItem OnUpdateInventoryItem;
public event CopyInventoryItem OnCopyInventoryItem;
public event MoveInventoryItem OnMoveInventoryItem;
public event RemoveInventoryFolder OnRemoveInventoryFolder;
public event RemoveInventoryItem OnRemoveInventoryItem;
public event UDPAssetUploadRequest OnAssetUploadRequest;
public event XferReceive OnXferReceive;
public event RequestXfer OnRequestXfer;
public event ConfirmXfer OnConfirmXfer;
public event AbortXfer OnAbortXfer;
public event RezScript OnRezScript;
public event UpdateTaskInventory OnUpdateTaskInventory;
public event MoveTaskInventory OnMoveTaskItem;
public event RemoveTaskInventory OnRemoveTaskItem;
public event RequestAsset OnRequestAsset;
public event UUIDNameRequest OnNameFromUUIDRequest;
public event ParcelAccessListRequest OnParcelAccessListRequest;
public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest;
public event ParcelPropertiesRequest OnParcelPropertiesRequest;
public event ParcelDivideRequest OnParcelDivideRequest;
public event ParcelJoinRequest OnParcelJoinRequest;
public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest;
public event ParcelSelectObjects OnParcelSelectObjects;
public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest;
public event ParcelAbandonRequest OnParcelAbandonRequest;
public event ParcelGodForceOwner OnParcelGodForceOwner;
public event ParcelReclaim OnParcelReclaim;
public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest;
public event ParcelDeedToGroup OnParcelDeedToGroup;
public event RegionInfoRequest OnRegionInfoRequest;
public event EstateCovenantRequest OnEstateCovenantRequest;
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event GrantUserFriendRights OnGrantUserRights;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
public event UpdateAvatarProperties OnUpdateAvatarProperties;
public event ParcelBuy OnParcelBuy;
public event RequestPayPrice OnRequestPayPrice;
public event ObjectSaleInfo OnObjectSaleInfo;
public event ObjectBuy OnObjectBuy;
public event BuyObjectInventory OnBuyObjectInventory;
public event RequestTerrain OnRequestTerrain;
public event RequestTerrain OnUploadTerrain;
public event ObjectIncludeInSearch OnObjectIncludeInSearch;
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
public event SetEstateFlagsRequest OnSetEstateFlagsRequest;
public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture;
public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture;
public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights;
public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest;
public event SetRegionTerrainSettings OnSetRegionTerrainSettings;
public event EstateRestartSimRequest OnEstateRestartSimRequest;
public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest;
public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest;
public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest;
public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest;
public event EstateDebugRegionRequest OnEstateDebugRegionRequest;
public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest;
public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest;
public event UUIDNameRequest OnUUIDGroupNameRequest;
public event RegionHandleRequest OnRegionHandleRequest;
public event ParcelInfoRequest OnParcelInfoRequest;
public event RequestObjectPropertiesFamily OnObjectGroupRequest;
public event ScriptReset OnScriptReset;
public event GetScriptRunning OnGetScriptRunning;
public event SetScriptRunning OnSetScriptRunning;
public event UpdateVector OnAutoPilotGo;
public event TerrainUnacked OnUnackedTerrain;
public event ActivateGesture OnActivateGesture;
public event DeactivateGesture OnDeactivateGesture;
public event ObjectOwner OnObjectOwner;
public event DirPlacesQuery OnDirPlacesQuery;
public event DirFindQuery OnDirFindQuery;
public event DirLandQuery OnDirLandQuery;
public event DirPopularQuery OnDirPopularQuery;
public event DirClassifiedQuery OnDirClassifiedQuery;
public event EventInfoRequest OnEventInfoRequest;
public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime;
public event MapItemRequest OnMapItemRequest;
public event OfferCallingCard OnOfferCallingCard;
public event AcceptCallingCard OnAcceptCallingCard;
public event DeclineCallingCard OnDeclineCallingCard;
public event SoundTrigger OnSoundTrigger;
public event StartLure OnStartLure;
public event TeleportLureRequest OnTeleportLureRequest;
public event NetworkStats OnNetworkStatsUpdate;
public event ClassifiedInfoRequest OnClassifiedInfoRequest;
public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
public event ClassifiedDelete OnClassifiedDelete;
public event ClassifiedDelete OnClassifiedGodDelete;
public event EventNotificationAddRequest OnEventNotificationAddRequest;
public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
public event EventGodDelete OnEventGodDelete;
public event ParcelDwellRequest OnParcelDwellRequest;
public event UserInfoRequest OnUserInfoRequest;
public event UpdateUserInfo OnUpdateUserInfo;
public event RetrieveInstantMessages OnRetrieveInstantMessages;
public event PickDelete OnPickDelete;
public event PickGodDelete OnPickGodDelete;
public event PickInfoUpdate OnPickInfoUpdate;
public event AvatarNotesUpdate OnAvatarNotesUpdate;
public event MuteListRequest OnMuteListRequest;
public event AvatarInterestUpdate OnAvatarInterestUpdate;
public event PlacesQuery OnPlacesQuery;
public event FindAgentUpdate OnFindAgent;
public event TrackAgentUpdate OnTrackAgent;
public event NewUserReport OnUserReport;
public event SaveStateHandler OnSaveState;
public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest;
public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest;
public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest;
public event FreezeUserUpdate OnParcelFreezeUser;
public event EjectUserUpdate OnParcelEjectUser;
public event ParcelBuyPass OnParcelBuyPass;
public event ParcelGodMark OnParcelGodMark;
public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest;
public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
public event SimWideDeletesDelegate OnSimWideDeletes;
public event SendPostcard OnSendPostcard;
public event MuteListEntryUpdate OnUpdateMuteListEntry;
public event MuteListEntryRemove OnRemoveMuteListEntry;
public event GodlikeMessage onGodlikeMessage;
public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate;
#pragma warning restore 67
public void SetDebugPacketLevel(int newDebug)
{
}
public void InPacket(object NewPack)
{
}
public void ProcessInPacket(Packet NewPack)
{
}
public void Close()
{
Disconnect();
}
public void Kick(string message)
{
Disconnect(message);
}
public void Start()
{
Scene.AddNewClient(this);
// Mimicking LLClientView which gets always set appearance from client.
Scene scene = (Scene)Scene;
AvatarAppearance appearance;
scene.GetAvatarAppearance(this, out appearance);
OnSetAppearance(this, appearance.Texture, (byte[])appearance.VisualParams.Clone());
}
public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
{
m_log.Info("[IRCd ClientStack] Completing Handshake to Region");
if (OnRegionHandShakeReply != null)
{
OnRegionHandShakeReply(this);
}
if (OnCompleteMovementToRegion != null)
{
OnCompleteMovementToRegion(this);
}
}
public void Stop()
{
Disconnect();
}
public void SendWearables(AvatarWearable[] wearables, int serial)
{
}
public void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry)
{
}
public void SendStartPingCheck(byte seq)
{
}
public void SendKillObject(ulong regionHandle, uint localID)
{
}
public void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs)
{
}
public void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible)
{
if (audible > 0 && message.Length > 0)
IRC_SendChannelPrivmsg(fromName, message);
}
private void IRC_SendChannelPrivmsg(string fromName, string message)
{
SendCommand(":" + fromName.Replace(" ", "") + " PRIVMSG " + IrcRegionName + " :" + message);
}
public void SendInstantMessage(GridInstantMessage im)
{
// TODO
}
public void SendGenericMessage(string method, List<string> message)
{
}
public void SendGenericMessage(string method, List<byte[]> message)
{
}
public void SendLayerData(float[] map)
{
}
public void SendLayerData(int px, int py, float[] map)
{
}
public void SendWindData(Vector2[] windSpeeds)
{
}
public void SendCloudData(float[] cloudCover)
{
}
public void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look)
{
}
public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint)
{
}
public AgentCircuitData RequestClientInfo()
{
return new AgentCircuitData();
}
public void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL)
{
}
public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
{
}
public void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags)
{
}
public void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL)
{
}
public void SendTeleportFailed(string reason)
{
}
public void SendTeleportStart(uint flags)
{
}
public void SendTeleportProgress(uint flags, string message)
{
}
public void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance)
{
}
public void SendPayPrice(UUID objectID, int[] payPrice)
{
}
public void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations)
{
}
public void SendAvatarDataImmediate(ISceneEntity avatar)
{
}
public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags)
{
}
public void ReprioritizeUpdates()
{
}
public void FlushPrimUpdates()
{
}
public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems)
{
}
public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item)
{
}
public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId)
{
}
public void SendRemoveInventoryItem(UUID itemID)
{
}
public void SendTakeControls(int controls, bool passToAgent, bool TakeControls)
{
}
public void SendTaskInventory(UUID taskID, short serial, byte[] fileName)
{
}
public void SendBulkUpdateInventory(InventoryNodeBase node)
{
}
public void SendXferPacket(ulong xferID, uint packet, byte[] data)
{
}
public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent)
{
}
public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
{
}
public void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
{
}
public void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID)
{
}
public void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags)
{
}
public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain)
{
}
public void SendAttachedSoundGainChange(UUID objectID, float gain)
{
}
public void SendNameReply(UUID profileId, string firstname, string lastname)
{
}
public void SendAlertMessage(string message)
{
IRC_SendChannelPrivmsg("Alert",message);
}
public void SendAgentAlertMessage(string message, bool modal)
{
}
public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url)
{
IRC_SendChannelPrivmsg(objectname,url);
}
public void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels)
{
}
public bool AddMoney(int debit)
{
return true;
}
public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition)
{
}
public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks)
{
}
public void SendViewerTime(int phase)
{
}
public UUID GetDefaultAnimation(string name)
{
return UUID.Zero;
}
public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID)
{
}
public void SendScriptQuestion(UUID taskID, string taskName, string ownerName, UUID itemID, int question)
{
}
public void SendHealth(float health)
{
}
public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID)
{
}
public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID)
{
}
public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
{
}
public void SendEstateCovenantInformation(UUID covenant)
{
}
public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner)
{
}
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
{
}
public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID)
{
}
public void SendForceClientSelectObjects(List<uint> objectIDs)
{
}
public void SendCameraConstraint(Vector4 ConstraintPlane)
{
}
public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount)
{
}
public void SendLandParcelOverlay(byte[] data, int sequence_id)
{
}
public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
{
}
public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
{
}
public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
{
}
public void SendConfirmXfer(ulong xferID, uint PacketID)
{
}
public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName)
{
}
public void SendInitiateDownload(string simFileName, string clientFileName)
{
}
public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
{
}
public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData)
{
}
public void SendImageNotFound(UUID imageid)
{
}
public void SendShutdownConnectionNotice()
{
// TODO
}
public void SendSimStats(SimStats stats)
{
}
public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description)
{
}
public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice)
{
}
public void SendAgentOffline(UUID[] agentIDs)
{
}
public void SendAgentOnline(UUID[] agentIDs)
{
}
public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook)
{
}
public void SendAdminResponse(UUID Token, uint AdminLevel)
{
}
public void SendGroupMembership(GroupMembershipData[] GroupMembership)
{
}
public void SendGroupNameReply(UUID groupLLUID, string GroupName)
{
}
public void SendJoinGroupReply(UUID groupID, bool success)
{
}
public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success)
{
}
public void SendLeaveGroupReply(UUID groupID, bool success)
{
}
public void SendCreateGroupReply(UUID groupID, bool success, string message)
{
}
public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia)
{
}
public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running)
{
}
public void SendAsset(AssetRequestToClient req)
{
}
public void SendTexture(AssetBase TextureAsset)
{
}
public virtual void SetChildAgentThrottle(byte[] throttle)
{
}
public byte[] GetThrottlesPacked(float multiplier)
{
return new byte[0];
}
public event ViewerEffectEventHandler OnViewerEffect;
public event Action<IClientAPI> OnLogout;
public event Action<IClientAPI> OnConnectionClosed;
public void SendBlueBoxMessage(UUID FromAvatarID, string FromAvatarName, string Message)
{
IRC_SendChannelPrivmsg(FromAvatarName, Message);
}
public void SendLogoutPacket()
{
Disconnect();
}
public EndPoint GetClientEP()
{
return null;
}
public ClientInfo GetClientInfo()
{
return new ClientInfo();
}
public void SetClientInfo(ClientInfo info)
{
}
public void SetClientOption(string option, string value)
{
}
public string GetClientOption(string option)
{
return String.Empty;
}
public void Terminate()
{
Disconnect();
}
public void SendSetFollowCamProperties(UUID objectID, SortedDictionary<int, float> parameters)
{
}
public void SendClearFollowCamProperties(UUID objectID)
{
}
public void SendRegionHandle(UUID regoinID, ulong handle)
{
}
public void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y)
{
}
public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt)
{
}
public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data)
{
}
public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data)
{
}
public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data)
{
}
public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data)
{
}
public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data)
{
}
public void SendDirLandReply(UUID queryID, DirLandReplyData[] data)
{
}
public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data)
{
}
public void SendEventInfoReply(EventData info)
{
}
public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
{
}
public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data)
{
}
public void SendOfferCallingCard(UUID srcID, UUID transactionID)
{
}
public void SendAcceptCallingCard(UUID transactionID)
{
}
public void SendDeclineCallingCard(UUID transactionID)
{
}
public void SendTerminateFriend(UUID exFriendID)
{
}
public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name)
{
}
public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price)
{
}
public void SendAgentDropGroup(UUID groupID)
{
}
public void RefreshGroupMembership()
{
}
public void SendAvatarNotesReply(UUID targetID, string text)
{
}
public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks)
{
}
public void SendPickInfoReply(UUID pickID, UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled)
{
}
public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds)
{
}
public void SendAvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages)
{
}
public void SendParcelDwellReply(int localID, UUID parcelID, float dwell)
{
}
public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
{
}
public void SendUseCachedMuteList()
{
}
public void SendMuteListUpdate(string filename)
{
}
public void KillEndDone()
{
}
public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
{
return true;
}
#endregion
#region Implementation of IClientIPEndpoint
public IPAddress EndPoint
{
get { return ((IPEndPoint) m_client.Client.RemoteEndPoint).Address; }
}
#endregion
public void SendRebakeAvatarTextures(UUID textureID)
{
}
public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages)
{
}
public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt)
{
}
public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier)
{
}
public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt)
{
}
public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes)
{
}
public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
{
}
public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
{
}
public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
{
}
public void StopFlying(ISceneEntity presence)
{
}
public void SendVoxelUpdate(int x, int y, int z, byte b)
{
}
public void SendChunkUpdate(int x, int y, int z)
{
}
}
}
| |
// 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 Xunit;
namespace System.Numerics.Tests
{
public class cast_toTest
{
public delegate void ExceptionGenerator();
private const int NumberOfRandomIterations = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunByteImplicitCastToBigIntegerTests()
{
// Byte Implicit Cast to BigInteger: Byte.MinValue
VerifyByteImplicitCastToBigInteger(Byte.MinValue);
// Byte Implicit Cast to BigInteger: 0
VerifyByteImplicitCastToBigInteger(0);
// Byte Implicit Cast to BigInteger: 1
VerifyByteImplicitCastToBigInteger(1);
// Byte Implicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyByteImplicitCastToBigInteger((Byte)s_random.Next(1, Byte.MaxValue));
}
// Byte Implicit Cast to BigInteger: Byte.MaxValue
VerifyByteImplicitCastToBigInteger(Byte.MaxValue);
}
[Fact]
public static void RunSByteImplicitCastToBigIntegerTests()
{
// SByte Implicit Cast to BigInteger: SByte.MinValue
VerifySByteImplicitCastToBigInteger(SByte.MinValue);
// SByte Implicit Cast to BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySByteImplicitCastToBigInteger((SByte)s_random.Next(SByte.MinValue, 0));
}
// SByte Implicit Cast to BigInteger: -1
VerifySByteImplicitCastToBigInteger(-1);
// SByte Implicit Cast to BigInteger: 0
VerifySByteImplicitCastToBigInteger(0);
// SByte Implicit Cast to BigInteger: 1
VerifySByteImplicitCastToBigInteger(1);
// SByte Implicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySByteImplicitCastToBigInteger((SByte)s_random.Next(1, SByte.MaxValue));
}
// SByte Implicit Cast to BigInteger: SByte.MaxValue
VerifySByteImplicitCastToBigInteger(SByte.MaxValue);
}
[Fact]
public static void RunUInt16ImplicitCastToBigIntegerTests()
{
// UInt16 Implicit Cast to BigInteger: UInt16.MinValue
VerifyUInt16ImplicitCastToBigInteger(UInt16.MinValue);
// UInt16 Implicit Cast to BigInteger: 0
VerifyUInt16ImplicitCastToBigInteger(0);
// UInt16 Implicit Cast to BigInteger: 1
VerifyUInt16ImplicitCastToBigInteger(1);
// UInt16 Implicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyUInt16ImplicitCastToBigInteger((UInt16)s_random.Next(1, UInt16.MaxValue));
}
// UInt16 Implicit Cast to BigInteger: UInt16.MaxValue
VerifyUInt16ImplicitCastToBigInteger(UInt16.MaxValue);
}
[Fact]
public static void RunInt16ImplicitCastToBigIntegerTests()
{
// Int16 Implicit Cast to BigInteger: Int16.MinValue
VerifyInt16ImplicitCastToBigInteger(Int16.MinValue);
// Int16 Implicit Cast to BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt16ImplicitCastToBigInteger((Int16)s_random.Next(Int16.MinValue, 0));
}
// Int16 Implicit Cast to BigInteger: -1
VerifyInt16ImplicitCastToBigInteger(-1);
// Int16 Implicit Cast to BigInteger: 0
VerifyInt16ImplicitCastToBigInteger(0);
// Int16 Implicit Cast to BigInteger: 1
VerifyInt16ImplicitCastToBigInteger(1);
// Int16 Implicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt16ImplicitCastToBigInteger((Int16)s_random.Next(1, Int16.MaxValue));
}
// Int16 Implicit Cast to BigInteger: Int16.MaxValue
VerifyInt16ImplicitCastToBigInteger(Int16.MaxValue);
}
[Fact]
public static void RunUInt32ImplicitCastToBigIntegerTests()
{
// UInt32 Implicit Cast to BigInteger: UInt32.MinValue
VerifyUInt32ImplicitCastToBigInteger(UInt32.MinValue);
// UInt32 Implicit Cast to BigInteger: 0
VerifyUInt32ImplicitCastToBigInteger(0);
// UInt32 Implicit Cast to BigInteger: 1
VerifyUInt32ImplicitCastToBigInteger(1);
// UInt32 Implicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyUInt32ImplicitCastToBigInteger((UInt32)(UInt32.MaxValue * s_random.NextDouble()));
}
// UInt32 Implicit Cast to BigInteger: UInt32.MaxValue
VerifyUInt32ImplicitCastToBigInteger(UInt32.MaxValue);
}
[Fact]
public static void RunInt32ImplicitCastToBigIntegerTests()
{
// Int32 Implicit Cast to BigInteger: Int32.MinValue
VerifyInt32ImplicitCastToBigInteger(Int32.MinValue);
// Int32 Implicit Cast to BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt32ImplicitCastToBigInteger((Int32)s_random.Next(Int32.MinValue, 0));
}
// Int32 Implicit Cast to BigInteger: -1
VerifyInt32ImplicitCastToBigInteger(-1);
// Int32 Implicit Cast to BigInteger: 0
VerifyInt32ImplicitCastToBigInteger(0);
// Int32 Implicit Cast to BigInteger: 1
VerifyInt32ImplicitCastToBigInteger(1);
// Int32 Implicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt32ImplicitCastToBigInteger((Int32)s_random.Next(1, Int32.MaxValue));
}
// Int32 Implicit Cast to BigInteger: Int32.MaxValue
VerifyInt32ImplicitCastToBigInteger(Int32.MaxValue);
}
[Fact]
public static void RunUInt64ImplicitCastToBigIntegerTests()
{
// UInt64 Implicit Cast to BigInteger: UInt64.MinValue
VerifyUInt64ImplicitCastToBigInteger(UInt64.MinValue);
// UInt64 Implicit Cast to BigInteger: 0
VerifyUInt64ImplicitCastToBigInteger(0);
// UInt64 Implicit Cast to BigInteger: 1
VerifyUInt64ImplicitCastToBigInteger(1);
// UInt64 Implicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyUInt64ImplicitCastToBigInteger((UInt64)(UInt64.MaxValue * s_random.NextDouble()));
}
// UInt64 Implicit Cast to BigInteger: UInt64.MaxValue
VerifyUInt64ImplicitCastToBigInteger(UInt64.MaxValue);
}
[Fact]
public static void RunInt64ImplicitCastToBigIntegerTests()
{
// Int64 Implicit Cast to BigInteger: Int64.MinValue
VerifyInt64ImplicitCastToBigInteger(Int64.MinValue);
// Int64 Implicit Cast to BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt64ImplicitCastToBigInteger(((Int64)(Int64.MaxValue * s_random.NextDouble())) - Int64.MaxValue);
}
// Int64 Implicit Cast to BigInteger: -1
VerifyInt64ImplicitCastToBigInteger(-1);
// Int64 Implicit Cast to BigInteger: 0
VerifyInt64ImplicitCastToBigInteger(0);
// Int64 Implicit Cast to BigInteger: 1
VerifyInt64ImplicitCastToBigInteger(1);
// Int64 Implicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt64ImplicitCastToBigInteger((Int64)(Int64.MaxValue * s_random.NextDouble()));
}
// Int64 Implicit Cast to BigInteger: Int64.MaxValue
VerifyInt64ImplicitCastToBigInteger(Int64.MaxValue);
}
[Fact]
public static void RunSingleExplicitCastToBigIntegerTests()
{
Single value;
// Single Explicit Cast to BigInteger: Single.NegativeInfinity
Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Single.NegativeInfinity; });
// Single Explicit Cast to BigInteger: Single.MinValue
VerifySingleExplicitCastToBigInteger(Single.MinValue);
// Single Explicit Cast to BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastToBigInteger(((Single)(Single.MaxValue * s_random.NextDouble())) - Single.MaxValue);
}
// Single Explicit Cast to BigInteger: Random Non-Integral Negative > -100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastToBigInteger((Single)(-100 * s_random.NextDouble()));
}
// Single Explicit Cast to BigInteger: -1
VerifySingleExplicitCastToBigInteger(-1);
// Single Explicit Cast to BigInteger: 0
VerifySingleExplicitCastToBigInteger(0);
// Single Explicit Cast to BigInteger: 1
VerifySingleExplicitCastToBigInteger(1);
// Single Explicit Cast to BigInteger: Random Non-Integral Positive < 100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastToBigInteger((Single)(100 * s_random.NextDouble()));
}
// Single Explicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastToBigInteger((Single)(Single.MaxValue * s_random.NextDouble()));
}
// Single Explicit Cast to BigInteger: Single.MaxValue
VerifySingleExplicitCastToBigInteger(Single.MaxValue);
// Single Explicit Cast to BigInteger: Single.PositiveInfinity
Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Single.PositiveInfinity; });
// Single Explicit Cast to BigInteger: Single.Epsilon
VerifySingleExplicitCastToBigInteger(Single.Epsilon);
// Single Explicit Cast to BigInteger: Single.NaN
Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Single.NaN; });
//There are multiple ways to represent a NaN just try another one
// Single Explicit Cast to BigInteger: Single.NaN 2
Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)ConvertInt32ToSingle(0x7FC00000); });
// Single Explicit Cast to BigInteger: Smallest Exponent
VerifySingleExplicitCastToBigInteger((Single)Math.Pow(2, -126));
// Single Explicit Cast to BigInteger: Largest Exponent
VerifySingleExplicitCastToBigInteger((Single)Math.Pow(2, 127));
// Single Explicit Cast to BigInteger: Largest number less then 1
value = 0;
for (int i = 1; i <= 24; ++i)
{
value += (Single)(Math.Pow(2, -i));
}
VerifySingleExplicitCastToBigInteger(value);
// Single Explicit Cast to BigInteger: Smallest number greater then 1
value = (Single)(1 + Math.Pow(2, -23));
VerifySingleExplicitCastToBigInteger(value);
// Single Explicit Cast to BigInteger: Largest number less then 2
value = 0;
for (int i = 1; i <= 23; ++i)
{
value += (Single)(Math.Pow(2, -i));
}
value += 1;
VerifySingleExplicitCastToBigInteger(value);
}
[Fact]
public static void RunDoubleExplicitCastToBigIntegerTests()
{
Double value;
// Double Explicit Cast to BigInteger: Double.NegativeInfinity
Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Double.NegativeInfinity; });
// Double Explicit Cast to BigInteger: Double.MinValue
VerifyDoubleExplicitCastToBigInteger(Double.MinValue);
// Double Explicit Cast to BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastToBigInteger(((Double)(Double.MaxValue * s_random.NextDouble())) - Double.MaxValue);
}
// Double Explicit Cast to BigInteger: Random Non-Integral Negative > -100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastToBigInteger((Double)(-100 * s_random.NextDouble()));
}
// Double Explicit Cast to BigInteger: -1
VerifyDoubleExplicitCastToBigInteger(-1);
// Double Explicit Cast to BigInteger: 0
VerifyDoubleExplicitCastToBigInteger(0);
// Double Explicit Cast to BigInteger: 1
VerifyDoubleExplicitCastToBigInteger(1);
// Double Explicit Cast to BigInteger: Random Non-Integral Positive < 100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastToBigInteger((Double)(100 * s_random.NextDouble()));
}
// Double Explicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastToBigInteger((Double)(Double.MaxValue * s_random.NextDouble()));
}
// Double Explicit Cast to BigInteger: Double.MaxValue
VerifyDoubleExplicitCastToBigInteger(Double.MaxValue);
// Double Explicit Cast to BigInteger: Double.PositiveInfinity
Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Double.PositiveInfinity; });
// Double Explicit Cast to BigInteger: Double.Epsilon
VerifyDoubleExplicitCastToBigInteger(Double.Epsilon);
// Double Explicit Cast to BigInteger: Double.NaN
Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)Double.NaN; });
//There are multiple ways to represent a NaN just try another one
// Double Explicit Cast to BigInteger: Double.NaN 2
Assert.Throws<OverflowException>(() => { BigInteger temp = (BigInteger)ConvertInt64ToDouble(0x7FF8000000000000); });
// Double Explicit Cast to BigInteger: Smallest Exponent
VerifyDoubleExplicitCastToBigInteger((Double)Math.Pow(2, -1022));
// Double Explicit Cast to BigInteger: Largest Exponent
VerifyDoubleExplicitCastToBigInteger((Double)Math.Pow(2, 1023));
// Double Explicit Cast to BigInteger: Largest number less then 1
value = 0;
for (int i = 1; i <= 53; ++i)
{
value += (Double)(Math.Pow(2, -i));
}
VerifyDoubleExplicitCastToBigInteger(value);
// Double Explicit Cast to BigInteger: Smallest number greater then 1
value = (Double)(1 + Math.Pow(2, -52));
VerifyDoubleExplicitCastToBigInteger(value);
// Double Explicit Cast to BigInteger: Largest number less then 2
value = 0;
for (int i = 1; i <= 52; ++i)
{
value += (Double)(Math.Pow(2, -i));
}
value += 1;
VerifyDoubleExplicitCastToBigInteger(value);
}
[Fact]
public static void RunDecimalExplicitCastToBigIntegerTests()
{
Decimal value;
// Decimal Explicit Cast to BigInteger: Decimal.MinValue
VerifyDecimalExplicitCastToBigInteger(Decimal.MinValue);
// Decimal Explicit Cast to BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
value = new Decimal(
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
true,
(byte)s_random.Next(0, 29));
VerifyDecimalExplicitCastToBigInteger(value);
}
// Decimal Explicit Cast to BigInteger: -1
VerifyDecimalExplicitCastToBigInteger(-1);
// Decimal Explicit Cast to BigInteger: 0
VerifyDecimalExplicitCastToBigInteger(0);
// Decimal Explicit Cast to BigInteger: 1
VerifyDecimalExplicitCastToBigInteger(1);
// Decimal Explicit Cast to BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
value = new Decimal(
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
false,
(byte)s_random.Next(0, 29));
VerifyDecimalExplicitCastToBigInteger(value);
}
// Decimal Explicit Cast to BigInteger: Decimal.MaxValue
VerifyDecimalExplicitCastToBigInteger(Decimal.MaxValue);
// Decimal Explicit Cast to BigInteger: Smallest Exponent
unchecked
{
value = new Decimal(1, 0, 0, false, 0);
}
VerifyDecimalExplicitCastToBigInteger(value);
// Decimal Explicit Cast to BigInteger: Largest Exponent and zero integer
unchecked
{
value = new Decimal(0, 0, 0, false, 28);
}
VerifyDecimalExplicitCastToBigInteger(value);
// Decimal Explicit Cast to BigInteger: Largest Exponent and non zero integer
unchecked
{
value = new Decimal(1, 0, 0, false, 28);
}
VerifyDecimalExplicitCastToBigInteger(value);
// Decimal Explicit Cast to BigInteger: Largest number less then 1
value = 1 - new Decimal(1, 0, 0, false, 28);
VerifyDecimalExplicitCastToBigInteger(value);
// Decimal Explicit Cast to BigInteger: Smallest number greater then 1
value = 1 + new Decimal(1, 0, 0, false, 28);
VerifyDecimalExplicitCastToBigInteger(value);
// Decimal Explicit Cast to BigInteger: Largest number less then 2
value = 2 - new Decimal(1, 0, 0, false, 28);
VerifyDecimalExplicitCastToBigInteger(value);
}
private static Single ConvertInt32ToSingle(Int32 value)
{
return BitConverter.ToSingle(BitConverter.GetBytes(value), 0);
}
private static Double ConvertInt64ToDouble(Int64 value)
{
return BitConverter.ToDouble(BitConverter.GetBytes(value), 0);
}
private static void VerifyByteImplicitCastToBigInteger(Byte value)
{
BigInteger bigInteger = value;
Assert.Equal(value, bigInteger);
Assert.Equal(value.ToString(), bigInteger.ToString());
Assert.Equal(value, (Byte)bigInteger);
if (value != Byte.MaxValue)
{
Assert.Equal((Byte)(value + 1), (Byte)(bigInteger + 1));
}
if (value != Byte.MinValue)
{
Assert.Equal((Byte)(value - 1), (Byte)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
private static void VerifySByteImplicitCastToBigInteger(SByte value)
{
BigInteger bigInteger = value;
Assert.Equal(value, bigInteger);
Assert.Equal(value.ToString(), bigInteger.ToString());
Assert.Equal(value, (SByte)bigInteger);
if (value != SByte.MaxValue)
{
Assert.Equal((SByte)(value + 1), (SByte)(bigInteger + 1));
}
if (value != SByte.MinValue)
{
Assert.Equal((SByte)(value - 1), (SByte)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
private static void VerifyUInt16ImplicitCastToBigInteger(UInt16 value)
{
BigInteger bigInteger = value;
Assert.Equal(value, bigInteger);
Assert.Equal(value.ToString(), bigInteger.ToString());
Assert.Equal(value, (UInt16)bigInteger);
if (value != UInt16.MaxValue)
{
Assert.Equal((UInt16)(value + 1), (UInt16)(bigInteger + 1));
}
if (value != UInt16.MinValue)
{
Assert.Equal((UInt16)(value - 1), (UInt16)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
private static void VerifyInt16ImplicitCastToBigInteger(Int16 value)
{
BigInteger bigInteger = value;
Assert.Equal(value, bigInteger);
Assert.Equal(value.ToString(), bigInteger.ToString());
Assert.Equal(value, (Int16)bigInteger);
if (value != Int16.MaxValue)
{
Assert.Equal((Int16)(value + 1), (Int16)(bigInteger + 1));
}
if (value != Int16.MinValue)
{
Assert.Equal((Int16)(value - 1), (Int16)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
private static void VerifyUInt32ImplicitCastToBigInteger(UInt32 value)
{
BigInteger bigInteger = value;
Assert.Equal(value, bigInteger);
Assert.Equal(value.ToString(), bigInteger.ToString());
Assert.Equal(value, (UInt32)bigInteger);
if (value != UInt32.MaxValue)
{
Assert.Equal((UInt32)(value + 1), (UInt32)(bigInteger + 1));
}
if (value != UInt32.MinValue)
{
Assert.Equal((UInt32)(value - 1), (UInt32)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
private static void VerifyInt32ImplicitCastToBigInteger(Int32 value)
{
BigInteger bigInteger = value;
Assert.Equal(value, bigInteger);
Assert.Equal(value.ToString(), bigInteger.ToString());
Assert.Equal(value, (Int32)bigInteger);
if (value != Int32.MaxValue)
{
Assert.Equal((Int32)(value + 1), (Int32)(bigInteger + 1));
}
if (value != Int32.MinValue)
{
Assert.Equal((Int32)(value - 1), (Int32)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
private static void VerifyUInt64ImplicitCastToBigInteger(UInt64 value)
{
BigInteger bigInteger = value;
Assert.Equal(value, bigInteger);
Assert.Equal(value.ToString(), bigInteger.ToString());
Assert.Equal(value, (UInt64)bigInteger);
if (value != UInt64.MaxValue)
{
Assert.Equal((UInt64)(value + 1), (UInt64)(bigInteger + 1));
}
if (value != UInt64.MinValue)
{
Assert.Equal((UInt64)(value - 1), (UInt64)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
private static void VerifyInt64ImplicitCastToBigInteger(Int64 value)
{
BigInteger bigInteger = value;
Assert.Equal(value, bigInteger);
Assert.Equal(value.ToString(), bigInteger.ToString());
Assert.Equal(value, (Int64)bigInteger);
if (value != Int64.MaxValue)
{
Assert.Equal((Int64)(value + 1), (Int64)(bigInteger + 1));
}
if (value != Int64.MinValue)
{
Assert.Equal((Int64)(value - 1), (Int64)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
private static void VerifySingleExplicitCastToBigInteger(Single value)
{
Single expectedValue;
BigInteger bigInteger;
if (value < 0)
{
expectedValue = (Single)Math.Ceiling(value);
}
else
{
expectedValue = (Single)Math.Floor(value);
}
bigInteger = (BigInteger)value;
Assert.Equal(expectedValue, (Single)bigInteger);
// Single can only accurately represent integers between -16777216 and 16777216 exclusive.
// ToString starts to become inaccurate at this point.
if (expectedValue < 16777216 && -16777216 < expectedValue)
{
Assert.Equal(expectedValue.ToString("G9"), bigInteger.ToString());
}
if (expectedValue != Math.Floor(Single.MaxValue))
{
Assert.Equal((Single)(expectedValue + 1), (Single)(bigInteger + 1));
}
if (expectedValue != Math.Ceiling(Single.MinValue))
{
Assert.Equal((Single)(expectedValue - 1), (Single)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue);
}
private static void VerifyDoubleExplicitCastToBigInteger(Double value)
{
Double expectedValue;
BigInteger bigInteger;
if (value < 0)
{
expectedValue = Math.Ceiling(value);
}
else
{
expectedValue = Math.Floor(value);
}
bigInteger = (BigInteger)value;
Assert.Equal(expectedValue, (Double)bigInteger);
// Double can only accurately represent integers between -9007199254740992 and 9007199254740992 exclusive.
// ToString starts to become inaccurate at this point.
if (expectedValue < 9007199254740992 && -9007199254740992 < expectedValue)
{
Assert.Equal(expectedValue.ToString(), bigInteger.ToString());
}
if (!Single.IsInfinity((Single)expectedValue))
{
Assert.Equal((Double)(expectedValue + 1), (Double)(bigInteger + 1));
Assert.Equal((Double)(expectedValue - 1), (Double)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue);
}
private static void VerifyDecimalExplicitCastToBigInteger(Decimal value)
{
Decimal expectedValue;
BigInteger bigInteger;
if (value < 0)
{
expectedValue = Math.Ceiling(value);
}
else
{
expectedValue = Math.Floor(value);
}
bigInteger = (BigInteger)value;
Assert.Equal(expectedValue.ToString(), bigInteger.ToString());
Assert.Equal(expectedValue, (Decimal)bigInteger);
VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue);
if (expectedValue != Math.Floor(Decimal.MaxValue))
{
Assert.Equal((Decimal)(expectedValue + 1), (Decimal)(bigInteger + 1));
}
if (expectedValue != Math.Ceiling(Decimal.MinValue))
{
Assert.Equal((Decimal)(expectedValue - 1), (Decimal)(bigInteger - 1));
}
}
private static void VerifyBigIntegerUsingIdentities(BigInteger bigInteger, bool isZero)
{
BigInteger tempBigInteger = new BigInteger(bigInteger.ToByteArray());
Assert.Equal(bigInteger, tempBigInteger);
if (isZero)
{
Assert.Equal(BigInteger.Zero, bigInteger);
}
else
{
Assert.NotEqual(BigInteger.Zero, bigInteger);
// x/x = 1
Assert.Equal(BigInteger.One, bigInteger / bigInteger);
}
// (x + 1) - 1 = x
Assert.Equal(bigInteger, (bigInteger + BigInteger.One) - BigInteger.One);
// (x + 1) - x = 1
Assert.Equal(BigInteger.One, (bigInteger + BigInteger.One) - bigInteger);
// x - x = 0
Assert.Equal(BigInteger.Zero, bigInteger - bigInteger);
// x + x = 2x
Assert.Equal(2 * bigInteger, bigInteger + bigInteger);
// x/1 = x
Assert.Equal(bigInteger, bigInteger / BigInteger.One);
// 1 * x = x
Assert.Equal(bigInteger, BigInteger.One * bigInteger);
}
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.TestFramework
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Logging;
using NUnit.Framework;
using Pipeline.Pipes;
using Transports.InMemory;
[TestFixture]
public class InMemoryTestFixture :
BusTestFixture
{
static readonly ILog _log = Logger.Get<InMemoryTestFixture>();
IBusControl _bus;
Uri _inputQueueAddress;
ISendEndpoint _inputQueueSendEndpoint;
ISendEndpoint _busSendEndpoint;
BusHandle _busHandle;
readonly Uri _baseAddress;
InMemoryTransportCache _inMemoryTransportCache;
readonly IBusCreationScope _busCreationScope;
public Uri BaseAddress => _baseAddress;
public InMemoryTestFixture(bool busPerTest = false)
{
_baseAddress = new Uri("loopback://localhost/");
_inputQueueAddress = new Uri("loopback://localhost/input_queue");
if (busPerTest)
_busCreationScope = new PerTestBusCreationScope(SetupBus, TeardownBus);
else
_busCreationScope = new PerTestFixtureBusCreationScope(SetupBus, TeardownBus);
}
/// <summary>
/// The sending endpoint for the InputQueue
/// </summary>
protected ISendEndpoint InputQueueSendEndpoint => _inputQueueSendEndpoint;
/// <summary>
/// The sending endpoint for the Bus
/// </summary>
protected ISendEndpoint BusSendEndpoint => _busSendEndpoint;
protected Uri BusAddress => _bus.Address;
protected Uri InputQueueAddress
{
get { return _inputQueueAddress; }
set
{
if (Bus != null)
throw new InvalidOperationException("The LocalBus has already been created, too late to change the URI");
_inputQueueAddress = value;
}
}
protected override IBus Bus => _bus;
protected IRequestClient<TRequest, TResponse> CreateRequestClient<TRequest, TResponse>()
where TRequest : class
where TResponse : class
{
return Bus.CreateRequestClient<TRequest, TResponse>(InputQueueAddress, TestTimeout);
}
[TestFixtureSetUp]
public void SetupInMemoryTestFixture()
{
_busCreationScope.TestFixtureSetup();
}
[SetUp]
public void SetupInMemoryTest()
{
_busCreationScope.TestSetup();
}
void SetupBus()
{
_bus = CreateBus();
ConnectObservers(_bus);
_busHandle = _bus.Start();
_busSendEndpoint = Await(() => GetSendEndpoint(_bus.Address));
_inputQueueSendEndpoint = Await(() => GetSendEndpoint(InputQueueAddress));
}
protected async Task<ISendEndpoint> GetSendEndpoint(Uri address)
{
ISendEndpoint sendEndpoint = await _bus.GetSendEndpoint(address).ConfigureAwait(false);
return sendEndpoint;
}
protected IPublishEndpointProvider PublishEndpointProvider => new InMemoryPublishEndpointProvider(Bus, _inMemoryTransportCache, PublishPipe.Empty);
[TestFixtureTearDown]
public void TearDownInMemoryTestFixture()
{
_busCreationScope.TestFixtureTeardown();
}
[TearDown]
public void TearDownInMemoryTest()
{
_busCreationScope.TestTeardown();
}
void TeardownBus()
{
try
{
_busHandle?.Stop(new CancellationTokenSource(TestTimeout).Token);
}
catch (Exception ex)
{
_log.Error("Bus Stop Failed: ", ex);
throw;
}
finally
{
_busHandle = null;
_bus = null;
}
}
protected virtual void ConfigureBus(IInMemoryBusFactoryConfigurator configurator)
{
}
protected virtual void ConnectObservers(IBus bus)
{
}
protected virtual void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
}
IBusControl CreateBus()
{
return MassTransit.Bus.Factory.CreateUsingInMemory(x =>
{
_inMemoryTransportCache = new InMemoryTransportCache(Environment.ProcessorCount);
x.SetTransportProvider(_inMemoryTransportCache);
ConfigureBus(x);
x.ReceiveEndpoint("input_queue", configurator => ConfigureInputQueueEndpoint(configurator));
});
}
interface IBusCreationScope
{
void TestFixtureSetup();
void TestSetup();
void TestTeardown();
void TestFixtureTeardown();
}
class PerTestFixtureBusCreationScope : IBusCreationScope
{
readonly Action _setupBus;
readonly Action _teardownBus;
public PerTestFixtureBusCreationScope(Action setupBus, Action teardownBus)
{
_setupBus = setupBus;
_teardownBus = teardownBus;
}
public void TestFixtureSetup()
{
_setupBus();
}
public void TestSetup()
{
}
public void TestTeardown()
{
}
public void TestFixtureTeardown()
{
_teardownBus();
}
}
class PerTestBusCreationScope : IBusCreationScope
{
readonly Action _setupBus;
readonly Action _teardownBus;
public PerTestBusCreationScope(Action setupBus, Action teardownBus)
{
_setupBus = setupBus;
_teardownBus = teardownBus;
}
public void TestFixtureSetup()
{
}
public void TestSetup()
{
_setupBus();
}
public void TestTeardown()
{
_teardownBus();
}
public void TestFixtureTeardown()
{
}
}
}
}
| |
using System;
using System.Globalization;
namespace Bmz.Framework.Extensions
{
/// <summary>
/// Extension methods for String class.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Adds a char to end of given string if it does not ends with the char.
/// </summary>
public static string EnsureEndsWith(this string str, char c)
{
return EnsureEndsWith(str, c, StringComparison.InvariantCulture);
}
/// <summary>
/// Adds a char to end of given string if it does not ends with the char.
/// </summary>
public static string EnsureEndsWith(this string str, char c, StringComparison comparisonType)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.EndsWith(c.ToString(CultureInfo.InvariantCulture), comparisonType))
{
return str;
}
return str + c;
}
/// <summary>
/// Adds a char to end of given string if it does not ends with the char.
/// </summary>
public static string EnsureEndsWith(this string str, char c, bool ignoreCase, CultureInfo culture)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.EndsWith(c.ToString(culture), ignoreCase, culture))
{
return str;
}
return str + c;
}
/// <summary>
/// Adds a char to beginning of given string if it does not starts with the char.
/// </summary>
public static string EnsureStartsWith(this string str, char c)
{
return EnsureStartsWith(str, c, StringComparison.InvariantCulture);
}
/// <summary>
/// Adds a char to beginning of given string if it does not starts with the char.
/// </summary>
public static string EnsureStartsWith(this string str, char c, StringComparison comparisonType)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.StartsWith(c.ToString(CultureInfo.InvariantCulture), comparisonType))
{
return str;
}
return c + str;
}
/// <summary>
/// Adds a char to beginning of given string if it does not starts with the char.
/// </summary>
public static string EnsureStartsWith(this string str, char c, bool ignoreCase, CultureInfo culture)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.StartsWith(c.ToString(culture), ignoreCase, culture))
{
return str;
}
return c + str;
}
/// <summary>
/// Indicates whether this string is null or an System.String.Empty string.
/// </summary>
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
/// <summary>
/// indicates whether this string is null, empty, or consists only of white-space characters.
/// </summary>
public static bool IsNullOrWhiteSpace(this string str)
{
return string.IsNullOrWhiteSpace(str);
}
/// <summary>
/// Gets a substring of a string from beginning of the string.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
public static string Left(this string str, int len)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.Length < len)
{
throw new ArgumentException("len argument can not be bigger than given string's length!");
}
return str.Substring(0, len);
}
/// <summary>
/// Converts line endings in the string to <see cref="Environment.NewLine"/>.
/// </summary>
public static string NormalizeLineEndings(this string str)
{
return str.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", Environment.NewLine);
}
/// <summary>
/// Gets index of nth occurence of a char in a string.
/// </summary>
/// <param name="str">source string to be searched</param>
/// <param name="c">Char to search in <see cref="str"/></param>
/// <param name="n">Count of the occurence</param>
public static int NthIndexOf(this string str, char c, int n)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
var count = 0;
for (var i = 0; i < str.Length; i++)
{
if (str[i] != c)
{
continue;
}
if ((++count) == n)
{
return i;
}
}
return -1;
}
/// <summary>
/// Gets a substring of a string from end of the string.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
public static string Right(this string str, int len)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.Length < len)
{
throw new ArgumentException("len argument can not be bigger than given string's length!");
}
return str.Substring(str.Length - len, len);
}
/// <summary>
/// Uses string.Split method to split given string by given separator.
/// </summary>
public static string[] Split(this string str, string separator)
{
return str.Split(new[] { separator }, StringSplitOptions.None);
}
/// <summary>
/// Uses string.Split method to split given string by given separator.
/// </summary>
public static string[] Split(this string str, string separator, StringSplitOptions options)
{
return str.Split(new[] { separator }, options);
}
/// <summary>
/// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>.
/// </summary>
public static string[] SplitToLines(this string str)
{
return str.Split(Environment.NewLine);
}
/// <summary>
/// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>.
/// </summary>
public static string[] SplitToLines(this string str, StringSplitOptions options)
{
return str.Split(Environment.NewLine, options);
}
/// <summary>
/// Converts PascalCase string to camelCase string.
/// </summary>
/// <param name="str">String to convert</param>
/// <returns>camelCase of the string</returns>
public static string ToCamelCase(this string str)
{
return str.ToCamelCase(CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts PascalCase string to camelCase string in specified culture.
/// </summary>
/// <param name="str">String to convert</param>
/// <param name="culture">An object that supplies culture-specific casing rules</param>
/// <returns>camelCase of the string</returns>
public static string ToCamelCase(this string str, CultureInfo culture)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
if (str.Length == 1)
{
return str.ToLower(culture);
}
return char.ToLower(str[0], culture) + str.Substring(1);
}
/// <summary>
/// Converts string to enum value.
/// </summary>
/// <typeparam name="T">Type of enum</typeparam>
/// <param name="value">String value to convert</param>
/// <returns>Returns enum object</returns>
public static T ToEnum<T>(this string value)
where T : struct
{
if (value == null)
{
throw new ArgumentNullException("value");
}
return (T)Enum.Parse(typeof(T), value);
}
/// <summary>
/// Converts string to enum value.
/// </summary>
/// <typeparam name="T">Type of enum</typeparam>
/// <param name="value">String value to convert</param>
/// <param name="ignoreCase">Ignore case</param>
/// <returns>Returns enum object</returns>
public static T ToEnum<T>(this string value, bool ignoreCase)
where T : struct
{
if (value == null)
{
throw new ArgumentNullException("value");
}
return (T)Enum.Parse(typeof(T), value, ignoreCase);
}
/// <summary>
/// Converts camelCase string to PascalCase string.
/// </summary>
/// <param name="str">String to convert</param>
/// <returns>PascalCase of the string</returns>
public static string ToPascalCase(this string str)
{
return str.ToPascalCase(CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts camelCase string to PascalCase string in specified culture.
/// </summary>
/// <param name="str">String to convert</param>
/// <param name="culture">An object that supplies culture-specific casing rules</param>
/// <returns>PascalCase of the string</returns>
public static string ToPascalCase(this string str, CultureInfo culture)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
if (str.Length == 1)
{
return str.ToUpper(culture);
}
return char.ToUpper(str[0], culture) + str.Substring(1);
}
/// <summary>
/// Gets a substring of a string from beginning of the string if it exceeds maximum length.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
public static string Truncate(this string str, int maxLength)
{
if (str == null)
{
return null;
}
if (str.Length <= maxLength)
{
return str;
}
return str.Left(maxLength);
}
/// <summary>
/// Gets a substring of a string from beginning of the string if it exceeds maximum length.
/// It adds a "..." postfix to end of the string if it's truncated.
/// Returning string can not be longer than maxLength.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
public static string TruncateWithPostfix(this string str, int maxLength)
{
return TruncateWithPostfix(str, maxLength, "...");
}
/// <summary>
/// Gets a substring of a string from beginning of the string if it exceeds maximum length.
/// It adds given <paramref name="postfix"/> to end of the string if it's truncated.
/// Returning string can not be longer than maxLength.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
public static string TruncateWithPostfix(this string str, int maxLength, string postfix)
{
if (str == null)
{
return null;
}
if (str == string.Empty || maxLength == 0)
{
return string.Empty;
}
if (str.Length <= maxLength)
{
return str;
}
if (maxLength <= postfix.Length)
{
return postfix.Left(maxLength);
}
return str.Left(maxLength - postfix.Length) + postfix;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Xml;
using Axiom.MathLib;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace Multiverse.Tools.WorldEditor
{
public class Water : IWorldObject, IObjectDelete
{
protected float height;
protected Axiom.SceneManagers.Multiverse.WaterPlane waterSemantic;
protected Boundary parent;
protected WorldEditor app;
protected WorldTreeNode node = null;
protected WorldTreeNode parentNode = null;
protected List<ToolStripButton> buttonBar;
bool inTree = false;
bool inScene = false;
public Water(float height, Boundary parent, WorldEditor app)
{
this.parent = parent;
this.app = app;
this.height = height;
}
[BrowsableAttribute(true), CategoryAttribute("Miscellaneous"), DescriptionAttribute("Altitude (in millimeters) of the water plane.")]
public float Height
{
get
{
return height;
}
set
{
height = value;
if (inScene)
{
waterSemantic.Height = height;
}
}
}
[DescriptionAttribute("The type of this object."), CategoryAttribute("Miscellaneous")]
public string ObjectType
{
get
{
return "Water";
}
}
[BrowsableAttribute(false)]
public bool IsGlobal
{
get
{
return false;
}
}
[BrowsableAttribute(false)]
public bool IsTopLevel
{
get
{
return false;
}
}
[BrowsableAttribute(false)]
public bool AcceptObjectPlacement
{
get
{
return false;
}
set
{
//not implemented for this type of object
}
}
public void ToXml(XmlWriter w)
{
w.WriteStartElement("Water");
w.WriteAttributeString("Height", this.Height.ToString());
w.WriteEndElement();
return;
}
public Water(XmlReader r, Boundary parent, WorldEditor app)
{
this.parent = parent;
this.app = app;
FromXml(r);
}
protected void FromXml(XmlReader r)
{
// first parse the attributes
for (int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
// set the field in this object based on the element we just read
switch (r.Name)
{
case "Height":
this.height = float.Parse(r.Value);
break;
}
}
r.MoveToElement(); //Moves the reader back to the element node.
}
#region IWorldObject Members
public void AddToScene()
{
if (!inScene)
{
inScene = true;
this.waterSemantic = new Axiom.SceneManagers.Multiverse.WaterPlane(this.Height, WorldEditor.GetUniqueName((parent as Boundary).Name, "BoundaryWaterSemantic"), null);
parent.SceneBoundary.AddSemantic(this.waterSemantic);
}
}
public void UpdateScene(UpdateTypes type, UpdateHint hint)
{
}
public void AddToTree(WorldTreeNode parentNode)
{
this.parentNode = parentNode;
if (!inTree)
{
inTree = true;
// create a node for the collection and add it to the parent
node = app.MakeTreeNode(this, "Water");
parentNode.Nodes.Add(node);
// build the menu
CommandMenuBuilder menuBuilder = new CommandMenuBuilder();
menuBuilder.Add("Copy Description", "", app.copyToClipboardMenuButton_Click);
menuBuilder.Add("Help", "Water", app.HelpClickHandler);
menuBuilder.Add("Delete", new DeleteObjectCommandFactory(app, parent, this), app.DefaultCommandClickHandler);
node.ContextMenuStrip = menuBuilder.Menu;
buttonBar = menuBuilder.ButtonBar;
}
}
public void Clone(IWorldContainer copyParent)
{
Water clone = new Water(height, copyParent as Boundary, app);
copyParent.Add(clone);
}
[BrowsableAttribute(false)]
public string ObjectAsString
{
get
{
string objString = String.Format("Name:{0}\r\n", ObjectType);
objString = String.Format("\tHeight={0}\r\n", Height);
objString += "\r\n";
return objString;
}
}
[BrowsableAttribute(false)]
public bool WorldViewSelectable
{
get
{
return false;
}
set
{
}
}
[BrowsableAttribute(false)]
public List<ToolStripButton> ButtonBar
{
get
{
return buttonBar;
}
}
public void RemoveFromTree()
{
if (inTree)
{
if (node.IsSelected)
{
node.UnSelect();
}
parentNode.Nodes.Remove(node);
parentNode = null;
node = null;
inTree = false;
}
}
public void RemoveFromScene()
{
if (inScene)
{
if (parent != null && parent.SceneBoundary != null && this.waterSemantic != null)
{
parent.SceneBoundary.RemoveSemantic(this.waterSemantic);
}
}
inScene = false;
}
public void CheckAssets()
{
}
[BrowsableAttribute(false)]
public Vector3 FocusLocation
{
get
{
return parent.FocusLocation;
}
}
[BrowsableAttribute(false)]
public bool Highlight
{
get
{
return parent.Highlight;
}
set
{
parent.Highlight = value;
}
}
[BrowsableAttribute(false)]
public WorldTreeNode Node
{
get
{
return node;
}
}
public void ToManifest(System.IO.StreamWriter w)
{
}
#endregion
#region IWorldDelete
[BrowsableAttribute(false)]
public IWorldContainer Parent
{
get
{
return parent as IWorldContainer;
}
}
#endregion IWorldDelete
#region IDisposable Members
public void Dispose()
{
RemoveFromScene();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Completion;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
[ComVisible(true)]
public class AutomationObject
{
private readonly Workspace _workspace;
internal AutomationObject(Workspace workspace)
{
_workspace = workspace;
}
/// <summary>
/// Unused. But kept around for back compat. Note this option is not about
/// turning warning into errors. It's about an aspect of 'remove unused using'
/// functionality we don't support anymore. Namely whether or not 'remove unused
/// using' should warn if you have any build errors as that might mean we
/// remove some usings inappropriately.
/// </summary>
public int WarnOnBuildErrors
{
get { return 0; }
set { }
}
public int AutoComment
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration); }
set { SetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration, value); }
}
public int AutoInsertAsteriskForNewLinesOfBlockComments
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString); }
set { SetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString, value); }
}
public int BringUpOnIdentifier
{
get { return GetBooleanOption(CompletionOptions.TriggerOnTypingLetters); }
set { SetBooleanOption(CompletionOptions.TriggerOnTypingLetters, value); }
}
public int HighlightMatchingPortionsOfCompletionListItems
{
get { return GetBooleanOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems); }
set { SetBooleanOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, value); }
}
public int ShowCompletionItemFilters
{
get { return GetBooleanOption(CompletionOptions.ShowCompletionItemFilters); }
set { SetBooleanOption(CompletionOptions.ShowCompletionItemFilters, value); }
}
[Obsolete("This SettingStore option has now been deprecated in favor of CSharpClosedFileDiagnostics")]
public int ClosedFileDiagnostics
{
get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); }
set
{
// Even though this option has been deprecated, we want to respect the setting if the user has explicitly turned off closed file diagnostics (which is the non-default value for 'ClosedFileDiagnostics').
// So, we invoke the setter only for value = 0.
if (value == 0)
{
SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value);
}
}
}
public int CSharpClosedFileDiagnostics
{
get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); }
set { SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value); }
}
public int DisplayLineSeparators
{
get { return GetBooleanOption(FeatureOnOffOptions.LineSeparator); }
set { SetBooleanOption(FeatureOnOffOptions.LineSeparator, value); }
}
public int EnableHighlightRelatedKeywords
{
get { return GetBooleanOption(FeatureOnOffOptions.KeywordHighlighting); }
set { SetBooleanOption(FeatureOnOffOptions.KeywordHighlighting, value); }
}
public int EnterOutliningModeOnOpen
{
get { return GetBooleanOption(FeatureOnOffOptions.Outlining); }
set { SetBooleanOption(FeatureOnOffOptions.Outlining, value); }
}
public int ExtractMethod_AllowMovingDeclaration
{
get { return GetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration); }
set { SetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration, value); }
}
public int ExtractMethod_DoNotPutOutOrRefOnStruct
{
get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); }
set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value); }
}
public int Formatting_TriggerOnBlockCompletion
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace); }
set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace, value); }
}
public int Formatting_TriggerOnPaste
{
get { return GetBooleanOption(FeatureOnOffOptions.FormatOnPaste); }
set { SetBooleanOption(FeatureOnOffOptions.FormatOnPaste, value); }
}
public int Formatting_TriggerOnStatementCompletion
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon); }
set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon, value); }
}
public int HighlightReferences
{
get { return GetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting); }
set { SetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting, value); }
}
public int Indent_BlockContents
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentBlock); }
set { SetBooleanOption(CSharpFormattingOptions.IndentBlock, value); }
}
public int Indent_Braces
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentBraces); }
set { SetBooleanOption(CSharpFormattingOptions.IndentBraces, value); }
}
public int Indent_CaseContents
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection); }
set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection, value); }
}
public int Indent_CaseLabels
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchSection); }
set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchSection, value); }
}
public int Indent_FlushLabelsLeft
{
get
{
var option = _workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning);
return option == LabelPositionOptions.LeftMost ? 1 : 0;
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent);
}
}
public int Indent_UnindentLabels
{
get
{
return (int)_workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning);
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value);
}
}
public int InsertNewlineOnEnterWithWholeWord
{
get { return (int)GetOption(CompletionOptions.EnterKeyBehavior); }
set { SetOption(CompletionOptions.EnterKeyBehavior, (EnterKeyRule)value); }
}
public int EnterKeyBehavior
{
get { return (int)GetOption(CompletionOptions.EnterKeyBehavior); }
set { SetOption(CompletionOptions.EnterKeyBehavior, (EnterKeyRule)value); }
}
public int SnippetsBehavior
{
get { return (int)GetOption(CompletionOptions.SnippetsBehavior); }
set { SetOption(CompletionOptions.SnippetsBehavior, (SnippetsRule)value); }
}
public int NewLines_AnonymousTypeInitializer_EachMember
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, value); }
}
public int NewLines_Braces_AnonymousMethod
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, value); }
}
public int NewLines_Braces_AnonymousTypeInitializer
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, value); }
}
public int NewLines_Braces_ControlFlow
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, value); }
}
public int NewLines_Braces_LambdaExpressionBody
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, value); }
}
public int NewLines_Braces_Method
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods, value); }
}
public int NewLines_Braces_Property
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties, value); }
}
public int NewLines_Braces_Accessor
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, value); }
}
public int NewLines_Braces_ObjectInitializer
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, value); }
}
public int NewLines_Braces_Type
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes, value); }
}
public int NewLines_Keywords_Catch
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForCatch); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForCatch, value); }
}
public int NewLines_Keywords_Else
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForElse); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForElse, value); }
}
public int NewLines_Keywords_Finally
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForFinally); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForFinally, value); }
}
public int NewLines_ObjectInitializer_EachMember
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, value); }
}
public int NewLines_QueryExpression_EachClause
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery, value); }
}
public int Refactoring_Verification_Enabled
{
get { return GetBooleanOption(FeatureOnOffOptions.RefactoringVerification); }
set { SetBooleanOption(FeatureOnOffOptions.RefactoringVerification, value); }
}
public int RenameSmartTagEnabled
{
get { return GetBooleanOption(FeatureOnOffOptions.RenameTracking); }
set { SetBooleanOption(FeatureOnOffOptions.RenameTracking, value); }
}
public int RenameTrackingPreview
{
get { return GetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview); }
set { SetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview, value); }
}
public int ShowKeywords
{
get { return 0; }
set { }
}
[Obsolete("Use SnippetsBehavior instead")]
public int ShowSnippets
{
get
{
return GetOption(CompletionOptions.SnippetsBehavior) == SnippetsRule.AlwaysInclude
? 1 : 0;
}
set
{
if (value == 0)
{
SetOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude);
}
else
{
SetOption(CompletionOptions.SnippetsBehavior, SnippetsRule.AlwaysInclude);
}
}
}
public int SortUsings_PlaceSystemFirst
{
get { return GetBooleanOption(OrganizerOptions.PlaceSystemNamespaceFirst); }
set { SetBooleanOption(OrganizerOptions.PlaceSystemNamespaceFirst, value); }
}
public int AddImport_SuggestForTypesInReferenceAssemblies
{
get { return GetBooleanOption(AddImportOptions.SuggestForTypesInReferenceAssemblies); }
set { SetBooleanOption(AddImportOptions.SuggestForTypesInReferenceAssemblies, value); }
}
public int AddImport_SuggestForTypesInNuGetPackages
{
get { return GetBooleanOption(AddImportOptions.SuggestForTypesInNuGetPackages); }
set { SetBooleanOption(AddImportOptions.SuggestForTypesInNuGetPackages, value); }
}
public int Space_AfterBasesColon
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, value); }
}
public int Space_AfterCast
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterCast); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterCast, value); }
}
public int Space_AfterComma
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterComma); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterComma, value); }
}
public int Space_AfterDot
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterDot); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterDot, value); }
}
public int Space_AfterMethodCallName
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName, value); }
}
public int Space_AfterMethodDeclarationName
{
get { return GetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName); }
set { SetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, value); }
}
public int Space_AfterSemicolonsInForStatement
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, value); }
}
public int Space_AroundBinaryOperator
{
get
{
var option = _workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator);
return option == BinaryOperatorSpacingOptions.Single ? 1 : 0;
}
set
{
var option = value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore;
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, option);
}
}
public int Space_BeforeBasesColon
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, value); }
}
public int Space_BeforeComma
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma, value); }
}
public int Space_BeforeDot
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot, value); }
}
public int Space_BeforeOpenSquare
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, value); }
}
public int Space_BeforeSemicolonsInForStatement
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, value); }
}
public int Space_BetweenEmptyMethodCallParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, value); }
}
public int Space_BetweenEmptyMethodDeclarationParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, value); }
}
public int Space_BetweenEmptySquares
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, value); }
}
public int Space_InControlFlowConstruct
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, value); }
}
public int Space_WithinCastParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses, value); }
}
public int Space_WithinExpressionParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, value); }
}
public int Space_WithinMethodCallParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, value); }
}
public int Space_WithinMethodDeclarationParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, value); }
}
public int Space_WithinOtherParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, value); }
}
public int Space_WithinSquares
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets, value); }
}
public int Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration
{
get { return GetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration); }
set { SetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value); }
}
public int Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess
{
get { return GetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); }
set { SetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value); }
}
public string Style_NamingPreferences
{
get
{
return _workspace.Options.GetOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp);
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp, value);
}
}
public string Style_QualifyFieldAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyFieldAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyFieldAccess, value); }
}
public string Style_QualifyPropertyAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyPropertyAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyPropertyAccess, value); }
}
public string Style_QualifyMethodAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyMethodAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyMethodAccess, value); }
}
public string Style_QualifyEventAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyEventAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyEventAccess, value); }
}
public int Style_UseVarWhenDeclaringLocals
{
get { return GetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals); }
set { SetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals, value); }
}
public string Style_UseImplicitTypeWherePossible
{
get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible); }
set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, value); }
}
public string Style_UseImplicitTypeWhereApparent
{
get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent); }
set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, value); }
}
public string Style_UseImplicitTypeForIntrinsicTypes
{
get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes); }
set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, value); }
}
public int Wrapping_IgnoreSpacesAroundBinaryOperators
{
get
{
return (int)_workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator);
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, value);
}
}
public int Wrapping_IgnoreSpacesAroundVariableDeclaration
{
get { return GetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration); }
set { SetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, value); }
}
public int Wrapping_KeepStatementsOnSingleLine
{
get { return GetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine); }
set { SetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, value); }
}
public int Wrapping_PreserveSingleLine
{
get { return GetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine); }
set { SetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine, value); }
}
private int GetBooleanOption(Option<bool> key)
{
return _workspace.Options.GetOption(key) ? 1 : 0;
}
private int GetBooleanOption(PerLanguageOption<bool> key)
{
return _workspace.Options.GetOption(key, LanguageNames.CSharp) ? 1 : 0;
}
private T GetOption<T>(PerLanguageOption<T> key)
{
return _workspace.Options.GetOption(key, LanguageNames.CSharp);
}
private void SetBooleanOption(Option<bool> key, int value)
{
_workspace.Options = _workspace.Options.WithChangedOption(key, value != 0);
}
private void SetBooleanOption(PerLanguageOption<bool> key, int value)
{
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, value != 0);
}
private void SetOption<T>(PerLanguageOption<T> key, T value)
{
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, value);
}
private int GetBooleanOption(PerLanguageOption<bool?> key)
{
var option = _workspace.Options.GetOption(key, LanguageNames.CSharp);
if (!option.HasValue)
{
return -1;
}
return option.Value ? 1 : 0;
}
private string GetXmlOption(Option<CodeStyleOption<bool>> option)
{
return _workspace.Options.GetOption(option).ToXElement().ToString();
}
private void SetBooleanOption(PerLanguageOption<bool?> key, int value)
{
bool? boolValue = (value < 0) ? (bool?)null : (value > 0);
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, boolValue);
}
private string GetXmlOption(PerLanguageOption<CodeStyleOption<bool>> option)
{
return _workspace.Options.GetOption(option, LanguageNames.CSharp).ToXElement().ToString();
}
private void SetXmlOption(Option<CodeStyleOption<bool>> option, string value)
{
var convertedValue = CodeStyleOption<bool>.FromXElement(XElement.Parse(value));
_workspace.Options = _workspace.Options.WithChangedOption(option, convertedValue);
}
private void SetXmlOption(PerLanguageOption<CodeStyleOption<bool>> option, string value)
{
var convertedValue = CodeStyleOption<bool>.FromXElement(XElement.Parse(value));
_workspace.Options = _workspace.Options.WithChangedOption(option, LanguageNames.CSharp, convertedValue);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update
{
using Microsoft.Azure.Management.Network.Fluent.HasPort.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions;
using Microsoft.Azure.Management.Network.Fluent.Models;
using System.IO;
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to control connection draining.
/// </summary>
public interface IWithConnectionDraining :
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithConnectionDrainingBeta
{
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to specify the port number.
/// </summary>
public interface IWithPort :
Microsoft.Azure.Management.Network.Fluent.HasPort.Update.IWithPort<Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate>
{
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to associate an existing probe.
/// </summary>
public interface IWithProbe
{
/// <summary>
/// Specifies an existing probe on this application gateway to associate with this backend.
/// If the probe with the specified name does not yet exist, it must be defined separately in the optional part
/// of the application gateway definition. This only adds a reference to the probe by its name.
/// </summary>
/// <param name="name">The name of an existing probe.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithProbe(string name);
/// <summary>
/// Removes the association with a probe.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithoutProbe();
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to enable or disable cookie based affinity.
/// </summary>
public interface IWithAffinity
{
/// <summary>
/// Disables cookie based affinity.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithoutCookieBasedAffinity();
/// <summary>
/// Enables cookie based affinity.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithCookieBasedAffinity();
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to specify the name for the affinity cookie.
/// </summary>
public interface IWithCookieName :
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithCookieNameBeta
{
}
/// <summary>
/// The entirety of an application gateway backend HTTPS configuration update as part of an application gateway update.
/// </summary>
public interface IUpdate :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions.ISettable<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate>,
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithPort,
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithAffinity,
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithProtocol,
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithRequestTimeout,
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithProbe,
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithHostHeader,
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithConnectionDraining,
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithCookieName,
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithPath,
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithAuthenticationCertificate
{
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to specify the protocol.
/// </summary>
public interface IWithProtocol :
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithProtocolBeta
{
/// <summary>
/// Specifies the transport protocol.
/// </summary>
/// <param name="protocol">A transport protocol.</param>
/// <return>The next stage of the update.</return>
/// <deprecated>Use .withHttp() or .withHttps() instead.</deprecated>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithProtocol(ApplicationGatewayProtocol protocol);
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to specify the path to use as the prefix for all HTTP requests.
/// </summary>
public interface IWithPath :
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithPathBeta
{
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to specify the request timeout.
/// </summary>
public interface IWithRequestTimeout
{
/// <summary>
/// Specifies the request timeout.
/// </summary>
/// <param name="seconds">A number of seconds.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithRequestTimeout(int seconds);
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to add an authentication certificate.
/// </summary>
public interface IWithAuthenticationCertificate :
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithAuthenticationCertificateBeta
{
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to specify the host header.
/// </summary>
public interface IWithHostHeader :
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IWithHostHeaderBeta
{
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to control connection draining.
/// </summary>
public interface IWithConnectionDrainingBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Specifies the number of seconds when connection draining is active.
/// </summary>
/// <param name="seconds">A number of seconds between 1 and 3600.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithConnectionDrainingTimeoutInSeconds(int seconds);
/// <summary>
/// Disables connection draining.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithoutConnectionDraining();
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to specify the name for the affinity cookie.
/// </summary>
public interface IWithCookieNameBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Specifies the name for the affinity cookie.
/// </summary>
/// <param name="name">A name.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithAffinityCookieName(string name);
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to specify the protocol.
/// </summary>
public interface IWithProtocolBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Specifies HTTP as the protocol.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithHttp();
/// <summary>
/// Specifies HTTPS as the protocol.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithHttps();
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to specify the path to use as the prefix for all HTTP requests.
/// </summary>
public interface IWithPathBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Specifies the path prefix for all HTTP requests.
/// </summary>
/// <param name="path">A path.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithPath(string path);
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to add an authentication certificate.
/// </summary>
public interface IWithAuthenticationCertificateBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Associates a new, automatically named certificate with this HTTP backend configuration based on the specified data.
/// Multiple calls to this method will add additional certificate references.
/// </summary>
/// <param name="derData">The DER-encoded data of an X.509 certificate.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithAuthenticationCertificateFromBytes(params byte[] derData);
/// <summary>
/// Removes all references to any authentication certificates.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithoutAuthenticationCertificates();
/// <summary>
/// Associates the specified authentication certificate that exists on this application gateway with this backend HTTP confifuration.
/// Multiple calls to this method will add additional certificate references.
/// </summary>
/// <param name="name">The name of an existing authentication certificate.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithAuthenticationCertificate(string name);
/// <summary>
/// Removes the reference to the specified authentication certificate from this HTTP backend configuration.
/// Note the certificate will remain associated with the application gateway until removed from it explicitly.
/// </summary>
/// <param name="name">The name of an existing authentication certificate associated with this HTTP backend configuration.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithoutAuthenticationCertificate(string name);
/// <summary>
/// Associates a new, automatically named certificate with this HTTP backend configuration loaded from the specified file.
/// Multiple calls to this method will add additional certificate references.
/// </summary>
/// <param name="base64Data">The base-64 encoded data of an X.509 certificate.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithAuthenticationCertificateFromBase64(string base64Data);
/// <summary>
/// Associates a new, automatically named certificate with this HTTP backend configuration loaded from the specified file.
/// </summary>
/// <param name="certificateFile">A file containing the DER representation of an X.509 certificate.</param>
/// <return>The next stage of the update.</return>
/// <throws>IOException when there are issues reading the specified file.</throws>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithAuthenticationCertificateFromFile(FileInfo certificateFile);
}
/// <summary>
/// The stage of an application gateway backend HTTP configuration allowing to specify the host header.
/// </summary>
public interface IWithHostHeaderBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Specifies that no host header should be used.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithoutHostHeader();
/// <summary>
/// Specifies the host header.
/// </summary>
/// <param name="hostHeader">The host header.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithHostHeader(string hostHeader);
/// <summary>
/// Specifies that the host header should come from the host name of the backend server.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate WithHostHeaderFromBackend();
}
}
| |
//! \file ArcAMI.cs
//! \date Thu Jul 03 09:40:40 2014
//! \brief Muv-Luv Amaterasu Translation archive.
//
// Copyright (C) 2014 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using GameRes.Compression;
using GameRes.Formats.Strings;
namespace GameRes.Formats.Amaterasu
{
internal class AmiEntry : PackedEntry
{
public uint Id;
private Lazy<string> m_ext;
private Lazy<string> m_name;
private Lazy<string> m_type;
public override string Name
{
get { return m_name.Value; }
set { m_name = new Lazy<string> (() => value); }
}
public override string Type
{
get { return m_type.Value; }
set { m_type = new Lazy<string> (() => value); }
}
public AmiEntry (uint id, Func<string> ext_factory)
{
Id = id;
m_ext = new Lazy<string> (ext_factory);
m_name = new Lazy<string> (GetName);
m_type = new Lazy<string> (GetEntryType);
}
private string GetName ()
{
return string.Format ("{0:x8}.{1}", Id, m_ext.Value);
}
private string GetEntryType ()
{
var ext = m_ext.Value;
if ("grp" == ext)
return "image";
if ("scr" == ext)
return "script";
return "";
}
}
internal class AmiOptions : ResourceOptions
{
public bool UseBaseArchive;
public string BaseArchive;
}
[Export(typeof(ArchiveFormat))]
public class AmiOpener : ArchiveFormat
{
public override string Tag { get { return "AMI"; } }
public override string Description { get { return Strings.arcStrings.AMIDescription; } }
public override uint Signature { get { return 0x00494D41; } } // 'AMI'
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return true; } }
public AmiOpener ()
{
Extensions = new string[] { "ami", "amr" };
}
public override ArcFile TryOpen (ArcView file)
{
int count = file.View.ReadInt32 (4);
if (count <= 0)
return null;
uint base_offset = file.View.ReadUInt32 (8);
long max_offset = file.MaxOffset;
if (base_offset >= max_offset)
return null;
uint cur_offset = 16;
var dir = new List<Entry> (count);
for (int i = 0; i < count; ++i)
{
if (cur_offset+16 > base_offset)
return null;
uint id = file.View.ReadUInt32 (cur_offset);
uint offset = file.View.ReadUInt32 (cur_offset+4);
uint size = file.View.ReadUInt32 (cur_offset+8);
uint packed_size = file.View.ReadUInt32 (cur_offset+12);
var entry = new AmiEntry (id, () => {
uint signature = file.View.ReadUInt32 (offset);
if (0x00524353 == signature)
return "scr";
else if (0 != packed_size || 0x00505247 == signature)
return "grp";
else
return "dat";
});
entry.Offset = offset;
entry.UnpackedSize = size;
entry.IsPacked = 0 != packed_size;
entry.Size = entry.IsPacked ? packed_size : size;
if (!entry.CheckPlacement (max_offset))
return null;
dir.Add (entry);
cur_offset += 16;
}
return new ArcFile (file, this, dir);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var input = base.OpenEntry (arc, entry);
var packed_entry = entry as AmiEntry;
if (null == packed_entry || !packed_entry.IsPacked)
return input;
else
return new ZLibStream (input, CompressionMode.Decompress);
}
public override void Create (Stream output, IEnumerable<Entry> list, ResourceOptions options,
EntryCallback callback)
{
ArcFile base_archive = null;
var ami_options = GetOptions<AmiOptions> (options);
if (null != ami_options && ami_options.UseBaseArchive && !string.IsNullOrEmpty (ami_options.BaseArchive))
{
var base_file = new ArcView (ami_options.BaseArchive);
try
{
if (base_file.View.ReadUInt32(0) == Signature)
base_archive = TryOpen (base_file);
if (null == base_archive)
throw new InvalidFormatException (string.Format ("{0}: base archive could not be read",
Path.GetFileName (ami_options.BaseArchive)));
base_file = null;
}
finally
{
if (null != base_file)
base_file.Dispose();
}
}
try
{
var file_table = new SortedDictionary<uint, PackedEntry>();
if (null != base_archive)
{
foreach (AmiEntry entry in base_archive.Dir)
file_table[entry.Id] = entry;
}
int update_count = UpdateFileTable (file_table, list);
if (0 == update_count)
throw new InvalidFormatException (arcStrings.AMINoFiles);
uint file_count = (uint)file_table.Count;
if (null != callback)
callback ((int)file_count+1, null, null);
int callback_count = 0;
long start_offset = output.Position;
uint data_offset = file_count * 16 + 16;
output.Seek (data_offset, SeekOrigin.Current);
foreach (var entry in file_table)
{
if (null != callback)
callback (callback_count++, entry.Value, arcStrings.MsgAddingFile);
long current_offset = output.Position;
if (current_offset > uint.MaxValue)
throw new FileSizeException();
if (entry.Value is AmiEntry)
CopyAmiEntry (base_archive, entry.Value, output);
else
entry.Value.Size = WriteAmiEntry (entry.Value, output);
entry.Value.Offset = (uint)current_offset;
}
if (null != callback)
callback (callback_count++, null, arcStrings.MsgWritingIndex);
output.Position = start_offset;
using (var header = new BinaryWriter (output, Encoding.ASCII, true))
{
header.Write (Signature);
header.Write (file_count);
header.Write (data_offset);
header.Write ((uint)0);
foreach (var entry in file_table)
{
header.Write (entry.Key);
header.Write ((uint)entry.Value.Offset);
header.Write ((uint)entry.Value.UnpackedSize);
header.Write ((uint)entry.Value.Size);
}
}
}
finally
{
if (null != base_archive)
base_archive.Dispose();
}
}
int UpdateFileTable (IDictionary<uint, PackedEntry> table, IEnumerable<Entry> list)
{
int update_count = 0;
foreach (var entry in list)
{
if (entry.Type != "image" && !entry.Name.HasExtension (".scr"))
continue;
uint id;
if (!uint.TryParse (Path.GetFileNameWithoutExtension (entry.Name), NumberStyles.HexNumber,
CultureInfo.InvariantCulture, out id))
continue;
PackedEntry existing;
if (table.TryGetValue (id, out existing) && !(existing is AmiEntry))
{
var file_new = new FileInfo (entry.Name);
if (!file_new.Exists)
continue;
var file_old = new FileInfo (existing.Name);
if (file_new.LastWriteTime <= file_old.LastWriteTime)
continue;
}
table[id] = new PackedEntry
{
Name = entry.Name,
Type = entry.Type
};
++update_count;
}
return update_count;
}
void CopyAmiEntry (ArcFile base_archive, Entry entry, Stream output)
{
using (var input = base_archive.File.CreateStream (entry.Offset, entry.Size))
input.CopyTo (output);
}
uint WriteAmiEntry (PackedEntry entry, Stream output)
{
uint packed_size = 0;
using (var input = VFS.OpenBinaryStream (entry))
{
long file_size = input.Length;
if (file_size > uint.MaxValue)
throw new FileSizeException();
entry.UnpackedSize = (uint)file_size;
if ("image" == entry.Type)
{
packed_size = WriteImageEntry (entry, input, output);
}
else
{
input.AsStream.CopyTo (output);
}
}
return packed_size;
}
static Lazy<GrpFormat> s_grp_format = new Lazy<GrpFormat> (() =>
FormatCatalog.Instance.ImageFormats.OfType<GrpFormat>().FirstOrDefault());
uint WriteImageEntry (PackedEntry entry, IBinaryStream input, Stream output)
{
var grp = s_grp_format.Value;
if (null == grp) // probably never happens
throw new FileFormatException ("GRP image encoder not available");
bool is_grp = grp.Signature == input.Signature;
input.Position = 0;
var start = output.Position;
using (var zstream = new ZLibStream (output, CompressionMode.Compress, CompressionLevel.Level9, true))
{
if (is_grp)
{
input.AsStream.CopyTo (zstream);
}
else
{
var image = ImageFormat.Read (input);
if (null == image)
throw new InvalidFormatException (string.Format (arcStrings.MsgInvalidImageFormat, entry.Name));
grp.Write (zstream, image);
entry.UnpackedSize = (uint)zstream.TotalIn;
}
}
return (uint)(output.Position - start);
}
public override ResourceOptions GetDefaultOptions ()
{
return new AmiOptions {
UseBaseArchive = Properties.Settings.Default.AMIUseBaseArchive,
BaseArchive = Properties.Settings.Default.AMIBaseArchive,
};
}
public override object GetCreationWidget ()
{
return new GUI.CreateAMIWidget();
}
}
public class AmiScriptData : ScriptData
{
public uint Id;
public uint Type;
}
[Export(typeof(ScriptFormat))]
public class ScrFormat : ScriptFormat
{
public override string Tag { get { return "SCR/AMI"; } }
public override string Description { get { return Strings.arcStrings.SCRDescription; } }
public override uint Signature { get { return 0x00524353; } }
public override ScriptData Read (string name, Stream stream)
{
if (Signature != FormatCatalog.ReadSignature (stream))
return null;
uint script_id = Convert.ToUInt32 (name, 16);
uint max_offset = (uint)Math.Min (stream.Length, 0xffffffff);
using (var file = new BinaryReader (stream, Encodings.cp932, true))
{
uint script_type = file.ReadUInt32();
var script = new AmiScriptData {
Id = script_id,
Type = script_type
};
uint count = file.ReadUInt32();
for (uint i = 0; i < count; ++i)
{
uint offset = file.ReadUInt32();
if (offset >= max_offset)
throw new InvalidFormatException ("Invalid offset in script data file");
int size = file.ReadInt32();
uint id = file.ReadUInt32();
var header_pos = file.BaseStream.Position;
file.BaseStream.Position = offset;
byte[] line = file.ReadBytes (size);
if (line.Length != size)
throw new InvalidFormatException ("Premature end of file");
string text = Encodings.cp932.GetString (line);
script.TextLines.Add (new ScriptLine { Id = id, Text = text });
file.BaseStream.Position = header_pos;
}
return script;
}
}
public string GetName (ScriptData script_data)
{
var script = script_data as AmiScriptData;
if (null != script)
return script.Id.ToString ("x8");
else
return null;
}
struct IndexEntry
{
public uint offset, size, id;
}
public override void Write (Stream stream, ScriptData script_data)
{
var script = script_data as AmiScriptData;
if (null == script)
throw new ArgumentException ("Illegal ScriptData", "script_data");
using (var file = new BinaryWriter (stream, Encodings.cp932, true))
{
file.Write (Signature);
file.Write (script.Type);
uint count = (uint)script.TextLines.Count;
file.Write (count);
var index_pos = file.BaseStream.Position;
file.Seek ((int)count*12, SeekOrigin.Current);
var index = new IndexEntry[count];
int i = 0;
foreach (var line in script.TextLines)
{
var text = Encodings.cp932.GetBytes (line.Text);
index[i].offset = (uint)file.BaseStream.Position;
index[i].size = (uint)text.Length;
index[i].id = line.Id;
file.Write (text);
file.Write ((byte)0);
++i;
}
var end_pos = file.BaseStream.Position;
file.BaseStream.Position = index_pos;
foreach (var entry in index)
{
file.Write (entry.offset);
file.Write (entry.size);
file.Write (entry.id);
}
file.BaseStream.Position = end_pos;
}
}
}
}
| |
// 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.Dis1998
{
/// <summary>
/// Section 5.2.5.4. Cancel of resupply by either the receiving or supplying entity. COMPLETE
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
public partial class ResupplyCancelPdu : LogisticsFamilyPdu, IEquatable<ResupplyCancelPdu>
{
/// <summary>
/// Entity that is receiving service
/// </summary>
private EntityID _receivingEntityID = new EntityID();
/// <summary>
/// Entity that is supplying
/// </summary>
private EntityID _supplyingEntityID = new EntityID();
/// <summary>
/// Initializes a new instance of the <see cref="ResupplyCancelPdu"/> class.
/// </summary>
public ResupplyCancelPdu()
{
PduType = (byte)8;
}
/// <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 !=(ResupplyCancelPdu left, ResupplyCancelPdu 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 ==(ResupplyCancelPdu left, ResupplyCancelPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._receivingEntityID.GetMarshalledSize(); // this._receivingEntityID
marshalSize += this._supplyingEntityID.GetMarshalledSize(); // this._supplyingEntityID
return marshalSize;
}
/// <summary>
/// Gets or sets the Entity that is receiving service
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "receivingEntityID")]
public EntityID ReceivingEntityID
{
get
{
return this._receivingEntityID;
}
set
{
this._receivingEntityID = value;
}
}
/// <summary>
/// Gets or sets the Entity that is supplying
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "supplyingEntityID")]
public EntityID SupplyingEntityID
{
get
{
return this._supplyingEntityID;
}
set
{
this._supplyingEntityID = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <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 override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._receivingEntityID.Marshal(dos);
this._supplyingEntityID.Marshal(dos);
}
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 override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._receivingEntityID.Unmarshal(dis);
this._supplyingEntityID.Unmarshal(dis);
}
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 override void Reflection(StringBuilder sb)
{
sb.AppendLine("<ResupplyCancelPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<receivingEntityID>");
this._receivingEntityID.Reflection(sb);
sb.AppendLine("</receivingEntityID>");
sb.AppendLine("<supplyingEntityID>");
this._supplyingEntityID.Reflection(sb);
sb.AppendLine("</supplyingEntityID>");
sb.AppendLine("</ResupplyCancelPdu>");
}
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 ResupplyCancelPdu;
}
/// <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(ResupplyCancelPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._receivingEntityID.Equals(obj._receivingEntityID))
{
ivarsEqual = false;
}
if (!this._supplyingEntityID.Equals(obj._supplyingEntityID))
{
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) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._receivingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._supplyingEntityID.GetHashCode();
return result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using GuruComponents.Netrix.Designer;
//using GuruComponents.Netrix.Licensing;
using GuruComponents.Netrix.PlugIns;
using GuruComponents.Netrix.SpellChecker.NetSpell;
using GuruComponents.Netrix.WebEditing.Elements;
using System.IO;
namespace GuruComponents.Netrix.SpellChecker
{
/// <summary>
/// The Spellchecker ExtenderProvider component.
/// </summary>
/// <remarks>
/// To use this plug-in simply add the component to the toolbox and drag drop to the current window.
/// It will extend all available editor instances there. This component is based on the common NetSpell classes
/// and the OpenOffice based dictionaries. Dictionaries are available as files so they can simply replaced by
/// newer or specialized versions.
/// <para>
/// Several methods need the current HtmlEditor instance. This is necessary because the Speller PlugIn exists only once and
///
/// </para>
/// <para>
/// The spellchecker supports both "as-you-type" (background checking) and interactive spell checking. Both methods
/// are event based and very fast.
/// </para>
/// <example>
/// First the recommended way to implement background spellchecking. Assume <c>backgroundOn</c> is set by some sort of
/// command or menu item click:
/// <code>
///if (backgroundOn)
///{
/// htmlEditor1.InvokeCommand(speller1.Commands.StartBackground);
///}
///else
///{
/// htmlEditor1.InvokeCommand(speller1.Commands.StopBackground);
/// htmlEditor1.InvokeCommand(speller1.Commands.RemoveHighLight);
///}
/// </code>
/// You can see that we invoke commands against an extender by calling the editor instance. This way we can deal with
/// many different instances, even if only one extender exists.
/// <para>
/// To change the current dictionary and start interactive spelling the following code gives you a starter:
/// </para>
/// <code>
/// switch (dicName)
///{
/// case "Deutsch":
/// speller1.Speller.GetSpellChecker(htmlEditor1).LanguageType = new CultureInfo("de-DE");
/// break;
/// case "English (US)":
/// speller1.Speller.GetSpellChecker(htmlEditor1).LanguageType = new CultureInfo("en-US");
/// break;
/// case "English (UK)":
/// speller1.Speller.GetSpellChecker(htmlEditor1).LanguageType = new CultureInfo("en-UK")
/// break;
/// case "Spanish":
/// speller1.Speller.GetSpellChecker(htmlEditor1).LanguageType = new CultureInfo("es-ES");
/// break;
/// case "French":
/// speller1.Speller.GetSpellChecker(htmlEditor1).LanguageType = new CultureInfo("fr-FR");
/// break;
/// case "Italian":
/// speller1.Speller.GetSpellChecker(htmlEditor1).LanguageType = new CultureInfo("it-IT");
/// break;
///}
///htmlEditor1.InvokeCommand(speller1.Commands.StartWordByWord);
/// </code>
/// <para>
/// However, all these examples will not work properly without attaching the appropriate events. First, operating with a context menu:
/// </para>
/// <code>
/// this.speller1.WordOnContext += new GuruComponents.Netrix.PlugIns.SpellChecker.WordOnContextHandler(this.speller1_WordOnContext);
/// </code>
/// It's necessary to use this event because it appears at a different time than the usual OnContextMenu event. This is necessary to first place
/// the caret on the word and open the menu, then. This makes it possible to get suggestions for the current word.
/// <code>
/// private void speller1_WordOnContext(object sender, GuruComponents.Netrix.PlugIns.SpellChecker.WordOnContextEventArgs e)
/// {
/// contextMenu1.MenuItems.Clear();
/// contextMenu1.MenuItems.Add(e.Word, new EventHandler(this.contextMenu_Word));
/// }
/// </code>
/// Here we simply add the word to the context menu, but the <c>e.Suggestions</c> property will provide suggestions, if any.
/// <para>
/// </para>
/// Various other events helps building sophisticated spell checker enabled applications.
/// </example>
/// <para>
/// The spellchecker will operate with defaults here, that means wrong spelled words have red waved lines.
/// </para>
/// <para>
/// Recommended readings regarding NetSpell are:
/// <list type="bullet">
/// <item>How to create a custom dictionary: http://www.loresoft.com/Applications/NetSpell/Articles/246.aspx </item>
/// <item>Overview NetSpell: http://www.loresoft.com/Applications/NetSpell/Articles/152.aspx </item>
/// </list>
/// </para>
/// </remarks>
[ToolboxBitmap(typeof(Speller), "Resources.Toolbox.ico")]
[ProvideProperty("Speller", typeof(GuruComponents.Netrix.IHtmlEditor))]
[DesignerAttribute(typeof(SpellControlDesigner))]
public class Speller : Component, IExtenderProvider, IPlugIn
{
private Hashtable properties;
private Hashtable checker;
/// <summary>
/// Indicates that a spell check operation is currently in progress.
/// </summary>
public bool IsInCheck { get; private set; }
/// <summary>
/// Indicates that the spell checker runs in background ('as you type') mode.
/// </summary>
public bool IsInBackground { get; private set; }
private System.Windows.Forms.ToolStrip toolStripSpeller;
private System.Windows.Forms.ToolStripButton toolStripButtonSpellerSpell;
private System.Windows.Forms.MenuStrip menuStripSpeller;
private System.Windows.Forms.ToolStripMenuItem toolStripParentSpeller;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemSpellerChecker;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemSpellerAsYouType;
/// <summary>
/// Default Constructor supports design time behavior.
/// </summary>
public Speller()
{
InitializeComponent();
properties = new Hashtable();
checker = new Hashtable();
}
/// <summary>
/// Constructor supports design time behavior.
/// </summary>
/// <param name="parent">Forms container the extender belongs to.</param>
public Speller(IContainer parent) : this()
{
parent.Add(this);
}
private SpellCheckerProperties EnsurePropertiesExists(IHtmlEditor key)
{
SpellCheckerProperties p = (SpellCheckerProperties) properties[key];
if (p == null)
{
p = new SpellCheckerProperties(EnsureSpellCheckerExists(key));
properties[key] = p;
}
return p;
}
private IDocumentSpellChecker EnsureSpellCheckerExists(IHtmlEditor key)
{
DocumentSpellChecker p = (DocumentSpellChecker)checker[key];
if (p == null)
{
p = new DocumentSpellChecker(key);
p.WordChecker += new WordCheckerHandler(p_WordChecker);
p.WordCheckerFinished += new WordCheckerFinishedHandler(p_WordCheckerFinished);
p.WordCheckerStop += new WordCheckerStopHandler(p_WordCheckerStop);
p.WordOnContext += new WordOnContextHandler(p_WordOnContext);
checker[key] = p;
}
return p;
}
void p_WordOnContext(object sender, WordOnContextEventArgs e)
{
InvokeWordOnContext(sender, e);
}
bool p_WordCheckerStop(object sender, EventArgs e)
{
return InvokeWordCheckerStop(sender, e);
}
void p_WordCheckerFinished(object sender, WordCheckerEventArgs e)
{
InvokeWordCheckerFinished(sender, e);
}
bool p_WordChecker(object sender, WordEventArgs e)
{
return InvokeWordChecker(sender, e);
}
/// <summary>
/// Returns the instance of base spell checker module for the given editor instance.
/// </summary>
/// <remarks>
/// This instance provides access to the commands as regular method calls. It's recommended to use the commands and HtmlEditor's Invoke
/// method. You may consider using this instance for advanced implementions that use more than just the common features.
/// </remarks>
/// <param name="key">The editor we reference to.</param>
/// <returns>The base spellchecker instance this extender uses.</returns>
public IDocumentSpellChecker GetSpellChecker(IHtmlEditor key)
{
return EnsureSpellCheckerExists(key);
}
private SpellCommands commands;
/// <summary>
/// Returns the definitions for commands accepted by the Speller extender.
/// </summary>
/// <remarks>
/// The <see cref="SpellCommands"/> class defines the commands, which the extender registers
/// within the base control. The host application is supposed to issue the commands via the base component
/// instead of calling the Speller directly to assure that multiple instances of the NetRox component are
/// invoked properly.
/// <seealso cref="SpellCommands"/>
/// </remarks>
[Browsable(false)]
public SpellCommands Commands
{
get
{
if (commands == null)
{
commands = new SpellCommands();
}
return commands;
}
}
/// <summary>
/// Support the designer infrastructure.
/// </summary>
/// <param name="htmlEditor"></param>
/// <returns></returns>
[ExtenderProvidedProperty(), Category("NetRix Component"), Description("SpellChecker Properties")]
[TypeConverter(typeof(ExpandableObjectConverter))]
[DefaultValue("0 properties changed")]
public SpellCheckerProperties GetSpeller(IHtmlEditor htmlEditor)
{
return this.EnsurePropertiesExists(htmlEditor);
}
/// <summary>
/// Support the designer infrastructure.
/// </summary>
/// <param name="htmlEditor"></param>
/// <param name="props"></param>
public void SetSpeller(IHtmlEditor htmlEditor, SpellCheckerProperties props)
{
if (props == null) return;
if (props.HighLightStyle != null)
{
EnsurePropertiesExists(htmlEditor).HighLightStyle.LineColor = props.HighLightStyle.LineColor;
EnsurePropertiesExists(htmlEditor).HighLightStyle.LineThroughStyle = props.HighLightStyle.LineThroughStyle;
EnsurePropertiesExists(htmlEditor).HighLightStyle.LineType = props.HighLightStyle.LineType;
EnsurePropertiesExists(htmlEditor).HighLightStyle.Priority = props.HighLightStyle.Priority;
EnsurePropertiesExists(htmlEditor).HighLightStyle.TextBackgroundColor = props.HighLightStyle.TextBackgroundColor;
EnsurePropertiesExists(htmlEditor).HighLightStyle.TextColor = props.HighLightStyle.TextColor;
EnsurePropertiesExists(htmlEditor).HighLightStyle.UnderlineStyle = props.HighLightStyle.UnderlineStyle;
}
EnsurePropertiesExists(htmlEditor).IgnoreUpperCaseWords = props.IgnoreUpperCaseWords;
EnsurePropertiesExists(htmlEditor).IgnoreWordsWithDigits = props.IgnoreWordsWithDigits;
EnsurePropertiesExists(htmlEditor).MaxSuggestionsCount = props.MaxSuggestionsCount;
EnsurePropertiesExists(htmlEditor).SuggestionType = props.SuggestionType;
EnsurePropertiesExists(htmlEditor).IgnoreHtml = props.IgnoreHtml;
EnsurePropertiesExists(htmlEditor).Dictionary = props.Dictionary;
EnsurePropertiesExists(htmlEditor).DictionaryPath = props.DictionaryPath;
EnsurePropertiesExists(htmlEditor).LanguageType = props.LanguageType;
EnsurePropertiesExists(htmlEditor).CheckInternal = props.CheckInternal;
EnsurePropertiesExists(htmlEditor).IgnoreList = props.IgnoreList;
EnsurePropertiesExists(htmlEditor).ReplaceList = props.ReplaceList;
EnsurePropertiesExists(htmlEditor).MainMenuVisible = props.MainMenuVisible;
EnsurePropertiesExists(htmlEditor).ToolStripVisible = props.ToolStripVisible;
if (menuStripSpeller != null && menuStripSpeller.Items.Count > 0 && props.MainMenuVisible)
{
menuStripSpeller.Items[0].Visible = true;
((HtmlEditor)htmlEditor).MenuStrip.Items.Add(menuStripSpeller.Items[0]);
}
if (toolStripSpeller != null && props.ToolStripVisible)
{
toolStripSpeller.Visible = true;
((HtmlEditor)htmlEditor).ToolStripContainer.TopToolStripPanel.Controls.Add(toolStripSpeller);
}
htmlEditor.RegisterPlugIn(this);
htmlEditor.Loaded += new GuruComponents.Netrix.Events.LoadEventHandler(htmlEditor_Loaded);
}
void htmlEditor_Loaded(object sender, GuruComponents.Netrix.Events.LoadEventArgs e)
{
IHtmlEditor editor = (IHtmlEditor)sender;
// add commands
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.RemoveHighLight));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StartBackground));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StopBackground));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StartWordByWord));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StopWordByWord));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StartBlock));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StopBlock));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.ClearBuffer));
}
/// <summary>
/// Informs the extender that the containing control is ready.
/// </summary>
/// <param name="editor"></param>
public void NotifyReadyStateCompleted(IHtmlEditor editor)
{
htmlEditor_ReadyStateCompleteInternal(editor);
// reset former state
if (IsInCheck)
{
EnsureSpellCheckerExists(editor).DoWordCheckingHighlights(EnsurePropertiesExists(editor).HighLightStyle, true);
}
else
{
EnsureSpellCheckerExists(editor).BackgroundService = false;
}
}
void htmlEditor_ReadyStateCompleteInternal(IHtmlEditor editor)
{
// add commands
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.RemoveHighLight));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StartBackground));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StopBackground));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StartWordByWord));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StopWordByWord));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StartBlock));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.StopBlock));
editor.AddCommand(new CommandWrapper(new EventHandler(SpellerOperation), Commands.ClearBuffer));
}
void SpellerOperation(object sender, EventArgs e)
{
CommandWrapper cw = (CommandWrapper) sender;
string checkpath;
if (cw.CommandID.Guid.Equals(Commands.CommandGroup))
{
DocumentSpellChecker ds = (DocumentSpellChecker)EnsureSpellCheckerExists(cw.TargetEditor);
switch ((SpellCommand)cw.ID)
{
case SpellCommand.RemoveHighLight:
EnsureSpellCheckerExists(cw.TargetEditor).RemoveWordCheckingHighlights();
break;
case SpellCommand.ClearBuffer:
EnsureSpellCheckerExists(cw.TargetEditor).MisSpelledWords.Clear();
break;
case SpellCommand.StopBackground:
IsInBackground = false;
EnsureSpellCheckerExists(cw.TargetEditor).BackgroundService = false;
IsInCheck = false;
break;
case SpellCommand.StartBackground:
IsInBackground = true;
if (ds.Spelling.Dictionary.DictionaryFolder == null)
{
ds.Spelling.Dictionary.DictionaryFolder = "Dictionary";
}
checkpath = Path.Combine(ds.Spelling.Dictionary.DictionaryFolder, ds.Spelling.Dictionary.DictionaryFile);
if (!File.Exists(checkpath))
{
ds.Spelling.Dictionary.DictionaryFile = String.Format("{0}.dic", EnsurePropertiesExists(cw.TargetEditor).LanguageType);
}
ds.Spelling.SuggestionMode = EnsurePropertiesExists(cw.TargetEditor).SuggestionType;
ds.Spelling.IgnoreAllCapsWords = EnsurePropertiesExists(cw.TargetEditor).IgnoreUpperCaseWords;
ds.Spelling.IgnoreWordsWithDigits = EnsurePropertiesExists(cw.TargetEditor).IgnoreWordsWithDigits;
ds.Spelling.MaxSuggestions = EnsurePropertiesExists(cw.TargetEditor).MaxSuggestionsCount;
ds.Spelling.IgnoreHtml = EnsurePropertiesExists(cw.TargetEditor).IgnoreHtml;
ds.Spelling.IgnoreList.AddRange(EnsurePropertiesExists(cw.TargetEditor).IgnoreList);
foreach (KeyValuePair<string, string> de in EnsurePropertiesExists(cw.TargetEditor).ReplaceList)
{
ds.Spelling.ReplaceList[de.Key] = de.Value;
}
IsInCheck = true;
EnsureSpellCheckerExists(cw.TargetEditor).DoWordCheckingHighlights(EnsurePropertiesExists(cw.TargetEditor).HighLightStyle, true);
break;
case SpellCommand.StartWordByWord:
if (ds.Spelling.Dictionary.DictionaryFolder == null)
{
ds.Spelling.Dictionary.DictionaryFolder = "Dictionary";
}
checkpath = Path.Combine(ds.Spelling.Dictionary.DictionaryFolder, ds.Spelling.Dictionary.DictionaryFile);
if (!File.Exists(checkpath))
{
ds.Spelling.Dictionary.DictionaryFile = String.Format("{0}.dic", EnsurePropertiesExists(cw.TargetEditor).LanguageType);
}
ds.Spelling.Dictionary.DictionaryFile = String.Format("{0}.dic", EnsurePropertiesExists(cw.TargetEditor).LanguageType);
ds.Spelling.SuggestionMode = EnsurePropertiesExists(cw.TargetEditor).SuggestionType;
ds.Spelling.IgnoreAllCapsWords = EnsurePropertiesExists(cw.TargetEditor).IgnoreUpperCaseWords;
ds.Spelling.IgnoreWordsWithDigits = EnsurePropertiesExists(cw.TargetEditor).IgnoreWordsWithDigits;
ds.Spelling.MaxSuggestions = EnsurePropertiesExists(cw.TargetEditor).MaxSuggestionsCount;
ds.Spelling.IgnoreHtml = EnsurePropertiesExists(cw.TargetEditor).IgnoreHtml;
ds.Spelling.IgnoreList.AddRange(EnsurePropertiesExists(cw.TargetEditor).IgnoreList);
foreach (KeyValuePair<string, string> de in EnsurePropertiesExists(cw.TargetEditor).ReplaceList)
{
ds.Spelling.ReplaceList[de.Key] = de.Value;
}
IsInCheck = true;
ds.DoWordCheckingHighlights(ds.HighLightStyle, false);
break;
case SpellCommand.StopWordByWord:
IsInCheck = false;
break;
case SpellCommand.StopBlock:
IsInCheck = false;
break;
case SpellCommand.StartBlock:
ds.Spelling.SuggestionMode = EnsurePropertiesExists(cw.TargetEditor).SuggestionType;
ds.Spelling.IgnoreAllCapsWords = EnsurePropertiesExists(cw.TargetEditor).IgnoreUpperCaseWords;
ds.Spelling.IgnoreWordsWithDigits = EnsurePropertiesExists(cw.TargetEditor).IgnoreWordsWithDigits;
ds.Spelling.MaxSuggestions = EnsurePropertiesExists(cw.TargetEditor).MaxSuggestionsCount;
IsInCheck = true;
ds.DoBlockCheckingHighlights(EnsurePropertiesExists(cw.TargetEditor).HighLightStyle);
break;
}
}
}
/// <summary>
/// Event fired for each word found. The event is disabled if the internal spell checker is being used (default).
/// </summary>
[Category("NetRix Events (external only)")]
public event WordCheckerHandler WordChecker;
/// <summary>
/// Event fired for each word found. The event is disabled if the internal spell checker is being used (default).
/// </summary>
/// <remarks>
/// The return value of the callback function is used to stop the checking
/// process immediately. In case of internal spell checker the event doesn't fire. One can use the
/// StopWordByWord command as well as the StopBackground command. Issuing commands is based on the
/// <see cref="GuruComponents.Netrix.IHtmlEditor.InvokeCommand"/>
/// </remarks>
[Category("NetRix Events (external only)")]
public event WordCheckerStopHandler WordCheckerStop;
/// <summary>
/// Event fired once the word checking is done.
/// </summary>
[Category("NetRix Events")]
public event WordCheckerFinishedHandler WordCheckerFinished;
/// <summary>
/// Event fired if the user has right clicked the word and the caret has moved.
/// </summary>
/// <remarks>
/// This event is later than
/// ContextMenu because it is necessary to being delayed to set the caret to the final position before
/// an attached context menu opens.
/// </remarks>
[Category("NetRix Events")]
public event WordOnContextHandler WordOnContext;
/// <summary>
/// This event is fired when a word is deleted.
/// </summary>
/// <remarks>
/// Use this event to update the parent text.
/// </remarks>
[Category("NetSpell Events ")]
public event WordEventHandler DeletedWord;
/// <summary>
/// This event is fired when word is detected two times in a row.
/// </summary>
[Category("NetSpell Events")]
public event WordEventHandler DoubledWord;
/// <summary>
/// This event is fired when the spell checker reaches the end of
/// the text in the Text property.
/// </summary>
[Category("NetSpell Events")]
public event WordEventHandler EndOfText;
/// <summary>
/// This event is fired when a word is skipped.
/// </summary>
[Category("NetSpell Events")]
public event WordEventHandler IgnoredWord;
/// <summary>
/// This event is fired when the spell checker finds a word that.
/// is not in the dictionaries
/// </summary>
[Category("NetSpell Events")]
public event WordEventHandler MisspelledWord;
/// <summary>
/// This event is fired when a word is replaced.
/// </summary>
/// <remarks>
/// Use this event to update the parent text.
/// </remarks>
[Category("NetSpell Events")]
public event ReplacedWordEventHandler ReplacedWord;
private bool InvokeWordChecker(object sender, WordEventArgs e)
{
if (WordChecker != null)
{
return WordChecker(sender, e);
}
return false;
}
private void InvokeWordOnContext(object sender, WordOnContextEventArgs e)
{
if (WordOnContext != null)
{
WordOnContext(sender, e);
}
}
private void InvokeWordCheckerFinished(object sender, WordCheckerEventArgs e)
{
if (WordCheckerFinished != null)
{
WordCheckerFinished(sender, e);
}
}
private bool InvokeWordCheckerStop(object sender, EventArgs e)
{
if (WordCheckerStop != null)
{
return WordCheckerStop(sender, e);
}
// if NetSpell is being used we return false if no longer in check mode
return !IsInCheck;
}
private void spellChecker_MisspelledWord(object sender, SpellingEventArgs e)
{
Debug.WriteLine(e.Word, "MISSPELLED");
if (MisspelledWord != null)
{
MisspelledWord(sender, e);
}
}
private void spellChecker_DeletedWord(object sender, SpellingEventArgs e)
{
Debug.WriteLine(e.Word, "DELETED");
if (DeletedWord != null)
{
DeletedWord(sender, e);
}
}
private void spellChecker_DoubledWord(object sender, SpellingEventArgs e)
{
Debug.WriteLine(e.Word, "DOUBLED");
if (DoubledWord != null)
{
DoubledWord(sender, e);
}
}
private void spellChecker_EndOfText(object sender, EventArgs e)
{
IsInCheck = false;
if (EndOfText != null)
{
EndOfText(sender, new SpellingEventArgs(null, 0, 0, null));
}
}
private void spellChecker_IgnoredWord(object sender, SpellingEventArgs e)
{
if (IgnoredWord != null)
{
IgnoredWord(sender, e);
}
}
private void spellChecker_ReplacedWord(object sender, ReplaceWordEventArgs e)
{
if (ReplacedWord != null)
{
ReplacedWord(sender, e);
}
}
/// <summary>
/// Returns the current assembly version number.
/// </summary>
[Category("NetRix Speller")]
public string Version
{
get
{
return this.GetType().Assembly.GetName().Version.ToString(4);
}
}
#region IExtenderProvider Member
/// <summary>
/// Informs the designer that the currently selected control can be extended by the Speller.
/// </summary>
/// <remarks>
/// To make the Speller available the component must derive from <see cref="IHtmlEditor"/>.
/// </remarks>
/// <param name="extendee">Control which tries to adopt the Speller. Expected control is NetRix HtmlEditor only.</param>
/// <returns>Returns <c>true</c> in case of NetRix component, <c>false</c> otherwise.</returns>
public bool CanExtend(object extendee)
{
if (extendee is IHtmlEditor)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Return the editor which the given instance actually extends.
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
internal IHtmlEditor GetExtendee(Speller instance)
{
return (IHtmlEditor) properties[instance];
}
#endregion
#region IPlugIn Members
/// <summary>
/// Type
/// </summary>
[Browsable(false)]
public Type Type
{
get { return this.GetType(); }
}
/// <summary>
/// Internal name
/// </summary>
[Category("NetRix Speller")]
public string Name
{
get { return "Speller"; }
}
/// <summary>
/// Extends Netrix
/// </summary>
[Browsable(false)]
public bool IsExtenderProvider
{
get { return true; }
}
/// <summary>
/// The Spellchecker does not support any extender features.
/// </summary>
[Browsable(false)]
public Feature Features
{
get { return Feature.None; }
}
/// <summary>
/// The Spellchecker control does not support any namespaces.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public IDictionary GetSupportedNamespaces(IHtmlEditor key)
{
return null;
}
private List<CommandExtender> extenderVerbs;
/// <summary>
/// List of element types, which the extender plugin extends.
/// </summary>
/// <remarks>
/// See <see cref="GuruComponents.Netrix.PlugIns.IPlugIn.GetElementExtenders"/> for background information.
/// </remarks>
public List<CommandExtender> GetElementExtenders(IElement component)
{
if (component is BodyElement)
{
extenderVerbs = new List<CommandExtender>();
CommandExtender ceOn = new CommandExtender(Commands.StartBackground);
ceOn.Text = "SpellChecker On";
extenderVerbs.Add(ceOn);
CommandExtender ceOff = new CommandExtender(Commands.StopBackground);
ceOff.Text = "SpellChecker Off";
extenderVerbs.Add(ceOff);
return extenderVerbs;
}
else
{
return null;
}
}
System.Web.UI.Control IPlugIn.CreateElement(string tagName, IHtmlEditor editor)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
# region Toolbar
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Speller));
this.toolStripSpeller = new System.Windows.Forms.ToolStrip();
this.toolStripButtonSpellerSpell = new System.Windows.Forms.ToolStripButton();
this.menuStripSpeller = new System.Windows.Forms.MenuStrip();
this.toolStripParentSpeller = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemSpellerChecker = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemSpellerAsYouType = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSpeller.SuspendLayout();
this.menuStripSpeller.SuspendLayout();
//
// toolStripSpeller
//
this.toolStripSpeller.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButtonSpellerSpell});
this.toolStripSpeller.Location = new System.Drawing.Point(0, 0);
this.toolStripSpeller.Name = "toolStripSpeller";
this.toolStripSpeller.Size = new System.Drawing.Size(100, 25);
this.toolStripSpeller.TabIndex = 0;
this.toolStripSpeller.Text = "Spell &Checker";
//
// toolStripButtonSpellerSpell
//
this.toolStripButtonSpellerSpell.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
//this.toolStripButtonSpellerSpell.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButtonSpellerSpell.Image")));
this.toolStripButtonSpellerSpell.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButtonSpellerSpell.Name = "toolStripButtonSpellerSpell";
this.toolStripButtonSpellerSpell.Size = new System.Drawing.Size(23, 22);
this.toolStripButtonSpellerSpell.Tag = "Spellcheck";
this.toolStripButtonSpellerSpell.Text = "Spell &Checker";
//
// menuStripSpeller
//
this.menuStripSpeller.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripParentSpeller});
this.menuStripSpeller.Location = new System.Drawing.Point(0, 0);
this.menuStripSpeller.Name = "menuStripSpeller";
this.menuStripSpeller.Size = new System.Drawing.Size(200, 24);
this.menuStripSpeller.TabIndex = 0;
this.menuStripSpeller.Text = "Spell &Checker";
//
// toolStripParentSpeller
//
this.toolStripParentSpeller.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItemSpellerChecker,
this.toolStripMenuItemSpellerAsYouType});
this.toolStripParentSpeller.Name = "toolStripParentSpeller";
this.toolStripParentSpeller.Size = new System.Drawing.Size(113, 20);
this.toolStripParentSpeller.Tag = "SpellerSpell";
this.toolStripParentSpeller.Text = "Specl &Checker";
//
// toolStripMenuItemSpellerChecker
//
this.toolStripMenuItemSpellerChecker.Name = "toolStripMenuItemSpellerChecker";
this.toolStripMenuItemSpellerChecker.Size = new System.Drawing.Size(149, 22);
this.toolStripMenuItemSpellerChecker.Tag = "SpellerChecker";
this.toolStripMenuItemSpellerChecker.Text = "Spell Checker";
//
// toolStripMenuItemSpellerAsYouType
//
this.toolStripMenuItemSpellerAsYouType.Name = "toolStripMenuItemSpellerAsYouType";
this.toolStripMenuItemSpellerAsYouType.Size = new System.Drawing.Size(149, 22);
this.toolStripMenuItemSpellerAsYouType.Tag = "SpellerAsYouType";
this.toolStripMenuItemSpellerAsYouType.Text = "As-You-Type";
this.toolStripSpeller.ResumeLayout(false);
this.toolStripSpeller.PerformLayout();
this.menuStripSpeller.ResumeLayout(false);
this.menuStripSpeller.PerformLayout();
}
# endregion
/*
# region External Speller Support
/// <summary>
/// Returns the word the caret is on or nearby.
/// </summary>
/// <returns>The recognized word, or <c>null</c>, if nothing was recognized.</returns>
public string WordUnderPointer(IHtmlEditor editor)
{
return WordUnderPointer(false, editor);
}
///<overloads/>
/// <summary>
/// Replaces the word the caret is on.
/// </summary>
/// <param name="replaceWith">String the word to be replaced with</param>
public void ReplaceWordUnderPointer(string replaceWith, IHtmlEditor editor)
{
ReplaceWordUnderPointer(false, replaceWith, editor);
}
/// <summary>
/// Replaces the word the caret is on.
/// </summary>
/// <param name="withHtml"></param>
/// <param name="replaceWith">tring the word to be replaced with</param>
public void ReplaceWordUnderPointer(bool withHtml, string replaceWith, IHtmlEditor editor)
{
WordUnderPointer(withHtml, editor);
Interop.IHTMLDocument2 activeDocument = editor.GetActiveDocument(false);
Interop.IHTMLTxtRange trg = ((Interop.IHtmlBodyElement)activeDocument.GetBody()).createTextRange();
if (trg != null && trg.GetText() != null)
{
trg.SetText(replaceWith);
}
}
/// <summary>
/// Returns the word with or without inline HTML the caret is on on nearby.
/// </summary>
/// <param name="withHtml">If true the method returns any embedded HTML too, otherwise HTML is stripped out.</param>
/// <returns>The recognized HTML, or <c>null</c>, if nothing was recognized.</returns>
public string WordUnderPointer(bool withHtml, IHtmlEditor editor)
{
Interop.IHTMLDocument2 activeDocument = editor.GetActiveDocument(false);
Interop.IDisplayServices ds = (Interop.IDisplayServices) activeDocument;
Interop.IMarkupServices ims = activeDocument as Interop.IMarkupServices;
Interop.IHTMLTxtRange tr = ((Interop.IHtmlBodyElement)activeDocument.GetBody()).createTextRange();
Interop.IMarkupPointer pStart, pEnd;
ims.CreateMarkupPointer(out pStart);
ims.CreateMarkupPointer(out pEnd);
// now reset pointer to caret
Interop.IHTMLCaret cr;
ds.GetCaret(out cr);
cr.MoveMarkupPointerToCaret(pStart);
cr.MoveMarkupPointerToCaret(pEnd);
Interop.CARET_DIRECTION dir;
cr.GetCaretDirection(out dir);
ims.MoveRangeToPointers(pStart, pEnd, tr);
int result = 0;
System.Diagnostics.Debug.WriteLine((Interop.CARET_DIRECTION)dir, "DIR");
while (tr.GetText() == null)
{
if ((Interop.CARET_DIRECTION)dir == Interop.CARET_DIRECTION.CARET_DIRECTION_BACKWARD)
{
// look forward for word if caret runs backward
result = tr.MoveEnd("word", 1);
if (result == 1)
{
// in case of success expand, to get full word
if (tr.Expand("word")) continue;
}
// look forward only if unsuccessfully
// avoid trailing spaces being part of the current range
TrimRange(tr);
// if still null, try looking backward
if (tr.GetText() == null)
{
tr.MoveEnd("word", -1);
tr.MoveStart("word", -1);
}
break;
}
else
{
// look backward for word if caret runs forward
result = tr.MoveStart("word", -1);
if (result == -1)
{
// in case of success expand, to get full word
if (tr.Expand("word")) continue;
}
// look forward only if unsuccessfully
// avoid trailing spaces being part of the current range
TrimRange(tr);
result = tr.MoveEnd("word", 1);
if (result == 1) continue;
// break if no result
break;
}
}
TrimRange(tr);
return tr.GetText();
}
private void TrimRange(Interop.IHTMLTxtRange tr)
{
string txt = null;
if (tr.GetText() != null)
{
txt = tr.GetText();
int i = txt.Length - 1;
while (txt != null
&&
i > 0 && i < txt.Length
&&
(
Char.IsPunctuation(txt[i])
||
Char.IsWhiteSpace(txt[i])
))
{
tr.MoveEnd("character", -1);
txt = tr.GetText();
i--;
}
i = 0;
while (txt != null
&&
i < txt.Length
&&
(
Char.IsPunctuation(txt[i])
||
Char.IsWhiteSpace(txt[i])
))
{
tr.MoveStart("character", 1);
txt = tr.GetText();
i++;
}
}
}
# endregion
* */
}
}
| |
/*
* StringFormat.cs - Implementation of the "System.Drawing.StringFormat" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Drawing
{
using System.Drawing.Toolkit;
using System.Drawing.Text;
public sealed class StringFormat
: MarshalByRefObject, ICloneable, IDisposable
{
// Internal state.
private StringFormatFlags options;
private int language;
private StringAlignment alignment;
private StringDigitSubstitute digitMethod;
private HotkeyPrefix hotkeyPrefix;
private StringAlignment lineAlignment;
private StringTrimming trimming;
internal CharacterRange[] ranges;
private float firstTabOffset;
private float[] tabStops;
// Constructors.
public StringFormat()
{
this.trimming = StringTrimming.Character;
}
public StringFormat(StringFormat format)
{
if(format == null)
{
throw new ArgumentNullException("format");
}
this.options = format.options;
this.language = format.language;
this.alignment = format.alignment;
this.digitMethod = format.digitMethod;
this.hotkeyPrefix = format.hotkeyPrefix;
this.lineAlignment = format.lineAlignment;
this.trimming = format.trimming;
this.ranges = format.ranges;
this.firstTabOffset = format.firstTabOffset;
this.tabStops = format.tabStops;
}
public StringFormat(StringFormatFlags options)
{
this.options = options;
this.trimming = StringTrimming.Character;
}
public StringFormat(StringFormatFlags options, int language)
{
this.options = options;
this.language = language;
this.trimming = StringTrimming.Character;
}
private StringFormat(bool typographic)
{
if(typographic)
{
this.options = (StringFormatFlags.LineLimit |
StringFormatFlags.NoClip);
}
else
{
this.trimming = StringTrimming.Character;
}
}
// Get or set this object's properties.
public StringAlignment Alignment
{
get
{
return alignment;
}
set
{
alignment = value;
}
}
public int DigitSubstitutionLanguage
{
get
{
return language;
}
}
public StringDigitSubstitute DigitSubstitutionMethod
{
get
{
return digitMethod;
}
set
{
digitMethod = value;
}
}
public StringFormatFlags FormatFlags
{
get
{
return options;
}
set
{
options = value;
}
}
public HotkeyPrefix HotkeyPrefix
{
get
{
return hotkeyPrefix;
}
set
{
hotkeyPrefix = value;
}
}
public StringAlignment LineAlignment
{
get
{
return lineAlignment;
}
set
{
lineAlignment = value;
}
}
public StringTrimming Trimming
{
get
{
return trimming;
}
set
{
trimming = value;
}
}
// Get the generic default string format.
public static StringFormat GenericDefault
{
get { return new StringFormat(false); }
}
// Get the generic typographic string format.
public static StringFormat GenericTypographic
{
get { return new StringFormat(true); }
}
// Clone this object.
public Object Clone()
{
return new StringFormat(this);
}
// Dispose of this object.
public void Dispose()
{
// Nothing to do here in this implementation.
}
// Get tab stop information for this format.
public float[] GetTabStops(out float firstTabOffset)
{
#if CONFIG_EXTENDED_NUMERICS
if(this.tabStops == null)
{
this.firstTabOffset = 8.0f;
this.tabStops = new float [] {8.0f};
}
#endif
firstTabOffset = this.firstTabOffset;
return this.tabStops;
}
// Set the digit substitution properties.
public void SetDigitSubstitution
(int language, StringDigitSubstitute substitute)
{
this.language = language;
this.digitMethod = digitMethod;
}
// Set the measurable character ranges.
public void SetMeasurableCharacterRanges(CharacterRange[] ranges)
{
this.ranges = ranges;
}
// Set the tab stops for this format.
public void SetTabStops(float firstTabOffset, float[] tabStops)
{
this.firstTabOffset = firstTabOffset;
this.tabStops = tabStops;
}
// Convert this object into a string.
public override String ToString()
{
return "[StringFormat, FormatFlags=" +
options.ToString() + "]";
}
}; // class StringFormat
}; // namespace System.Drawing
| |
#region Imports
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using TribalWars.Maps.AttackPlans;
using TribalWars.Maps.Controls;
using TribalWars.Maps.Manipulators.EventArg;
using TribalWars.Maps.Manipulators.Implementations.Church;
using TribalWars.Maps.Manipulators.Managers;
using TribalWars.Maps.Polygons;
using TribalWars.Tools;
using TribalWars.Villages;
using TribalWars.Worlds;
using TribalWars.Worlds.Events.Impls;
#endregion
namespace TribalWars.Maps.Manipulators
{
/// <summary>
/// Manages the user interaction with a map
/// </summary>
public class ManipulatorManagerController
{
#region Delegates
public delegate void MouseMovedDelegate(MouseEventArgs e, Point mapLocation, Village village, Point activeLocation, Point activeVillage);
#endregion
#region Fields
private readonly Dictionary<ManipulatorManagerTypes, ManipulatorManagerBase> _manipulators;
private ManipulatorManagerTypes? _previousType;
private readonly List<ManipulatorBase> _roaming = new List<ManipulatorBase>();
private ChurchManipulator _churchManipulator;
private MouseMovedDelegate _mouseMoved;
#endregion
#region Properties
/// <summary>
/// Gets the currently active manipulatormanager
/// </summary>
public ManipulatorManagerBase CurrentManipulator { get; private set; }
/// <summary>
/// Gets all available manipulatormanagers
/// </summary>
public Dictionary<ManipulatorManagerTypes, ManipulatorManagerBase> Manipulators
{
get { return _manipulators; }
}
/// <summary>
/// Gets the map the manipulators are active on
/// </summary>
private Map Map { get; set; }
/// <summary>
/// Gets the default manipulator
/// </summary>
private DefaultManipulatorManager DefaultManipulator { get; set; }
/// <summary>
/// Gets the polygon manipulator
/// </summary>
public PolygonManipulatorManager PolygonManipulator { get; private set; }
public AttackManipulatorManager AttackManipulator { get; private set; }
public ChurchManipulator ChurchManipulator
{
get
{
if (_churchManipulator == null)
{
_churchManipulator = new ChurchManipulator(Map);
}
return _churchManipulator;
}
}
/// <summary>
/// The last village the cursor was on or is still on
/// </summary>
private Point ActiveVillage { get; set; }
/// <summary>
/// The 2nd last village the cursors was on
/// </summary>
private Point LastActiveVillage { get; set; }
/// <summary>
/// The location the cursors is on
/// </summary>
private Point ActiveLocation { get; set; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new ManipulatorManager for a minimap
/// </summary>
public ManipulatorManagerController(Map miniMap, Map mainMap)
{
Map = miniMap;
_manipulators = new Dictionary<ManipulatorManagerTypes, ManipulatorManagerBase>();
CurrentManipulator = new MiniMapManipulatorManager(miniMap, mainMap);
_manipulators.Add(ManipulatorManagerTypes.Default, CurrentManipulator);
}
/// <summary>
/// Initializes a new ManipulatorManager
/// </summary>
public ManipulatorManagerController(Map map)
{
Map = map;
_manipulators = new Dictionary<ManipulatorManagerTypes, ManipulatorManagerBase>();
DefaultManipulator = new DefaultManipulatorManager(map);
CurrentManipulator = DefaultManipulator;
_manipulators.Add(ManipulatorManagerTypes.Default, CurrentManipulator);
PolygonManipulator = new PolygonManipulatorManager(map);
_manipulators.Add(ManipulatorManagerTypes.Polygon, PolygonManipulator);
AttackManipulator = new AttackManipulatorManager(map);
_manipulators.Add(ManipulatorManagerTypes.Attack, AttackManipulator);
}
#endregion
#region Manipulators
/// <summary>
/// Changes the active manipulatormanager
/// </summary>
public void SetManipulator(ManipulatorManagerTypes manipulator)
{
if (manipulator != ManipulatorManagerTypes.Default)
{
_previousType = manipulator;
}
Map.EventPublisher.Deselect(this);
CurrentManipulator = _manipulators[manipulator];
CurrentManipulator.Initialize();
Map.EventPublisher.ChangeManipulator(this, new ManipulatorEventArgs(manipulator));
}
/// <summary>
/// Keep track of last non-default manipulator
/// and switch between default and last
/// </summary>
public void SwitchManipulator()
{
if (!_previousType.HasValue)
{
SetManipulator(ManipulatorManagerTypes.Attack);
}
else if (CurrentManipulator == _manipulators[ManipulatorManagerTypes.Default])
{
SetManipulator(_previousType.Value);
}
else
{
SetManipulator(ManipulatorManagerTypes.Default);
}
}
public void ToggleChurchManipulator()
{
ToggleRoamingManipulator(ChurchManipulator);
}
#region Roaming Manipulator
/// <summary>
/// A roaming manipulator is not part of a <see cref="ManipulatorManagerBase"/> but
/// is added to whichever is active
/// </summary>
/// <remarks>
/// ATTN: !!! Incomplete roaming manipulators implementation: !!!
/// - Only those events used by <see cref="ChurchManipulator"/> are actually called
/// - New roaming manipulators are not automatically persisted
/// - etc..
/// </remarks>
private void ToggleRoamingManipulator(ManipulatorBase manipulator)
{
Debug.Assert(manipulator is ChurchManipulator, "See remark above. RoamingManipulators only implemented for the Church.");
if (_roaming.Contains(manipulator))
{
_roaming.Remove(manipulator);
}
else
{
_roaming.Add(manipulator);
}
}
public string GetRoamingXml()
{
var str = new StringBuilder();
str.Append(ChurchManipulator.WriteXml());
return str.ToString();
}
public void ReadRoamingXml(XDocument newReader)
{
ChurchManipulator.ReadXml(newReader);
}
#endregion
#endregion
#region KeyEvents
public bool KeyDown(KeyEventArgs e)
{
return CurrentManipulator.OnKeyDownCore(new MapKeyEventArgs(e));
}
public bool KeyUp(KeyEventArgs e)
{
return CurrentManipulator.OnKeyUpCore(new MapKeyEventArgs(e));
}
#endregion
#region MouseEvents
/// <summary>
/// Add a method that will be triggered each time the mouse
/// moves over the map
/// </summary>
public void AddMouseMoved(MouseMovedDelegate moved)
{
_mouseMoved += moved;
}
public bool OnVillageDoubleClick(MouseEventArgs e, Village village)
{
return CurrentManipulator.OnVillageDoubleClickCore(new MapVillageEventArgs(e, village));
}
public bool MouseDown(MouseEventArgs e, Village village)
{
bool redraw = false;
if (village != null && e.Button == MouseButtons.Left)
{
redraw = CurrentManipulator.OnVillageClickCore(new MapVillageEventArgs(e, village));
}
return CurrentManipulator.MouseDownCore(new MapMouseEventArgs(e, village))
|| redraw;
}
public bool MouseUp(MouseEventArgs e, Village village)
{
bool redraw = CurrentManipulator.MouseUpCore(new MapMouseEventArgs(e, village));
return redraw;
}
public bool MouseLeave()
{
// Avoid showing a tooltip outside the MapControl
Map.StopTooltip();
return CurrentManipulator.MouseLeave();
}
public bool MouseMove(MouseEventArgs e)
{
Point game = Map.Display.GetGameLocation(e.Location);
Village village = World.Default.GetVillage(game);
Point map = Map.Display.GetMapLocation(game);
// Display village tooltip
if (village != null)
{
if (ActiveVillage != village.Location)
{
LastActiveVillage = ActiveVillage;
ActiveVillage = village.Location;
CurrentManipulator.ShowTooltip(village);
}
}
else
{
Map.StopTooltip();
}
// Invoke the MouseMoved delegate each time the current mouse location is different from the last location
if (_mouseMoved != null && ActiveLocation != game)
{
ActiveLocation = game;
_mouseMoved(e, map, village, ActiveLocation, ActiveVillage);
}
return CurrentManipulator.MouseMoveCore(new MapMouseMoveEventArgs(e, map, village));
}
public bool MouseWheel(MouseEventArgs e)
{
return CurrentManipulator.MouseWheel(e);
}
#endregion
#region Painting
public void Paint(MapPaintEventArgs e)
{
foreach (ManipulatorBase roaming in _roaming)
{
roaming.Paint(e, false);
}
foreach (ManipulatorManagerBase manipulator in _manipulators.Values)
{
manipulator.Paint(e, manipulator == CurrentManipulator);
}
}
public void TimerPaint(ScrollableMapControl mapPicture, Rectangle fullMap)
{
Graphics g = mapPicture.CreateGraphics();
foreach (ManipulatorManagerBase manipulator in _manipulators.Values)
manipulator.TimerPaint(new MapTimerPaintEventArgs(g, fullMap, manipulator == CurrentManipulator));
}
#endregion
public void CleanUp()
{
foreach (var manipulator in _roaming)
{
manipulator.CleanUp();
}
_manipulators.ForEach(d => d.Value.CleanUp());
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace DocumentFormat.OpenXml.Packaging
{
/// <summary>
/// Represents an internal reference relationship to a DataPart element.
/// </summary>
public class DataPartReferenceRelationship : ReferenceRelationship
{
/// <summary>
/// Initializes a new instance of the DataPartReferenceRelationship class.
/// </summary>
/// <remarks>
/// A call to Initialize() must be made after calling this constructor.
/// </remarks>
internal DataPartReferenceRelationship()
{
}
/// <summary>
/// Initializes a new instance of the DataPartReferenceRelationship class using the supplied
/// DataPart, relationship type, and relationship ID.
/// </summary>
/// <param name="dataPart">The target DataPart of the reference relationship.</param>
/// <param name="relationshipType">The relationship type of the reference relationship.</param>
/// <param name="id">The relationship ID.</param>
internal protected DataPartReferenceRelationship(DataPart dataPart, string relationshipType, string id)
: base(dataPart.Uri, false, relationshipType, id)
{
this.DataPart = dataPart;
}
/// <summary>
/// Gets the referenced target DataPart.
/// </summary>
public virtual DataPart DataPart
{
get;
private set;
}
/// <summary>
/// Initializes the current instance of the DataPartRelationship class.
/// </summary>
/// <param name="containter">The owner <see cref="OpenXmlPartContainer"/> that holds the <see cref="ReferenceRelationship"/>.</param>
/// <param name="dataPart">The target DataPart of the reference relationship.</param>
/// <param name="relationshipType">The relationship type of the reference relationship.</param>
/// <param name="id">The relationship ID.</param>
internal void Initialize(OpenXmlPartContainer containter, DataPart dataPart, string relationshipType, string id)
{
Debug.Assert(containter != null);
Debug.Assert(dataPart != null);
this.Initialize(dataPart.Uri, false, relationshipType, id);
this.Container = containter;
this.DataPart = dataPart;
}
internal static bool IsDataPartReferenceRelationship(string relationshipType)
{
switch (relationshipType)
{
case MediaReferenceRelationship.RelationshipTypeConst:
case AudioReferenceRelationship.RelationshipTypeConst:
case VideoReferenceRelationship.RelationshipTypeConst:
return true;
default:
return false;
}
}
/// <summary>
/// Creates a new instance of the DataPartRelationship class based on the relationship type.
/// </summary>
/// <param name="containter">The owner <see cref="OpenXmlPartContainer"/> that holds the <see cref="ReferenceRelationship"/>.</param>
/// <param name="dataPart">The target DataPart of the reference relationship.</param>
/// <param name="relationshipType">The relationship type of the reference relationship.</param>
/// <param name="id">The relationship ID.</param>
internal static DataPartReferenceRelationship CreateDataPartReferenceRelationship(OpenXmlPartContainer containter, DataPart dataPart, string relationshipType, string id)
{
Debug.Assert(containter != null);
Debug.Assert(dataPart != null);
DataPartReferenceRelationship dataPartReferenceRelationship;
switch (relationshipType)
{
case MediaReferenceRelationship.RelationshipTypeConst:
dataPartReferenceRelationship = new MediaReferenceRelationship((MediaDataPart)dataPart, id);
break;
case AudioReferenceRelationship.RelationshipTypeConst:
dataPartReferenceRelationship = new AudioReferenceRelationship((MediaDataPart)dataPart, id);
break;
case VideoReferenceRelationship.RelationshipTypeConst:
dataPartReferenceRelationship = new VideoReferenceRelationship((MediaDataPart)dataPart, id);
break;
default:
throw new ArgumentOutOfRangeException("relationshipType");
}
dataPartReferenceRelationship.Container = containter;
return dataPartReferenceRelationship;
}
}
/// <summary>
/// Represents an internal media reference relationship to a MediaDataPart element.
/// </summary>
public class MediaReferenceRelationship : DataPartReferenceRelationship
{
/// <summary>
/// Represents the fixed value of the RelationshipType.
/// </summary>
internal const String RelationshipTypeConst = @"http://schemas.microsoft.com/office/2007/relationships/media";
/// <summary>
/// Gets the source relationship type for a media reference.
/// </summary>
public static string MediaReferenceRelationshipType
{
get { return RelationshipTypeConst; }
}
/// <summary>
/// Initializes a new instance of the MediaReferenceRelationship class.
/// </summary>
/// <remarks>
/// A call to Initialize() must be made after calling this constructor.
/// </remarks>
internal MediaReferenceRelationship()
{
}
/// <summary>
/// Initializes a new instance of the MediaReferenceRelationship class using
/// the supplied MediaDataPart and relationship ID.
/// </summary>
/// <param name="mediaDataPart">The target DataPart of the reference relationship.</param>
/// <param name="id">The relationship ID.</param>
internal protected MediaReferenceRelationship(MediaDataPart mediaDataPart, string id)
: base(mediaDataPart, RelationshipTypeConst, id)
{
}
/// <summary>
/// Gets the relationship type for a media reference.
/// </summary>
public override string RelationshipType
{
get { return RelationshipTypeConst; }
}
}
/// <summary>
/// Represents an internal audio reference relationship to a MediaDataPart element.
/// </summary>
public class AudioReferenceRelationship : DataPartReferenceRelationship
{
/// <summary>
/// Represents the fixed value of the RelationshipType.
/// </summary>
internal const String RelationshipTypeConst = @"http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio";
/// <summary>
/// Gets the source relationship type for an audio reference.
/// </summary>
public static string AudioReferenceRelationshipType
{
get { return RelationshipTypeConst; }
}
/// <summary>
/// Initializes a new instance of the AudioReferenceRelationship.
/// </summary>
/// <remarks>
/// A call to Initialize() must be made after calling this constructor.
/// </remarks>
internal AudioReferenceRelationship()
{
}
/// <summary>
/// Initializes a new instance of the AudioReferenceRelationship using the supplied
/// MediaDataPart and relationship ID.
/// </summary>
/// <param name="mediaDataPart">The target DataPart of the reference relationship.</param>
/// <param name="id">The relationship ID.</param>
internal protected AudioReferenceRelationship(MediaDataPart mediaDataPart, string id)
: base(mediaDataPart, RelationshipTypeConst, id)
{
}
/// <summary>
/// Gets the relationship type for an audio reference.
/// </summary>
public override string RelationshipType
{
get { return RelationshipTypeConst; }
}
}
/// <summary>
/// Represents an internal video reference relationship to a MediaDataPart element.
/// </summary>
public class VideoReferenceRelationship : DataPartReferenceRelationship
{
/// <summary>
/// Represents the fixed value of the RelationshipType.
/// </summary>
internal const String RelationshipTypeConst = @"http://schemas.openxmlformats.org/officeDocument/2006/relationships/video";
/// <summary>
/// Gets the source relationship type for an audio reference.
/// </summary>
public static string VideoReferenceRelationshipType
{
get { return RelationshipTypeConst; }
}
/// <summary>
/// Initializes a new instance of the VideoReferenceRelationship class.
/// </summary>
/// <remarks>
/// A call to Initialize() must be made after calling this constructor.
/// </remarks>
internal VideoReferenceRelationship()
{
}
/// <summary>
/// Initializes a new instance of the VideoReferenceRelationship class using the supplied
/// MediaDataPart and relationship ID.
/// </summary>
/// <param name="mediaDataPart">The target DataPart of the reference relationship.</param>
/// <param name="id">The relationship ID.</param>
internal protected VideoReferenceRelationship(MediaDataPart mediaDataPart, string id)
: base(mediaDataPart, RelationshipTypeConst, id)
{
}
/// <summary>
/// Gets the relationship type for a video reference.
/// </summary>
public override string RelationshipType
{
get { return RelationshipTypeConst; }
}
}
}
| |
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using SimpleContainer.Configuration;
using SimpleContainer.Infection;
using SimpleContainer.Interface;
using SimpleContainer.Tests.Helpers;
namespace SimpleContainer.Tests.ConstructionLog
{
public abstract class ConstructionLogTest : SimpleContainerTestBase
{
public class DumpSimpleTypesFromFactoryInConstructionLog : ConstructionLogTest
{
public class A
{
public readonly string parameter;
public A(string parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(b => b.BindDependencyFactory<A>("parameter", _ => "qq"));
const string expectedConstructionLog = "A\r\n\tparameter -> qq";
Assert.That(container.Resolve<A>().GetConstructionLog(), Is.EqualTo(expectedConstructionLog));
}
}
public class PrintFuncArgumentNameWhenInvokedFromCtor : ConstructionLogTest
{
public class A
{
public readonly int v;
public readonly B b;
public A(int v, Func<B> myFactory)
{
this.v = v;
b = myFactory();
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(c => c.BindDependency<A>("v", 76).BindDependency<B>("parameter", 67));
var resolved = container.Resolve<A>();
Assert.That(resolved.GetConstructionLog(), Is.EqualTo("A\r\n\tv -> 76\r\n\tFunc<B>\r\n\t() => B\r\n\t\tparameter -> 67"));
}
}
public class CommentExplicitDontUse : ConstructionLogTest
{
public class A
{
public readonly B b;
public A(B b = null)
{
this.b = b;
}
}
public class B
{
}
[Test]
public void Test()
{
var container = Container(b => b.DontUse<B>());
var resolvedService = container.Resolve<A>();
Assert.That(resolvedService.Single().b, Is.Null);
Assert.That(resolvedService.GetConstructionLog(), Is.EqualTo("A\r\n\tB - DontUse -> <null>"));
}
}
public class CommentIgnoreImplementation : ConstructionLogTest
{
public class A
{
public readonly B b;
public A(B b = null)
{
this.b = b;
}
}
[DontUse]
public class B
{
}
[Test]
public void Test()
{
var container = Container();
var resolvedService = container.Resolve<A>();
Assert.That(resolvedService.Single().b, Is.Null);
Assert.That(resolvedService.GetConstructionLog(), Is.EqualTo("A\r\n\tB - DontUse -> <null>"));
}
}
public class ExplicitNull : ConstructionLogTest
{
public class A
{
public readonly string parameter;
public A(string parameter = null)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container();
const string expectedConstructionLog = "A\r\n\tparameter -> <null>";
Assert.That(container.Resolve<A>().GetConstructionLog(), Is.EqualTo(expectedConstructionLog));
}
}
public class MergeFailedConstructionLog : ConstructionLogTest
{
public class A
{
public readonly IB b;
public A(IB b)
{
this.b = b;
}
}
public interface IB
{
}
public class B1 : IB
{
}
public class B2 : IB
{
}
public class C
{
public readonly A a;
public C(A a)
{
this.a = a;
}
}
[Test]
public void Test()
{
var container = Container();
Assert.Throws<SimpleContainerException>(() => container.Get<A>());
var error = Assert.Throws<SimpleContainerException>(() => container.Get<C>());
const string expectedMessage =
"many instances for [IB]\r\n\tB1\r\n\tB2\r\n\r\n!C\r\n\t!A\r\n\t\tIB++\r\n\t\t\tB1\r\n\t\t\tB2";
Assert.That(error.Message, Is.EqualTo(expectedMessage));
}
}
public class DumpCommentOnlyOnce : ConstructionLogTest
{
public class X
{
public readonly IA a1;
public readonly IA a2;
public X(IA a1, IA a2)
{
this.a1 = a1;
this.a2 = a2;
}
}
public interface IA
{
}
public class A1 : IA
{
}
public class A2 : IA
{
}
public class AConfigurator : IServiceConfigurator<IA>
{
public void Configure(ConfigurationContext context, ServiceConfigurationBuilder<IA> builder)
{
builder.WithInstanceFilter(a => a.GetType() == typeof (A2));
}
}
[Test]
public void Test()
{
var container = Container();
Assert.That(container.Resolve<X>().GetConstructionLog(),
Is.EqualTo("X\r\n\tIA - instance filter\r\n\t\tA1\r\n\t\tA2\r\n\tIA"));
}
}
public class ConstructionLogForReusedService : ConstructionLogTest
{
public class A
{
}
public class B
{
public readonly A a1;
public readonly A a2;
public readonly A a3;
public B(A a1, A a2, A a3)
{
this.a1 = a1;
this.a2 = a2;
this.a3 = a3;
}
}
[Test]
public void Test()
{
var container = Container();
Assert.That(container.Resolve<B>().GetConstructionLog(), Is.EqualTo("B\r\n\tA\r\n\tA\r\n\tA"));
}
}
public class DisplayInitializingStatus : ConstructionLogTest
{
private static readonly StringBuilder log = new StringBuilder();
public class A : IInitializable
{
public readonly B b;
public static ManualResetEventSlim goInitialize = new ManualResetEventSlim();
public A(B b)
{
this.b = b;
}
public void Initialize()
{
goInitialize.Wait();
log.Append("A.Initialize ");
}
}
public class B: IInitializable
{
public static ManualResetEventSlim goInitialize = new ManualResetEventSlim();
public void Initialize()
{
goInitialize.Wait();
log.Append("B.Initialize ");
}
}
[Test]
public void Test()
{
var container = Container();
var t = Task.Run(() => container.Get<A>());
Thread.Sleep(15);
Assert.That(container.Resolve<A>().GetConstructionLog(), Is.EqualTo("A, initializing ...\r\n\tB, initializing ..."));
Assert.That(log.ToString(), Is.EqualTo(""));
B.goInitialize.Set();
Thread.Sleep(5);
Assert.That(container.Resolve<A>().GetConstructionLog(), Is.EqualTo("A, initializing ...\r\n\tB"));
Assert.That(log.ToString(), Is.EqualTo("B.Initialize "));
A.goInitialize.Set();
Thread.Sleep(5);
Assert.That(container.Resolve<A>().GetConstructionLog(), Is.EqualTo("A\r\n\tB"));
Assert.That(log.ToString(), Is.EqualTo("B.Initialize A.Initialize "));
t.Wait();
}
}
public class DisplayDisposingStatus : ConstructionLogTest
{
private static readonly StringBuilder log = new StringBuilder();
public class A : IDisposable
{
public readonly B b;
public static ManualResetEventSlim go = new ManualResetEventSlim();
public A(B b)
{
this.b = b;
}
public void Dispose()
{
go.Wait();
log.Append("A.Dispose ");
}
}
public class B: IDisposable
{
public static ManualResetEventSlim go = new ManualResetEventSlim();
public void Dispose()
{
go.Wait();
log.Append("B.Dispose ");
}
}
protected override void TearDown()
{
A.go.Set();
B.go.Set();
base.TearDown();
}
[Test]
public void Test()
{
var container = Container();
container.Get<A>();
var t = Task.Run(() => container.Dispose());
Thread.Sleep(15);
Assert.That(container.Resolve<A>().GetConstructionLog(), Is.EqualTo("A, disposing ...\r\n\tB"));
Assert.That(log.ToString(), Is.EqualTo(""));
A.go.Set();
Thread.Sleep(5);
Assert.That(container.Resolve<A>().GetConstructionLog(), Is.EqualTo("A\r\n\tB, disposing ..."));
Assert.That(log.ToString(), Is.EqualTo("A.Dispose "));
B.go.Set();
Thread.Sleep(5);
Assert.Throws<ObjectDisposedException>(() => container.Resolve<A>());
t.Wait();
}
}
public class CycleSpanningContainerDependency : ConstructionLogTest
{
public class A
{
public A(IContainer container)
{
container.Get<B>();
}
}
public class B
{
public readonly A a;
public B(A a)
{
this.a = a;
}
}
[Test]
public void Test()
{
var container = Container();
var exception = Assert.Throws<SimpleContainerException>(() => container.Get<A>());
Assert.That(exception.Message, Is.EqualTo("cyclic dependency for service [A], stack\r\n\tA\r\n\tB\r\n\tA\r\n\r\n!A\r\n\tIContainer\r\n\t!() => B\r\n\t\t!A"));
Assert.That(exception.InnerException, Is.Null);
}
}
public class PrettyLogForBadResolveInDependencyFactoryDelegate : ConstructionLogTest
{
[TestContract("c1")]
public class A
{
public readonly string item;
public A(string item)
{
this.item = item;
}
}
public class B
{
public string value = "42";
}
[Test]
public void Test()
{
const string expectedMessage = @"
contract [c1] already declared, stack
A[c1]
item
B[c1]
!A
!item
!() => B <---------------";
var container = Container(b => b.BindDependencyFactory<A>("item", c => c.Get<B>("c1").value));
var exception = Assert.Throws<SimpleContainerException>(() => container.Get<A>());
Assert.That(exception.Message, Is.EqualTo(FormatExpectedMessage(expectedMessage)));
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace PsMsBuildHelper
{
public class XmlMsBuildLogger : Logger, INodeLogger
{
public static object BuildProject(string projectPath, string outputPath, string configuration = null, string platform = null, string[] targets = null)
{
if (projectPath == null)
throw new ArgumentNullException("projectPath");
if (outputPath == null)
throw new ArgumentNullException("outputPath");
if (projectPath.Trim().Length == 0 || !File.Exists(projectPath))
throw new FileNotFoundException("Project file not found", projectPath);
if (outputPath.Trim().Length == 0 || !Directory.Exists(Path.GetDirectoryName(outputPath)))
throw new DirectoryNotFoundException("Output Directory not found");
try {
XmlMsBuildLogger logger = new XmlMsBuildLogger();
logger.Parameters = outputPath;
Project project;
if (ProjectCollection.GlobalProjectCollection.Count > 0)
ProjectCollection.GlobalProjectCollection.UnloadAllProjects();
project = ProjectCollection.GlobalProjectCollection.LoadProject(projectPath);
if (configuration != null && (configuration = configuration.Trim()).Length > 0)
project.SetProperty("Configuration", configuration);
if (configuration != null && (platform = platform.Trim()).Length > 0)
project.SetProperty("Platform", platform);
return (targets.Length == 0) ? project.Build(logger) : project.Build(targets, new ILogger[] { logger });
} catch (Exception exception) {
return exception;
}
}
public const string RoundTrimDateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz";
private XmlWriter _writer = null;
private object _syncRoot = new object();
private IEventSource _eventSource = null;
private int _cpuCount = -1;
private string _outputPath = "";
private StopwatchDictionary _stopwatches = null;
static class ParameterParseHelper
{
public static readonly Regex _boolRegex = new Regex(@"^((?<false>f(alse)?|no?|-|[+\-]?0+(\.0+)?))|(?<true>)t(rue)?|y(es)?|\+|[+\-]?(0*[1-9]\d*(\.\d+)?|0+\.0*[1-9]\d*))$", RegexOptions.IgnoreCase);
internal static bool ParseBoolean(string parameterName, string text)
{
Match m = _boolRegex.Match(text.Trim());
if (!m.Success)
throw new Exception("'" + text + "' is not recognized yes/no value for the '" + parameterName + "' parameter.");
return m.Groups["true"].Success;
}
internal static TEnum ParseEnum<TEnum>(string parameterName, string text)
where TEnum : struct
{
TEnum result;
if (!Enum.TryParse<TEnum>(text.Trim(), out result))
throw new Exception("'" + text + "' is not recognized option for the '" + parameterName + "' parameter.");
return result;
}
}
private void _Initialize(IEventSource eventSource, Int32 nodeCount)
{
if (eventSource == null)
throw new ArgumentNullException("eventSource");
Monitor.Enter(_syncRoot);
try
{
if (_eventSource != null)
{
if (!ReferenceEquals(_eventSource, eventSource))
throw new ArgumentException("Only one event source can be logged at a time", "eventSource");
_cpuCount = nodeCount;
return;
}
XmlWriterSettings settings = new XmlWriterSettings
{
Async = true,
CheckCharacters = false,
Indent = true,
WriteEndDocumentOnClose = true
};
bool emitIdentifier = false;
bool bigEndian = false;
bool allowOpt = false;
foreach (var g in ((Parameters == null) ? "" : Parameters.Trim()).Split(Path.PathSeparator).Select(p =>
{
string[] kvp = p.Split(new char[] { '=' }, 2);
if (kvp.Length == 1)
{
if ((kvp[0]= kvp[0].Trim()).Length > 0)
return new { Key = "Path", Value = kvp[0] };
return new { Key = "Path", Value = null as string };
}
return new { Key = kvp[0].Trim(), Value = kvp[1].Trim() };
}).GroupBy(kvp => kvp.Key, StringComparer.InvariantCultureIgnoreCase))
{
if (g.Count() > 1)
throw new Exception("Parameter '" + g.Key + "' cannot be defined more than once.");
string text = g.First().Value;
if (text == null)
continue;
switch (g.Key.ToLower())
{
case "path":
if (text.Length == 0)
throw new Exception("Parameter '" + g.Key + "' cannot be a zero-length string.");
_outputPath = text.Trim();
break;
case "writeenddocumentonclose":
settings.WriteEndDocumentOnClose = ParameterParseHelper.ParseBoolean(g.Key, text);
break;
case "namespacehandling":
settings.NamespaceHandling = ParameterParseHelper.ParseEnum<NamespaceHandling>(g.Key, text);
break;
case "checkcharacters":
settings.CheckCharacters = ParameterParseHelper.ParseBoolean(g.Key, text);
break;
case "conformancelevel":
settings.ConformanceLevel = ParameterParseHelper.ParseEnum<ConformanceLevel>(g.Key, text);
break;
case "newlineonattributes":
settings.NewLineOnAttributes = ParameterParseHelper.ParseBoolean(g.Key, text);
break;
case "indentchars":
if (text.Length == 0)
throw new Exception("Parameter '" + g.Key + "' cannot be a zero-length string.");
settings.IndentChars = text;
break;
case "indent":
settings.Indent = ParameterParseHelper.ParseBoolean(g.Key, text);
break;
case "newlinehandling":
settings.NewLineHandling = ParameterParseHelper.ParseEnum<NewLineHandling>(g.Key, text);
break;
case "omitxmldeclaration":
settings.OmitXmlDeclaration = ParameterParseHelper.ParseBoolean(g.Key, text);
break;
case "donotescapeuriattributes":
settings.DoNotEscapeUriAttributes = ParameterParseHelper.ParseBoolean(g.Key, text);
break;
case "emitidentifier":
emitIdentifier = ParameterParseHelper.ParseBoolean(g.Key, text);
break;
case "bigendian":
bigEndian = ParameterParseHelper.ParseBoolean(g.Key, text);
break;
case "allowopt":
allowOpt = ParameterParseHelper.ParseBoolean(g.Key, text);
break;
case "encoding":
if ((text = text.Trim()).Length == 0)
throw new Exception("Parameter '" + g.Key + "' cannot be a zero-length string.");
Encoding encoding;
try { encoding = Encoding.GetEncoding(text.Trim()); }
catch { encoding = null; }
if (encoding == null)
throw new Exception("'" + text + "' is not recognized yes/no value for the '" + g.Key + "' parameter.");
break;
}
}
if (settings.Encoding is UTF8Encoding)
settings.Encoding = new UTF8Encoding(emitIdentifier);
else if (settings.Encoding is UnicodeEncoding)
settings.Encoding = new UnicodeEncoding(bigEndian, emitIdentifier);
else if (settings.Encoding is UTF32Encoding)
settings.Encoding = new UTF32Encoding(bigEndian, emitIdentifier);
else if (settings.Encoding is UTF7Encoding)
settings.Encoding = new UTF7Encoding(allowOpt);
else
if (String.IsNullOrEmpty(_outputPath))
throw new Exception("Path parameter not provided");
_writer = XmlWriter.Create(_outputPath, settings);
_writer.WriteStartElement("BuildResult");
_writer.WriteAttributeString("Started", XmlConvert.ToString(DateTime.Now, RoundTrimDateTimeFormat));
_writer.WriteAttributeString("CpuCount", XmlConvert.ToString(nodeCount));
_eventSource = eventSource;
_cpuCount = nodeCount;
_stopwatches = new StopwatchDictionary();
eventSource.MessageRaised += OnMessageRaised;
eventSource.ErrorRaised += OnErrorRaised;
eventSource.WarningRaised += OnWarningRaised;
eventSource.BuildStarted += OnBuildStarted;
eventSource.BuildFinished += OnBuildFinished;
eventSource.ProjectStarted += OnProjectStarted;
eventSource.ProjectFinished += OnProjectFinished;
eventSource.TargetStarted += OnTargetStarted;
eventSource.TargetFinished += OnTargetFinished;
eventSource.TaskStarted += OnTaskStarted;
eventSource.TaskFinished += OnTaskFinished;
eventSource.CustomEventRaised += OnCustomEventRaised;
}
catch (Exception exception)
{
throw new LoggerException((String.IsNullOrEmpty(exception.Message)) ? "Unexpected " + exception.GetType().Name : exception.Message, exception);
}
finally { Monitor.Exit(_syncRoot); }
}
public void Initialize(IEventSource eventSource, Int32 nodeCount)
{
_Initialize(eventSource, nodeCount);
}
public override void Initialize(IEventSource eventSource)
{
_Initialize(eventSource, -1);
}
public override void Shutdown()
{
Monitor.Enter(_syncRoot);
try
{
if (_eventSource != null)
{
if (_writer != null)
{
try
{
_writer.WriteStartElement("Completed");
try
{
_writer.WriteAttributeString("TotalDuration", XmlConvert.ToString(_stopwatches.Stop()));
}
finally { _writer.WriteEndElement(); }
}
finally
{
try
{
_writer.WriteEndElement();
_writer.Flush();
}
finally
{
try { _writer.Close(); }
finally { _writer = null; }
}
}
}
_eventSource.MessageRaised -= OnMessageRaised;
_eventSource.ErrorRaised -= OnErrorRaised;
_eventSource.WarningRaised -= OnWarningRaised;
_eventSource.BuildStarted -= OnBuildStarted;
_eventSource.BuildFinished -= OnBuildFinished;
_eventSource.ProjectStarted -= OnProjectStarted;
_eventSource.ProjectFinished -= OnProjectFinished;
_eventSource.TargetStarted -= OnTargetStarted;
_eventSource.TargetFinished -= OnTargetFinished;
_eventSource.TaskStarted -= OnTaskStarted;
_eventSource.TaskFinished -= OnTaskFinished;
_eventSource.CustomEventRaised -= OnCustomEventRaised;
}
}
finally
{
_eventSource = null;
Monitor.Exit(_syncRoot);
}
}
public static readonly Regex RequiresCDataRegex = new Regex(@"^(\s+|[^\p{C}<>&""]*([\r\n\t]+[^\p{C}<>&""]+)*[^\p{C}<>&""]|\S+(\s+\S+)*\s)", RegexOptions.Compiled);
private void WriteBuildEventContext(BuildEventContext context, string elementName = "Context")
{
if (context == null)
return;
_writer.WriteStartElement(elementName);
try
{
_writer.WriteAttributeString("BuildRequest", XmlConvert.ToString(context.BuildRequestId));
if (context.SubmissionId != BuildEventContext.InvalidSubmissionId)
_writer.WriteAttributeString("Submission", XmlConvert.ToString(context.SubmissionId));
if (context.ProjectContextId != BuildEventContext.InvalidProjectContextId)
_writer.WriteAttributeString("ProjectContext", XmlConvert.ToString(context.ProjectContextId));
if (context.ProjectInstanceId != BuildEventContext.InvalidProjectInstanceId)
_writer.WriteAttributeString("ProjectInstance", XmlConvert.ToString(context.ProjectInstanceId));
if (context.TargetId != BuildEventContext.InvalidTargetId)
_writer.WriteAttributeString("Target", XmlConvert.ToString(context.TargetId));
if (context.TaskId != BuildEventContext.InvalidTaskId)
_writer.WriteAttributeString("Task", XmlConvert.ToString(context.TaskId));
}
finally { _writer.WriteEndElement(); }
}
private void WriteEventArgsProperties(BuildEventArgs e, bool doNotWriteBuildEventContext = false)
{
_writer.WriteAttributeString("ThreadId", XmlConvert.ToString(e.ThreadId));
_writer.WriteAttributeString("Timestamp", XmlConvert.ToString(e.Timestamp, RoundTrimDateTimeFormat));
if (e.HelpKeyword != null)
_writer.WriteAttributeString("HelpKeyword", e.HelpKeyword);
if (e.HelpKeyword != null)
_writer.WriteAttributeString("SenderName", e.SenderName);
if (e.Message != null)
{
_writer.WriteStartElement("Message");
try
{
if (e.Message.Length > 0 && RequiresCDataRegex.IsMatch(e.Message))
_writer.WriteCData(e.Message);
else
_writer.WriteString(e.Message);
}
finally { _writer.WriteEndElement(); }
}
if (!doNotWriteBuildEventContext)
WriteBuildEventContext(e.BuildEventContext);
}
private void OnBuildStarted(object sender, BuildStartedEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_stopwatches.StartNewBuild(e.BuildEventContext);
_writer.WriteStartElement("BuildStarted");
try
{
WriteEventArgsProperties(e);
if (e.BuildEnvironment != null && e.BuildEnvironment.Count > 0)
{
_writer.WriteStartElement("Environment");
try
{
foreach (string key in e.BuildEnvironment.Keys)
{
_writer.WriteStartElement("Var");
try
{
_writer.WriteAttributeString("Name", key);
string value = e.BuildEnvironment[key];
if (e.BuildEnvironment[key] != null)
{
if (value.Length > 0 && RequiresCDataRegex.IsMatch(value))
_writer.WriteCData(value);
else
_writer.WriteString(value);
}
}
finally { _writer.WriteEndElement(); }
}
}
finally { _writer.WriteEndElement(); }
}
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private void OnBuildFinished(object sender, BuildFinishedEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_writer.WriteStartElement("BuildFinished");
try
{
_writer.WriteAttributeString("Succeeded", XmlConvert.ToString(e.Succeeded));
_writer.WriteAttributeString("Duration", XmlConvert.ToString(_stopwatches.StopBuild(e.BuildEventContext)));
WriteEventArgsProperties(e);
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private string ObjectToXmlString(object value, out string typeName)
{
if (value == null || value is DBNull)
{
typeName = "null";
return "";
}
if (value is string)
{
typeName = null;
return (string)value;
}
if (value is int)
{
typeName = null;
return XmlConvert.ToString((int)value);
}
if (value is TimeSpan)
{
typeName = "duration";
return XmlConvert.ToString((TimeSpan)value);
}
if (value is double)
{
typeName = "double";
return XmlConvert.ToString((double)value);
}
if (value is decimal)
{
typeName = "decimal";
return XmlConvert.ToString((decimal)value);
}
if (value is bool)
{
typeName = "bool";
return XmlConvert.ToString((bool)value);
}
if (value is sbyte)
{
typeName = "sbyte";
return XmlConvert.ToString((sbyte)value);
}
if (value is short)
{
typeName = "short";
return XmlConvert.ToString((short)value);
}
if (value is char)
{
typeName = "char";
return XmlConvert.ToString((char)value);
}
if (value is byte)
{
typeName = "byte";
return XmlConvert.ToString((byte)value);
}
if (value is ushort)
{
typeName = "ushort";
return XmlConvert.ToString((ushort)value);
}
if (value is uint)
{
typeName = "uint";
return XmlConvert.ToString((uint)value);
}
if (value is ulong)
{
typeName = "ulong";
return XmlConvert.ToString((ulong)value);
}
if (value is float)
{
typeName = "float";
return XmlConvert.ToString((float)value);
}
if (value is long)
{
typeName = "long";
return XmlConvert.ToString((long)value);
}
Type t = value.GetType();
typeName = t.GetType().Name;
if (t.IsEnum)
return Enum.GetName(t, value);
if (value is DateTime)
return XmlConvert.ToString((DateTime)value, RoundTrimDateTimeFormat);
if (value is Guid)
return XmlConvert.ToString((Guid)value);
if (value is DateTimeOffset)
return XmlConvert.ToString((DateTimeOffset)value);
if (value is IConvertible)
{
IConvertible convertible = (IConvertible)value;
try
{
object obj;
IFormatProvider fmt = System.Globalization.CultureInfo.CurrentCulture;
switch (convertible.GetTypeCode())
{
case TypeCode.Boolean:
if ((obj = convertible.ToBoolean(fmt)) != null && obj is bool)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.Byte:
if ((obj = convertible.ToByte(fmt)) != null && obj is byte)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.Char:
if ((obj = convertible.ToChar(fmt)) != null && obj is char)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.DateTime:
if ((obj = convertible.ToDateTime(fmt)) != null && obj is DateTime)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.DBNull:
return ObjectToXmlString(null, out typeName);
case TypeCode.Decimal:
if ((obj = convertible.ToDecimal(fmt)) != null && obj is decimal)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.Double:
if ((obj = convertible.ToDouble(fmt)) != null && obj is double)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.Int16:
if ((obj = convertible.ToInt16(fmt)) != null && obj is short)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.Int32:
if ((obj = convertible.ToInt32(fmt)) != null && obj is int)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.Int64:
if ((obj = convertible.ToInt64(fmt)) != null && obj is long)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.SByte:
if ((obj = convertible.ToSByte(fmt)) != null && obj is bool)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.Single:
if ((obj = convertible.ToSingle(fmt)) != null && obj is float)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.String:
if ((obj = convertible.ToString(fmt)) != null && obj is string)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.UInt16:
if ((obj = convertible.ToUInt16(fmt)) != null && obj is ushort)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.UInt32:
if ((obj = convertible.ToUInt32(fmt)) != null && obj is uint)
return ObjectToXmlString(obj, out typeName);
break;
case TypeCode.UInt64:
if ((obj = convertible.ToUInt64(fmt)) != null && obj is ulong)
return ObjectToXmlString(obj, out typeName);
break;
}
}
catch { }
}
return value.ToString();
}
private void WriteObjectElement(object value, string elementName, int maxDepth = 16)
{
_writer.WriteStartElement(elementName);
try
{
if (value != null && value is DictionaryEntry)
WriteDictionaryEntry((DictionaryEntry)value, elementName, maxDepth);
else
WriteObjectElementValue(value, maxDepth);
}
finally { _writer.WriteEndElement(); }
}
private static readonly string _keyValuePairName = (typeof(System.Collections.Generic.KeyValuePair<,>)).AssemblyQualifiedName;
private static readonly string _dictionaryName = (typeof(System.Collections.Generic.IDictionary<,>)).AssemblyQualifiedName;
private void WriteObjectElementValue(object value, int maxDepth = 16)
{
if (value == null || value is DBNull)
_writer.WriteAttributeString("Type", "null");
else if (value is string)
{
string s = (string)value;
if (RequiresCDataRegex.IsMatch(s))
_writer.WriteCData(s);
else
_writer.WriteString(s);
}
else if (value is int)
{
_writer.WriteAttributeString("Type", "int");
_writer.WriteString(XmlConvert.ToString((int)value));
}
else if (value is TimeSpan)
{
_writer.WriteAttributeString("Type", "duration");
_writer.WriteString(XmlConvert.ToString((TimeSpan)value));
}
else if (value is DateTime)
{
_writer.WriteAttributeString("Type", "DateTime");
_writer.WriteString(XmlConvert.ToString((DateTime)value, RoundTrimDateTimeFormat));
}
else if (value is Guid)
{
_writer.WriteAttributeString("Type", "Guid");
_writer.WriteString(XmlConvert.ToString((Guid)value));
}
else if (value is DateTimeOffset)
{
_writer.WriteAttributeString("Type", "DateTimeOffset");
_writer.WriteString(XmlConvert.ToString((DateTimeOffset)value));
}
else
{
Type t = value.GetType();
string typeName;
if (t.IsPrimitive)
{
string txt = ObjectToXmlString(value, out typeName);
if (typeName != null)
_writer.WriteAttributeString("Type", typeName);
if (txt != null)
_writer.WriteString(txt);
}
else if (t.IsArray)
{
Array array = (Array)value;
_writer.WriteAttributeString("Type", t.Name);
if (maxDepth < 1)
_writer.WriteString("[" + t.FullName + "].Length = " + XmlConvert.ToString(array.Length));
else
{
foreach (object obj in array)
WriteObjectElement(obj, "Element", maxDepth - 1);
}
}
if (t.IsEnum)
{
_writer.WriteAttributeString("Type", t.Name);
_writer.WriteString(Enum.GetName(t, value));
}
else if (value is IConvertible)
{
IConvertible convertible = (IConvertible)value;
try
{
object obj;
IFormatProvider fmt = System.Globalization.CultureInfo.CurrentCulture;
switch (convertible.GetTypeCode())
{
case TypeCode.Boolean:
if ((obj = convertible.ToBoolean(fmt)) != null && obj is bool)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.Byte:
if ((obj = convertible.ToByte(fmt)) != null && obj is byte)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.Char:
if ((obj = convertible.ToChar(fmt)) != null && obj is char)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.DateTime:
if ((obj = convertible.ToDateTime(fmt)) != null && obj is DateTime)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.DBNull:
WriteObjectElementValue(DBNull.Value, maxDepth);
return;
case TypeCode.Decimal:
if ((obj = convertible.ToDecimal(fmt)) != null && obj is decimal)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.Double:
if ((obj = convertible.ToDouble(fmt)) != null && obj is double)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.Int16:
if ((obj = convertible.ToInt16(fmt)) != null && obj is short)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.Int32:
if ((obj = convertible.ToInt32(fmt)) != null && obj is int)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.Int64:
if ((obj = convertible.ToInt64(fmt)) != null && obj is long)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.SByte:
if ((obj = convertible.ToSByte(fmt)) != null && obj is bool)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.Single:
if ((obj = convertible.ToSingle(fmt)) != null && obj is float)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.String:
if ((obj = convertible.ToString(fmt)) != null && obj is string)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.UInt16:
if ((obj = convertible.ToUInt16(fmt)) != null && obj is ushort)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.UInt32:
if ((obj = convertible.ToUInt32(fmt)) != null && obj is uint)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
case TypeCode.UInt64:
if ((obj = convertible.ToUInt64(fmt)) != null && obj is ulong)
{
WriteObjectElementValue(obj, maxDepth);
return;
}
break;
}
}
catch { }
_writer.WriteAttributeString("Type", t.Name);
_writer.WriteString(value.ToString());
}
else if (maxDepth < 1)
{
_writer.WriteAttributeString("Type", t.Name);
if (value is ICollection)
_writer.WriteString("(" + t.FullName + ").Count = " + XmlConvert.ToString(((ICollection)value).Count));
else
_writer.WriteString("(" + t.FullName + ")");
}
else if (t.IsGenericType && t.GetGenericTypeDefinition().AssemblyQualifiedName == _keyValuePairName)
{
WriteObjectElement(t.GetProperty("Key").GetValue(value), "Key", maxDepth - 1);
WriteObjectElement(t.GetProperty("Value").GetValue(value), "Value", maxDepth - 1);
}
else if (value is DictionaryEntry)
{
DictionaryEntry de = (DictionaryEntry)value;
_writer.WriteAttributeString("Type", t.Name);
WriteObjectElement(de.Key, "Key", maxDepth - 1);
WriteObjectElement(de.Value, "Value", maxDepth - 1);
}
else if (value is IDictionary)
{
_writer.WriteAttributeString("Type", t.Name);
IDictionary dictionary = (IDictionary)value;
foreach (object k in dictionary.Keys)
WriteDictionaryEntry(k, dictionary[k], "DictionaryEntry", maxDepth - 1);
}
else if (value is IEnumerable)
{
_writer.WriteAttributeString("Type", t.Name);
IEnumerable enumerable = (IEnumerable)value;
Type it = t.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition().AssemblyQualifiedName == _dictionaryName);
if (it != null)
{
t = (typeof(KeyValuePair<,>)).MakeGenericType(it.GetGenericArguments());
PropertyInfo kp = t.GetProperty("Key");
PropertyInfo vp = t.GetProperty("Value");
foreach (object kvp in enumerable)
WriteDictionaryEntry(kp.GetValue(value), vp.GetValue(value), "KeyValuePair", maxDepth - 1);
}
else
{
foreach (object obj in enumerable)
WriteObjectElement(obj, "Item", maxDepth - 1);
}
}
else
{
_writer.WriteAttributeString("Type", t.Name);
_writer.WriteString(value.ToString());
}
}
}
private void WriteDictionaryEntry(object entryKey, object value, string elementName, int maxDepth = 16)
{
_writer.WriteStartElement(elementName);
try
{
string typeName;
string key;
if (entryKey is string)
_writer.WriteAttributeString("Name", (string)entryKey);
else if (entryKey is int)
_writer.WriteAttributeString("Number", XmlConvert.ToString((int)entryKey));
else
{
key = ObjectToXmlString(entryKey, out typeName);
if (key == null)
key = "";
_writer.WriteAttributeString("Key", key);
if (typeName != null)
_writer.WriteAttributeString("KeyType", typeName);
}
WriteObjectElementValue(value, maxDepth);
}
finally { _writer.WriteEndElement(); }
}
private void WriteDictionaryEntry(DictionaryEntry entry, string elementName = "Item", int maxDepth = 16)
{
WriteDictionaryEntry(entry.Key, entry.Value, elementName, maxDepth);
}
private void WriteTypeInfo(Type type, string elementName = "Type", int maxDepth = 12)
{
if (type == null)
return;
_writer.WriteStartElement(elementName);
try
{
_writer.WriteAttributeString("Name", type.Name);
if (type.Namespace != null)
_writer.WriteAttributeString("Namespace", type.Namespace);
if (type.IsClass && type.FullName != "System.String")
_writer.WriteAttributeString("Assembly", type.Assembly.FullName);
if (type.IsGenericType)
{
foreach (Type t in type.GetGenericArguments())
WriteTypeInfo(t, "GenericArgument", maxDepth - 1);
}
if (type.IsArray)
WriteTypeInfo(type.GetElementType(), "ElementType", maxDepth);
else if (maxDepth > 0 && !type.IsPrimitive && type.FullName != "System.String")
{
foreach (Type t in type.GetInterfaces())
WriteTypeInfo(t, "Interface", maxDepth - 1);
if (type.IsClass)
WriteTypeInfo(type.BaseType, "BaseType", maxDepth - 1);
}
}
finally { _writer.WriteEndElement(); }
}
private void OnProjectStarted(object sender, ProjectStartedEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_stopwatches.StartNewProject(e.BuildEventContext);
_writer.WriteStartElement("ProjectStarted");
try
{
_writer.WriteAttributeString("Id", XmlConvert.ToString(e.ProjectId));
if (e.ProjectFile != null)
_writer.WriteAttributeString("File", e.ProjectFile);
if (e.ToolsVersion != null)
_writer.WriteAttributeString("ToolsVersion", e.ToolsVersion);
WriteEventArgsProperties(e, true);
if (e.TargetNames != null && e.TargetNames.Length > 0)
{
_writer.WriteStartElement("TargetNames");
try
{
if (e.Message.Length > 0 && RequiresCDataRegex.IsMatch(e.TargetNames))
_writer.WriteCData(e.TargetNames);
else
_writer.WriteString(e.TargetNames);
}
finally { _writer.WriteEndElement(); }
}
WriteBuildEventContext(e.BuildEventContext);
if (e.ParentProjectBuildEventContext != null)
WriteBuildEventContext(e.ParentProjectBuildEventContext, "Parent");
if (e.Items != null)
{
_writer.WriteStartElement("Items");
try
{
foreach (object obj in e.Properties)
WriteObjectElement(obj, "Item");
}
finally { _writer.WriteEndElement(); }
}
if (e.Properties != null)
{
_writer.WriteStartElement("Properties");
try
{
foreach (object obj in e.Properties)
WriteObjectElement(obj, "Property");
}
finally { _writer.WriteEndElement(); }
}
if (e.GlobalProperties != null && e.GlobalProperties.Count > 0)
{
_writer.WriteStartElement("GlobalProperties");
try
{
foreach (string key in e.GlobalProperties.Keys)
{
_writer.WriteStartElement("Property");
try
{
_writer.WriteAttributeString("Name", key);
string value = e.GlobalProperties[key];
if (e.GlobalProperties[key] != null)
{
if (value.Length > 0 && RequiresCDataRegex.IsMatch(value))
_writer.WriteCData(value);
else
_writer.WriteString(value);
}
}
finally { _writer.WriteEndElement(); }
}
}
finally { _writer.WriteEndElement(); }
}
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private void OnProjectFinished(object sender, ProjectFinishedEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_writer.WriteStartElement("ProjectFinished");
try
{
_writer.WriteAttributeString("Succeeded", XmlConvert.ToString(e.Succeeded));
_writer.WriteAttributeString("Duration", XmlConvert.ToString(_stopwatches.StopProject(e.BuildEventContext)));
if (e.ProjectFile != null)
_writer.WriteAttributeString("File", e.ProjectFile);
WriteEventArgsProperties(e);
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private void OnTargetStarted(object sender, TargetStartedEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_stopwatches.StartNewTarget(e.BuildEventContext);
_writer.WriteStartElement("TargetStarted");
try
{
if (e.TargetName != null)
_writer.WriteAttributeString("Name", e.TargetName);
if (e.TargetFile != null)
_writer.WriteAttributeString("File", e.TargetFile);
if (e.ProjectFile != null)
_writer.WriteAttributeString("ProjectFile", e.ProjectFile);
if (e.ParentTarget != null)
_writer.WriteAttributeString("Parent", e.ParentTarget);
WriteEventArgsProperties(e);
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private void OnTargetFinished(object sender, TargetFinishedEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_writer.WriteStartElement("TargetFinished");
try
{
_writer.WriteAttributeString("Succeeded", XmlConvert.ToString(e.Succeeded));
if (e.TargetName != null)
_writer.WriteAttributeString("Name", e.TargetName);
if (e.TargetFile != null)
_writer.WriteAttributeString("File", e.TargetFile);
if (e.ProjectFile != null)
_writer.WriteAttributeString("ProjectFile", e.ProjectFile);
_writer.WriteAttributeString("Duration", XmlConvert.ToString(_stopwatches.StopTarget(e.BuildEventContext)));
WriteEventArgsProperties(e);
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private void OnTaskStarted(object sender, TaskStartedEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_stopwatches.StartNewTask(e.BuildEventContext);
_writer.WriteStartElement("TaskStarted");
try
{
if (e.TaskName != null)
_writer.WriteAttributeString("Name", e.TaskName);
if (e.TaskFile != null)
_writer.WriteAttributeString("File", e.TaskFile);
if (e.ProjectFile != null)
_writer.WriteAttributeString("ProjectFile", e.ProjectFile);
WriteEventArgsProperties(e);
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private void OnTaskFinished(object sender, TaskFinishedEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_writer.WriteStartElement("TaskFinished");
try
{
_writer.WriteAttributeString("Succeeded", XmlConvert.ToString(e.Succeeded));
_writer.WriteAttributeString("Duration", XmlConvert.ToString(_stopwatches.StopTask(e.BuildEventContext)));
if (e.TaskName != null)
_writer.WriteAttributeString("Name", e.TaskName);
if (e.TaskFile != null)
_writer.WriteAttributeString("File", e.TaskFile);
if (e.ProjectFile != null)
_writer.WriteAttributeString("ProjectFile", e.ProjectFile);
WriteEventArgsProperties(e);
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private void OnMessageRaised(object sender, BuildMessageEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_writer.WriteStartElement("Message");
try
{
_writer.WriteAttributeString("Importance", Enum.GetName(e.Importance.GetType(), e.Importance));
if (e.LineNumber > 0)
_writer.WriteAttributeString("Line", XmlConvert.ToString(e.LineNumber));
if (e.ColumnNumber > 0)
_writer.WriteAttributeString("Column", XmlConvert.ToString(e.ColumnNumber));
if (e.EndLineNumber > 0 && e.EndLineNumber != e.LineNumber)
_writer.WriteAttributeString("EndLine", XmlConvert.ToString(e.EndLineNumber));
if (e.EndColumnNumber > 0 && e.EndColumnNumber != e.ColumnNumber)
_writer.WriteAttributeString("EndColumn", XmlConvert.ToString(e.EndColumnNumber));
if (e.Code != null)
_writer.WriteAttributeString("Code", e.Code);
if (e.Subcategory != null)
_writer.WriteAttributeString("Subcategory", e.Subcategory);
if (e.File != null)
_writer.WriteAttributeString("File", e.File);
if (e.ProjectFile != null)
_writer.WriteAttributeString("ProjectFile", e.ProjectFile);
WriteEventArgsProperties(e);
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private void OnErrorRaised(object sender, BuildErrorEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_writer.WriteStartElement("Error");
try
{
if (e.LineNumber > 0)
_writer.WriteAttributeString("Line", XmlConvert.ToString(e.LineNumber));
if (e.ColumnNumber > 0)
_writer.WriteAttributeString("Column", XmlConvert.ToString(e.ColumnNumber));
if (e.EndLineNumber > 0 && e.EndLineNumber != e.LineNumber)
_writer.WriteAttributeString("EndLine", XmlConvert.ToString(e.EndLineNumber));
if (e.EndColumnNumber > 0 && e.EndColumnNumber != e.ColumnNumber)
_writer.WriteAttributeString("EndColumn", XmlConvert.ToString(e.EndColumnNumber));
if (e.Code != null)
_writer.WriteAttributeString("Code", e.Code);
if (e.Subcategory != null)
_writer.WriteAttributeString("Subcategory", e.Subcategory);
if (e.File != null)
_writer.WriteAttributeString("File", e.File);
if (e.ProjectFile != null)
_writer.WriteAttributeString("ProjectFile", e.ProjectFile);
WriteEventArgsProperties(e);
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private void OnWarningRaised(object sender, BuildWarningEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_writer.WriteStartElement("Warning");
try
{
if (e.LineNumber > 0)
_writer.WriteAttributeString("Line", XmlConvert.ToString(e.LineNumber));
if (e.ColumnNumber > 0)
_writer.WriteAttributeString("Column", XmlConvert.ToString(e.ColumnNumber));
if (e.EndLineNumber > 0 && e.EndLineNumber != e.LineNumber)
_writer.WriteAttributeString("EndLine", XmlConvert.ToString(e.EndLineNumber));
if (e.EndColumnNumber > 0 && e.EndColumnNumber != e.ColumnNumber)
_writer.WriteAttributeString("EndColumn", XmlConvert.ToString(e.EndColumnNumber));
if (e.Code != null)
_writer.WriteAttributeString("Code", e.Code);
if (e.Subcategory != null)
_writer.WriteAttributeString("Subcategory", e.Subcategory);
if (e.File != null)
_writer.WriteAttributeString("File", e.File);
if (e.ProjectFile != null)
_writer.WriteAttributeString("ProjectFile", e.ProjectFile);
WriteEventArgsProperties(e);
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
private void OnCustomEventRaised(object sender, CustomBuildEventArgs e)
{
Monitor.Enter(_syncRoot);
try
{
_writer.WriteStartElement("CustomEvent");
try
{
WriteEventArgsProperties(e);
}
finally { _writer.WriteEndElement(); }
}
finally { Monitor.Exit(_syncRoot); }
}
}
}
| |
using UnityEngine;
using System.Collections;
using Pathfinding;
/** Example AI.
* \deprecated This script has been deprecated, use AIPath, RichAI or MineBotAI instead */
[RequireComponent (typeof(Seeker))]
[RequireComponent (typeof(CharacterController))]
[AddComponentMenu("Pathfinding/AI/AIFollow (deprecated)")]
public class AIFollow : MonoBehaviour {
/** Target to move to */
public Transform target;
/** How often to search for a new path */
public float repathRate = 0.1F;
/** The minimum distance to a waypoint to consider it as "reached" */
public float pickNextWaypointDistance = 1F;
/** The minimum distance to the end point of a path to consider it "reached" (multiplied with #pickNextWaypointDistance).
* This value is multiplied with #pickNextWaypointDistance before it is used. Recommended range [0...1] */
public float targetReached = 0.2F;
/** Units per second */
public float speed = 5;
/** How fast the AI can turn around */
public float rotationSpeed = 1;
public bool drawGizmos = false;
/** Should paths be searched for.
* Setting this to false will make the AI not search for paths anymore, can save some CPU cycles.
* It will check every #repathRate seconds if it should start to search for paths again.
* \note It will not cancel paths which are currently being calculated */
public bool canSearch = true;
/** Can it move. Enables or disables movement and rotation */
public bool canMove = true;
/** Seeker component which handles pathfinding calls */
protected Seeker seeker;
/** CharacterController which handles movement */
protected CharacterController controller;
/** NavmeshController which handles movement if not null*/
protected NavmeshController navmeshController;
/** Transform, cached because of performance */
protected Transform tr;
protected float lastPathSearch = -9999;
protected int pathIndex = 0;
/** This is the path the AI is currently following */
protected Vector3[] path;
/** Use this for initialization */
public void Start () {
seeker = GetComponent<Seeker>();
controller = GetComponent<CharacterController>();
navmeshController = GetComponent<NavmeshController>();
tr = transform;
Repath ();
}
/** Will make the AI give up it's current path and stop completely. */
public void Reset () {
path = null;
}
/** Called when a path has completed it's calculation */
public void OnPathComplete (Path p) {
/*if (Time.time-lastPathSearch >= repathRate) {
Repath ();
} else {*/
StartCoroutine (WaitToRepath ());
//}
//If the path didn't succeed, don't proceed
if (p.error) {
return;
}
//Get the calculated path as a Vector3 array
path = p.vectorPath.ToArray();
//Find the segment in the path which is closest to the AI
//If a closer segment hasn't been found in '6' iterations, break because it is unlikely to find any closer ones then
float minDist = Mathf.Infinity;
int notCloserHits = 0;
for (int i=0;i<path.Length-1;i++) {
float dist = AstarMath.DistancePointSegmentStrict (path[i],path[i+1],tr.position);
if (dist < minDist) {
notCloserHits = 0;
minDist = dist;
pathIndex = i+1;
} else if (notCloserHits > 6) {
break;
}
}
}
/** Waits the remaining time until the AI should issue a new path request.
* The remaining time is defined by Time.time - lastPathSearch */
public IEnumerator WaitToRepath () {
float timeLeft = repathRate - (Time.time-lastPathSearch);
yield return new WaitForSeconds (timeLeft);
Repath ();
}
/** Stops the AI.
* Also stops new search queries from being made
* \since Before 3.0.8 This does not prevent new path calls from making the AI move again
* \see #Resume
* \see #canMove
* \see #canSearch */
public void Stop () {
canMove = false;
canSearch = false;
}
/** Resumes walking and path searching the AI.
* \since Added in 3.0.8
* \see #Stop
* \see #canMove
* \see #canSearch */
public void Resume () {
canMove = true;
canSearch = true;
}
/** Recalculates the path to #target.
* Queries a path request to the Seeker, the path will not be calculated instantly, but will be put on a queue and calculated as fast as possible.
* It will wait if the current path request by this seeker has not been completed yet.
* \see Seeker.IsDone */
public virtual void Repath () {
lastPathSearch = Time.time;
if (seeker == null || target == null || !canSearch || !seeker.IsDone ()) {
StartCoroutine (WaitToRepath ());
return;
}
//for (int i=0;i<1000;i++) {
//MultithreadPath mp = new MultithreadPath (transform.position,target.position,null);
//Path p = new Path (transform.position,target.position,null);
// AstarPath.StartPath (mp);
//}
//Debug.Log (AstarPath.pathQueue.Count);
//StartCoroutine (WaitToRepath ());
/*ConstantPath cpath = new ConstantPath(transform.position,null);
//Must be set to avoid it from searching towards Vector3.zero
cpath.heuristic = Heuristic.None;
//Here you set how far it should search
cpath.maxGScore = 2000;
AstarPath.StartPath (cpath);*/
//FloodPathTracer fpathTrace = new FloodPathTracer (transform.position,fpath,null);
//seeker.StartPath (fpathTrace,OnPathComplete);
Path p = ABPath.Construct(transform.position,target.position,null);
seeker.StartPath (p,OnPathComplete);
//Start a new path from transform.positon to target.position, return the result to the function OnPathComplete
//seeker.StartPath (transform.position,target.position,OnPathComplete);
}
/** Start a new path moving to \a targetPoint */
public void PathToTarget (Vector3 targetPoint) {
lastPathSearch = Time.time;
if (seeker == null) {
return;
}
//Start a new path from transform.positon to target.position, return the result to OnPathComplete
seeker.StartPath (transform.position,targetPoint,OnPathComplete);
}
/** Called when the AI reached the end of path.
* This will be called once for every path it completes, so if you have a really fast repath rate it will call this function often if when it stands on the end point.
*/
public virtual void ReachedEndOfPath () {
//The AI has reached the end of the path
}
/** Update is called once per frame */
public void Update () {
if (path == null || pathIndex >= path.Length || pathIndex < 0 || !canMove) {
return;
}
//Change target to the next waypoint if the current one is close enough
Vector3 currentWaypoint = path[pathIndex];
currentWaypoint.y = tr.position.y;
while ((currentWaypoint - tr.position).sqrMagnitude < pickNextWaypointDistance*pickNextWaypointDistance) {
pathIndex++;
if (pathIndex >= path.Length) {
//Use a lower pickNextWaypointDistance for the last point. If it isn't that close, then decrement the pathIndex to the previous value and break the loop
if ((currentWaypoint - tr.position).sqrMagnitude < (pickNextWaypointDistance*targetReached)*(pickNextWaypointDistance*targetReached)) {
ReachedEndOfPath ();
return;
} else {
pathIndex--;
//Break the loop, otherwise it will try to check for the last point in an infinite loop
break;
}
}
currentWaypoint = path[pathIndex];
currentWaypoint.y = tr.position.y;
}
Vector3 dir = currentWaypoint - tr.position;
// Rotate towards the target
tr.rotation = Quaternion.Slerp (tr.rotation, Quaternion.LookRotation(dir), rotationSpeed * Time.deltaTime);
tr.eulerAngles = new Vector3(0, tr.eulerAngles.y, 0);
Vector3 forwardDir = transform.forward;
//Move Forwards - forwardDir is already normalized
forwardDir = forwardDir * speed;
forwardDir *= Mathf.Clamp01 (Vector3.Dot (dir.normalized, tr.forward));
if (navmeshController != null) {
} else if (controller != null) {
controller.SimpleMove (forwardDir);
} else {
transform.Translate (forwardDir*Time.deltaTime, Space.World);
}
}
/** Draws helper gizmos.
* Currently draws a circle around the current target point with the size showing how close the AI need to get to it for it to count as "reached".
*/
public void OnDrawGizmos () {
if (!drawGizmos || path == null || pathIndex >= path.Length || pathIndex < 0) {
return;
}
Vector3 currentWaypoint = path[pathIndex];
currentWaypoint.y = tr.position.y;
Debug.DrawLine (transform.position,currentWaypoint,Color.blue);
float rad = pickNextWaypointDistance;
if (pathIndex == path.Length-1) {
rad *= targetReached;
}
Vector3 pP = currentWaypoint + rad*new Vector3 (1,0,0);
for (float i=0;i<2*System.Math.PI;i+= 0.1F) {
Vector3 cP = currentWaypoint + new Vector3 ((float)System.Math.Cos (i)*rad,0,(float)System.Math.Sin(i)*rad);
Debug.DrawLine (pP,cP,Color.yellow);
pP = cP;
}
Debug.DrawLine (pP, currentWaypoint + rad*new Vector3 (1,0,0),Color.yellow);
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
namespace Mono.Cecil.Cil {
public sealed class PortablePdbReaderProvider : ISymbolReaderProvider {
public ISymbolReader GetSymbolReader (ModuleDefinition module, string fileName)
{
Mixin.CheckModule (module);
Mixin.CheckFileName (fileName);
var file = File.OpenRead (Mixin.GetPdbFileName (fileName));
return GetSymbolReader (module, Disposable.Owned (file as Stream), file.Name);
}
public ISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream)
{
Mixin.CheckModule (module);
Mixin.CheckStream (symbolStream);
return GetSymbolReader (module, Disposable.NotOwned (symbolStream), symbolStream.GetFileName ());
}
ISymbolReader GetSymbolReader (ModuleDefinition module, Disposable<Stream> symbolStream, string fileName)
{
return new PortablePdbReader (ImageReader.ReadPortablePdb (symbolStream, fileName, out _), module);
}
}
public sealed class PortablePdbReader : ISymbolReader {
readonly Image image;
readonly ModuleDefinition module;
readonly MetadataReader reader;
readonly MetadataReader debug_reader;
bool IsEmbedded { get { return reader.image == debug_reader.image; } }
internal PortablePdbReader (Image image, ModuleDefinition module)
{
this.image = image;
this.module = module;
this.reader = module.reader;
this.debug_reader = new MetadataReader (image, module, this.reader);
}
public ISymbolWriterProvider GetWriterProvider ()
{
return new PortablePdbWriterProvider ();
}
public bool ProcessDebugHeader (ImageDebugHeader header)
{
if (image == module.Image)
return true;
foreach (var entry in header.Entries) {
if (!IsMatchingEntry (image.PdbHeap, entry))
continue;
ReadModule ();
return true;
}
return false;
}
static bool IsMatchingEntry (PdbHeap heap, ImageDebugHeaderEntry entry)
{
if (entry.Directory.Type != ImageDebugType.CodeView)
return false;
var data = entry.Data;
if (data.Length < 24)
return false;
var magic = ReadInt32 (data, 0);
if (magic != 0x53445352)
return false;
var buffer = new byte [16];
Buffer.BlockCopy (data, 4, buffer, 0, 16);
var module_guid = new Guid (buffer);
Buffer.BlockCopy (heap.Id, 0, buffer, 0, 16);
var pdb_guid = new Guid (buffer);
return module_guid == pdb_guid;
}
static int ReadInt32 (byte [] bytes, int start)
{
return (bytes [start]
| (bytes [start + 1] << 8)
| (bytes [start + 2] << 16)
| (bytes [start + 3] << 24));
}
void ReadModule ()
{
module.custom_infos = debug_reader.GetCustomDebugInformation (module);
}
public MethodDebugInformation Read (MethodDefinition method)
{
var info = new MethodDebugInformation (method);
ReadSequencePoints (info);
ReadScope (info);
ReadStateMachineKickOffMethod (info);
ReadCustomDebugInformations (info);
return info;
}
void ReadSequencePoints (MethodDebugInformation method_info)
{
method_info.sequence_points = debug_reader.ReadSequencePoints (method_info.method);
}
void ReadScope (MethodDebugInformation method_info)
{
method_info.scope = debug_reader.ReadScope (method_info.method);
}
void ReadStateMachineKickOffMethod (MethodDebugInformation method_info)
{
method_info.kickoff_method = debug_reader.ReadStateMachineKickoffMethod (method_info.method);
}
void ReadCustomDebugInformations (MethodDebugInformation info)
{
info.method.custom_infos = debug_reader.GetCustomDebugInformation (info.method);
}
public void Dispose ()
{
if (IsEmbedded)
return;
image.Dispose ();
}
}
public sealed class EmbeddedPortablePdbReaderProvider : ISymbolReaderProvider {
public ISymbolReader GetSymbolReader (ModuleDefinition module, string fileName)
{
Mixin.CheckModule (module);
var header = module.GetDebugHeader ();
var entry = header.GetEmbeddedPortablePdbEntry ();
if (entry == null)
throw new InvalidOperationException ();
return new EmbeddedPortablePdbReader (
(PortablePdbReader) new PortablePdbReaderProvider ().GetSymbolReader (module, GetPortablePdbStream (entry)));
}
static Stream GetPortablePdbStream (ImageDebugHeaderEntry entry)
{
var compressed_stream = new MemoryStream (entry.Data);
var reader = new BinaryStreamReader (compressed_stream);
reader.ReadInt32 (); // signature
var length = reader.ReadInt32 ();
var decompressed_stream = new MemoryStream (length);
using (var deflate_stream = new DeflateStream (compressed_stream, CompressionMode.Decompress, leaveOpen: true))
deflate_stream.CopyTo (decompressed_stream);
return decompressed_stream;
}
public ISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream)
{
throw new NotSupportedException ();
}
}
public sealed class EmbeddedPortablePdbReader : ISymbolReader
{
private readonly PortablePdbReader reader;
internal EmbeddedPortablePdbReader (PortablePdbReader reader)
{
if (reader == null)
throw new ArgumentNullException ();
this.reader = reader;
}
public ISymbolWriterProvider GetWriterProvider ()
{
return new EmbeddedPortablePdbWriterProvider ();
}
public bool ProcessDebugHeader (ImageDebugHeader header)
{
return reader.ProcessDebugHeader (header);
}
public MethodDebugInformation Read (MethodDefinition method)
{
return reader.Read (method);
}
public void Dispose ()
{
reader.Dispose ();
}
}
public sealed class PortablePdbWriterProvider : ISymbolWriterProvider
{
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName)
{
Mixin.CheckModule (module);
Mixin.CheckFileName (fileName);
var file = File.Open (Mixin.GetPdbFileName (fileName), FileMode.OpenOrCreate, FileAccess.ReadWrite);
return GetSymbolWriter (module, Disposable.Owned (file as Stream), Disposable.NotOwned ((Stream)null));
}
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream)
{
Mixin.CheckModule (module);
Mixin.CheckStream (symbolStream);
// In order to compute the PDB checksum, the stream we're writing to needs to be able to
// seek and read as well. We can't assume this about a stream provided by the user.
// So in this case, create a memory stream to cache the PDB.
return GetSymbolWriter (module, Disposable.Owned (new MemoryStream() as Stream), Disposable.NotOwned (symbolStream));
}
ISymbolWriter GetSymbolWriter (ModuleDefinition module, Disposable<Stream> stream, Disposable<Stream> final_stream)
{
var metadata = new MetadataBuilder (module, this);
var writer = ImageWriter.CreateDebugWriter (module, metadata, stream);
return new PortablePdbWriter (metadata, module, writer, final_stream);
}
}
public sealed class PortablePdbWriter : ISymbolWriter {
readonly MetadataBuilder pdb_metadata;
readonly ModuleDefinition module;
readonly ImageWriter writer;
readonly Disposable<Stream> final_stream;
MetadataBuilder module_metadata;
internal byte [] pdb_checksum;
internal Guid pdb_id_guid;
internal uint pdb_id_stamp;
bool IsEmbedded { get { return writer == null; } }
internal PortablePdbWriter (MetadataBuilder pdb_metadata, ModuleDefinition module)
{
this.pdb_metadata = pdb_metadata;
this.module = module;
this.module_metadata = module.metadata_builder;
if (module_metadata != pdb_metadata)
this.pdb_metadata.metadata_builder = this.module_metadata;
pdb_metadata.AddCustomDebugInformations (module);
}
internal PortablePdbWriter (MetadataBuilder pdb_metadata, ModuleDefinition module, ImageWriter writer, Disposable<Stream> final_stream)
: this (pdb_metadata, module)
{
this.writer = writer;
this.final_stream = final_stream;
}
public ISymbolReaderProvider GetReaderProvider ()
{
return new PortablePdbReaderProvider ();
}
public void Write (MethodDebugInformation info)
{
CheckMethodDebugInformationTable ();
pdb_metadata.AddMethodDebugInformation (info);
}
public void Write ()
{
if (IsEmbedded)
return;
WritePdbFile ();
if (final_stream.value != null) {
writer.BaseStream.Seek (0, SeekOrigin.Begin);
var buffer = new byte [8192];
CryptoService.CopyStreamChunk (writer.BaseStream, final_stream.value, buffer, (int)writer.BaseStream.Length);
}
}
public ImageDebugHeader GetDebugHeader ()
{
if (IsEmbedded)
return new ImageDebugHeader ();
ImageDebugHeaderEntry codeViewEntry;
{
var codeViewDirectory = new ImageDebugDirectory () {
MajorVersion = 256,
MinorVersion = 20557,
Type = ImageDebugType.CodeView,
TimeDateStamp = (int)pdb_id_stamp,
};
var buffer = new ByteBuffer ();
// RSDS
buffer.WriteUInt32 (0x53445352);
// Module ID
buffer.WriteBytes (pdb_id_guid.ToByteArray ());
// PDB Age
buffer.WriteUInt32 (1);
// PDB Path
var fileName = writer.BaseStream.GetFileName ();
if (string.IsNullOrEmpty (fileName)) {
fileName = module.Assembly.Name.Name + ".pdb";
}
buffer.WriteBytes (System.Text.Encoding.UTF8.GetBytes (fileName));
buffer.WriteByte (0);
var data = new byte [buffer.length];
Buffer.BlockCopy (buffer.buffer, 0, data, 0, buffer.length);
codeViewDirectory.SizeOfData = data.Length;
codeViewEntry = new ImageDebugHeaderEntry (codeViewDirectory, data);
}
ImageDebugHeaderEntry pdbChecksumEntry;
{
var pdbChecksumDirectory = new ImageDebugDirectory () {
MajorVersion = 1,
MinorVersion = 0,
Type = ImageDebugType.PdbChecksum,
TimeDateStamp = 0
};
var buffer = new ByteBuffer ();
// SHA256 - Algorithm name
buffer.WriteBytes (System.Text.Encoding.UTF8.GetBytes ("SHA256"));
buffer.WriteByte (0);
// Checksum - 32 bytes
buffer.WriteBytes (pdb_checksum);
var data = new byte [buffer.length];
Buffer.BlockCopy (buffer.buffer, 0, data, 0, buffer.length);
pdbChecksumDirectory.SizeOfData = data.Length;
pdbChecksumEntry = new ImageDebugHeaderEntry (pdbChecksumDirectory, data);
}
return new ImageDebugHeader (new ImageDebugHeaderEntry [] { codeViewEntry, pdbChecksumEntry });
}
void CheckMethodDebugInformationTable ()
{
var mdi = pdb_metadata.table_heap.GetTable<MethodDebugInformationTable> (Table.MethodDebugInformation);
if (mdi.length > 0)
return;
// The MethodDebugInformation table has the same length as the Method table
mdi.rows = new Row<uint, uint> [module_metadata.method_rid - 1];
mdi.length = mdi.rows.Length;
}
public void Dispose ()
{
writer.stream.Dispose ();
final_stream.Dispose ();
}
void WritePdbFile ()
{
WritePdbHeap ();
WriteTableHeap ();
writer.BuildMetadataTextMap ();
writer.WriteMetadataHeader ();
writer.WriteMetadata ();
writer.Flush ();
ComputeChecksumAndPdbId ();
WritePdbId ();
}
void WritePdbHeap ()
{
var pdb_heap = pdb_metadata.pdb_heap;
// PDB ID ( GUID + TimeStamp ) are left zeroed out for now. Will be filled at the end with a hash.
pdb_heap.WriteBytes (20);
pdb_heap.WriteUInt32 (module_metadata.entry_point.ToUInt32 ());
var table_heap = module_metadata.table_heap;
var tables = table_heap.tables;
ulong valid = 0;
for (int i = 0; i < tables.Length; i++) {
if (tables [i] == null || tables [i].Length == 0)
continue;
valid |= (1UL << i);
}
pdb_heap.WriteUInt64 (valid);
for (int i = 0; i < tables.Length; i++) {
if (tables [i] == null || tables [i].Length == 0)
continue;
pdb_heap.WriteUInt32 ((uint) tables [i].Length);
}
}
void WriteTableHeap ()
{
pdb_metadata.table_heap.string_offsets = pdb_metadata.string_heap.WriteStrings ();
pdb_metadata.table_heap.ComputeTableInformations ();
pdb_metadata.table_heap.WriteTableHeap ();
}
void ComputeChecksumAndPdbId ()
{
var buffer = new byte [8192];
// Compute the has of the entire file - PDB ID is zeroes still
writer.BaseStream.Seek (0, SeekOrigin.Begin);
var sha256 = SHA256.Create ();
using (var crypto_stream = new CryptoStream (Stream.Null, sha256, CryptoStreamMode.Write)) {
CryptoService.CopyStreamChunk (writer.BaseStream, crypto_stream, buffer, (int)writer.BaseStream.Length);
}
pdb_checksum = sha256.Hash;
var hashBytes = new ByteBuffer (pdb_checksum);
pdb_id_guid = new Guid (hashBytes.ReadBytes (16));
pdb_id_stamp = hashBytes.ReadUInt32 ();
}
void WritePdbId ()
{
// PDB ID is the first 20 bytes of the PdbHeap
writer.MoveToRVA (TextSegment.PdbHeap);
writer.WriteBytes (pdb_id_guid.ToByteArray ());
writer.WriteUInt32 (pdb_id_stamp);
}
}
public sealed class EmbeddedPortablePdbWriterProvider : ISymbolWriterProvider {
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName)
{
Mixin.CheckModule (module);
Mixin.CheckFileName (fileName);
var stream = new MemoryStream ();
var pdb_writer = (PortablePdbWriter) new PortablePdbWriterProvider ().GetSymbolWriter (module, stream);
return new EmbeddedPortablePdbWriter (stream, pdb_writer);
}
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream)
{
throw new NotSupportedException ();
}
}
public sealed class EmbeddedPortablePdbWriter : ISymbolWriter {
readonly Stream stream;
readonly PortablePdbWriter writer;
internal EmbeddedPortablePdbWriter (Stream stream, PortablePdbWriter writer)
{
this.stream = stream;
this.writer = writer;
}
public ISymbolReaderProvider GetReaderProvider ()
{
return new EmbeddedPortablePdbReaderProvider ();
}
public void Write (MethodDebugInformation info)
{
writer.Write (info);
}
public ImageDebugHeader GetDebugHeader ()
{
ImageDebugHeader pdbDebugHeader = writer.GetDebugHeader ();
var directory = new ImageDebugDirectory {
Type = ImageDebugType.EmbeddedPortablePdb,
MajorVersion = 0x0100,
MinorVersion = 0x0100,
};
var data = new MemoryStream ();
var w = new BinaryStreamWriter (data);
w.WriteByte (0x4d);
w.WriteByte (0x50);
w.WriteByte (0x44);
w.WriteByte (0x42);
w.WriteInt32 ((int) stream.Length);
stream.Position = 0;
using (var compress_stream = new DeflateStream (data, CompressionMode.Compress, leaveOpen: true))
stream.CopyTo (compress_stream);
directory.SizeOfData = (int) data.Length;
var debugHeaderEntries = new ImageDebugHeaderEntry [pdbDebugHeader.Entries.Length + 1];
for (int i = 0; i < pdbDebugHeader.Entries.Length; i++)
debugHeaderEntries [i] = pdbDebugHeader.Entries [i];
debugHeaderEntries [debugHeaderEntries.Length - 1] = new ImageDebugHeaderEntry (directory, data.ToArray ());
return new ImageDebugHeader (debugHeaderEntries);
}
public void Write ()
{
writer.Write ();
}
public void Dispose ()
{
writer.Dispose ();
}
}
static class PdbGuidMapping {
static readonly Dictionary<Guid, DocumentLanguage> guid_language = new Dictionary<Guid, DocumentLanguage> ();
static readonly Dictionary<DocumentLanguage, Guid> language_guid = new Dictionary<DocumentLanguage, Guid> ();
static PdbGuidMapping ()
{
AddMapping (DocumentLanguage.C, new Guid ("63a08714-fc37-11d2-904c-00c04fa302a1"));
AddMapping (DocumentLanguage.Cpp, new Guid ("3a12d0b7-c26c-11d0-b442-00a0244a1dd2"));
AddMapping (DocumentLanguage.CSharp, new Guid ("3f5162f8-07c6-11d3-9053-00c04fa302a1"));
AddMapping (DocumentLanguage.Basic, new Guid ("3a12d0b8-c26c-11d0-b442-00a0244a1dd2"));
AddMapping (DocumentLanguage.Java, new Guid ("3a12d0b4-c26c-11d0-b442-00a0244a1dd2"));
AddMapping (DocumentLanguage.Cobol, new Guid ("af046cd1-d0e1-11d2-977c-00a0c9b4d50c"));
AddMapping (DocumentLanguage.Pascal, new Guid ("af046cd2-d0e1-11d2-977c-00a0c9b4d50c"));
AddMapping (DocumentLanguage.Cil, new Guid ("af046cd3-d0e1-11d2-977c-00a0c9b4d50c"));
AddMapping (DocumentLanguage.JScript, new Guid ("3a12d0b6-c26c-11d0-b442-00a0244a1dd2"));
AddMapping (DocumentLanguage.Smc, new Guid ("0d9b9f7b-6611-11d3-bd2a-0000f80849bd"));
AddMapping (DocumentLanguage.MCpp, new Guid ("4b35fde8-07c6-11d3-9053-00c04fa302a1"));
AddMapping (DocumentLanguage.FSharp, new Guid ("ab4f38c9-b6e6-43ba-be3b-58080b2ccce3"));
}
static void AddMapping (DocumentLanguage language, Guid guid)
{
guid_language.Add (guid, language);
language_guid.Add (language, guid);
}
static readonly Guid type_text = new Guid ("5a869d0b-6611-11d3-bd2a-0000f80849bd");
public static DocumentType ToType (this Guid guid)
{
if (guid == type_text)
return DocumentType.Text;
return DocumentType.Other;
}
public static Guid ToGuid (this DocumentType type)
{
if (type == DocumentType.Text)
return type_text;
return new Guid ();
}
static readonly Guid hash_md5 = new Guid ("406ea660-64cf-4c82-b6f0-42d48172a799");
static readonly Guid hash_sha1 = new Guid ("ff1816ec-aa5e-4d10-87f7-6f4963833460");
static readonly Guid hash_sha256 = new Guid ("8829d00f-11b8-4213-878b-770e8597ac16");
public static DocumentHashAlgorithm ToHashAlgorithm (this Guid guid)
{
if (guid == hash_md5)
return DocumentHashAlgorithm.MD5;
if (guid == hash_sha1)
return DocumentHashAlgorithm.SHA1;
if (guid == hash_sha256)
return DocumentHashAlgorithm.SHA256;
return DocumentHashAlgorithm.None;
}
public static Guid ToGuid (this DocumentHashAlgorithm hash_algo)
{
if (hash_algo == DocumentHashAlgorithm.MD5)
return hash_md5;
if (hash_algo == DocumentHashAlgorithm.SHA1)
return hash_sha1;
if (hash_algo == DocumentHashAlgorithm.SHA256)
return hash_sha256;
return new Guid ();
}
public static DocumentLanguage ToLanguage (this Guid guid)
{
DocumentLanguage language;
if (!guid_language.TryGetValue (guid, out language))
return DocumentLanguage.Other;
return language;
}
public static Guid ToGuid (this DocumentLanguage language)
{
Guid guid;
if (!language_guid.TryGetValue (language, out guid))
return new Guid ();
return guid;
}
static readonly Guid vendor_ms = new Guid ("994b45c4-e6e9-11d2-903f-00c04fa302a1");
public static DocumentLanguageVendor ToVendor (this Guid guid)
{
if (guid == vendor_ms)
return DocumentLanguageVendor.Microsoft;
return DocumentLanguageVendor.Other;
}
public static Guid ToGuid (this DocumentLanguageVendor vendor)
{
if (vendor == DocumentLanguageVendor.Microsoft)
return vendor_ms;
return new Guid ();
}
}
}
| |
/**
* (C) Copyright IBM Corp. 2018, 2020.
*
* 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 Newtonsoft.Json;
namespace IBM.Watson.Discovery.v1.Model
{
/// <summary>
/// Object containing details of the stored credentials.
///
/// Obtain credentials for your source from the administrator of the source.
/// </summary>
public class CredentialDetails
{
/// <summary>
/// The authentication method for this credentials definition. The **credential_type** specified must be
/// supported by the **source_type**. The following combinations are possible:
///
/// - `"source_type": "box"` - valid `credential_type`s: `oauth2`
/// - `"source_type": "salesforce"` - valid `credential_type`s: `username_password`
/// - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or
/// `ntlm_v1` with **source_version** of `2016`
/// - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic`
/// - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`.
/// </summary>
public class CredentialTypeEnumValue
{
/// <summary>
/// Constant OAUTH2 for oauth2
/// </summary>
public const string OAUTH2 = "oauth2";
/// <summary>
/// Constant SAML for saml
/// </summary>
public const string SAML = "saml";
/// <summary>
/// Constant USERNAME_PASSWORD for username_password
/// </summary>
public const string USERNAME_PASSWORD = "username_password";
/// <summary>
/// Constant NOAUTH for noauth
/// </summary>
public const string NOAUTH = "noauth";
/// <summary>
/// Constant BASIC for basic
/// </summary>
public const string BASIC = "basic";
/// <summary>
/// Constant NTLM_V1 for ntlm_v1
/// </summary>
public const string NTLM_V1 = "ntlm_v1";
/// <summary>
/// Constant AWS4_HMAC for aws4_hmac
/// </summary>
public const string AWS4_HMAC = "aws4_hmac";
}
/// <summary>
/// The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of
/// `sharepoint`.
/// </summary>
public class SourceVersionEnumValue
{
/// <summary>
/// Constant ONLINE for online
/// </summary>
public const string ONLINE = "online";
}
/// <summary>
/// The authentication method for this credentials definition. The **credential_type** specified must be
/// supported by the **source_type**. The following combinations are possible:
///
/// - `"source_type": "box"` - valid `credential_type`s: `oauth2`
/// - `"source_type": "salesforce"` - valid `credential_type`s: `username_password`
/// - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or
/// `ntlm_v1` with **source_version** of `2016`
/// - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic`
/// - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`.
/// Constants for possible values can be found using CredentialDetails.CredentialTypeEnumValue
/// </summary>
[JsonProperty("credential_type", NullValueHandling = NullValueHandling.Ignore)]
public string CredentialType { get; set; }
/// <summary>
/// The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of
/// `sharepoint`.
/// Constants for possible values can be found using CredentialDetails.SourceVersionEnumValue
/// </summary>
[JsonProperty("source_version", NullValueHandling = NullValueHandling.Ignore)]
public string SourceVersion { get; set; }
/// <summary>
/// The **client_id** of the source that these credentials connect to. Only valid, and required, with a
/// **credential_type** of `oauth2`.
/// </summary>
[JsonProperty("client_id", NullValueHandling = NullValueHandling.Ignore)]
public string ClientId { get; set; }
/// <summary>
/// The **enterprise_id** of the Box site that these credentials connect to. Only valid, and required, with a
/// **source_type** of `box`.
/// </summary>
[JsonProperty("enterprise_id", NullValueHandling = NullValueHandling.Ignore)]
public string EnterpriseId { get; set; }
/// <summary>
/// The **url** of the source that these credentials connect to. Only valid, and required, with a
/// **credential_type** of `username_password`, `noauth`, and `basic`.
/// </summary>
[JsonProperty("url", NullValueHandling = NullValueHandling.Ignore)]
public string Url { get; set; }
/// <summary>
/// The **username** of the source that these credentials connect to. Only valid, and required, with a
/// **credential_type** of `saml`, `username_password`, `basic`, or `ntlm_v1`.
/// </summary>
[JsonProperty("username", NullValueHandling = NullValueHandling.Ignore)]
public string Username { get; set; }
/// <summary>
/// The **organization_url** of the source that these credentials connect to. Only valid, and required, with a
/// **credential_type** of `saml`.
/// </summary>
[JsonProperty("organization_url", NullValueHandling = NullValueHandling.Ignore)]
public string OrganizationUrl { get; set; }
/// <summary>
/// The **site_collection.path** of the source that these credentials connect to. Only valid, and required, with
/// a **source_type** of `sharepoint`.
/// </summary>
[JsonProperty("site_collection.path", NullValueHandling = NullValueHandling.Ignore)]
public string SiteCollectionPath { get; set; }
/// <summary>
/// The **client_secret** of the source that these credentials connect to. Only valid, and required, with a
/// **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying
/// **credentials**.
/// </summary>
[JsonProperty("client_secret", NullValueHandling = NullValueHandling.Ignore)]
public string ClientSecret { get; set; }
/// <summary>
/// The **public_key_id** of the source that these credentials connect to. Only valid, and required, with a
/// **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying
/// **credentials**.
/// </summary>
[JsonProperty("public_key_id", NullValueHandling = NullValueHandling.Ignore)]
public string PublicKeyId { get; set; }
/// <summary>
/// The **private_key** of the source that these credentials connect to. Only valid, and required, with a
/// **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying
/// **credentials**.
/// </summary>
[JsonProperty("private_key", NullValueHandling = NullValueHandling.Ignore)]
public string PrivateKey { get; set; }
/// <summary>
/// The **passphrase** of the source that these credentials connect to. Only valid, and required, with a
/// **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying
/// **credentials**.
/// </summary>
[JsonProperty("passphrase", NullValueHandling = NullValueHandling.Ignore)]
public string Passphrase { get; set; }
/// <summary>
/// The **password** of the source that these credentials connect to. Only valid, and required, with
/// **credential_type**s of `saml`, `username_password`, `basic`, or `ntlm_v1`.
///
/// **Note:** When used with a **source_type** of `salesforce`, the password consists of the Salesforce password
/// and a valid Salesforce security token concatenated. This value is never returned and is only used when
/// creating or modifying **credentials**.
/// </summary>
[JsonProperty("password", NullValueHandling = NullValueHandling.Ignore)]
public string Password { get; set; }
/// <summary>
/// The ID of the **gateway** to be connected through (when connecting to intranet sites). Only valid with a
/// **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are created using the
/// `/v1/environments/{environment_id}/gateways` methods.
/// </summary>
[JsonProperty("gateway_id", NullValueHandling = NullValueHandling.Ignore)]
public string GatewayId { get; set; }
/// <summary>
/// SharePoint OnPrem WebApplication URL. Only valid, and required, with a **source_version** of `2016`. If a
/// port is not supplied, the default to port `80` for http and port `443` for https connections are used.
/// </summary>
[JsonProperty("web_application_url", NullValueHandling = NullValueHandling.Ignore)]
public string WebApplicationUrl { get; set; }
/// <summary>
/// The domain used to log in to your OnPrem SharePoint account. Only valid, and required, with a
/// **source_version** of `2016`.
/// </summary>
[JsonProperty("domain", NullValueHandling = NullValueHandling.Ignore)]
public string Domain { get; set; }
/// <summary>
/// The endpoint associated with the cloud object store that your are connecting to. Only valid, and required,
/// with a **credential_type** of `aws4_hmac`.
/// </summary>
[JsonProperty("endpoint", NullValueHandling = NullValueHandling.Ignore)]
public string Endpoint { get; set; }
/// <summary>
/// The access key ID associated with the cloud object store. Only valid, and required, with a
/// **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying
/// **credentials**. For more infomation, see the [cloud object store
/// documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials).
/// </summary>
[JsonProperty("access_key_id", NullValueHandling = NullValueHandling.Ignore)]
public string AccessKeyId { get; set; }
/// <summary>
/// The secret access key associated with the cloud object store. Only valid, and required, with a
/// **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying
/// **credentials**. For more infomation, see the [cloud object store
/// documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials).
/// </summary>
[JsonProperty("secret_access_key", NullValueHandling = NullValueHandling.Ignore)]
public string SecretAccessKey { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\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 ExtractVector128UInt161()
{
var test = new ExtractVector128Test__ExtractVector128UInt161();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// 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 ExtractVector128Test__ExtractVector128UInt161
{
private struct TestStruct
{
public Vector256<UInt16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(ExtractVector128Test__ExtractVector128UInt161 testClass)
{
var result = Avx2.ExtractVector128(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector256<UInt16> _clsVar;
private Vector256<UInt16> _fld;
private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable;
static ExtractVector128Test__ExtractVector128UInt161()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public ExtractVector128Test__ExtractVector128UInt161()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ExtractVector128(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ExtractVector128(
Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ExtractVector128(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ExtractVector128(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr);
var result = Avx2.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ExtractVector128Test__ExtractVector128UInt161();
var result = Avx2.ExtractVector128(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ExtractVector128(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ExtractVector128(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _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(Vector256<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != firstOp[8])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((result[i] != firstOp[i + 8]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ExtractVector128)}<UInt16>(Vector256<UInt16><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace MyWebSite.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// TarHeader.cs
//
// Copyright (C) 2001 Mike Krueger
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
/* The tar format and its POSIX successor PAX have a long history which makes for compatability
issues when creating and reading files.
This is further complicated by a large number of programs with variations on formats
One common issue is the handling of names longer than 100 characters.
GNU style long names are currently supported.
This is the ustar (Posix 1003.1) header.
struct header
{
char t_name[100]; // 0 Filename
char t_mode[8]; // 100 Permissions
char t_uid[8]; // 108 Numerical User ID
char t_gid[8]; // 116 Numerical Group ID
char t_size[12]; // 124 Filesize
char t_mtime[12]; // 136 st_mtime
char t_chksum[8]; // 148 Checksum
char t_typeflag; // 156 Type of File
char t_linkname[100]; // 157 Target of Links
char t_magic[6]; // 257 "ustar" or other...
char t_version[2]; // 263 Version fixed to 00
char t_uname[32]; // 265 User Name
char t_gname[32]; // 297 Group Name
char t_devmajor[8]; // 329 Major for devices
char t_devminor[8]; // 337 Minor for devices
char t_prefix[155]; // 345 Prefix for t_name
char t_mfill[12]; // 500 Filler up to 512
};
*/
using System;
using System.Text;
namespace ICSharpCode.SharpZipLib.Tar
{
/// <summary>
/// This class encapsulates the Tar Entry Header used in Tar Archives.
/// The class also holds a number of tar constants, used mostly in headers.
/// </summary>
public class TarHeader : ICloneable
{
#region Constants
/// <summary>
/// The length of the name field in a header buffer.
/// </summary>
public const int NAMELEN = 100;
/// <summary>
/// The length of the mode field in a header buffer.
/// </summary>
public const int MODELEN = 8;
/// <summary>
/// The length of the user id field in a header buffer.
/// </summary>
public const int UIDLEN = 8;
/// <summary>
/// The length of the group id field in a header buffer.
/// </summary>
public const int GIDLEN = 8;
/// <summary>
/// The length of the checksum field in a header buffer.
/// </summary>
public const int CHKSUMLEN = 8;
/// <summary>
/// Offset of checksum in a header buffer.
/// </summary>
public const int CHKSUMOFS = 148;
/// <summary>
/// The length of the size field in a header buffer.
/// </summary>
public const int SIZELEN = 12;
/// <summary>
/// The length of the magic field in a header buffer.
/// </summary>
public const int MAGICLEN = 6;
/// <summary>
/// The length of the version field in a header buffer.
/// </summary>
public const int VERSIONLEN = 2;
/// <summary>
/// The length of the modification time field in a header buffer.
/// </summary>
public const int MODTIMELEN = 12;
/// <summary>
/// The length of the user name field in a header buffer.
/// </summary>
public const int UNAMELEN = 32;
/// <summary>
/// The length of the group name field in a header buffer.
/// </summary>
public const int GNAMELEN = 32;
/// <summary>
/// The length of the devices field in a header buffer.
/// </summary>
public const int DEVLEN = 8;
//
// LF_ constants represent the "type" of an entry
//
/// <summary>
/// The "old way" of indicating a normal file.
/// </summary>
public const byte LF_OLDNORM = 0;
/// <summary>
/// Normal file type.
/// </summary>
public const byte LF_NORMAL = (byte) '0';
/// <summary>
/// Link file type.
/// </summary>
public const byte LF_LINK = (byte) '1';
/// <summary>
/// Symbolic link file type.
/// </summary>
public const byte LF_SYMLINK = (byte) '2';
/// <summary>
/// Character device file type.
/// </summary>
public const byte LF_CHR = (byte) '3';
/// <summary>
/// Block device file type.
/// </summary>
public const byte LF_BLK = (byte) '4';
/// <summary>
/// Directory file type.
/// </summary>
public const byte LF_DIR = (byte) '5';
/// <summary>
/// FIFO (pipe) file type.
/// </summary>
public const byte LF_FIFO = (byte) '6';
/// <summary>
/// Contiguous file type.
/// </summary>
public const byte LF_CONTIG = (byte) '7';
/// <summary>
/// Posix.1 2001 global extended header
/// </summary>
public const byte LF_GHDR = (byte) 'g';
/// <summary>
/// Posix.1 2001 extended header
/// </summary>
public const byte LF_XHDR = (byte) 'x';
// POSIX allows for upper case ascii type as extensions
/// <summary>
/// Solaris access control list file type
/// </summary>
public const byte LF_ACL = (byte) 'A';
/// <summary>
/// GNU dir dump file type
/// This is a dir entry that contains the names of files that were in the
/// dir at the time the dump was made
/// </summary>
public const byte LF_GNU_DUMPDIR = (byte) 'D';
/// <summary>
/// Solaris Extended Attribute File
/// </summary>
public const byte LF_EXTATTR = (byte) 'E' ;
/// <summary>
/// Inode (metadata only) no file content
/// </summary>
public const byte LF_META = (byte) 'I';
/// <summary>
/// Identifies the next file on the tape as having a long link name
/// </summary>
public const byte LF_GNU_LONGLINK = (byte) 'K';
/// <summary>
/// Identifies the next file on the tape as having a long name
/// </summary>
public const byte LF_GNU_LONGNAME = (byte) 'L';
/// <summary>
/// Continuation of a file that began on another volume
/// </summary>
public const byte LF_GNU_MULTIVOL = (byte) 'M';
/// <summary>
/// For storing filenames that dont fit in the main header (old GNU)
/// </summary>
public const byte LF_GNU_NAMES = (byte) 'N';
/// <summary>
/// GNU Sparse file
/// </summary>
public const byte LF_GNU_SPARSE = (byte) 'S';
/// <summary>
/// GNU Tape/volume header ignore on extraction
/// </summary>
public const byte LF_GNU_VOLHDR = (byte) 'V';
/// <summary>
/// The magic tag representing a POSIX tar archive. (includes trailing NULL)
/// </summary>
public const string TMAGIC = "ustar ";
/// <summary>
/// The magic tag representing an old GNU tar archive where version is included in magic and overwrites it
/// </summary>
public const string GNU_TMAGIC = "ustar ";
const long timeConversionFactor = 10000000L; // 1 tick == 100 nanoseconds
readonly static DateTime dateTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
#endregion
#region Constructors
/// <summary>
/// Initialise a default TarHeader instance
/// </summary>
public TarHeader()
{
Magic = TMAGIC;
Version = " ";
Name = "";
LinkName = "";
UserId = defaultUserId;
GroupId = defaultGroupId;
UserName = defaultUser;
GroupName = defaultGroupName;
Size = 0;
}
#endregion
#region Properties
/// <summary>
/// Get/set the name for this tar entry.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set the property to null.</exception>
public string Name
{
get { return name; }
set {
if ( value == null ) {
throw new ArgumentNullException("value");
}
name = value;
}
}
/// <summary>
/// Get the name of this entry.
/// </summary>
/// <returns>The entry's name.</returns>
[Obsolete("Use the Name property instead", true)]
public string GetName()
{
return name;
}
/// <summary>
/// Get/set the entry's Unix style permission mode.
/// </summary>
public int Mode
{
get { return mode; }
set { mode = value; }
}
/// <summary>
/// The entry's user id.
/// </summary>
/// <remarks>
/// This is only directly relevant to unix systems.
/// The default is zero.
/// </remarks>
public int UserId
{
get { return userId; }
set { userId = value; }
}
/// <summary>
/// Get/set the entry's group id.
/// </summary>
/// <remarks>
/// This is only directly relevant to linux/unix systems.
/// The default value is zero.
/// </remarks>
public int GroupId
{
get { return groupId; }
set { groupId = value; }
}
/// <summary>
/// Get/set the entry's size.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown when setting the size to less than zero.</exception>
public long Size
{
get { return size; }
set {
if ( value < 0 ) {
#if NETCF_1_0
throw new ArgumentOutOfRangeException("value");
#else
throw new ArgumentOutOfRangeException("value", "Cannot be less than zero");
#endif
}
size = value;
}
}
/// <summary>
/// Get/set the entry's modification time.
/// </summary>
/// <remarks>
/// The modification time is only accurate to within a second.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">Thrown when setting the date time to less than 1/1/1970.</exception>
public DateTime ModTime
{
get { return modTime; }
set {
if ( value < dateTime1970 )
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("value");
#else
throw new ArgumentOutOfRangeException("value", "ModTime cannot be before Jan 1st 1970");
#endif
}
modTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second);
}
}
/// <summary>
/// Get the entry's checksum. This is only valid/updated after writing or reading an entry.
/// </summary>
public int Checksum
{
get { return checksum; }
}
/// <summary>
/// Get value of true if the header checksum is valid, false otherwise.
/// </summary>
public bool IsChecksumValid
{
get { return isChecksumValid; }
}
/// <summary>
/// Get/set the entry's type flag.
/// </summary>
public byte TypeFlag
{
get { return typeFlag; }
set { typeFlag = value; }
}
/// <summary>
/// The entry's link name.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set LinkName to null.</exception>
public string LinkName
{
get { return linkName; }
set {
if ( value == null ) {
throw new ArgumentNullException("value");
}
linkName = value;
}
}
/// <summary>
/// Get/set the entry's magic tag.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set Magic to null.</exception>
public string Magic
{
get { return magic; }
set {
if ( value == null ) {
throw new ArgumentNullException("value");
}
magic = value;
}
}
/// <summary>
/// The entry's version.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set Version to null.</exception>
public string Version
{
get {
return version;
}
set {
if ( value == null ) {
throw new ArgumentNullException("value");
}
version = value;
}
}
/// <summary>
/// The entry's user name.
/// </summary>
public string UserName
{
get { return userName; }
set {
if (value != null) {
userName = value.Substring(0, Math.Min(UNAMELEN, value.Length));
}
else {
#if NETCF_1_0 || NETCF_2_0
string currentUser = "PocketPC";
#else
string currentUser = Environment.UserName;
#endif
if (currentUser.Length > UNAMELEN) {
currentUser = currentUser.Substring(0, UNAMELEN);
}
userName = currentUser;
}
}
}
/// <summary>
/// Get/set the entry's group name.
/// </summary>
/// <remarks>
/// This is only directly relevant to unix systems.
/// </remarks>
public string GroupName
{
get { return groupName; }
set {
if ( value == null ) {
groupName = "None";
}
else {
groupName = value;
}
}
}
/// <summary>
/// Get/set the entry's major device number.
/// </summary>
public int DevMajor
{
get { return devMajor; }
set { devMajor = value; }
}
/// <summary>
/// Get/set the entry's minor device number.
/// </summary>
public int DevMinor
{
get { return devMinor; }
set { devMinor = value; }
}
#endregion
#region ICloneable Members
/// <summary>
/// Create a new <see cref="TarHeader"/> that is a copy of the current instance.
/// </summary>
/// <returns>A new <see cref="Object"/> that is a copy of the current instance.</returns>
public object Clone()
{
return MemberwiseClone();
}
#endregion
/// <summary>
/// Parse TarHeader information from a header buffer.
/// </summary>
/// <param name = "header">
/// The tar entry header buffer to get information from.
/// </param>
public void ParseBuffer(byte[] header)
{
if ( header == null )
{
throw new ArgumentNullException("header");
}
int offset = 0;
name = TarHeader.ParseName(header, offset, TarHeader.NAMELEN).ToString();
offset += TarHeader.NAMELEN;
mode = (int)TarHeader.ParseOctal(header, offset, TarHeader.MODELEN);
offset += TarHeader.MODELEN;
UserId = (int)TarHeader.ParseOctal(header, offset, TarHeader.UIDLEN);
offset += TarHeader.UIDLEN;
GroupId = (int)TarHeader.ParseOctal(header, offset, TarHeader.GIDLEN);
offset += TarHeader.GIDLEN;
Size = TarHeader.ParseOctal(header, offset, TarHeader.SIZELEN);
offset += TarHeader.SIZELEN;
ModTime = GetDateTimeFromCTime(TarHeader.ParseOctal(header, offset, TarHeader.MODTIMELEN));
offset += TarHeader.MODTIMELEN;
checksum = (int)TarHeader.ParseOctal(header, offset, TarHeader.CHKSUMLEN);
offset += TarHeader.CHKSUMLEN;
TypeFlag = header[ offset++ ];
LinkName = TarHeader.ParseName(header, offset, TarHeader.NAMELEN).ToString();
offset += TarHeader.NAMELEN;
Magic = TarHeader.ParseName(header, offset, TarHeader.MAGICLEN).ToString();
offset += TarHeader.MAGICLEN;
Version = TarHeader.ParseName(header, offset, TarHeader.VERSIONLEN).ToString();
offset += TarHeader.VERSIONLEN;
UserName = TarHeader.ParseName(header, offset, TarHeader.UNAMELEN).ToString();
offset += TarHeader.UNAMELEN;
GroupName = TarHeader.ParseName(header, offset, TarHeader.GNAMELEN).ToString();
offset += TarHeader.GNAMELEN;
DevMajor = (int)TarHeader.ParseOctal(header, offset, TarHeader.DEVLEN);
offset += TarHeader.DEVLEN;
DevMinor = (int)TarHeader.ParseOctal(header, offset, TarHeader.DEVLEN);
// Fields past this point not currently parsed or used...
isChecksumValid = Checksum == TarHeader.MakeCheckSum(header);
}
/// <summary>
/// 'Write' header information to buffer provided, updating the <see cref="Checksum">check sum</see>.
/// </summary>
/// <param name="outBuffer">output buffer for header information</param>
public void WriteHeader(byte[] outBuffer)
{
if ( outBuffer == null )
{
throw new ArgumentNullException("outBuffer");
}
int offset = 0;
offset = GetNameBytes(Name, outBuffer, offset, NAMELEN);
offset = GetOctalBytes(mode, outBuffer, offset, MODELEN);
offset = GetOctalBytes(UserId, outBuffer, offset, UIDLEN);
offset = GetOctalBytes(GroupId, outBuffer, offset, GIDLEN);
offset = GetLongOctalBytes(Size, outBuffer, offset, SIZELEN);
offset = GetLongOctalBytes(GetCTime(ModTime), outBuffer, offset, MODTIMELEN);
int csOffset = offset;
for (int c = 0; c < CHKSUMLEN; ++c)
{
outBuffer[offset++] = (byte)' ';
}
outBuffer[offset++] = TypeFlag;
offset = GetNameBytes(LinkName, outBuffer, offset, NAMELEN);
offset = GetAsciiBytes(Magic, 0, outBuffer, offset, MAGICLEN);
offset = GetNameBytes(Version, outBuffer, offset, VERSIONLEN);
offset = GetNameBytes(UserName, outBuffer, offset, UNAMELEN);
offset = GetNameBytes(GroupName, outBuffer, offset, GNAMELEN);
if ((TypeFlag == LF_CHR) || (TypeFlag == LF_BLK))
{
offset = GetOctalBytes(DevMajor, outBuffer, offset, DEVLEN);
offset = GetOctalBytes(DevMinor, outBuffer, offset, DEVLEN);
}
for ( ; offset < outBuffer.Length; )
{
outBuffer[offset++] = 0;
}
checksum = ComputeCheckSum(outBuffer);
GetCheckSumOctalBytes(checksum, outBuffer, csOffset, CHKSUMLEN);
isChecksumValid = true;
}
/// <summary>
/// Get a hash code for the current object.
/// </summary>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode()
{
return Name.GetHashCode();
}
/// <summary>
/// Determines if this instance is equal to the specified object.
/// </summary>
/// <param name="obj">The object to compare with.</param>
/// <returns>true if the objects are equal, false otherwise.</returns>
public override bool Equals(object obj)
{
TarHeader localHeader = obj as TarHeader;
bool result;
if ( localHeader != null )
{
result = (name == localHeader.name)
&& (mode == localHeader.mode)
&& (UserId == localHeader.UserId)
&& (GroupId == localHeader.GroupId)
&& (Size == localHeader.Size)
&& (ModTime == localHeader.ModTime)
&& (Checksum == localHeader.Checksum)
&& (TypeFlag == localHeader.TypeFlag)
&& (LinkName == localHeader.LinkName)
&& (Magic == localHeader.Magic)
&& (Version == localHeader.Version)
&& (UserName == localHeader.UserName)
&& (GroupName == localHeader.GroupName)
&& (DevMajor == localHeader.DevMajor)
&& (DevMinor == localHeader.DevMinor);
}
else
{
result = false;
}
return result;
}
/// <summary>
/// Set defaults for values used when constructing a TarHeader instance.
/// </summary>
/// <param name="userId">Value to apply as a default for userId.</param>
/// <param name="userName">Value to apply as a default for userName.</param>
/// <param name="groupId">Value to apply as a default for groupId.</param>
/// <param name="groupName">Value to apply as a default for groupName.</param>
static internal void SetValueDefaults(int userId, string userName, int groupId, string groupName)
{
defaultUserId = userIdAsSet = userId;
defaultUser = userNameAsSet = userName;
defaultGroupId = groupIdAsSet = groupId;
defaultGroupName = groupNameAsSet = groupName;
}
static internal void RestoreSetValues()
{
defaultUserId = userIdAsSet;
defaultUser = userNameAsSet;
defaultGroupId = groupIdAsSet;
defaultGroupName = groupNameAsSet;
}
/// <summary>
/// Parse an octal string from a header buffer.
/// </summary>
/// <param name = "header">The header buffer from which to parse.</param>
/// <param name = "offset">The offset into the buffer from which to parse.</param>
/// <param name = "length">The number of header bytes to parse.</param>
/// <returns>The long equivalent of the octal string.</returns>
static public long ParseOctal(byte[] header, int offset, int length)
{
if ( header == null ) {
throw new ArgumentNullException("header");
}
long result = 0;
bool stillPadding = true;
int end = offset + length;
for (int i = offset; i < end ; ++i) {
if (header[i] == 0) {
break;
}
if (header[i] == (byte)' ' || header[i] == '0') {
if (stillPadding) {
continue;
}
if (header[i] == (byte)' ') {
break;
}
}
stillPadding = false;
result = (result << 3) + (header[i] - '0');
}
return result;
}
/// <summary>
/// Parse a name from a header buffer.
/// </summary>
/// <param name="header">
/// The header buffer from which to parse.
/// </param>
/// <param name="offset">
/// The offset into the buffer from which to parse.
/// </param>
/// <param name="length">
/// The number of header bytes to parse.
/// </param>
/// <returns>
/// The name parsed.
/// </returns>
static public StringBuilder ParseName(byte[] header, int offset, int length)
{
if ( header == null ) {
throw new ArgumentNullException("header");
}
if ( offset < 0 ) {
#if NETCF_1_0
throw new ArgumentOutOfRangeException("offset");
#else
throw new ArgumentOutOfRangeException("offset", "Cannot be less than zero");
#endif
}
if ( length < 0 )
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("length");
#else
throw new ArgumentOutOfRangeException("length", "Cannot be less than zero");
#endif
}
if ( offset + length > header.Length )
{
throw new ArgumentException("Exceeds header size", "length");
}
StringBuilder result = new StringBuilder(length);
for (int i = offset; i < offset + length; ++i) {
if (header[i] == 0) {
break;
}
result.Append((char)header[i]);
}
return result;
}
/// <summary>
/// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
/// </summary>
/// <param name="name">The name to add</param>
/// <param name="nameOffset">The offset of the first character</param>
/// <param name="buffer">The buffer to add to</param>
/// <param name="bufferOffset">The index of the first byte to add</param>
/// <param name="length">The number of characters/bytes to add</param>
/// <returns>The next free index in the <paramref name="buffer"/></returns>
public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buffer, int bufferOffset, int length)
{
if ( name == null ) {
throw new ArgumentNullException("name");
}
if ( buffer == null ) {
throw new ArgumentNullException("buffer");
}
return GetNameBytes(name.ToString(), nameOffset, buffer, bufferOffset, length);
}
/// <summary>
/// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
/// </summary>
/// <param name="name">The name to add</param>
/// <param name="nameOffset">The offset of the first character</param>
/// <param name="buffer">The buffer to add to</param>
/// <param name="bufferOffset">The index of the first byte to add</param>
/// <param name="length">The number of characters/bytes to add</param>
/// <returns>The next free index in the <paramref name="buffer"/></returns>
public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length)
{
if ( name == null )
{
throw new ArgumentNullException("name");
}
if ( buffer == null )
{
throw new ArgumentNullException("buffer");
}
int i;
for (i = 0 ; i < length - 1 && nameOffset + i < name.Length; ++i) {
buffer[bufferOffset + i] = (byte)name[nameOffset + i];
}
for (; i < length ; ++i) {
buffer[bufferOffset + i] = 0;
}
return bufferOffset + length;
}
/// <summary>
/// Add an entry name to the buffer
/// </summary>
/// <param name="name">
/// The name to add
/// </param>
/// <param name="buffer">
/// The buffer to add to
/// </param>
/// <param name="offset">
/// The offset into the buffer from which to start adding
/// </param>
/// <param name="length">
/// The number of header bytes to add
/// </param>
/// <returns>
/// The index of the next free byte in the buffer
/// </returns>
public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, int length)
{
if ( name == null ) {
throw new ArgumentNullException("name");
}
if ( buffer == null ) {
throw new ArgumentNullException("buffer");
}
return GetNameBytes(name.ToString(), 0, buffer, offset, length);
}
/// <summary>
/// Add an entry name to the buffer
/// </summary>
/// <param name="name">The name to add</param>
/// <param name="buffer">The buffer to add to</param>
/// <param name="offset">The offset into the buffer from which to start adding</param>
/// <param name="length">The number of header bytes to add</param>
/// <returns>The index of the next free byte in the buffer</returns>
public static int GetNameBytes(string name, byte[] buffer, int offset, int length)
{
if ( name == null ) {
throw new ArgumentNullException("name");
}
if ( buffer == null )
{
throw new ArgumentNullException("buffer");
}
return GetNameBytes(name, 0, buffer, offset, length);
}
/// <summary>
/// Add a string to a buffer as a collection of ascii bytes.
/// </summary>
/// <param name="toAdd">The string to add</param>
/// <param name="nameOffset">The offset of the first character to add.</param>
/// <param name="buffer">The buffer to add to.</param>
/// <param name="bufferOffset">The offset to start adding at.</param>
/// <param name="length">The number of ascii characters to add.</param>
/// <returns>The next free index in the buffer.</returns>
public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length )
{
if ( toAdd == null ) {
throw new ArgumentNullException("toAdd");
}
if ( buffer == null ) {
throw new ArgumentNullException("buffer");
}
for (int i = 0 ; i < length && nameOffset + i < toAdd.Length; ++i)
{
buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i];
}
return bufferOffset + length;
}
/// <summary>
/// Put an octal representation of a value into a buffer
/// </summary>
/// <param name = "value">
/// the value to be converted to octal
/// </param>
/// <param name = "buffer">
/// buffer to store the octal string
/// </param>
/// <param name = "offset">
/// The offset into the buffer where the value starts
/// </param>
/// <param name = "length">
/// The length of the octal string to create
/// </param>
/// <returns>
/// The offset of the character next byte after the octal string
/// </returns>
public static int GetOctalBytes(long value, byte[] buffer, int offset, int length)
{
if ( buffer == null ) {
throw new ArgumentNullException("buffer");
}
int localIndex = length - 1;
// Either a space or null is valid here. We use NULL as per GNUTar
buffer[offset + localIndex] = 0;
--localIndex;
if (value > 0) {
for ( long v = value; (localIndex >= 0) && (v > 0); --localIndex ) {
buffer[offset + localIndex] = (byte)((byte)'0' + (byte)(v & 7));
v >>= 3;
}
}
for ( ; localIndex >= 0; --localIndex ) {
buffer[offset + localIndex] = (byte)'0';
}
return offset + length;
}
/// <summary>
/// Put an octal representation of a value into a buffer
/// </summary>
/// <param name = "value">Value to be convert to octal</param>
/// <param name = "buffer">The buffer to update</param>
/// <param name = "offset">The offset into the buffer to store the value</param>
/// <param name = "length">The length of the octal string</param>
/// <returns>Index of next byte</returns>
public static int GetLongOctalBytes(long value, byte[] buffer, int offset, int length)
{
return GetOctalBytes(value, buffer, offset, length);
}
/// <summary>
/// Add the checksum integer to header buffer.
/// </summary>
/// <param name = "value"></param>
/// <param name = "buffer">The header buffer to set the checksum for</param>
/// <param name = "offset">The offset into the buffer for the checksum</param>
/// <param name = "length">The number of header bytes to update.
/// It's formatted differently from the other fields: it has 6 digits, a
/// null, then a space -- rather than digits, a space, then a null.
/// The final space is already there, from checksumming
/// </param>
/// <returns>The modified buffer offset</returns>
static int GetCheckSumOctalBytes(long value, byte[] buffer, int offset, int length)
{
TarHeader.GetOctalBytes(value, buffer, offset, length - 1);
return offset + length;
}
/// <summary>
/// Compute the checksum for a tar entry header.
/// The checksum field must be all spaces prior to this happening
/// </summary>
/// <param name = "buffer">The tar entry's header buffer.</param>
/// <returns>The computed checksum.</returns>
static int ComputeCheckSum(byte[] buffer)
{
int sum = 0;
for (int i = 0; i < buffer.Length; ++i) {
sum += buffer[i];
}
return sum;
}
/// <summary>
/// Make a checksum for a tar entry ignoring the checksum contents.
/// </summary>
/// <param name = "buffer">The tar entry's header buffer.</param>
/// <returns>The checksum for the buffer</returns>
static int MakeCheckSum(byte[] buffer)
{
int sum = 0;
for ( int i = 0; i < CHKSUMOFS; ++i )
{
sum += buffer[i];
}
for ( int i = 0; i < TarHeader.CHKSUMLEN; ++i)
{
sum += (byte)' ';
}
for (int i = CHKSUMOFS + CHKSUMLEN; i < buffer.Length; ++i)
{
sum += buffer[i];
}
return sum;
}
static int GetCTime(System.DateTime dateTime)
{
return unchecked((int)((dateTime.Ticks - dateTime1970.Ticks) / timeConversionFactor));
}
static DateTime GetDateTimeFromCTime(long ticks)
{
DateTime result;
try {
result = new DateTime(dateTime1970.Ticks + ticks * timeConversionFactor);
}
catch(ArgumentOutOfRangeException) {
result = dateTime1970;
}
return result;
}
#region Instance Fields
string name;
int mode;
int userId;
int groupId;
long size;
DateTime modTime;
int checksum;
bool isChecksumValid;
byte typeFlag;
string linkName;
string magic;
string version;
string userName;
string groupName;
int devMajor;
int devMinor;
#endregion
#region Class Fields
// Values used during recursive operations.
static internal int userIdAsSet;
static internal int groupIdAsSet;
static internal string userNameAsSet;
static internal string groupNameAsSet = "None";
static internal int defaultUserId;
static internal int defaultGroupId;
static internal string defaultGroupName = "None";
static internal string defaultUser;
#endregion
}
}
/* The original Java file had this header:
*
** Authored by Timothy Gerard Endres
** <mailto:time@gjt.org> <http://www.trustice.com>
**
** This work has been placed into the public domain.
** You may use this work in any way and for any purpose you wish.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/
| |
using System;
using System.IO;
using System.Globalization;
using System.Text;
namespace Weborb.Protocols.JsonRPC
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only means of
/// emitting JSON data formatted as JSON text (RFC 4627).
/// </summary>
public class JsonTextWriter : JsonWriter
{
private readonly TextWriter _writer;
//
// Pretty printing as per:
// http://developer.mozilla.org/es4/proposals/json_encoding_and_decoding.html
//
// <quote>
// ...linefeeds are inserted after each { and , and before } , and multiples
// of 4 spaces are inserted to indicate the level of nesting, and one space
// will be inserted after :. Otherwise, no whitespace is inserted between
// the tokens.
// </quote>
//
private bool _prettyPrint;
private bool _newLine;
private int _indent;
private char[] _indentBuffer;
public JsonTextWriter() :
this(null) {}
public JsonTextWriter(TextWriter writer)
{
_writer = writer != null ? writer : new StringWriter();
}
public bool PrettyPrint
{
get { return _prettyPrint; }
set { _prettyPrint = value; }
}
protected TextWriter InnerWriter
{
get { return _writer; }
}
public override void Flush()
{
_writer.Flush();
}
public override string ToString()
{
StringWriter stringWriter = _writer as StringWriter;
return stringWriter != null ?
stringWriter.ToString() : base.ToString();
}
protected override void WriteStartObjectImpl()
{
OnWritingValue();
WriteDelimiter('{');
PrettySpace();
}
protected override void WriteEndObjectImpl()
{
if (Index > 0)
{
PrettyLine();
_indent--;
}
WriteDelimiter('}');
}
protected override void WriteMemberImpl(string name)
{
if (Index > 0)
{
WriteDelimiter(',');
PrettyLine();
}
else
{
PrettyLine();
_indent++;
}
WriteStringImpl(name);
WriteDelimiter(':');
PrettySpace();
}
public void WriteCachedJSON( string p )
{
EnsureMemberOnObjectBracket();
WriteScalar( p );
OnValueWritten();
}
protected override void WriteStringImpl(string value)
{
WriteScalar(Enquote(value, null).ToString());
}
private static StringBuilder Enquote( string s, StringBuilder sb )
{
if ( s == null || s.Length == 0 )
return new StringBuilder( "\"\"" );
int length = (s == null ? "" : s).Length;
if ( sb == null )
sb = new StringBuilder( length + 4 );
sb.Append( '"' );
char last;
char ch = '\0';
for ( int index = 0; index < length; index++ )
{
last = ch;
ch = s[ index ];
switch ( ch )
{
case '\\':
case '"':
{
sb.Append( '\\' );
sb.Append( ch );
break;
}
case '/':
{
if ( last == '<' )
sb.Append( '\\' );
sb.Append( ch );
break;
}
case '\b': sb.Append( "\\b" ); break;
case '\t': sb.Append( "\\t" ); break;
case '\n': sb.Append( "\\n" ); break;
case '\f': sb.Append( "\\f" ); break;
case '\r': sb.Append( "\\r" ); break;
default:
{
if ( ch < ' ' )
{
sb.Append( "\\u" );
sb.Append( ( (int)ch ).ToString( "x4", CultureInfo.InvariantCulture ) );
}
else
{
sb.Append( ch );
}
break;
}
}
}
return sb.Append( '"' );
}
protected override void WriteNumberImpl(string value)
{
WriteScalar(value);
}
protected override void WriteBooleanImpl(bool value)
{
WriteScalar(value ? "true" : "false");
}
protected override void WriteNullImpl()
{
WriteScalar( "null" );
}
protected override void WriteStartArrayImpl()
{
OnWritingValue();
WriteDelimiter('[');
PrettySpace();
}
protected override void WriteEndArrayImpl()
{
if (IsNonEmptyArray())
PrettySpace();
WriteDelimiter(']');
}
public void WriteScalar(string text)
{
OnWritingValue();
PrettyIndent();
_writer.Write(text);
}
private bool IsNonEmptyArray()
{
return Bracket == JsonWriterBracket.Array && Index > 0;
}
//
// Methods below are mostly related to pretty-printing of JSON text.
//
private void OnWritingValue()
{
if (IsNonEmptyArray())
{
WriteDelimiter(',');
PrettySpace();
}
}
private void WriteDelimiter(char ch)
{
PrettyIndent();
_writer.Write(ch);
}
private void PrettySpace()
{
if (!_prettyPrint) return;
WriteDelimiter(' ');
}
private void PrettyLine()
{
if (!_prettyPrint) return;
_writer.WriteLine();
_newLine = true;
}
private void PrettyIndent()
{
if (!_prettyPrint)
return;
if (_newLine)
{
if (_indent > 0)
{
int spaces = _indent * 4;
if (_indentBuffer == null || _indentBuffer.Length < spaces)
_indentBuffer = new string(' ', spaces * 4).ToCharArray();
_writer.Write(_indentBuffer, 0, spaces);
}
_newLine = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Xunit;
using Shouldly;
using System.Linq;
using System.Dynamic;
using System.Linq.Expressions;
using AutoMapper.Internal;
using AutoMapper.Internal.Mappers;
namespace AutoMapper.UnitTests.ArraysAndLists
{
public class When_mapping_to_Existing_IEnumerable : AutoMapperSpecBase
{
public class Source
{
public IEnumerable<SourceItem> Items { get; set; } = Enumerable.Empty<SourceItem>();
}
public class Destination
{
public IEnumerable<DestinationItem> Items { get; set; } = Enumerable.Empty<DestinationItem>();
}
public class SourceItem
{
public string Value { get; set; }
}
public class DestinationItem
{
public string Value { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(c =>
{
c.CreateMap<Source, Destination>();
c.CreateMap<SourceItem, DestinationItem>();
});
[Fact]
public void Should_overwrite_the_existing_list()
{
var destination = new Destination();
var existingList = destination.Items;
Mapper.Map(new Source(), destination);
destination.Items.ShouldNotBeSameAs(existingList);
destination.Items.ShouldBeEmpty();
}
}
public class When_mapping_to_an_array_as_ICollection_with_MapAtRuntime : AutoMapperSpecBase
{
Destination _destination;
SourceItem[] _sourceItems = new [] { new SourceItem { Value = "1" }, new SourceItem { Value = "2" }, new SourceItem { Value = "3" } };
public class Source
{
public ICollection<SourceItem> Items { get; set; }
}
public class Destination
{
public ICollection<DestinationItem> Items { get; set; }
}
public class SourceItem
{
public string Value { get; set; }
}
public class DestinationItem
{
public string Value { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(c =>
{
c.CreateMap<Source, Destination>().ForMember(d=>d.Items, o=>o.MapAtRuntime());
c.CreateMap<SourceItem, DestinationItem>();
});
protected override void Because_of()
{
var source = new Source { Items = _sourceItems };
_destination = Mapper.Map(source, new Destination { Items = new[] { new DestinationItem { Value = "4" } } });
}
[Fact]
public void Should_map_ok()
{
_destination.Items.Select(i => i.Value).SequenceEqual(_sourceItems.Select(i => i.Value)).ShouldBeTrue();
}
}
public class When_mapping_an_array : AutoMapperSpecBase
{
decimal[] _source = Enumerable.Range(1, 10).Select(i=>(decimal)i).ToArray();
decimal[] _destination;
protected override MapperConfiguration CreateConfiguration() => new(c =>{});
protected override void Because_of()
{
_destination = Mapper.Map<decimal[]>(_source);
}
[Fact]
public void Should_return_a_copy()
{
_destination.ShouldNotBeSameAs(_source);
}
}
public class When_mapping_a_primitive_array : AutoMapperSpecBase
{
int[] _source = Enumerable.Range(1, 10).ToArray();
long[] _destination;
protected override MapperConfiguration CreateConfiguration() => new(c =>{});
protected override void Because_of()
{
_destination = Mapper.Map<long[]>(_source);
}
[Fact]
public void Should_return_a_copy()
{
var source = new int[] {1, 2, 3, 4};
var dest = new long[4];
Array.Copy(source, dest, 4);
dest[3].ShouldBe(4L);
var plan = Configuration.BuildExecutionPlan(typeof(int[]), typeof(long[]));
_destination.ShouldNotBeSameAs(_source);
}
}
public class When_mapping_a_primitive_array_with_custom_mapping_function : AutoMapperSpecBase
{
int[] _source = Enumerable.Range(1, 10).ToArray();
int[] _destination;
protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap<int, int>().ConstructUsing(i => i * 1000));
protected override void Because_of()
{
_destination = Mapper.Map<int[]>(_source);
}
[Fact]
public void Should_map_each_item()
{
for (var i = 0; i < _source.Length; i++)
{
_destination[i].ShouldBe((i+1) * 1000);
}
}
}
public class When_mapping_a_primitive_array_with_custom_object_mapper : AutoMapperSpecBase
{
int[] _source = Enumerable.Range(1, 10).ToArray();
int[] _destination;
private class IntToIntMapper : IObjectMapper
{
public bool IsMatch(TypePair context)
=> context.SourceType == typeof(int) && context.DestinationType == typeof(int);
public Expression MapExpression(IGlobalConfiguration configurationProvider, ProfileMap profileMap,
MemberMap memberMap,
Expression sourceExpression, Expression destExpression)
=> Expression.Multiply(Expression.Convert(sourceExpression, typeof(int)), Expression.Constant(1000));
}
protected override MapperConfiguration CreateConfiguration() => new(c => c.Internal().Mappers.Insert(0, new IntToIntMapper()));
protected override void Because_of()
{
_destination = Mapper.Map<int[]>(_source);
}
[Fact]
public void Should_not_use_custom_mapper_but_probably_should()
{
for (var i = 0; i < _source.Length; i++)
{
_destination[i].ShouldBe(i + 1);
}
}
}
public class When_mapping_null_list_to_array: AutoMapperSpecBase
{
Destination _destination;
class Source
{
public List<SourceItem> Items { get; set; }
}
class Destination
{
public DestinationItem[] Items { get; set; }
}
class SourceItem
{
public int Value { get; set; }
}
class DestinationItem
{
public int Value { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<SourceItem, DestinationItem>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Destination>(new Source());
}
[Fact]
public void Should_map_ok()
{
_destination.Items.Length.ShouldBe(0);
}
}
public class When_mapping_null_array_to_list : AutoMapperSpecBase
{
Destination _destination;
class Source
{
public SourceItem[] Items { get; set; }
}
class Destination
{
public List<DestinationItem> Items { get; set; }
}
class SourceItem
{
public int Value { get; set; }
}
class DestinationItem
{
public int Value { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<SourceItem, DestinationItem>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Destination>(new Source());
}
[Fact]
public void Should_map_ok()
{
_destination.Items.Count.ShouldBe(0);
}
}
public class When_mapping_collections : AutoMapperSpecBase
{
Author mappedAuthor;
protected override MapperConfiguration CreateConfiguration() => new(delegate{});
protected override void Because_of()
{
dynamic authorDynamic = new ExpandoObject();
authorDynamic.Name = "Charles Dickens";
dynamic book1 = new ExpandoObject();
book1.Name = "Great Expectations";
dynamic book2 = new ExpandoObject();
book2.Name = "Oliver Twist";
authorDynamic.Books = new List<object> { book1, book2 };
mappedAuthor = Mapper.Map<Author>((object)authorDynamic);
}
[Fact]
public void Should_map_by_item_type()
{
mappedAuthor.Name.ShouldBe("Charles Dickens");
mappedAuthor.Books[0].Name.ShouldBe("Great Expectations");
mappedAuthor.Books[1].Name.ShouldBe("Oliver Twist");
}
public class Author
{
public string Name { get; set; }
public Book[] Books { get; set; }
}
public class Book
{
public string Name { get; set; }
}
}
public class When_mapping_to_an_existing_HashSet_typed_as_IEnumerable : AutoMapperSpecBase
{
private Destination _destination = new Destination();
public class Source
{
public int[] IntCollection { get; set; } = new int[0];
}
public class Destination
{
public IEnumerable<int> IntCollection { get; set; } = new HashSet<int> { 1, 2, 3, 4, 5 };
public string Unmapped { get; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map(new Source(), _destination);
}
[Fact]
public void Should_clear_the_destination()
{
_destination.IntCollection.Count().ShouldBe(0);
}
}
public class When_mapping_to_an_existing_array_typed_as_IEnumerable : AutoMapperSpecBase
{
private Destination _destination = new Destination();
public class Source
{
public int[] IntCollection { get; set; } = new int[0];
}
public class Destination
{
public IEnumerable<int> IntCollection { get; set; } = new[] { 1, 2, 3, 4, 5 };
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map(new Source(), _destination);
}
[Fact]
public void Should_create_destination_array_the_same_size_as_the_source()
{
_destination.IntCollection.Count().ShouldBe(0);
}
}
public class When_mapping_to_a_concrete_non_generic_ienumerable : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public IEnumerable Values { get; set; }
public IEnumerable Values2 { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
[Fact]
public void Should_map_from_the_generic_list_of_values()
{
_destination.Values2.ShouldNotBeNull();
_destination.Values2.ShouldContain(9);
_destination.Values2.ShouldContain(8);
_destination.Values2.ShouldContain(7);
_destination.Values2.ShouldContain(6);
}
}
public class When_mapping_to_a_concrete_generic_ienumerable : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public IEnumerable<int> Values { get; set; }
public IEnumerable<string> Values2 { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
[Fact]
public void Should_map_from_the_generic_list_of_values_with_formatting()
{
_destination.Values2.ShouldNotBeNull();
_destination.Values2.ShouldContain("9");
_destination.Values2.ShouldContain("8");
_destination.Values2.ShouldContain("7");
_destination.Values2.ShouldContain("6");
}
}
public class When_mapping_to_a_getter_only_ienumerable : AutoMapperSpecBase
{
private Destination _destination = new Destination();
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public IEnumerable<int> Values { get; } = new List<int>();
public IEnumerable<string> Values2 { get; } = new List<string>();
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of() => _destination = Mapper.Map<Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } });
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldBe(new[] { 1, 2, 3, 4 });
_destination.Values2.ShouldBe(new[] { "9", "8", "7", "6" });
}
}
public class When_mapping_to_a_getter_only_existing_ienumerable : AutoMapperSpecBase
{
private Destination _destination = new Destination();
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public IEnumerable<int> Values { get; } = new List<int>();
public IEnumerable<string> Values2 { get; } = new List<string>();
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of() => Mapper.Map(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } }, _destination);
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldBe(new[] { 1, 2, 3, 4 });
_destination.Values2.ShouldBe(new[]{ "9", "8", "7", "6" });
}
}
public class When_mapping_to_a_concrete_non_generic_icollection : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public ICollection Values { get; set; }
public ICollection Values2 { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
[Fact]
public void Should_map_from_a_non_array_source()
{
_destination.Values2.ShouldNotBeNull();
_destination.Values2.ShouldContain(9);
_destination.Values2.ShouldContain(8);
_destination.Values2.ShouldContain(7);
_destination.Values2.ShouldContain(6);
}
}
public class When_mapping_to_a_concrete_generic_icollection : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
}
public class Destination
{
public ICollection<string> Values { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain("1");
_destination.Values.ShouldContain("2");
_destination.Values.ShouldContain("3");
_destination.Values.ShouldContain("4");
}
}
public class When_mapping_to_a_concrete_ilist : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
}
public class Destination
{
public IList Values { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
}
public class When_mapping_to_a_concrete_generic_ilist : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
}
public class Destination
{
public IList<string> Values { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain("1");
_destination.Values.ShouldContain("2");
_destination.Values.ShouldContain("3");
_destination.Values.ShouldContain("4");
}
}
public class When_mapping_to_a_custom_list_with_the_same_type : AutoMapperSpecBase
{
private Destination _destination;
private Source _source;
public class ValueCollection : Collection<int>
{
}
public class Source
{
public ValueCollection Values { get; set; }
}
public class Destination
{
public ValueCollection Values { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_source = new Source { Values = new ValueCollection { 1, 2, 3, 4 } };
_destination = Mapper.Map<Source, Destination>(_source);
}
[Fact]
public void Should_assign_the_value_directly()
{
_source.Values.ShouldBe(_destination.Values);
}
}
public class When_mapping_to_a_collection_with_instantiation_managed_by_the_destination : AutoMapperSpecBase
{
private Destination _destination;
private Source _source;
public class SourceItem
{
public int Value { get; set; }
}
public class DestItem
{
public int Value { get; set; }
}
public class Source
{
public List<SourceItem> Values { get; set; }
}
public class Destination
{
private List<DestItem> _values = new List<DestItem>();
public List<DestItem> Values
{
get { return _values; }
}
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Values, opt => opt.UseDestinationValue());
cfg.CreateMap<SourceItem, DestItem>();
});
protected override void Because_of()
{
_source = new Source { Values = new List<SourceItem> { new SourceItem { Value = 5 }, new SourceItem { Value = 10 } } };
_destination = Mapper.Map<Source, Destination>(_source);
}
[Fact]
public void Should_assign_the_value_directly()
{
_destination.Values.Count.ShouldBe(2);
_destination.Values[0].Value.ShouldBe(5);
_destination.Values[1].Value.ShouldBe(10);
}
}
public class When_mapping_to_an_existing_list_with_existing_items : AutoMapperSpecBase
{
private Destination _destination;
private Source _source;
public class SourceItem
{
public int Value { get; set; }
}
public class DestItem
{
public int Value { get; set; }
}
public class Source
{
public List<SourceItem> Values { get; set; }
}
public class Destination
{
private List<DestItem> _values = new List<DestItem>();
public List<DestItem> Values
{
get { return _values; }
}
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Values, opt => opt.UseDestinationValue());
cfg.CreateMap<SourceItem, DestItem>();
});
protected override void Because_of()
{
_source = new Source { Values = new List<SourceItem> { new SourceItem { Value = 5 }, new SourceItem { Value = 10 } } };
_destination = new Destination();
_destination.Values.Add(new DestItem());
Mapper.Map(_source, _destination);
}
[Fact]
public void Should_clear_the_list_before_mapping()
{
_destination.Values.Count.ShouldBe(2);
}
}
public class When_mapping_to_getter_only_list_with_existing_items : AutoMapperSpecBase
{
public class SourceItem
{
public int Value { get; set; }
}
public class DestItem
{
public int Value { get; set; }
}
public class Source
{
public List<SourceItem> Values { get; set; }
public List<SourceItem> IValues { get; set; }
}
public class Destination
{
public List<DestItem> Values { get; } = new();
public IEnumerable<DestItem> IValues { get; } = new List<DestItem>();
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<SourceItem, DestItem>();
});
[Fact]
public void Should_clear_the_list_before_mapping()
{
var destination = new Destination { Values = { new DestItem() } };
((List<DestItem>)destination.IValues).Add(new DestItem());
Mapper.Map(new Source(), destination);
destination.Values.ShouldBeEmpty();
destination.IValues.ShouldBeEmpty();
}
}
public class When_mapping_to_list_with_existing_items : AutoMapperSpecBase
{
public class SourceItem
{
public int Value { get; set; }
}
public class DestItem
{
public int Value { get; set; }
}
public class Source
{
public List<SourceItem> Values { get; set; } = new();
}
public class Destination
{
public List<DestItem> Values { get; set; } = new();
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<SourceItem, DestItem>();
});
[Fact]
public void Should_clear_the_list_before_mapping()
{
var destination = new Destination { Values = { new DestItem { } } };
Mapper.Map(new Source { Values = { new SourceItem { Value = 42 } } }, destination);
destination.Values.Single().Value.ShouldBe(42);
}
[Fact]
public void Should_clear_the_list_before_mapping_when_the_source_is_null()
{
var destination = new Destination { Values = { new DestItem { } } };
Mapper.Map(new Source { Values = null }, destination);
destination.Values.ShouldBeEmpty();
}
}
public class When_mapping_a_collection_with_null_members : AutoMapperSpecBase
{
const string FirstString = null;
private IEnumerable<string> _strings = new List<string> { FirstString };
private List<string> _mappedStrings = new List<string>();
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.AllowNullDestinationValues = true;
});
protected override void Because_of()
{
_mappedStrings = Mapper.Map<IEnumerable<string>, List<string>>(_strings);
}
[Fact]
public void Should_map_correctly()
{
_mappedStrings.ShouldNotBeNull();
_mappedStrings.Count.ShouldBe(1);
_mappedStrings[0].ShouldBeNull();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.DotNet.XUnitExtensions;
using Test.Cryptography;
using Xunit;
using Xunit.Abstractions;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public class CertTests
{
private const string PrivateKeySectionHeader = "[Private Key]";
private const string PublicKeySectionHeader = "[Public Key]";
private readonly ITestOutputHelper _log;
public CertTests(ITestOutputHelper output)
{
_log = output;
}
[Fact]
public static void X509CertTest()
{
string certSubject = @"CN=Microsoft Corporate Root Authority, OU=ITG, O=Microsoft, L=Redmond, S=WA, C=US, E=pkit@microsoft.com";
string certSubjectObsolete = @"E=pkit@microsoft.com, C=US, S=WA, L=Redmond, O=Microsoft, OU=ITG, CN=Microsoft Corporate Root Authority";
using (X509Certificate cert = new X509Certificate(Path.Combine("TestData", "microsoft.cer")))
{
Assert.Equal(certSubject, cert.Subject);
Assert.Equal(certSubject, cert.Issuer);
#pragma warning disable CS0618 // Type or member is obsolete
Assert.Equal(certSubjectObsolete, cert.GetName());
Assert.Equal(certSubjectObsolete, cert.GetIssuerName());
#pragma warning restore CS0618
int snlen = cert.GetSerialNumber().Length;
Assert.Equal(16, snlen);
byte[] serialNumber = new byte[snlen];
Buffer.BlockCopy(cert.GetSerialNumber(), 0,
serialNumber, 0,
snlen);
Assert.Equal(0xF6, serialNumber[0]);
Assert.Equal(0xB3, serialNumber[snlen / 2]);
Assert.Equal(0x2A, serialNumber[snlen - 1]);
Assert.Equal("1.2.840.113549.1.1.1", cert.GetKeyAlgorithm());
int pklen = cert.GetPublicKey().Length;
Assert.Equal(270, pklen);
byte[] publicKey = new byte[pklen];
Buffer.BlockCopy(cert.GetPublicKey(), 0,
publicKey, 0,
pklen);
Assert.Equal(0x30, publicKey[0]);
Assert.Equal(0xB6, publicKey[9]);
Assert.Equal(1, publicKey[pklen - 1]);
}
}
[Fact]
public static void X509Cert2Test()
{
string certName = @"E=admin@digsigtrust.com, CN=ABA.ECOM Root CA, O=""ABA.ECOM, INC."", L=Washington, S=DC, C=US";
DateTime notBefore = new DateTime(1999, 7, 12, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
DateTime notAfter = new DateTime(2009, 7, 9, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.cer")))
{
Assert.Equal(certName, cert2.IssuerName.Name);
Assert.Equal(certName, cert2.SubjectName.Name);
Assert.Equal("ABA.ECOM Root CA", cert2.GetNameInfo(X509NameType.DnsName, true));
PublicKey pubKey = cert2.PublicKey;
Assert.Equal("RSA", pubKey.Oid.FriendlyName);
Assert.Equal(notAfter, cert2.NotAfter);
Assert.Equal(notBefore, cert2.NotBefore);
Assert.Equal(notAfter.ToString(), cert2.GetExpirationDateString());
Assert.Equal(notBefore.ToString(), cert2.GetEffectiveDateString());
Assert.Equal("00D01E4090000046520000000100000004", cert2.SerialNumber);
Assert.Equal("1.2.840.113549.1.1.5", cert2.SignatureAlgorithm.Value);
Assert.Equal("7A74410FB0CD5C972A364B71BF031D88A6510E9E", cert2.Thumbprint);
Assert.Equal(3, cert2.Version);
}
}
[ConditionalFact]
[OuterLoop("May require using the network, to download CRLs and intermediates")]
public void TestVerify()
{
bool success;
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
{
// Fails because expired (NotAfter = 10/16/2016)
Assert.False(microsoftDotCom.Verify(), "MicrosoftDotComSslCertBytes");
}
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
{
// NotAfter=10/31/2023
success = microsoftDotComIssuer.Verify();
if (!success)
{
LogVerifyErrors(microsoftDotComIssuer, "MicrosoftDotComIssuerBytes");
if (PlatformDetection.IsMacOsMojaveOrHigher)
{
// ActiveIssue: 29779
throw new SkipTestException("Certificate validation unstable on 10.14");
}
}
Assert.True(success, "MicrosoftDotComIssuerBytes");
}
// High Sierra fails to build a chain for a self-signed certificate with revocation enabled.
// https://github.com/dotnet/corefx/issues/21875
if (!PlatformDetection.IsMacOsHighSierraOrHigher)
{
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
// NotAfter=7/17/2036
success = microsoftDotComRoot.Verify();
if (!success)
{
LogVerifyErrors(microsoftDotComRoot, "MicrosoftDotComRootBytes");
}
Assert.True(success, "MicrosoftDotComRootBytes");
}
}
}
private void LogVerifyErrors(X509Certificate2 cert, string testName)
{
// Emulate cert.Verify() implementation in order to capture and log errors.
try
{
using (var chain = new X509Chain())
{
if (!chain.Build(cert))
{
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
_log.WriteLine(string.Format($"X509Certificate2.Verify error: {testName}, {chainStatus.Status}, {chainStatus.StatusInformation}"));
}
}
else
{
_log.WriteLine(string.Format($"X509Certificate2.Verify expected error; received none: {testName}"));
}
}
}
catch (Exception e)
{
_log.WriteLine($"X509Certificate2.Verify exception: {testName}, {e}");
}
}
[Fact]
public static void X509CertEmptyToString()
{
using (var c = new X509Certificate())
{
string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate";
Assert.Equal(expectedResult, c.ToString());
Assert.Equal(expectedResult, c.ToString(false));
Assert.Equal(expectedResult, c.ToString(true));
}
}
[Fact]
public static void X509Cert2EmptyToString()
{
using (var c2 = new X509Certificate2())
{
string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate2";
Assert.Equal(expectedResult, c2.ToString());
Assert.Equal(expectedResult, c2.ToString(false));
Assert.Equal(expectedResult, c2.ToString(true));
}
}
[Fact]
public static void X509Cert2ToStringVerbose()
{
using (X509Store store = new X509Store("My", StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 c in store.Certificates)
{
Assert.False(string.IsNullOrWhiteSpace(c.ToString(true)));
c.Dispose();
}
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void X509Certificate2ToStringVerbose_WithPrivateKey(X509KeyStorageFlags keyStorageFlags)
{
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags))
{
string certToString = cert.ToString(true);
Assert.Contains(PrivateKeySectionHeader, certToString);
Assert.Contains(PublicKeySectionHeader, certToString);
}
}
[Fact]
public static void X509Certificate2ToStringVerbose_NoPrivateKey()
{
using (var cert = new X509Certificate2(TestData.MsCertificatePemBytes))
{
string certToString = cert.ToString(true);
Assert.DoesNotContain(PrivateKeySectionHeader, certToString);
Assert.Contains(PublicKeySectionHeader, certToString);
}
}
[Fact]
public static void X509Cert2CreateFromEmptyPfx()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.EmptyPfx));
}
[Fact]
public static void X509Cert2CreateFromPfxFile()
{
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "DummyTcpServer.pfx")))
{
// OID=RSA Encryption
Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm());
}
}
[Fact]
public static void X509Cert2CreateFromPfxWithPassword()
{
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.pfx"), "test"))
{
// OID=RSA Encryption
Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm());
}
}
[Fact]
public static void X509Certificate2FromPkcs7DerFile()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7b")));
}
[Fact]
public static void X509Certificate2FromPkcs7PemFile()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7c")));
}
[Fact]
public static void X509Certificate2FromPkcs7DerBlob()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SingleDerBytes));
}
[Fact]
public static void X509Certificate2FromPkcs7PemBlob()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SinglePemBytes));
}
[Fact]
public static void UseAfterDispose()
{
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
IntPtr h = c.Handle;
// Do a couple of things that would only be true on a valid certificate, as a precondition.
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = c.GetCertHash();
c.Dispose();
// For compat reasons, Dispose() acts like the now-defunct Reset() method rather than
// causing ObjectDisposedExceptions.
h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
// State held on X509Certificate
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString());
#if HAVE_THUMBPRINT_OVERLOADS
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash(HashAlgorithmName.SHA256));
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString(HashAlgorithmName.SHA256));
#endif
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber());
Assert.ThrowsAny<CryptographicException>(() => c.Issuer);
Assert.ThrowsAny<CryptographicException>(() => c.Subject);
Assert.ThrowsAny<CryptographicException>(() => c.NotBefore);
Assert.ThrowsAny<CryptographicException>(() => c.NotAfter);
#if HAVE_THUMBPRINT_OVERLOADS
Assert.ThrowsAny<CryptographicException>(
() => c.TryGetCertHash(HashAlgorithmName.SHA256, Array.Empty<byte>(), out _));
#endif
// State held on X509Certificate2
Assert.ThrowsAny<CryptographicException>(() => c.RawData);
Assert.ThrowsAny<CryptographicException>(() => c.SignatureAlgorithm);
Assert.ThrowsAny<CryptographicException>(() => c.Version);
Assert.ThrowsAny<CryptographicException>(() => c.SubjectName);
Assert.ThrowsAny<CryptographicException>(() => c.IssuerName);
Assert.ThrowsAny<CryptographicException>(() => c.PublicKey);
Assert.ThrowsAny<CryptographicException>(() => c.Extensions);
Assert.ThrowsAny<CryptographicException>(() => c.PrivateKey);
}
}
[Fact]
public static void ExportPublicKeyAsPkcs12()
{
using (X509Certificate2 publicOnly = new X509Certificate2(TestData.MsCertificate))
{
// Pre-condition: There's no private key
Assert.False(publicOnly.HasPrivateKey);
// macOS 10.12 (Sierra) fails to create a PKCS#12 blob if it has no private keys within it.
bool shouldThrow = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
try
{
byte[] pkcs12Bytes = publicOnly.Export(X509ContentType.Pkcs12);
Assert.False(shouldThrow, "PKCS#12 export of a public-only certificate threw as expected");
// Read it back as a collection, there should be only one cert, and it should
// be equal to the one we started with.
using (ImportedCollection ic = Cert.Import(pkcs12Bytes))
{
X509Certificate2Collection fromPfx = ic.Collection;
Assert.Equal(1, fromPfx.Count);
Assert.Equal(publicOnly, fromPfx[0]);
}
}
catch (CryptographicException)
{
if (!shouldThrow)
{
throw;
}
}
}
}
[Fact]
public static void X509Certificate2WithT61String()
{
string certSubject = @"E=mabaul@microsoft.com, OU=Engineering, O=Xamarin, S=Massachusetts, C=US, CN=test-server.local";
using (var cert = new X509Certificate2(TestData.T61StringCertificate))
{
Assert.Equal(certSubject, cert.Subject);
Assert.Equal(certSubject, cert.Issuer);
Assert.Equal("9E7A5CCC9F951A8700", cert.GetSerialNumber().ByteArrayToHex());
Assert.Equal("1.2.840.113549.1.1.1", cert.GetKeyAlgorithm());
Assert.Equal(74, cert.GetPublicKey().Length);
Assert.Equal("test-server.local", cert.GetNameInfo(X509NameType.SimpleName, false));
Assert.Equal("mabaul@microsoft.com", cert.GetNameInfo(X509NameType.EmailName, false));
}
}
public static IEnumerable<object> StorageFlags => CollectionImportTests.StorageFlags;
}
}
| |
/*
* Copyright (c) 2012 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* 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 Facebook.MiniJSON
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json
{
// interpret all numbers as if they are english US formatted numbers
private static NumberFormatInfo numberFormat = (new CultureInfo("en-US")).NumberFormat;
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json)
{
// save the string for debug information
if (json == null)
{
return null;
}
return Parser.Parse(json);
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj)
{
return Serializer.Serialize(obj);
}
private sealed class Parser : IDisposable
{
private const string WhiteSpace = " \t\n\r";
private const string WordBreak = " \t\n\r{}[],:\"";
private StringReader json;
private Parser(string jsonString)
{
this.json = new StringReader(jsonString);
}
private enum TOKEN
{
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
}
private char PeekChar
{
get
{
return Convert.ToChar(this.json.Peek());
}
}
private char NextChar
{
get
{
return Convert.ToChar(this.json.Read());
}
}
private string NextWord
{
get
{
StringBuilder word = new StringBuilder();
while (WordBreak.IndexOf(this.PeekChar) == -1)
{
word.Append(this.NextChar);
if (this.json.Peek() == -1)
{
break;
}
}
return word.ToString();
}
}
private TOKEN NextToken
{
get
{
this.EatWhitespace();
if (this.json.Peek() == -1)
{
return TOKEN.NONE;
}
char c = this.PeekChar;
switch (c)
{
case '{':
return TOKEN.CURLY_OPEN;
case '}':
this.json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
this.json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
this.json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
string word = this.NextWord;
switch (word)
{
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
public static object Parse(string jsonString)
{
using (var instance = new Parser(jsonString))
{
return instance.ParseValue();
}
}
public void Dispose()
{
this.json.Dispose();
this.json = null;
}
private Dictionary<string, object> ParseObject()
{
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
this.json.Read();
// {
while (true)
{
switch (this.NextToken)
{
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = this.ParseString();
if (name == null)
{
return null;
}
// :
if (this.NextToken != TOKEN.COLON)
{
return null;
}
// ditch the colon
this.json.Read();
// value
table[name] = this.ParseValue();
break;
}
}
}
private List<object> ParseArray()
{
List<object> array = new List<object>();
// ditch opening bracket
this.json.Read();
// [
var parsing = true;
while (parsing)
{
TOKEN nextToken = this.NextToken;
switch (nextToken)
{
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = this.ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
private object ParseValue()
{
TOKEN nextToken = this.NextToken;
return this.ParseByToken(nextToken);
}
private object ParseByToken(TOKEN token)
{
switch (token)
{
case TOKEN.STRING:
return this.ParseString();
case TOKEN.NUMBER:
return this.ParseNumber();
case TOKEN.CURLY_OPEN:
return this.ParseObject();
case TOKEN.SQUARED_OPEN:
return this.ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
private string ParseString()
{
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
this.json.Read();
bool parsing = true;
while (parsing)
{
if (this.json.Peek() == -1)
{
parsing = false;
break;
}
c = this.NextChar;
switch (c)
{
case '"':
parsing = false;
break;
case '\\':
if (this.json.Peek() == -1)
{
parsing = false;
break;
}
c = this.NextChar;
switch (c)
{
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new StringBuilder();
for (int i = 0; i < 4; i++)
{
hex.Append(this.NextChar);
}
s.Append((char)Convert.ToInt32(hex.ToString(), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
private object ParseNumber()
{
string number = this.NextWord;
if (number.IndexOf('.') == -1)
{
return long.Parse(number, numberFormat);
}
return double.Parse(number, numberFormat);
}
private void EatWhitespace()
{
while (WhiteSpace.IndexOf(this.PeekChar) != -1)
{
this.json.Read();
if (this.json.Peek() == -1)
{
break;
}
}
}
}
private sealed class Serializer
{
private StringBuilder builder;
private Serializer()
{
this.builder = new StringBuilder();
}
public static string Serialize(object obj)
{
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
private void SerializeValue(object value)
{
IList asList;
IDictionary asDict;
string asStr;
if (value == null)
{
this.builder.Append("null");
}
else if ((asStr = value as string) != null)
{
this.SerializeString(asStr);
}
else if (value is bool)
{
this.builder.Append(value.ToString().ToLower());
}
else if ((asList = value as IList) != null)
{
this.SerializeArray(asList);
}
else if ((asDict = value as IDictionary) != null)
{
this.SerializeObject(asDict);
}
else if (value is char)
{
this.SerializeString(value.ToString());
}
else
{
this.SerializeOther(value);
}
}
private void SerializeObject(IDictionary obj)
{
bool first = true;
this.builder.Append('{');
foreach (object e in obj.Keys)
{
if (!first)
{
this.builder.Append(',');
}
this.SerializeString(e.ToString());
this.builder.Append(':');
this.SerializeValue(obj[e]);
first = false;
}
this.builder.Append('}');
}
private void SerializeArray(IList array)
{
this.builder.Append('[');
bool first = true;
foreach (object obj in array)
{
if (!first)
{
this.builder.Append(',');
}
this.SerializeValue(obj);
first = false;
}
this.builder.Append(']');
}
private void SerializeString(string str)
{
this.builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray)
{
switch (c)
{
case '"':
this.builder.Append("\\\"");
break;
case '\\':
this.builder.Append("\\\\");
break;
case '\b':
this.builder.Append("\\b");
break;
case '\f':
this.builder.Append("\\f");
break;
case '\n':
this.builder.Append("\\n");
break;
case '\r':
this.builder.Append("\\r");
break;
case '\t':
this.builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126))
{
this.builder.Append(c);
}
else
{
this.builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
break;
}
}
this.builder.Append('\"');
}
private void SerializeOther(object value)
{
if (value is float
|| value is int
|| value is uint
|| value is long
|| value is double
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong
|| value is decimal)
{
this.builder.Append(value.ToString());
}
else
{
this.SerializeString(value.ToString());
}
}
}
}
}
| |
namespace T5Suite2
{
partial class frmBoostBiasRange
{
/// <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.groupControl1 = new DevExpress.XtraEditors.GroupControl();
this.spinEdit3 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl3 = new DevExpress.XtraEditors.LabelControl();
this.spinEdit4 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl4 = new DevExpress.XtraEditors.LabelControl();
this.spinEdit1 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton();
this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton();
((System.ComponentModel.ISupportInitialize)(this.groupControl1)).BeginInit();
this.groupControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).BeginInit();
this.SuspendLayout();
//
// groupControl1
//
this.groupControl1.Controls.Add(this.spinEdit3);
this.groupControl1.Controls.Add(this.labelControl3);
this.groupControl1.Controls.Add(this.spinEdit4);
this.groupControl1.Controls.Add(this.labelControl4);
this.groupControl1.Controls.Add(this.spinEdit1);
this.groupControl1.Controls.Add(this.labelControl1);
this.groupControl1.Location = new System.Drawing.Point(9, 9);
this.groupControl1.Name = "groupControl1";
this.groupControl1.Size = new System.Drawing.Size(442, 127);
this.groupControl1.TabIndex = 0;
this.groupControl1.Text = "Select boost boost bias range parameters";
//
// spinEdit3
//
this.spinEdit3.EditValue = new decimal(new int[] {
5500,
0,
0,
0});
this.spinEdit3.Enabled = false;
this.spinEdit3.Location = new System.Drawing.Point(332, 72);
this.spinEdit3.Name = "spinEdit3";
this.spinEdit3.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit3.Properties.Increment = new decimal(new int[] {
50,
0,
0,
0});
this.spinEdit3.Properties.IsFloatValue = false;
this.spinEdit3.Properties.Mask.EditMask = "N00";
this.spinEdit3.Size = new System.Drawing.Size(70, 20);
this.spinEdit3.TabIndex = 7;
//
// labelControl3
//
this.labelControl3.Location = new System.Drawing.Point(266, 75);
this.labelControl3.Name = "labelControl3";
this.labelControl3.Size = new System.Drawing.Size(46, 13);
this.labelControl3.TabIndex = 6;
this.labelControl3.Text = "rpm upto ";
//
// spinEdit4
//
this.spinEdit4.EditValue = new decimal(new int[] {
2500,
0,
0,
0});
this.spinEdit4.Enabled = false;
this.spinEdit4.Location = new System.Drawing.Point(171, 72);
this.spinEdit4.Name = "spinEdit4";
this.spinEdit4.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit4.Properties.Increment = new decimal(new int[] {
50,
0,
0,
0});
this.spinEdit4.Properties.IsFloatValue = false;
this.spinEdit4.Properties.Mask.EditMask = "N00";
this.spinEdit4.Size = new System.Drawing.Size(70, 20);
this.spinEdit4.TabIndex = 5;
//
// labelControl4
//
this.labelControl4.Location = new System.Drawing.Point(34, 75);
this.labelControl4.Name = "labelControl4";
this.labelControl4.Size = new System.Drawing.Size(76, 13);
this.labelControl4.TabIndex = 4;
this.labelControl4.Text = "Result rpm from";
//
// spinEdit1
//
this.spinEdit1.EditValue = new decimal(new int[] {
10,
0,
0,
0});
this.spinEdit1.Location = new System.Drawing.Point(171, 46);
this.spinEdit1.Name = "spinEdit1";
this.spinEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit1.Properties.IsFloatValue = false;
this.spinEdit1.Properties.Mask.EditMask = "N00";
this.spinEdit1.Properties.MaxValue = new decimal(new int[] {
20,
0,
0,
0});
this.spinEdit1.Properties.MinValue = new decimal(new int[] {
5,
0,
0,
0});
this.spinEdit1.Size = new System.Drawing.Size(70, 20);
this.spinEdit1.TabIndex = 1;
this.spinEdit1.ValueChanged += new System.EventHandler(this.spinEdit1_ValueChanged);
//
// labelControl1
//
this.labelControl1.Location = new System.Drawing.Point(34, 49);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(75, 13);
this.labelControl1.TabIndex = 0;
this.labelControl1.Text = "Axis step range";
//
// simpleButton1
//
this.simpleButton1.Location = new System.Drawing.Point(376, 142);
this.simpleButton1.Name = "simpleButton1";
this.simpleButton1.Size = new System.Drawing.Size(75, 23);
this.simpleButton1.TabIndex = 1;
this.simpleButton1.Text = "Ok";
this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click);
//
// simpleButton2
//
this.simpleButton2.Location = new System.Drawing.Point(295, 142);
this.simpleButton2.Name = "simpleButton2";
this.simpleButton2.Size = new System.Drawing.Size(75, 23);
this.simpleButton2.TabIndex = 2;
this.simpleButton2.Text = "Cancel";
this.simpleButton2.Click += new System.EventHandler(this.simpleButton2_Click);
//
// frmBoostBiasRange
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(461, 175);
this.ControlBox = false;
this.Controls.Add(this.simpleButton2);
this.Controls.Add(this.simpleButton1);
this.Controls.Add(this.groupControl1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "frmBoostBiasRange";
this.ShowIcon = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Boost bias control trim";
((System.ComponentModel.ISupportInitialize)(this.groupControl1)).EndInit();
this.groupControl1.ResumeLayout(false);
this.groupControl1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraEditors.GroupControl groupControl1;
private DevExpress.XtraEditors.SpinEdit spinEdit3;
private DevExpress.XtraEditors.LabelControl labelControl3;
private DevExpress.XtraEditors.SpinEdit spinEdit4;
private DevExpress.XtraEditors.LabelControl labelControl4;
private DevExpress.XtraEditors.SpinEdit spinEdit1;
private DevExpress.XtraEditors.LabelControl labelControl1;
private DevExpress.XtraEditors.SimpleButton simpleButton1;
private DevExpress.XtraEditors.SimpleButton simpleButton2;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using GraphQL.Types;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using OrchardCore.Apis.GraphQL;
using OrchardCore.Apis.GraphQL.Queries;
using OrchardCore.Apis.GraphQL.Resolvers;
using OrchardCore.ContentManagement.GraphQL.Options;
using OrchardCore.ContentManagement.GraphQL.Queries.Predicates;
using OrchardCore.ContentManagement.GraphQL.Queries.Types;
using OrchardCore.ContentManagement.Records;
using OrchardCore.Environment.Shell;
using YesSql;
using Expression = OrchardCore.ContentManagement.GraphQL.Queries.Predicates.Expression;
namespace OrchardCore.ContentManagement.GraphQL.Queries
{
/// <summary>
/// This type is used by <see cref="ContentTypeQuery"/> to represent a query on a content type
/// </summary>
public class ContentItemsFieldType : FieldType
{
private static readonly List<string> ContentItemProperties;
private readonly int _defaultNumberOfItems;
static ContentItemsFieldType()
{
ContentItemProperties = new List<string>();
foreach (var property in typeof(ContentItemIndex).GetProperties())
{
ContentItemProperties.Add(property.Name);
}
}
public ContentItemsFieldType(string contentItemName, ISchema schema, IOptions<GraphQLContentOptions> optionsAccessor, IOptions<GraphQLSettings> settingsAccessor)
{
Name = "ContentItems";
Type = typeof(ListGraphType<ContentItemType>);
var whereInput = new ContentItemWhereInput(contentItemName, optionsAccessor);
var orderByInput = new ContentItemOrderByInput(contentItemName);
Arguments = new QueryArguments(
new QueryArgument<ContentItemWhereInput> { Name = "where", Description = "filters the content items", ResolvedType = whereInput },
new QueryArgument<ContentItemOrderByInput> { Name = "orderBy", Description = "sort order", ResolvedType = orderByInput },
new QueryArgument<IntGraphType> { Name = "first", Description = "the first n content items", ResolvedType = new IntGraphType() },
new QueryArgument<IntGraphType> { Name = "skip", Description = "the number of content items to skip", ResolvedType = new IntGraphType() },
new QueryArgument<PublicationStatusGraphType> { Name = "status", Description = "publication status of the content item", ResolvedType = new PublicationStatusGraphType(), DefaultValue = PublicationStatusEnum.Published }
);
Resolver = new LockedAsyncFieldResolver<IEnumerable<ContentItem>>(Resolve);
schema.RegisterType(whereInput);
schema.RegisterType(orderByInput);
schema.RegisterType<PublicationStatusGraphType>();
_defaultNumberOfItems = settingsAccessor.Value.DefaultNumberOfResults;
}
private async Task<IEnumerable<ContentItem>> Resolve(ResolveFieldContext context)
{
var graphContext = (GraphQLContext)context.UserContext;
var versionOption = VersionOptions.Published;
if (context.HasPopulatedArgument("status"))
{
versionOption = GetVersionOption(context.GetArgument<PublicationStatusEnum>("status"));
}
JObject where = null;
if (context.HasArgument("where"))
{
where = JObject.FromObject(context.Arguments["where"]);
}
var session = graphContext.ServiceProvider.GetService<ISession>();
var preQuery = session.Query<ContentItem>();
var filters = graphContext.ServiceProvider.GetServices<IGraphQLFilter<ContentItem>>();
foreach (var filter in filters)
{
preQuery = await filter.PreQueryAsync(preQuery, context);
}
var query = preQuery.With<ContentItemIndex>();
query = FilterVersion(query, versionOption);
query = FilterContentType(query, context);
query = OrderBy(query, context);
var contentItemsQuery = await FilterWhereArguments(query, where, context, session, graphContext);
contentItemsQuery = PageQuery(contentItemsQuery, context, graphContext);
var contentItems = await contentItemsQuery.ListAsync();
foreach (var filter in filters)
{
contentItems = await filter.PostQueryAsync(contentItems, context);
}
return contentItems;
}
private async Task<IQuery<ContentItem>> FilterWhereArguments(
IQuery<ContentItem, ContentItemIndex> query,
JObject where,
ResolveFieldContext fieldContext,
ISession session,
GraphQLContext context)
{
if (where == null)
{
return query;
}
var transaction = await session.DemandAsync();
IPredicateQuery predicateQuery = new PredicateQuery(
dialect: SqlDialectFactory.For(transaction.Connection),
shellSettings: context.ServiceProvider.GetService<ShellSettings>(),
propertyProviders: context.ServiceProvider.GetServices<IIndexPropertyProvider>());
// Create the default table alias
predicateQuery.CreateAlias("", nameof(ContentItemIndex));
// Add all provided table alias to the current predicate query
var providers = context.ServiceProvider.GetServices<IIndexAliasProvider>();
var indexes = new Dictionary<string, IndexAlias>(StringComparer.OrdinalIgnoreCase);
var indexAliases = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var aliasProvider in providers)
{
foreach (var alias in aliasProvider.GetAliases())
{
predicateQuery.CreateAlias(alias.Alias, alias.Index);
indexAliases.Add(alias.Alias, alias.Alias);
if (!indexes.ContainsKey(alias.Index))
{
indexes.Add(alias.Index, alias);
}
}
}
var expressions = Expression.Conjunction();
BuildWhereExpressions(where, expressions, null, fieldContext, indexAliases);
var whereSqlClause = expressions.ToSqlString(predicateQuery);
query = query.Where(whereSqlClause);
// Add all parameters that were used in the predicate query
foreach (var parameter in predicateQuery.Parameters)
{
query = query.WithParameter(parameter.Key, parameter.Value);
}
// Add all Indexes that were used in the predicate query
IQuery<ContentItem> contentQuery = query;
foreach (var usedAlias in predicateQuery.GetUsedAliases())
{
if (indexes.ContainsKey(usedAlias))
{
contentQuery = indexes[usedAlias].With(contentQuery);
}
}
return contentQuery;
}
private IQuery<ContentItem> PageQuery(IQuery<ContentItem> contentItemsQuery, ResolveFieldContext context, GraphQLContext graphQLContext)
{
var first = context.GetArgument<int>("first");
if (first == 0)
{
first = _defaultNumberOfItems;
}
contentItemsQuery = contentItemsQuery.Take(first);
if (context.HasPopulatedArgument("skip"))
{
var skip = context.GetArgument<int>("skip");
contentItemsQuery = contentItemsQuery.Skip(skip);
}
return contentItemsQuery;
}
private VersionOptions GetVersionOption(PublicationStatusEnum status)
{
switch (status)
{
case PublicationStatusEnum.Published: return VersionOptions.Published;
case PublicationStatusEnum.Draft: return VersionOptions.Draft;
case PublicationStatusEnum.Latest: return VersionOptions.Latest;
case PublicationStatusEnum.All: return VersionOptions.AllVersions;
default: return VersionOptions.Published;
}
}
private static IQuery<ContentItem, ContentItemIndex> FilterContentType(IQuery<ContentItem, ContentItemIndex> query, ResolveFieldContext context)
{
var contentType = ((ListGraphType)context.ReturnType).ResolvedType.Name;
return query.Where(q => q.ContentType == contentType);
}
private static IQuery<ContentItem, ContentItemIndex> FilterVersion(IQuery<ContentItem, ContentItemIndex> query, VersionOptions versionOption)
{
if (versionOption.IsPublished)
{
query = query.Where(q => q.Published == true);
}
else if (versionOption.IsDraft)
{
query = query.Where(q => q.Latest == true && q.Published == false);
}
else if (versionOption.IsLatest)
{
query = query.Where(q => q.Latest == true);
}
return query;
}
private void BuildWhereExpressions(JToken where, Junction expressions, string tableAlias, ResolveFieldContext fieldContext, IDictionary<string, string> indexAliases)
{
if (where is JArray array)
{
foreach (var child in array.Children())
{
if (child is JObject whereObject)
{
BuildExpressionsInternal(whereObject, expressions, tableAlias, fieldContext, indexAliases);
}
}
}
else if (where is JObject whereObject)
{
BuildExpressionsInternal(whereObject, expressions, tableAlias, fieldContext, indexAliases);
}
}
private void BuildExpressionsInternal(JObject where, Junction expressions, string tableAlias, ResolveFieldContext fieldContext, IDictionary<string, string> indexAliases)
{
foreach (var entry in where.Properties())
{
IPredicate expression = null;
var values = entry.Name.Split('_', 2);
// Gets the full path name without the comparison e.g. aliasPart.alias, not aliasPart.alias_contains.
var property = values[0];
// figure out table aliases for collapsed parts and ones with the part suffix removed by the dsl
if (tableAlias == null || !tableAlias.EndsWith("Part", StringComparison.OrdinalIgnoreCase))
{
var whereArgument = fieldContext?.FieldDefinition?.Arguments.FirstOrDefault(x => x.Name == "where");
if (whereArgument != null)
{
var whereInput = (WhereInputObjectGraphType)whereArgument.ResolvedType;
foreach (var field in whereInput.Fields.Where(x => x.GetMetadata<string>("PartName") != null))
{
var partName = field.GetMetadata<string>("PartName");
if ((tableAlias == null && field.GetMetadata<bool>("PartCollapsed") && field.Name.Equals(property, StringComparison.OrdinalIgnoreCase)) ||
(tableAlias != null && partName.ToFieldName().Equals(tableAlias, StringComparison.OrdinalIgnoreCase)))
{
tableAlias = indexAliases.TryGetValue(partName, out var indexTableAlias) ? indexTableAlias : tableAlias;
break;
}
}
}
}
if (tableAlias != null)
{
property = $"{tableAlias}.{property}";
}
if (values.Length == 1)
{
if (string.Equals(values[0], "or", StringComparison.OrdinalIgnoreCase))
{
expression = Expression.Disjunction();
BuildWhereExpressions(entry.Value, (Junction)expression, tableAlias, fieldContext, indexAliases);
}
else if (string.Equals(values[0], "and", StringComparison.OrdinalIgnoreCase))
{
expression = Expression.Conjunction();
BuildWhereExpressions(entry.Value, (Junction)expression, tableAlias, fieldContext, indexAliases);
}
else if (string.Equals(values[0], "not", StringComparison.OrdinalIgnoreCase))
{
expression = Expression.Conjunction();
BuildWhereExpressions(entry.Value, (Junction)expression, tableAlias, fieldContext, indexAliases);
expression = Expression.Not(expression);
}
else if (entry.HasValues && entry.Value.Type == JTokenType.Object)
{
// Loop through the part's properties, passing the name of the part as the table tableAlias.
// This tableAlias can then be used with the table alias to index mappings to join with the correct table.
BuildWhereExpressions(entry.Value, expressions, values[0], fieldContext, indexAliases);
}
else
{
var propertyValue = entry.Value.ToObject<object>();
expression = Expression.Equal(property, propertyValue);
}
}
else
{
var value = entry.Value.ToObject<object>();
switch (values[1])
{
case "not": expression = Expression.Not(Expression.Equal(property, value)); break;
case "gt": expression = Expression.GreaterThan(property, value); break;
case "gte": expression = Expression.GreaterThanOrEqual(property, value); break;
case "lt": expression = Expression.LessThan(property, value); break;
case "lte": expression = Expression.LessThanOrEqual(property, value); break;
case "contains": expression = Expression.Like(property, (string)value, MatchOptions.Contains); break;
case "not_contains": expression = Expression.Not(Expression.Like(property, (string)value, MatchOptions.Contains)); break;
case "starts_with": expression = Expression.Like(property, (string)value, MatchOptions.StartsWith); break;
case "not_starts_with": expression = Expression.Not(Expression.Like(property, (string)value, MatchOptions.StartsWith)); break;
case "ends_with": expression = Expression.Like(property, (string)value, MatchOptions.EndsWith); break;
case "not_ends_with": expression = Expression.Not(Expression.Like(property, (string)value, MatchOptions.EndsWith)); break;
case "in": expression = Expression.In(property, entry.Value.ToObject<object[]>()); break;
case "not_in": expression = Expression.Not(Expression.In(property, entry.Value.ToObject<object[]>())); break;
default: expression = Expression.Equal(property, value); break;
}
}
if (expression != null)
{
expressions.Add(expression);
}
}
}
private IQuery<ContentItem, ContentItemIndex> OrderBy(IQuery<ContentItem, ContentItemIndex> query,
ResolveFieldContext context)
{
if (context.HasPopulatedArgument("orderBy"))
{
var orderByArguments = JObject.FromObject(context.Arguments["orderBy"]);
if (orderByArguments != null)
{
var thenBy = false;
foreach (var property in orderByArguments.Properties())
{
var direction = (OrderByDirection)property.Value.Value<int>();
Expression<Func<ContentItemIndex, object>> selector = null;
switch (property.Name)
{
case "contentItemId": selector = x => x.ContentItemId; break;
case "contentItemVersionId": selector = x => x.ContentItemVersionId; break;
case "displayText": selector = x => x.DisplayText; break;
case "published": selector = x => x.Published; break;
case "latest": selector = x => x.Latest; break;
case "createdUtc": selector = x => x.CreatedUtc; break;
case "modifiedUtc": selector = x => x.ModifiedUtc; break;
case "publishedUtc": selector = x => x.PublishedUtc; break;
case "owner": selector = x => x.Owner; break;
case "author": selector = x => x.Author; break;
}
if (selector != null)
{
if (!thenBy)
{
query = direction == OrderByDirection.Ascending
? query.OrderBy(selector)
: query.OrderByDescending(selector)
;
}
else
{
query = direction == OrderByDirection.Ascending
? query.ThenBy(selector)
: query.ThenByDescending(selector)
;
}
thenBy = true;
}
}
}
}
else
{
query = query.OrderByDescending(x => x.CreatedUtc);
}
return query;
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="YEdStateMachineReportGenerator.cs" company="Appccelerate">
// Copyright (c) 2008-2015
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.Reports
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Appccelerate.StateMachine.Machine;
using Appccelerate.StateMachine.Machine.Transitions;
/// <summary>
/// generates a graph meta language file that can be read by yEd.
/// </summary>
/// <typeparam name="TState">The type of the state.</typeparam>
/// <typeparam name="TEvent">The type of the event.</typeparam>
public class YEdStateMachineReportGenerator<TState, TEvent> : IStateMachineReport<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
// ReSharper disable StaticFieldInGenericType
private static readonly XNamespace N = "http://graphml.graphdrawing.org/xmlns";
private static readonly XNamespace Xsi = "http://www.w3.org/2001/XMLSchema-instance";
private static readonly XNamespace Y = "http://www.yworks.com/xml/graphml";
private static readonly XNamespace YEd = "http://www.yworks.com/xml/yed/3";
private static readonly XNamespace SchemaLocation = "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd";
// ReSharper restore StaticFieldInGenericType
private readonly TextWriter textWriter;
private int edgeId;
private Initializable<TState> initialStateId;
/// <summary>
/// Initializes a new instance of the <see cref="YEdStateMachineReportGenerator<TState, TEvent>"/> class.
/// </summary>
/// <param name="textWriter">The output writer.</param>
public YEdStateMachineReportGenerator(TextWriter textWriter)
{
this.textWriter = textWriter;
}
/// <summary>
/// Generates a report of the state machine.
/// </summary>
/// <param name="name">The name of the state machine.</param>
/// <param name="states">The states.</param>
/// <param name="initialState">The initial state id.</param>
public void Report(string name, IEnumerable<IState<TState, TEvent>> states, Initializable<TState> initialState)
{
var statesList = states.ToList();
this.edgeId = 0;
this.initialStateId = initialState;
Ensure.ArgumentNotNull(statesList, "states");
XElement graph = CreateGraph();
this.AddNodes(graph, statesList);
this.AddEdges(graph, statesList);
XDocument doc = CreateXmlDocument(graph);
doc.Save(this.textWriter);
}
private static XElement CreateGraph()
{
return new XElement(N + "graph", new XAttribute("edgedefault", "directed"), new XAttribute("id", "G"));
}
private static XDocument CreateXmlDocument(XElement graph)
{
var doc = new XDocument(
new XElement(
N + "graphml",
new XComment("Created by Appccelerate.StateMachine.YEdStateMachineReportGenerator"),
new XElement(N + "key", new XAttribute("for", "graphml"), new XAttribute("id", "d0"), new XAttribute("yfiles.type", "resources")),
new XElement(N + "key", new XAttribute("for", "port"), new XAttribute("id", "d1"), new XAttribute("yfiles.type", "portgraphics")),
new XElement(N + "key", new XAttribute("for", "port"), new XAttribute("id", "d2"), new XAttribute("yfiles.type", "portgeometry")),
new XElement(N + "key", new XAttribute("for", "port"), new XAttribute("id", "d3"), new XAttribute("yfiles.type", "portuserdata")),
new XElement(N + "key", new XAttribute("attr.name", "url"), new XAttribute("attr.type", "string"), new XAttribute("for", "node"), new XAttribute("id", "d4")),
new XElement(N + "key", new XAttribute("attr.name", "description"), new XAttribute("attr.type", "string"), new XAttribute("for", "node"), new XAttribute("id", "d5")),
new XElement(N + "key", new XAttribute("for", "node"), new XAttribute("id", "d6"), new XAttribute("yfiles.type", "nodegraphics")),
new XElement(N + "key", new XAttribute("attr.name", "Beschreibung"), new XAttribute("attr.type", "string"), new XAttribute("for", "graph"), new XAttribute("id", "d7"), new XElement(N + "default")),
new XElement(N + "key", new XAttribute("attr.name", "url"), new XAttribute("attr.type", "string"), new XAttribute("for", "edge"), new XAttribute("id", "d8")),
new XElement(N + "key", new XAttribute("attr.name", "description"), new XAttribute("attr.type", "string"), new XAttribute("for", "edge"), new XAttribute("id", "d9")),
new XElement(N + "key", new XAttribute("for", "edge"), new XAttribute("id", "d10"), new XAttribute("yfiles.type", "edgegraphics")),
graph,
new XElement(N + "data", new XAttribute("key", "d0"), new XElement(Y + "Resources"))));
doc.Root.SetAttributeValue(XNamespace.Xmlns + "y", Y);
doc.Root.SetAttributeValue(XNamespace.Xmlns + "xsi", Xsi);
doc.Root.SetAttributeValue(XNamespace.Xmlns + "yed", YEd);
doc.Root.SetAttributeValue(XNamespace.Xmlns + "schemaLocation", SchemaLocation);
return doc;
}
private static string CreateExitActionsDescription(IState<TState, TEvent> state)
{
return state.ExitActions.Any()
? (state.ExitActions.Aggregate(Environment.NewLine + "(", (aggregate, action) => (aggregate.Length > 3 ? aggregate + ", " : aggregate) + action.Describe()) + ")")
: string.Empty;
}
private static string CreateEntryActionDescription(IState<TState, TEvent> state)
{
return state.EntryActions.Any()
? (state.EntryActions.Aggregate("(", (aggregate, action) => (aggregate.Length > 1 ? aggregate + ", " : aggregate) + action.Describe()) + ")" + Environment.NewLine)
: string.Empty;
}
private static string CreateGuardDescription(TransitionInfo<TState, TEvent> transition)
{
return transition.Guard != null ? "[" + transition.Guard.Describe() + "]" : string.Empty;
}
private static string CreateActionsDescription(TransitionInfo<TState, TEvent> transition)
{
return transition.Actions.Any() ? (transition.Actions.Aggregate("(", (aggregate, action) => (aggregate.Length > 1 ? aggregate + ", " : aggregate) + action.Describe()) + ")") : string.Empty;
}
private void AddEdges(XElement graph, IEnumerable<IState<TState, TEvent>> states)
{
foreach (var state in states)
{
foreach (var transition in state.Transitions.GetTransitions())
{
this.AddEdge(graph, transition);
}
}
}
private void AddEdge(XElement graph, TransitionInfo<TState, TEvent> transition)
{
string actions = CreateActionsDescription(transition);
string guard = CreateGuardDescription(transition);
string arrow;
string lineStyle;
string targetId;
if (transition.Target != null)
{
arrow = "standard";
lineStyle = "line";
targetId = transition.Target.Id.ToString();
}
else
{
arrow = "plain";
lineStyle = "dashed";
targetId = transition.Source.Id.ToString();
}
var edge = new XElement(
N + "edge",
new XAttribute("id", transition.EventId + (this.edgeId++).ToString(CultureInfo.InvariantCulture)),
new XAttribute("source", transition.Source.Id),
new XAttribute("target", targetId));
edge.Add(new XElement(
N + "data",
new XAttribute("key", "d10"),
new XElement(Y + "PolyLineEdge", new XElement(Y + "LineStyle", new XAttribute("type", lineStyle)), new XElement(Y + "Arrows", new XAttribute("source", "none"), new XAttribute("target", arrow)), new XElement(Y + "EdgeLabel", guard + transition.EventId + actions))));
graph.Add(edge);
}
private void AddNodes(XElement graph, IEnumerable<IState<TState, TEvent>> states)
{
foreach (var state in states.Where(s => s.SuperState == null))
{
this.AddNode(graph, state);
}
}
private void AddNode(XElement graph, IState<TState, TEvent> state)
{
var node = new XElement(N + "node", new XAttribute("id", state.Id.ToString()));
bool initialState = this.DetermineWhetherThisIsAnInitialState(state);
string entryActions = CreateEntryActionDescription(state);
string exitActions = CreateExitActionsDescription(state);
if (state.SubStates.Any())
{
var label = new XElement(Y + "NodeLabel", entryActions + state.Id + exitActions, new XAttribute("alignment", "right"), new XAttribute("autoSizePolicy", "node_width"), new XAttribute("backgroundColor", "#EBEBEB"), new XAttribute("modelName", "internal"), new XAttribute("modelPosition", "t"));
var groupNode = new XElement(Y + "GroupNode", label, new XElement(Y + "State", new XAttribute("closed", "false"), new XAttribute("innerGraphDisplayEnabled", "true")));
node.Add(new XElement(N + "data", new XAttribute("key", "d6"), new XElement(Y + "ProxyAutoBoundsNode", new XElement(Y + "Realizers", new XAttribute("active", "0"), groupNode))));
if (initialState)
{
groupNode.Add(new XElement(Y + "BorderStyle", new XAttribute("width", "2.0")));
}
var subGraph = new XElement(N + "graph", new XAttribute("edgedefault", "directed"), new XAttribute("id", state.Id + ":"));
node.Add(subGraph);
foreach (var subState in state.SubStates)
{
this.AddNode(subGraph, subState);
}
}
else
{
var shape = new XElement(
Y + "ShapeNode",
new XElement(Y + "NodeLabel", entryActions + state.Id + exitActions),
new XElement(Y + "Shape", new XAttribute("type", "ellipse")));
if (initialState)
{
shape.Add(new XElement(Y + "BorderStyle", new XAttribute("width", "2.0")));
}
node.Add(new XElement(N + "data", new XAttribute("key", "d6"), shape));
}
graph.Add(node);
}
private bool DetermineWhetherThisIsAnInitialState(IState<TState, TEvent> state)
{
return (this.initialStateId.IsInitialized && state.Id.ToString() == this.initialStateId.Value.ToString()) || (state.SuperState != null && state.SuperState.InitialState == state);
}
}
}
| |
/*
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
namespace CleanSqlite
{
public partial class Sqlite3
{
//#define TK_SEMI 1
//#define TK_EXPLAIN 2
//#define TK_QUERY 3
//#define TK_PLAN 4
//#define TK_BEGIN 5
//#define TK_TRANSACTION 6
//#define TK_DEFERRED 7
//#define TK_IMMEDIATE 8
//#define TK_EXCLUSIVE 9
//#define TK_COMMIT 10
//#define TK_END 11
//#define TK_ROLLBACK 12
//#define TK_SAVEPOINT 13
//#define TK_RELEASE 14
//#define TK_TO 15
//#define TK_TABLE 16
//#define TK_CREATE 17
//#define TK_IF 18
//#define TK_NOT 19
//#define TK_EXISTS 20
//#define TK_TEMP 21
//#define TK_LP 22
//#define TK_RP 23
//#define TK_AS 24
//#define TK_COMMA 25
//#define TK_ID 26
//#define TK_INDEXED 27
//#define TK_ABORT 28
//#define TK_ACTION 29
//#define TK_AFTER 30
//#define TK_ANALYZE 31
//#define TK_ASC 32
//#define TK_ATTACH 33
//#define TK_BEFORE 34
//#define TK_BY 35
//#define TK_CASCADE 36
//#define TK_CAST 37
//#define TK_COLUMNKW 38
//#define TK_CONFLICT 39
//#define TK_DATABASE 40
//#define TK_DESC 41
//#define TK_DETACH 42
//#define TK_EACH 43
//#define TK_FAIL 44
//#define TK_FOR 45
//#define TK_IGNORE 46
//#define TK_INITIALLY 47
//#define TK_INSTEAD 48
//#define TK_LIKE_KW 49
//#define TK_MATCH 50
//#define TK_NO 51
//#define TK_KEY 52
//#define TK_OF 53
//#define TK_OFFSET 54
//#define TK_PRAGMA 55
//#define TK_RAISE 56
//#define TK_REPLACE 57
//#define TK_RESTRICT 58
//#define TK_ROW 59
//#define TK_TRIGGER 60
//#define TK_VACUUM 61
//#define TK_VIEW 62
//#define TK_VIRTUAL 63
//#define TK_REINDEX 64
//#define TK_RENAME 65
//#define TK_CTIME_KW 66
//#define TK_ANY 67
//#define TK_OR 68
//#define TK_AND 69
//#define TK_IS 70
//#define TK_BETWEEN 71
//#define TK_IN 72
//#define TK_ISNULL 73
//#define TK_NOTNULL 74
//#define TK_NE 75
//#define TK_EQ 76
//#define TK_GT 77
//#define TK_LE 78
//#define TK_LT 79
//#define TK_GE 80
//#define TK_ESCAPE 81
//#define TK_BITAND 82
//#define TK_BITOR 83
//#define TK_LSHIFT 84
//#define TK_RSHIFT 85
//#define TK_PLUS 86
//#define TK_MINUS 87
//#define TK_STAR 88
//#define TK_SLASH 89
//#define TK_REM 90
//#define TK_CONCAT 91
//#define TK_COLLATE 92
//#define TK_BITNOT 93
//#define TK_STRING 94
//#define TK_JOIN_KW 95
//#define TK_CONSTRAINT 96
//#define TK_DEFAULT 97
//#define TK_NULL 98
//#define TK_PRIMARY 99
//#define TK_UNIQUE 100
//#define TK_CHECK 101
//#define TK_REFERENCES 102
//#define TK_AUTOINCR 103
//#define TK_ON 104
//#define TK_INSERT 105
//#define TK_DELETE 106
//#define TK_UPDATE 107
//#define TK_SET 108
//#define TK_DEFERRABLE 109
//#define TK_FOREIGN 110
//#define TK_DROP 111
//#define TK_UNION 112
//#define TK_ALL 113
//#define TK_EXCEPT 114
//#define TK_INTERSECT 115
//#define TK_SELECT 116
//#define TK_DISTINCT 117
//#define TK_DOT 118
//#define TK_FROM 119
//#define TK_JOIN 120
//#define TK_USING 121
//#define TK_ORDER 122
//#define TK_GROUP 123
//#define TK_HAVING 124
//#define TK_LIMIT 125
//#define TK_WHERE 126
//#define TK_INTO 127
//#define TK_VALUES 128
//#define TK_INTEGER 129
//#define TK_FLOAT 130
//#define TK_BLOB 131
//#define TK_REGISTER 132
//#define TK_VARIABLE 133
//#define TK_CASE 134
//#define TK_WHEN 135
//#define TK_THEN 136
//#define TK_ELSE 137
//#define TK_INDEX 138
//#define TK_ALTER 139
//#define TK_ADD 140
//#define TK_TO_TEXT 141
//#define TK_TO_BLOB 142
//#define TK_TO_NUMERIC 143
//#define TK_TO_INT 144
//#define TK_TO_REAL 145
//#define TK_ISNOT 146
//#define TK_END_OF_FILE 147
//#define TK_ILLEGAL 148
//#define TK_SPACE 149
//#define TK_UNCLOSED_STRING 150
//#define TK_FUNCTION 151
//#define TK_COLUMN 152
//#define TK_AGG_FUNCTION 153
//#define TK_AGG_COLUMN 154
//#define TK_CONST_FUNC 155
//#define TK_UMINUS 156
//#define TK_UPLUS 157
public const int TK_SEMI = 1;
public const int TK_EXPLAIN = 2;
public const int TK_QUERY = 3;
public const int TK_PLAN = 4;
public const int TK_BEGIN = 5;
public const int TK_TRANSACTION = 6;
public const int TK_DEFERRED = 7;
public const int TK_IMMEDIATE = 8;
public const int TK_EXCLUSIVE = 9;
public const int TK_COMMIT = 10;
public const int TK_END = 11;
public const int TK_ROLLBACK = 12;
public const int TK_SAVEPOINT = 13;
public const int TK_RELEASE = 14;
public const int TK_TO = 15;
public const int TK_TABLE = 16;
public const int TK_CREATE = 17;
public const int TK_IF = 18;
public const int TK_NOT = 19;
public const int TK_EXISTS = 20;
public const int TK_TEMP = 21;
public const int TK_LP = 22;
public const int TK_RP = 23;
public const int TK_AS = 24;
public const int TK_COMMA = 25;
public const int TK_ID = 26;
public const int TK_INDEXED = 27;
public const int TK_ABORT = 28;
public const int TK_ACTION = 29;
public const int TK_AFTER = 30;
public const int TK_ANALYZE = 31;
public const int TK_ASC = 32;
public const int TK_ATTACH = 33;
public const int TK_BEFORE = 34;
public const int TK_BY = 35;
public const int TK_CASCADE = 36;
public const int TK_CAST = 37;
public const int TK_COLUMNKW = 38;
public const int TK_CONFLICT = 39;
public const int TK_DATABASE = 40;
public const int TK_DESC = 41;
public const int TK_DETACH = 42;
public const int TK_EACH = 43;
public const int TK_FAIL = 44;
public const int TK_FOR = 45;
public const int TK_IGNORE = 46;
public const int TK_INITIALLY = 47;
public const int TK_INSTEAD = 48;
public const int TK_LIKE_KW = 49;
public const int TK_MATCH = 50;
public const int TK_NO = 51;
public const int TK_KEY = 52;
public const int TK_OF = 53;
public const int TK_OFFSET = 54;
public const int TK_PRAGMA = 55;
public const int TK_RAISE = 56;
public const int TK_REPLACE = 57;
public const int TK_RESTRICT = 58;
public const int TK_ROW = 59;
public const int TK_TRIGGER = 60;
public const int TK_VACUUM = 61;
public const int TK_VIEW = 62;
public const int TK_VIRTUAL = 63;
public const int TK_REINDEX = 64;
public const int TK_RENAME = 65;
public const int TK_CTIME_KW = 66;
public const int TK_ANY = 67;
public const int TK_OR = 68;
public const int TK_AND = 69;
public const int TK_IS = 70;
public const int TK_BETWEEN = 71;
public const int TK_IN = 72;
public const int TK_ISNULL = 73;
public const int TK_NOTNULL = 74;
public const int TK_NE = 75;
public const int TK_EQ = 76;
public const int TK_GT = 77;
public const int TK_LE = 78;
public const int TK_LT = 79;
public const int TK_GE = 80;
public const int TK_ESCAPE = 81;
public const int TK_BITAND = 82;
public const int TK_BITOR = 83;
public const int TK_LSHIFT = 84;
public const int TK_RSHIFT = 85;
public const int TK_PLUS = 86;
public const int TK_MINUS = 87;
public const int TK_STAR = 88;
public const int TK_SLASH = 89;
public const int TK_REM = 90;
public const int TK_CONCAT = 91;
public const int TK_COLLATE = 92;
public const int TK_BITNOT = 93;
public const int TK_STRING = 94;
public const int TK_JOIN_KW = 95;
public const int TK_CONSTRAINT = 96;
public const int TK_DEFAULT = 97;
public const int TK_NULL = 98;
public const int TK_PRIMARY = 99;
public const int TK_UNIQUE = 100;
public const int TK_CHECK = 101;
public const int TK_REFERENCES = 102;
public const int TK_AUTOINCR = 103;
public const int TK_ON = 104;
public const int TK_INSERT = 105;
public const int TK_DELETE = 106;
public const int TK_UPDATE = 107;
public const int TK_SET = 108;
public const int TK_DEFERRABLE = 109;
public const int TK_FOREIGN = 110;
public const int TK_DROP = 111;
public const int TK_UNION = 112;
public const int TK_ALL = 113;
public const int TK_EXCEPT = 114;
public const int TK_INTERSECT = 115;
public const int TK_SELECT = 116;
public const int TK_DISTINCT = 117;
public const int TK_DOT = 118;
public const int TK_FROM = 119;
public const int TK_JOIN = 120;
public const int TK_USING = 121;
public const int TK_ORDER = 122;
public const int TK_GROUP = 123;
public const int TK_HAVING = 124;
public const int TK_LIMIT = 125;
public const int TK_WHERE = 126;
public const int TK_INTO = 127;
public const int TK_VALUES = 128;
public const int TK_INTEGER = 129;
public const int TK_FLOAT = 130;
public const int TK_BLOB = 131;
public const int TK_REGISTER = 132;
public const int TK_VARIABLE = 133;
public const int TK_CASE = 134;
public const int TK_WHEN = 135;
public const int TK_THEN = 136;
public const int TK_ELSE = 137;
public const int TK_INDEX = 138;
public const int TK_ALTER = 139;
public const int TK_ADD = 140;
public const int TK_TO_TEXT = 141;
public const int TK_TO_BLOB = 142;
public const int TK_TO_NUMERIC = 143;
public const int TK_TO_INT = 144;
public const int TK_TO_REAL = 145;
public const int TK_ISNOT = 146;
public const int TK_END_OF_FILE = 147;
public const int TK_ILLEGAL = 148;
public const int TK_SPACE = 149;
public const int TK_UNCLOSED_STRING = 150;
public const int TK_FUNCTION = 151;
public const int TK_COLUMN = 152;
public const int TK_AGG_FUNCTION = 153;
public const int TK_AGG_COLUMN = 154;
public const int TK_CONST_FUNC = 155;
public const int TK_UMINUS = 156;
public const int TK_UPLUS = 157;
}
}
| |
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
public class UseRenderingPlugin : MonoBehaviour
{
int width = 1024;
int height = 576;
// int width = 1280;
// int height = 7;
public Texture2D tex;
int startCount = 0;
int awakeCount = 0;
Camera movingCamera;
Color[] blackTexture;
//public GameObject sys;
//private MainScript mainScript;
Color[] correctSelectionIndicator;
Color[] incorrectSelectionIndicator;
[DllImport("UnityServerPlugin")]
private static extern void SetTextureFromUnity(System.IntPtr texture);
[DllImport("UnityServerPlugin")]
private static extern void setLog();
[DllImport("UnityServerPlugin")]
private static extern void endServer();
[DllImport("UnityServerPlugin")]
private static extern void SetTimeFromUnity(float t);
void Awake()
{
setLog();
//Texture2D ci = (Texture2D)Resources.Load("CorrectSelection", typeof(Texture2D));
//Texture2D ii = (Texture2D)Resources.Load("IncorrectSelection", typeof(Texture2D));
//correctSelectionIndicator = ci.GetPixels();
//incorrectSelectionIndicator = ii.GetPixels();
blackTexture = new Color[width * height];
for (int i = 0; i < width * height; i++)
{
blackTexture[i] = Color.black;
}
//sys = GameObject.Find("System");
//mainScript = sys.GetComponent<MainScript>();
ServerThread server = new ServerThread();
Thread st = new Thread(new ThreadStart(server.startServer));
st.Start();
Debug.Log("Started Server");
OSCPhaseSpaceThread oscPSClient = new OSCPhaseSpaceThread();
Thread oscPSt = new Thread(new ThreadStart(oscPSClient.startServer));
oscPSt.Start();
Debug.Log("Started OSC Client");
OSCThread oscClient = new OSCThread();
Thread osct = new Thread(new ThreadStart(oscClient.startServer));
osct.Start();
}
public float posX = 512f; //Position the DrawTexture command while testing.
public float posY = 512f;
Texture2D ARSelectionTexture;
//void Start(){
//Debug.Log ("Started.");
IEnumerator Start()
{
ARSelectionTexture = Resources.Load("GUISelectionBox") as Texture2D;
CreateTextureAndPassToPlugin();
yield return StartCoroutine("CallPluginAtEndOfFrames");
}
void OnApplicationQuit()
{
PlayerPrefs.Save();
endServer();
}
bool drawIndicator = false;
float startTime;
public void drawSelectionIndication()
{
drawIndicator = true;
startTime = Time.time; // set start time for timer
}
private void CreateTextureAndPassToPlugin()
{
//movingCamera = GameObject.Find("MonoCamera").GetComponent<Camera>();//Camera.allCameras[2];
movingCamera = GameObject.Find("Camera").GetComponent<Camera>();//Camera.allCameras[2]; //**This is the stereo renderer
//movingCamera.rect = new Rect(0,0,width,height);
// Create a texture
tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// Set point filtering just so we can see the pixels clearly
//tex.filterMode = FilterMode.Point;
// Call Apply() so it's actually uploaded to the GPU
tex.Apply();
// Set texture onto our matrial
//renderer.material.mainTexture = tex;
// Pass texture pointer to the plugin
SetTextureFromUnity(tex.GetNativeTexturePtr());
}
int num = 0;
private IEnumerator CallPluginAtEndOfFrames()
{
while (true)
{
if (Input.GetKeyDown("f"))
{
Screen.fullScreen = !Screen.fullScreen;
}
if (Input.GetKeyDown("q"))
{
endServer();
Application.Quit();
}
// Wait until all frame rendering is done
yield return new WaitForEndOfFrame();
//Need to call this (or any plugin function) to keep calling native rendering events
//SetTextureFromUnity(tex.GetNativeTexturePtr());
//movingCamera.Render();
RenderTexture.active = movingCamera.targetTexture;
// if(mainScript.getExperimentInterface() == (int)MainScript.interfaces.Pointing)
// {
//tex.SetPixels(blackTexture);
// }
// else
// {
tex.ReadPixels(new Rect(0, 224 /*192*/, width, height), 0, 0);
//tex.Apply ();
//}
// if(drawIndicator)
// {
//
// tex.SetPixels (0,0,64,64,correctSelectionIndicator);
// }
//tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
RenderTexture.active = null;
//if(drawIndicator)
//
// RenderTexture.active = movingCamera.targetTexture;
// //RenderTexture.active = cam3.targetTexture; //Set my RenderTexture active so DrawTexture will draw to it.
// GL.PushMatrix (); //Saves both projection and modelview matrices to the matrix stack.
// GL.LoadPixelMatrix (0, 1024, 1024, 0); //Setup a matrix for pixel-correct rendering.
// //Draw my stampTexture on my RenderTexture positioned by posX and posY.
// Graphics.DrawTexture (new Rect (posX - ARSelectionTexture.width / 2, (1024 - posY) - ARSelectionTexture.height / 2, ARSelectionTexture.width, ARSelectionTexture.height), ARSelectionTexture);
// GL.PopMatrix (); //Restores both projection and modelview matrices off the top of the matrix stack.
// RenderTexture.active = null; //De-activate my RenderTexture.
tex.Apply();
//var bytes = tex.EncodeToPNG();
//File.WriteAllBytes(Application.dataPath + "/../SavedScreen" + num + ".png", bytes);
//num++;
GL.IssuePluginEvent(0);
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
#if DEBUG
//#define MINIMAP_DEBUG
#endif
namespace System.Activities.Presentation
{
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Windows.Threading;
using System.Globalization;
// This class is a control displaying minimap of the attached scrollableview control
// this class's functionality is limited to delegating events to minimap view controller
partial class MiniMapControl : UserControl
{
public static readonly DependencyProperty MapSourceProperty =
DependencyProperty.Register("MapSource",
typeof(ScrollViewer),
typeof(MiniMapControl),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnMapSourceChanged)));
MiniMapViewController lookupWindowManager;
bool isMouseDown = false;
public MiniMapControl()
{
InitializeComponent();
this.lookupWindowManager = new MiniMapViewController(this.lookupCanvas, this.lookupWindow, this.contentGrid);
}
public ScrollViewer MapSource
{
get { return GetValue(MapSourceProperty) as ScrollViewer; }
set { SetValue(MapSourceProperty, value); }
}
static void OnMapSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
MiniMapControl mapControl = (MiniMapControl)sender;
mapControl.lookupWindowManager.MapSource = mapControl.MapSource;
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
if (this.lookupWindowManager.StartMapLookupDrag(e))
{
this.CaptureMouse();
this.isMouseDown = true;
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (this.isMouseDown)
{
this.lookupWindowManager.DoMapLookupDrag(e);
}
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonUp(e);
if (this.isMouseDown)
{
Mouse.Capture(null);
this.isMouseDown = false;
this.lookupWindowManager.StopMapLookupDrag();
}
}
protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
{
this.lookupWindowManager.CenterView(e);
e.Handled = true;
base.OnMouseDoubleClick(e);
}
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
this.lookupWindowManager.MapViewSizeChanged(sizeInfo);
}
// This class wraps positioning and calculating logic of the map view lookup window
// It is also responsible for handling mouse movements
internal class LookupWindow
{
Point mousePosition;
Rectangle lookupWindowRectangle;
MiniMapViewController parent;
public LookupWindow(MiniMapViewController parent, Rectangle lookupWindowRectangle)
{
this.mousePosition = new Point();
this.parent = parent;
this.lookupWindowRectangle = lookupWindowRectangle;
}
public double Left
{
get { return Canvas.GetLeft(this.lookupWindowRectangle); }
set
{
//check if left corner is within minimap's range - clip if necessary
double left = Math.Max(value - this.mousePosition.X, 0.0);
//check if right corner is within minimap's range - clip if necessary
left = (left + Width > this.parent.MapWidth ? this.parent.MapWidth - Width : left);
//update canvas
Canvas.SetLeft(this.lookupWindowRectangle, left);
}
}
public double Top
{
get { return Canvas.GetTop(this.lookupWindowRectangle); }
set
{
//check if top corner is within minimap's range - clip if necessary
double top = Math.Max(value - this.mousePosition.Y, 0.0);
//check if bottom corner is within minimap's range - clip if necessary
top = (top + Height > this.parent.MapHeight ? this.parent.MapHeight - Height : top);
//update canvas
Canvas.SetTop(this.lookupWindowRectangle, top);
}
}
public double Width
{
get { return this.lookupWindowRectangle.Width; }
set { this.lookupWindowRectangle.Width = value; }
}
public double Height
{
get { return this.lookupWindowRectangle.Height; }
set { this.lookupWindowRectangle.Height = value; }
}
public double MapCenterXPoint
{
get { return this.Left + (this.Width / 2.0); }
}
public double MapCenterYPoint
{
get { return this.Top + (this.Height / 2.0); }
}
public double MousePositionX
{
get { return this.mousePosition.X; }
}
public double MousePositionY
{
get { return this.mousePosition.Y; }
}
public bool IsSelected
{
get;
private set;
}
public void SetPosition(double left, double top)
{
Left = left;
Top = top;
}
public void SetSize(double width, double height)
{
Width = width;
Height = height;
}
//whenever user clicks on the minimap, i check if clicked object is
//a lookup window - if yes - i store mouse offset within the window
//and mark it as selected
public bool Select(object clickedItem, Point clickedPosition)
{
if (clickedItem == this.lookupWindowRectangle)
{
this.mousePosition = clickedPosition;
this.IsSelected = true;
}
else
{
Unselect();
}
return this.IsSelected;
}
public void Unselect()
{
this.mousePosition.X = 0;
this.mousePosition.Y = 0;
this.IsSelected = false;
}
public void Center(double x, double y)
{
Left = x - (Width / 2.0);
Top = y - (Height / 2.0);
}
public void Refresh(bool unselect)
{
if (unselect)
{
Unselect();
}
SetPosition(Left, Top);
}
}
// This class is responsible for calculating size of the minimap's view area, as well as
// maintaining the bi directional link between minimap and control beeing visualized.
// Whenever minimap's view window position is updated, the control's content is scrolled
// to calculated position
// Whenever control's content is resized or scrolled, minimap reflects that change in
// recalculating view's window size and/or position
internal class MiniMapViewController
{
Canvas lookupCanvas;
Grid contentGrid;
ScrollViewer mapSource;
LookupWindow lookupWindow;
public MiniMapViewController(Canvas lookupCanvas, Rectangle lookupWindowRectangle, Grid contentGrid)
{
this.lookupWindow = new LookupWindow(this, lookupWindowRectangle);
this.lookupCanvas = lookupCanvas;
this.contentGrid = contentGrid;
}
public ScrollViewer MapSource
{
get { return this.mapSource; }
set
{
this.mapSource = value;
//calculate view's size and set initial position
this.lookupWindow.Unselect();
this.CalculateLookupWindowSize();
this.lookupWindow.SetPosition(0.0, 0.0);
CalculateMapPosition(this.lookupWindow.Left, this.lookupWindow.Top);
this.UpdateContentGrid();
if (null != this.mapSource && null != this.mapSource.Content && this.mapSource.Content is FrameworkElement)
{
FrameworkElement content = (FrameworkElement)this.mapSource.Content;
//hook up for all content size changes - handle them in OnContentSizeChanged method
content.SizeChanged += (s, e) =>
{
this.contentGrid.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
new Action(() => { OnContentSizeChanged(s, e); }));
};
//in case of scroll viewer - there are two different events to handle in one notification:
this.mapSource.ScrollChanged += (s, e) =>
{
this.contentGrid.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
new Action(() =>
{
//when user changes scroll position - delegate it to OnMapSourceScrollChange
if (0.0 != e.HorizontalChange || 0.0 != e.VerticalChange)
{
OnMapSourceScrollChanged(s, e);
}
//when size of the scroll changes delegate it to OnContentSizeChanged
if (0.0 != e.ViewportWidthChange || 0.0 != e.ViewportHeightChange)
{
OnContentSizeChanged(s, e);
}
}));
};
this.OnMapSourceScrollChanged(this, null);
this.OnContentSizeChanged(this, null);
}
}
}
//bunch of helper getters - used to increase algorithm readability and provide default
//values, always valid values, so no additional divide-by-zero checks are neccessary
public double MapWidth
{
get { return this.contentGrid.ActualWidth - 2 * (this.contentGrid.ColumnDefinitions[0].MinWidth); }
}
public double MapHeight
{
get { return this.contentGrid.ActualHeight - 2 * (this.contentGrid.RowDefinitions[0].MinHeight); }
}
internal LookupWindow LookupWindow
{
get { return this.lookupWindow; }
}
double VisibleSourceWidth
{
get { return (null == MapSource || 0.0 == MapSource.ViewportWidth ? 1.0 : MapSource.ViewportWidth); }
}
double VisibleSourceHeight
{
get { return (null == MapSource || 0.0 == MapSource.ViewportHeight ? 1.0 : MapSource.ViewportHeight); }
}
public void CenterView(MouseEventArgs args)
{
Point pt = args.GetPosition(this.lookupCanvas);
this.lookupWindow.Unselect();
this.lookupWindow.Center(pt.X, pt.Y);
CalculateMapPosition(this.lookupWindow.Left, this.lookupWindow.Top);
}
public void MapViewSizeChanged(SizeChangedInfo sizeInfo)
{
this.OnContentSizeChanged(this, EventArgs.Empty);
this.lookupWindow.Unselect();
this.CalculateLookupWindowSize();
if (sizeInfo.WidthChanged && 0.0 != sizeInfo.PreviousSize.Width)
{
this.lookupWindow.Left =
this.lookupWindow.Left * (sizeInfo.NewSize.Width / sizeInfo.PreviousSize.Width);
}
if (sizeInfo.HeightChanged && 0.0 != sizeInfo.PreviousSize.Height)
{
this.lookupWindow.Top =
this.lookupWindow.Top * (sizeInfo.NewSize.Height / sizeInfo.PreviousSize.Height);
}
}
public bool StartMapLookupDrag(MouseEventArgs args)
{
bool result = false;
HitTestResult hitTest =
VisualTreeHelper.HitTest(this.lookupCanvas, args.GetPosition(this.lookupCanvas));
if (null != hitTest && null != hitTest.VisualHit)
{
Point clickedPosition = args.GetPosition(hitTest.VisualHit as IInputElement);
result = this.lookupWindow.Select(hitTest.VisualHit, clickedPosition);
}
return result;
}
public void StopMapLookupDrag()
{
this.lookupWindow.Unselect();
}
public void DoMapLookupDrag(MouseEventArgs args)
{
if (args.LeftButton == MouseButtonState.Released && this.lookupWindow.IsSelected)
{
this.lookupWindow.Unselect();
}
if (this.lookupWindow.IsSelected)
{
Point to = args.GetPosition(this.lookupCanvas);
this.lookupWindow.SetPosition(to.X, to.Y);
CalculateMapPosition(
to.X - this.lookupWindow.MousePositionX,
to.Y - this.lookupWindow.MousePositionY);
}
}
void CalculateMapPosition(double left, double top)
{
if (null != MapSource && 0 != this.lookupWindow.Width && 0 != this.lookupWindow.Height)
{
MapSource.ScrollToHorizontalOffset((left / this.lookupWindow.Width) * VisibleSourceWidth);
MapSource.ScrollToVerticalOffset((top / this.lookupWindow.Height) * VisibleSourceHeight);
}
}
//this method calculates position of the lookup window on the minimap - it should be triggered when:
// - user modifies a scroll position by draggin a scroll bar
// - scroll sizes are updated by change of the srcollviewer size
// - user drags minimap view - however, in this case no lookup update takes place
void OnMapSourceScrollChanged(object sender, ScrollChangedEventArgs e)
{
if (!this.lookupWindow.IsSelected && null != MapSource)
{
this.lookupWindow.Unselect();
this.lookupWindow.Left =
this.lookupWindow.Width * (MapSource.HorizontalOffset / VisibleSourceWidth);
this.lookupWindow.Top =
this.lookupWindow.Height * (MapSource.VerticalOffset / VisibleSourceHeight);
}
DumpData("OnMapSourceScrollChange");
}
//this method calculates size and position of the minimap view - it should be triggered when:
// - zoom changes
// - visible size of the scrollviewer (which is map source) changes
// - visible size of the minimap control changes
void OnContentSizeChanged(object sender, EventArgs e)
{
//get old center point coordinates
double centerX = this.lookupWindow.MapCenterXPoint;
double centeryY = this.lookupWindow.MapCenterYPoint;
//update the minimap itself
this.UpdateContentGrid();
//calculate new size
this.CalculateLookupWindowSize();
//try to center around old center points (window may be moved if doesn't fit)
this.lookupWindow.Center(centerX, centeryY);
DumpData("OnContentSizeChanged");
}
//this method calculates size of the lookup rectangle, based on the visible size of the object,
//including current map width
void CalculateLookupWindowSize()
{
double width = this.MapWidth;
double height = this.MapHeight;
if (this.MapSource.ScrollableWidth != 0 && this.MapSource.ExtentWidth != 0)
{
width = (this.MapSource.ViewportWidth / this.MapSource.ExtentWidth) * this.MapWidth;
}
else
{
//width =
}
if (this.MapSource.ScrollableHeight != 0 && this.MapSource.ExtentHeight != 0)
{
height = (this.MapSource.ViewportHeight / this.MapSource.ExtentHeight) * this.MapHeight;
}
this.lookupWindow.SetSize(width, height);
}
//this method updates content grid of the minimap - most likely, minimap view will be scaled to fit
//the window - so there will be some extra space visible on the left and right sides or above and below actual
//mini map view - we don't want lookup rectangle to navigate within that area, since it is not representing
//actual view - we increase margins of the minimap to disallow this
void UpdateContentGrid()
{
bool resetToDefault = true;
if (this.MapSource.ExtentWidth != 0 && this.MapSource.ExtentHeight != 0)
{
//get width to height ratio from map source - we want to display our minimap in the same ratio
double widthToHeightRatio = this.MapSource.ExtentWidth / this.MapSource.ExtentHeight;
//calculate current width to height ratio on the minimap
double height = this.contentGrid.ActualHeight;
double width = this.contentGrid.ActualWidth;
//ideally - it should be 1 - whole view perfectly fits minimap
double minimapWidthToHeightRatio = (height * widthToHeightRatio) / (width > 1.0 ? width : 1.0);
//if value is greater than one - we have to reduce height
if (minimapWidthToHeightRatio > 1.0)
{
double margin = (height - (height / minimapWidthToHeightRatio)) / 2.0;
this.contentGrid.ColumnDefinitions[0].MinWidth = 0.0;
this.contentGrid.ColumnDefinitions[2].MinWidth = 0.0;
this.contentGrid.RowDefinitions[0].MinHeight = margin;
this.contentGrid.RowDefinitions[2].MinHeight = margin;
resetToDefault = false;
}
//if value is less than one - we have to reduce width
else if (minimapWidthToHeightRatio < 1.0)
{
double margin = (width - (width * minimapWidthToHeightRatio)) / 2.0;
this.contentGrid.ColumnDefinitions[0].MinWidth = margin;
this.contentGrid.ColumnDefinitions[2].MinWidth = margin;
this.contentGrid.RowDefinitions[0].MinHeight = 0.0;
this.contentGrid.RowDefinitions[2].MinHeight = 0.0;
resetToDefault = false;
}
}
//perfect match or nothing to display - no need to setup margins
if (resetToDefault)
{
this.contentGrid.ColumnDefinitions[0].MinWidth = 0.0;
this.contentGrid.ColumnDefinitions[2].MinWidth = 0.0;
this.contentGrid.RowDefinitions[0].MinHeight = 0.0;
this.contentGrid.RowDefinitions[2].MinHeight = 0.0;
}
}
[Conditional("MINIMAP_DEBUG")]
void DumpData(string prefix)
{
System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} ScrollViewer: EWidth {1}, EHeight {2}, AWidth {3}, AHeight {4}, ViewPortW {5} ViewPortH {6}", prefix, mapSource.ExtentWidth, mapSource.ExtentHeight, mapSource.ActualWidth, mapSource.ActualHeight, mapSource.ViewportWidth, mapSource.ViewportHeight));
}
}
}
}
| |
// Copyright (c) 2012-2013 Rotorz Limited. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System;
namespace InControl.ReorderableList
{
/// <summary>
/// Reorderable list adaptor for serialized array property.
/// </summary>
/// <remarks>
/// <para>This adaptor can be subclassed to add special logic to item height calculation.
/// You may want to implement a custom adaptor class where specialised functionality
/// is needed.</para>
/// </remarks>
public class SerializedPropertyAdaptor : IReorderableListAdaptor
{
private SerializedProperty _arrayProperty;
/// <summary>
/// Fixed height of each list item.
/// </summary>
/// <remarks>
/// <para>Non-zero value overrides property drawer height calculation
/// which is more efficient.</para>
/// </remarks>
public float fixedItemHeight;
/// <summary>
/// Gets element from list.
/// </summary>
/// <param name="index">Zero-based index of element.</param>
/// <returns>
/// Serialized property wrapper for array element.
/// </returns>
public SerializedProperty this[ int index ]
{
get { return _arrayProperty.GetArrayElementAtIndex( index ); }
}
/// <summary>
/// Gets the underlying serialized array property.
/// </summary>
public SerializedProperty arrayProperty
{
get { return _arrayProperty; }
}
#region Construction
/// <summary>
/// Initializes a new instance of <see cref="SerializedPropertyAdaptor"/>.
/// </summary>
/// <param name="arrayProperty">Serialized property for entire array.</param>
/// <param name="fixedItemHeight">Non-zero height overrides property drawer height calculation.</param>
public SerializedPropertyAdaptor( SerializedProperty arrayProperty, float fixedItemHeight )
{
if (arrayProperty == null)
throw new ArgumentNullException( "Array property was null." );
if (!arrayProperty.isArray)
throw new InvalidOperationException( "Specified serialized propery is not an array." );
this._arrayProperty = arrayProperty;
this.fixedItemHeight = fixedItemHeight;
}
/// <summary>
/// Initializes a new instance of <see cref="SerializedPropertyAdaptor"/>.
/// </summary>
/// <param name="arrayProperty">Serialized property for entire array.</param>
public SerializedPropertyAdaptor( SerializedProperty arrayProperty ) : this( arrayProperty, 0f )
{
}
#endregion
#region IReorderableListAdaptor - Implementation
/// <inheritdoc/>
public int Count
{
get { return _arrayProperty.arraySize; }
}
/// <inheritdoc/>
public virtual bool CanDrag( int index )
{
return true;
}
/// <inheritdoc/>
public virtual bool CanRemove( int index )
{
return true;
}
/// <inheritdoc/>
public void Add()
{
int newIndex = _arrayProperty.arraySize;
++_arrayProperty.arraySize;
ResetValue( _arrayProperty.GetArrayElementAtIndex( newIndex ) );
}
/// <inheritdoc/>
public void Insert( int index )
{
_arrayProperty.InsertArrayElementAtIndex( index );
ResetValue( _arrayProperty.GetArrayElementAtIndex( index ) );
}
/// <inheritdoc/>
public void Duplicate( int index )
{
_arrayProperty.InsertArrayElementAtIndex( index );
}
/// <inheritdoc/>
public void Remove( int index )
{
_arrayProperty.DeleteArrayElementAtIndex( index );
}
/// <inheritdoc/>
public void Move( int sourceIndex, int destIndex )
{
if (destIndex > sourceIndex)
--destIndex;
_arrayProperty.MoveArrayElement( sourceIndex, destIndex );
}
/// <inheritdoc/>
public void Clear()
{
_arrayProperty.ClearArray();
}
/// <inheritdoc/>
public virtual void DrawItem( Rect position, int index )
{
EditorGUI.PropertyField( position, this[index], GUIContent.none, false );
}
/// <inheritdoc/>
public virtual float GetItemHeight( int index )
{
return fixedItemHeight != 0f
? fixedItemHeight
: EditorGUI.GetPropertyHeight( this[index], GUIContent.none, false );
}
#endregion
#region Methods
/// <summary>
/// Reset value of array element.
/// </summary>
/// <param name="element">Serializd property for array element.</param>
private void ResetValue( SerializedProperty element )
{
switch (element.type)
{
case "string":
element.stringValue = "";
break;
case "Vector2f":
element.vector2Value = Vector2.zero;
break;
case "Vector3f":
element.vector3Value = Vector3.zero;
break;
case "Rectf":
element.rectValue = new Rect();
break;
case "Quaternionf":
element.quaternionValue = Quaternion.identity;
break;
case "int":
element.intValue = 0;
break;
case "float":
element.floatValue = 0f;
break;
case "UInt8":
element.boolValue = false;
break;
case "ColorRGBA":
element.colorValue = Color.black;
break;
default:
if (element.type.StartsWith( "PPtr" ))
element.objectReferenceValue = null;
break;
}
}
#endregion
}
}
#endif
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Commands;
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, IPythonOptions, 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();
}
}
#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.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();
}
}
}
}
| |
using System;
using System.Xml;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace Stetic
{
public class Project: MarshalByRefObject
{
Application app;
ProjectBackend backend;
string fileName;
IResourceProvider resourceProvider;
Component selection;
string tmpProjectFile;
bool reloadRequested;
List<WidgetInfo> widgets = new List<WidgetInfo> ();
List<ActionGroupInfo> groups = new List<ActionGroupInfo> ();
bool modified;
ImportFileDelegate importFileDelegate;
public event WidgetInfoEventHandler WidgetAdded;
public event WidgetInfoEventHandler WidgetRemoved;
public event ComponentNameEventHandler ComponentNameChanged;
public event EventHandler ComponentTypesChanged;
public event EventHandler ActionGroupsChanged;
public event EventHandler ModifiedChanged;
public event EventHandler Changed;
// Internal events
internal event BackendChangingHandler BackendChanging;
internal event BackendChangedHandler BackendChanged;
internal event ComponentSignalEventHandler SignalAdded;
internal event ComponentSignalEventHandler SignalRemoved;
internal event ComponentSignalEventHandler SignalChanged;
public event EventHandler ProjectReloading;
public event EventHandler ProjectReloaded;
internal Project (Application app): this (app, null)
{
}
internal Project (Application app, ProjectBackend backend)
{
this.app = app;
if (backend != null) {
this.backend = backend;
backend.SetFrontend (this);
}
if (app is IsolatedApplication) {
IsolatedApplication iapp = app as IsolatedApplication;
iapp.BackendChanging += OnBackendChanging;
iapp.BackendChanged += OnBackendChanged;
}
}
internal ProjectBackend ProjectBackend {
get {
if (backend == null) {
backend = app.Backend.CreateProject ();
backend.SetFrontend (this);
if (resourceProvider != null)
backend.ResourceProvider = resourceProvider;
if (fileName != null)
backend.Load (fileName);
}
return backend;
}
}
internal bool IsBackendLoaded {
get { return backend != null; }
}
internal Application App {
get { return app; }
}
internal event EventHandler Disposed;
public void Dispose ()
{
if (app is IsolatedApplication) {
IsolatedApplication iapp = app as IsolatedApplication;
iapp.BackendChanging -= OnBackendChanging;
iapp.BackendChanged -= OnBackendChanged;
}
if (tmpProjectFile != null && File.Exists (tmpProjectFile)) {
File.Delete (tmpProjectFile);
tmpProjectFile = null;
}
if (backend != null)
backend.Dispose ();
if (Disposed != null)
Disposed (this, EventArgs.Empty);
System.Runtime.Remoting.RemotingServices.Disconnect (this);
}
public override object InitializeLifetimeService ()
{
// Will be disconnected when calling Dispose
return null;
}
public string FileName {
get { return fileName; }
}
public IResourceProvider ResourceProvider {
get { return resourceProvider; }
set {
resourceProvider = value;
if (backend != null)
backend.ResourceProvider = value;
}
}
public Stetic.ProjectIconFactory IconFactory {
get { return ProjectBackend.IconFactory; }
set { backend.IconFactory = value; }
}
public ImportFileDelegate ImportFileCallback {
get { return importFileDelegate; }
set { importFileDelegate = value; }
}
public bool CanGenerateCode {
get { return ProjectBackend.CanGenerateCode; }
}
public Component Selection {
get { return selection; }
}
public string ImagesRootPath {
get { return ProjectBackend.ImagesRootPath; }
set { ProjectBackend.ImagesRootPath = value; }
}
public string TargetGtkVersion {
get { return ProjectBackend.TargetGtkVersion; }
set { ProjectBackend.TargetGtkVersion = value; }
}
public void Close ()
{
if (backend != null)
backend.Close ();
}
public void Load (string fileName)
{
this.fileName = fileName;
if (backend != null)
backend.Load (fileName);
using (StreamReader sr = new StreamReader (fileName)) {
XmlTextReader reader = new XmlTextReader (sr);
reader.MoveToContent ();
if (reader.IsEmptyElement)
return;
reader.ReadStartElement ("stetic-interface");
if (reader.IsEmptyElement)
return;
while (reader.NodeType != XmlNodeType.EndElement) {
if (reader.NodeType == XmlNodeType.Element) {
if (reader.LocalName == "widget")
ReadWidget (reader);
else if (reader.LocalName == "action-group")
ReadActionGroup (reader);
else
reader.Skip ();
}
else {
reader.Skip ();
}
reader.MoveToContent ();
}
}
}
void ReadWidget (XmlTextReader reader)
{
WidgetInfo w = new WidgetInfo (this, reader.GetAttribute ("id"), reader.GetAttribute ("class"));
widgets.Add (w);
if (reader.IsEmptyElement) {
reader.Skip ();
return;
}
reader.ReadStartElement ();
reader.MoveToContent ();
while (reader.NodeType != XmlNodeType.EndElement) {
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "action-group") {
w.AddGroup (reader.GetAttribute ("name"));
}
reader.Skip ();
reader.MoveToContent ();
}
reader.ReadEndElement ();
}
void ReadActionGroup (XmlTextReader reader)
{
groups.Add (new ActionGroupInfo (this, reader.GetAttribute ("name")));
reader.Skip ();
}
public void Save (string fileName)
{
this.fileName = fileName;
if (backend != null)
backend.Save (fileName);
}
public void ImportGlade (string fileName)
{
ProjectBackend.ImportGlade (fileName);
}
public void ExportGlade (string fileName)
{
ProjectBackend.ExportGlade (fileName);
}
public bool Modified {
get {
if (backend != null)
return backend.Modified;
else
return modified;
}
set {
if (backend != null)
backend.Modified = value;
else
modified = true;
}
}
public IEnumerable<WidgetInfo> Widgets {
get { return widgets; }
}
public IEnumerable<ActionGroupInfo> ActionGroups {
get { return groups; }
}
public WidgetInfo GetWidget (string name)
{
foreach (WidgetInfo w in widgets)
if (w.Name == name)
return w;
return null;
}
public ActionGroupInfo GetActionGroup (string name)
{
foreach (ActionGroupInfo w in groups)
if (w.Name == name)
return w;
return null;
}
public WidgetDesigner CreateWidgetDesigner (WidgetInfo widgetInfo, bool autoCommitChanges)
{
return new WidgetDesigner (this, widgetInfo.Name, autoCommitChanges);
}
public ActionGroupDesigner CreateActionGroupDesigner (ActionGroupInfo actionGroup, bool autoCommitChanges)
{
return new ActionGroupDesigner (this, null, actionGroup.Name, null, autoCommitChanges);
}
public WidgetInfo AddNewComponent (ComponentType type, string name)
{
object ob = ProjectBackend.AddNewWidget (type.Name, name);
WidgetComponent wc = (WidgetComponent) App.GetComponent (ob, null, null);
WidgetInfo wi = GetWidget (wc.Name);
if (wi == null) {
wi = new WidgetInfo (this, wc);
widgets.Add (wi);
}
return wi;
}
public WidgetInfo AddNewComponent (XmlElement template)
{
object ob = ProjectBackend.AddNewWidgetFromTemplate (template.OuterXml);
WidgetComponent wc = (WidgetComponent) App.GetComponent (ob, null, null);
WidgetInfo wi = GetWidget (wc.Name);
if (wi == null) {
wi = new WidgetInfo (this, wc);
widgets.Add (wi);
}
return wi;
}
public ComponentType[] GetComponentTypes ()
{
ArrayList types = new ArrayList ();
ArrayList typeNames = ProjectBackend.GetComponentTypes ();
for (int n=0; n<typeNames.Count; n++)
types.Add (app.GetComponentType ((string) typeNames [n]));
// Global action groups
foreach (ActionGroupComponent grp in GetActionGroups ()) {
foreach (ActionComponent ac in grp.GetActions ())
types.Add (new ComponentType (app, ac));
}
return (ComponentType[]) types.ToArray (typeof(ComponentType));
}
// Returns a list of all support widget types (including base classes)
public string[] GetWidgetTypes ()
{
return ProjectBackend.GetWidgetTypes ();
}
public void RemoveComponent (WidgetInfo component)
{
ProjectBackend.RemoveWidget (component.Name);
}
public WidgetComponent GetComponent (string name)
{
object ob = ProjectBackend.GetTopLevelWrapper (name, false);
if (ob != null)
return (WidgetComponent) App.GetComponent (ob, name, null);
else
return null;
}
public ActionGroupComponent AddNewActionGroup (string id)
{
object ob = ProjectBackend.AddNewActionGroup (id);
ActionGroupComponent ac = (ActionGroupComponent) App.GetComponent (ob, id, null);
// Don't wait for the group added event to come to update the groups list since
// it may be too late.
ActionGroupInfo gi = GetActionGroup (ac.Name);
if (gi == null) {
gi = new ActionGroupInfo (this, ac.Name);
groups.Add (gi);
}
return ac;
}
public ActionGroupComponent AddNewActionGroup (XmlElement template)
{
object ob = ProjectBackend.AddNewActionGroupFromTemplate (template.OuterXml);
ActionGroupComponent ac = (ActionGroupComponent) App.GetComponent (ob, null, null);
// Don't wait for the group added event to come to update the groups list since
// it may be too late.
ActionGroupInfo gi = GetActionGroup (ac.Name);
if (gi == null) {
gi = new ActionGroupInfo (this, ac.Name);
groups.Add (gi);
}
return ac;
}
public void RemoveActionGroup (ActionGroupInfo group)
{
ActionGroupComponent ac = (ActionGroupComponent) group.Component;
ProjectBackend.RemoveActionGroup ((Stetic.Wrapper.ActionGroup) ac.Backend);
}
internal ActionGroupComponent[] GetActionGroups ()
{
Wrapper.ActionGroup[] acs = ProjectBackend.GetActionGroups ();
ArrayList comps = new ArrayList (acs.Length);
for (int n=0; n<acs.Length; n++) {
ActionGroupComponent ag = (ActionGroupComponent) App.GetComponent (acs[n], null, null);
if (ag != null)
comps.Add (ag);
}
return (ActionGroupComponent[]) comps.ToArray (typeof(ActionGroupComponent));
}
public void AddWidgetLibrary (string assemblyPath)
{
AddWidgetLibrary (assemblyPath, false);
}
public void AddWidgetLibrary (string assemblyPath, bool isInternal)
{
reloadRequested = false;
ProjectBackend.AddWidgetLibrary (assemblyPath);
app.UpdateWidgetLibraries (false, false);
if (!reloadRequested)
ProjectBackend.Reload ();
}
public void RemoveWidgetLibrary (string assemblyPath)
{
reloadRequested = false;
ProjectBackend.RemoveWidgetLibrary (assemblyPath);
app.UpdateWidgetLibraries (false, false);
if (!reloadRequested)
ProjectBackend.Reload ();
}
public string[] WidgetLibraries {
get {
return (string[]) ProjectBackend.WidgetLibraries.ToArray (typeof(string));
}
}
public void SetWidgetLibraries (string[] libraries, string[] internalLibraries)
{
reloadRequested = false;
ArrayList libs = new ArrayList ();
libs.AddRange (libraries);
libs.AddRange (internalLibraries);
ProjectBackend.WidgetLibraries = libs;
libs = new ArrayList ();
libs.AddRange (internalLibraries);
ProjectBackend.InternalWidgetLibraries = libs;
app.UpdateWidgetLibraries (false, false);
if (!reloadRequested)
ProjectBackend.Reload ();
}
/* public bool CanCopySelection {
get { return Selection != null ? Selection.CanCopy : false; }
}
public bool CanCutSelection {
get { return Selection != null ? Selection.CanCut : false; }
}
public bool CanPasteToSelection {
get { return Selection != null ? Selection.CanPaste : false; }
}
public void CopySelection ()
{
if (Selection != null)
backend.ClipboardCopySelection ();
}
public void CutSelection ()
{
if (Selection != null)
backend.ClipboardCutSelection ();
}
public void PasteToSelection ()
{
if (Selection != null)
backend.ClipboardPaste ();
}
public void DeleteSelection ()
{
backend.DeleteSelection ();
}
*/
public void EditIcons ()
{
ProjectBackend.EditIcons ();
}
internal void NotifyWidgetAdded (object obj, string name, string typeName)
{
GuiDispatch.InvokeSync (
delegate {
Component c = App.GetComponent (obj, name, typeName);
if (c != null) {
WidgetInfo wi = GetWidget (c.Name);
if (wi == null) {
wi = new WidgetInfo (this, c);
widgets.Add (wi);
}
if (WidgetAdded != null)
WidgetAdded (this, new WidgetInfoEventArgs (this, wi));
}
}
);
}
internal void NotifyWidgetRemoved (string name)
{
GuiDispatch.InvokeSync (
delegate {
WidgetInfo wi = GetWidget (name);
if (wi != null) {
widgets.Remove (wi);
if (WidgetRemoved != null)
WidgetRemoved (this, new WidgetInfoEventArgs (this, wi));
}
}
);
}
internal void NotifyModifiedChanged ()
{
GuiDispatch.InvokeSync (
delegate {
if (ModifiedChanged != null)
ModifiedChanged (this, EventArgs.Empty);
}
);
}
internal void NotifyChanged ()
{
GuiDispatch.InvokeSync (
delegate {
if (Changed != null)
Changed (this, EventArgs.Empty);
// TODO: Optimize
foreach (ProjectItemInfo it in widgets)
it.NotifyChanged ();
foreach (ProjectItemInfo it in groups)
it.NotifyChanged ();
}
);
}
internal void NotifyWidgetNameChanged (object obj, string oldName, string newName, bool isRoot)
{
WidgetComponent c = obj != null ? (WidgetComponent) App.GetComponent (obj, null, null) : null;
if (c != null)
c.UpdateName (newName);
if (isRoot) {
WidgetInfo wi = GetWidget (oldName);
if (wi != null)
wi.NotifyNameChanged (newName);
}
GuiDispatch.InvokeSync (
delegate {
if (c != null) {
if (ComponentNameChanged != null)
ComponentNameChanged (this, new ComponentNameEventArgs (this, c, oldName));
}
}
);
}
internal void NotifyActionGroupAdded (string group)
{
GuiDispatch.InvokeSync (delegate {
ActionGroupInfo gi = GetActionGroup (group);
if (gi == null) {
gi = new ActionGroupInfo (this, group);
groups.Add (gi);
}
if (ActionGroupsChanged != null)
ActionGroupsChanged (this, EventArgs.Empty);
});
}
internal void NotifyActionGroupRemoved (string group)
{
GuiDispatch.InvokeSync (delegate {
ActionGroupInfo gi = GetActionGroup (group);
if (gi != null) {
groups.Remove (gi);
if (ActionGroupsChanged != null)
ActionGroupsChanged (this, EventArgs.Empty);
}
});
}
internal void NotifySignalAdded (object obj, string name, Signal signal)
{
GuiDispatch.InvokeSync (delegate {
if (SignalAdded != null) {
Component c = App.GetComponent (obj, name, null);
if (c != null)
SignalAdded (this, new ComponentSignalEventArgs (this, c, null, signal));
}
});
}
internal void NotifySignalRemoved (object obj, string name, Signal signal)
{
GuiDispatch.InvokeSync (delegate {
if (SignalRemoved != null) {
Component c = App.GetComponent (obj, name, null);
if (c != null)
SignalRemoved (this, new ComponentSignalEventArgs (this, c, null, signal));
}
});
}
internal void NotifySignalChanged (object obj, string name, Signal oldSignal, Signal signal)
{
GuiDispatch.InvokeSync (delegate {
if (SignalChanged != null) {
Component c = App.GetComponent (obj, name, null);
if (c != null)
SignalChanged (this, new ComponentSignalEventArgs (this, c, oldSignal, signal));
}
});
}
internal void NotifyProjectReloaded ()
{
GuiDispatch.InvokeSync (delegate {
if (ProjectReloaded != null)
ProjectReloaded (this, EventArgs.Empty);
});
}
internal void NotifyProjectReloading ()
{
GuiDispatch.InvokeSync (delegate {
if (ProjectReloading != null)
ProjectReloading (this, EventArgs.Empty);
});
}
internal void NotifyComponentTypesChanged ()
{
GuiDispatch.InvokeSync (delegate {
if (ComponentTypesChanged != null)
ComponentTypesChanged (this, EventArgs.Empty);
});
}
internal string ImportFile (string filePath)
{
if (importFileDelegate != null) {
string res = null;
GuiDispatch.InvokeSync (delegate {
res = importFileDelegate (filePath);
});
return res;
}
else
return filePath;
}
internal void NotifyUpdateLibraries ()
{
app.UpdateWidgetLibraries (false, false);
}
void OnBackendChanging ()
{
selection = null;
if (BackendChanging != null)
BackendChanging ();
}
void OnBackendChanged (ApplicationBackend oldBackend)
{
if (oldBackend != null) {
tmpProjectFile = Path.GetTempFileName ();
backend.Save (tmpProjectFile);
}
backend = app.Backend.CreateProject ();
backend.SetFrontend (this);
if (tmpProjectFile != null && File.Exists (tmpProjectFile)) {
backend.Load (tmpProjectFile, fileName);
File.Delete (tmpProjectFile);
tmpProjectFile = null;
} else if (fileName != null) {
backend.Load (fileName);
}
if (resourceProvider != null)
backend.ResourceProvider = resourceProvider;
if (BackendChanged != null)
BackendChanged (oldBackend);
if (ProjectReloaded != null)
ProjectReloaded (this, EventArgs.Empty);
}
}
public abstract class ProjectItemInfo
{
string name;
protected Project project;
public event EventHandler Changed;
internal ProjectItemInfo (Project project, string name)
{
this.name = name;
this.project = project;
}
public string Name {
get { return name; }
set { Component.Name = value; name = value; }
}
internal void NotifyNameChanged (string name)
{
this.name = name;
NotifyChanged ();
}
internal void NotifyChanged ()
{
if (Changed != null)
Changed (this, EventArgs.Empty);
}
public abstract Component Component { get; }
}
public class WidgetInfo: ProjectItemInfo
{
string type;
List<ActionGroupInfo> groups;
internal WidgetInfo (Project project, string name, string type): base (project, name)
{
this.type = type;
}
internal WidgetInfo (Project project, Component c): base (project, c.Name)
{
type = c.Type.Name;
}
public IEnumerable<ActionGroupInfo> ActionGroups {
get {
if (groups != null)
return groups;
else
return new ActionGroupInfo [0];
}
}
public string Type {
get { return type; }
}
public bool IsWindow {
get { return type == "Gtk.Dialog" || type == "Gtk.Window"; }
}
public override Component Component {
get { return project.GetComponent (Name); }
}
internal void AddGroup (string group)
{
if (groups == null)
groups = new List<ActionGroupInfo> ();
groups.Add (new ActionGroupInfo (project, group, Name));
}
}
public class ActionGroupInfo: ProjectItemInfo
{
string widgetName;
internal ActionGroupInfo (Project project, string name): base (project, name)
{
}
internal ActionGroupInfo (Project project, string name, string widgetName): base (project, name)
{
this.widgetName = widgetName;
}
public override Component Component {
get {
ActionGroupComponent[] ags;
if (widgetName != null) {
WidgetComponent c = project.GetComponent (widgetName) as WidgetComponent;
if (c == null)
return null;
ags = c.GetActionGroups ();
}
else {
ags = project.GetActionGroups ();
}
foreach (ActionGroupComponent ag in ags)
if (ag.Name == Name)
return ag;
return null;
}
}
}
public delegate string ImportFileDelegate (string fileName);
}
| |
// 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;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
/// <summary>
/// Represents a list that lets users select multiple items.
/// This class is typically rendered as an HTML <c><select multiple="multiple"></c> element with the specified collection
/// of <see cref="SelectListItem"/> objects.
/// </summary>
public class MultiSelectList : IEnumerable<SelectListItem>
{
private readonly IList<SelectListGroup> _groups;
private IList<SelectListItem> _selectListItems;
/// <summary>
/// Initialize a new instance of <see cref="MultiSelectList"/>.
/// </summary>
/// <param name="items">The items.</param>
public MultiSelectList(IEnumerable items)
: this(items, selectedValues: null)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
}
/// <summary>
/// Initialize a new instance of <see cref="MultiSelectList"/>.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="selectedValues">The selected values.</param>
public MultiSelectList(IEnumerable items, IEnumerable selectedValues)
: this(items, dataValueField: null, dataTextField: null, selectedValues: selectedValues)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
}
/// <summary>
/// Initialize a new instance of <see cref="MultiSelectList"/>.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="dataValueField">The data value field.</param>
/// <param name="dataTextField">The data text field.</param>
public MultiSelectList(IEnumerable items, string dataValueField, string dataTextField)
: this(items, dataValueField, dataTextField, selectedValues: null)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
}
/// <summary>
/// Initialize a new instance of <see cref="MultiSelectList"/>.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="dataValueField">The data value field.</param>
/// <param name="dataTextField">The data text field.</param>
/// <param name="selectedValues">The selected values.</param>
public MultiSelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
IEnumerable selectedValues)
: this(items, dataValueField, dataTextField, selectedValues, dataGroupField: null)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
}
/// <summary>
/// Initializes a new instance of the MultiSelectList class by using the items to include in the list,
/// the data value field, the data text field, the selected values, and the data group field.
/// </summary>
/// <param name="items">The items used to build each <see cref="SelectListItem"/> of the list.</param>
/// <param name="dataValueField">The data value field. Used to match the Value property of the corresponding
/// <see cref="SelectListItem"/>.</param>
/// <param name="dataTextField">The data text field. Used to match the Text property of the corresponding
/// <see cref="SelectListItem"/>.</param>
/// <param name="selectedValues">The selected values field. Used to match the Selected property of the
/// corresponding <see cref="SelectListItem"/>.</param>
/// <param name="dataGroupField">The data group field. Used to match the Group property of the corresponding
/// <see cref="SelectListItem"/>.</param>
public MultiSelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
IEnumerable selectedValues,
string dataGroupField)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
Items = items;
DataValueField = dataValueField;
DataTextField = dataTextField;
SelectedValues = selectedValues;
DataGroupField = dataGroupField;
if (DataGroupField != null)
{
_groups = new List<SelectListGroup>();
}
}
/// <summary>
/// Gets the data group field.
/// </summary>
public string DataGroupField { get; }
/// <summary>
/// Gets the data text field.
/// </summary>
public string DataTextField { get; }
/// <summary>
/// Gets the data value field.
/// </summary>
public string DataValueField { get; }
/// <summary>
/// Gets the items.
/// </summary>
public IEnumerable Items { get; }
/// <summary>
/// Gets the selected values.
/// </summary>
public IEnumerable SelectedValues { get; }
/// <inheritdoc />
public virtual IEnumerator<SelectListItem> GetEnumerator()
{
if (_selectListItems == null)
{
_selectListItems = GetListItems();
}
return _selectListItems.GetEnumerator();
}
private IList<SelectListItem> GetListItems()
{
return (!string.IsNullOrEmpty(DataValueField)) ?
GetListItemsWithValueField() :
GetListItemsWithoutValueField();
}
private IList<SelectListItem> GetListItemsWithValueField()
{
var selectedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (SelectedValues != null)
{
foreach (var value in SelectedValues)
{
var stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);
selectedValues.Add(stringValue);
}
}
var listItems = new List<SelectListItem>();
foreach (var item in Items)
{
var value = Eval(item, DataValueField);
var newListItem = new SelectListItem
{
Group = GetGroup(item),
Value = value,
Text = Eval(item, DataTextField),
Selected = selectedValues.Contains(value),
};
listItems.Add(newListItem);
}
return listItems;
}
private IList<SelectListItem> GetListItemsWithoutValueField()
{
var selectedValues = new HashSet<object>();
if (SelectedValues != null)
{
selectedValues.UnionWith(SelectedValues.Cast<object>());
}
var listItems = new List<SelectListItem>();
foreach (var item in Items)
{
var newListItem = new SelectListItem
{
Group = GetGroup(item),
Text = Eval(item, DataTextField),
Selected = selectedValues.Contains(item),
};
listItems.Add(newListItem);
}
return listItems;
}
private static string Eval(object container, string expression)
{
var value = container;
if (!string.IsNullOrEmpty(expression))
{
var viewDataInfo = ViewDataEvaluator.Eval(container, expression);
value = viewDataInfo.Value;
}
return Convert.ToString(value, CultureInfo.CurrentCulture);
}
private SelectListGroup GetGroup(object container)
{
if (_groups == null)
{
return null;
}
var groupName = Eval(container, DataGroupField);
if (string.IsNullOrEmpty(groupName))
{
return null;
}
// We use StringComparison.CurrentCulture because the group name is used to display as the value of
// optgroup HTML tag's label attribute.
SelectListGroup group = null;
for (var index = 0; index < _groups.Count; index++)
{
if (string.Equals(_groups[index].Name, groupName, StringComparison.CurrentCulture))
{
group = _groups[index];
break;
}
}
if (group == null)
{
group = new SelectListGroup() { Name = groupName };
_groups.Add(group);
}
return group;
}
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
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.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
namespace MSNPSharp.P2P
{
using MSNPSharp;
using MSNPSharp.Core;
#region P2PMessage
/// <summary>
/// Represents a single P2P framework message.
/// </summary>
[Serializable]
public class P2PMessage : NetworkMessage
{
private P2PVersion version = P2PVersion.P2PV1;
private P2PHeader header = null;
private uint footer = 0;
public P2PMessage(P2PVersion ver)
{
version = ver;
if (ver == P2PVersion.P2PV1)
{
header = new P2Pv1Header();
}
else if (ver == P2PVersion.P2PV2)
{
header = new P2Pv2Header();
}
}
public P2PMessage(P2PMessage message)
: this(message.Version)
{
Header.SessionId = message.Header.SessionId;
Header.Identifier = message.Header.Identifier;
Header.TotalSize = message.Header.TotalSize;
Header.MessageSize = message.Header.MessageSize;
Header.AckIdentifier = message.Header.AckIdentifier;
if (message.Version == P2PVersion.P2PV1)
{
V1Header.Offset = message.V1Header.Offset;
V1Header.Flags = message.V1Header.Flags;
V1Header.AckSessionId = message.V1Header.AckSessionId;
V1Header.AckTotalSize = message.V1Header.AckTotalSize;
}
else if (message.Version == P2PVersion.P2PV2)
{
V2Header.OperationCode = message.V2Header.OperationCode;
V2Header.TFCombination = message.V2Header.TFCombination;
V2Header.PackageNumber = message.V2Header.PackageNumber;
V2Header.DataRemaining = message.V2Header.DataRemaining;
if (message.V2Header.HeaderTLVs.Count > 0)
{
foreach (KeyValuePair<byte, byte[]> keyvalue in message.V2Header.HeaderTLVs)
{
V2Header.HeaderTLVs[keyvalue.Key] = keyvalue.Value;
}
}
if (message.V2Header.DataPacketTLVs.Count > 0)
{
foreach (KeyValuePair<byte, byte[]> keyvalue in message.V2Header.DataPacketTLVs)
{
V2Header.DataPacketTLVs[keyvalue.Key] = keyvalue.Value;
}
}
}
if (message.InnerMessage != null)
InnerMessage = message.InnerMessage;
if (message.InnerBody != null)
InnerBody = message.InnerBody;
Footer = message.Footer;
}
/// <summary>
/// The p2p framework currently using.
/// </summary>
public P2PVersion Version
{
get
{
return version;
}
}
public P2PHeader Header
{
get
{
return header;
}
private set
{
if ((Version == P2PVersion.P2PV1 && value is P2Pv1Header)
|| (Version == P2PVersion.P2PV2 && value is P2Pv2Header))
{
header = value;
}
}
}
public P2Pv1Header V1Header
{
get
{
return (header as P2Pv1Header);
}
}
public P2Pv2Header V2Header
{
get
{
return (header as P2Pv2Header);
}
}
/// <summary>
/// The footer, or Application Identifier (BIG ENDIAN).
/// </summary>
public uint Footer
{
get
{
return footer;
}
set
{
footer = value;
}
}
/// <summary>
/// Payload data
/// </summary>
public new byte[] InnerBody
{
get
{
return base.InnerBody;
}
set
{
base.InnerBody = value;
base.InnerMessage = null; // Data changed, re-parse SLP message
if (version == P2PVersion.P2PV1)
{
header.MessageSize = (uint)value.Length;
header.TotalSize = Math.Max(header.TotalSize, (ulong)value.Length);
}
else if (version == P2PVersion.P2PV2)
{
if (value.Length > 0)
{
header.MessageSize = (uint)value.Length; // DataPacketHeaderLength depends on MessageSize
header.MessageSize += (uint)V2Header.DataPacketHeaderLength;
header.TotalSize = Math.Max(header.TotalSize, (ulong)value.Length);
}
else
{
header.MessageSize = 0;
header.TotalSize = 0;
}
}
}
}
/// <summary>
/// SLP Message
/// </summary>
public new NetworkMessage InnerMessage
{
get
{
if (base.InnerMessage == null && InnerBody != null && InnerBody.Length > 0)
{
if (Version == P2PVersion.P2PV1 && V1Header.MessageSize == V1Header.TotalSize)
{
base.InnerMessage = SLPMessage.Parse(InnerBody);
}
else if (Version == P2PVersion.P2PV2 && V2Header.DataRemaining == 0 && V2Header.TFCombination == TFCombination.First)
{
base.InnerMessage = SLPMessage.Parse(InnerBody);
}
}
return base.InnerMessage;
}
set
{
this.InnerBody = value.GetBytes();
base.InnerMessage = null; // Data changed, re-parse SLP message
}
}
public bool IsSLPData
{
get
{
if (Header.MessageSize > 0 && Header.SessionId == 0)
{
if ((Version == P2PVersion.P2PV1 && (V1Header.Flags == P2PFlag.Normal || V1Header.Flags == P2PFlag.MSNSLPInfo))
||
(Version == P2PVersion.P2PV2 && (V2Header.TFCombination == TFCombination.None || V2Header.TFCombination == TFCombination.First)))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Creates an acknowledgement message to this message.
/// </summary>
/// <returns></returns>
public virtual P2PMessage CreateAcknowledgement()
{
P2PMessage ack = new P2PMessage(Version);
ack.Header = Header.CreateAck();
if (Version == P2PVersion.P2PV1)
{
ack.Footer = Footer; //Keep the same as the message to acknowladge.
}
return ack;
}
/// <summary>
/// Split big P2PMessages to transport over sb or dc.
/// </summary>
/// <param name="maxSize"></param>
/// <returns></returns>
public P2PMessage[] SplitMessage(int maxSize)
{
uint payloadMessageSize = 0;
if (Version == P2PVersion.P2PV1)
{
payloadMessageSize = V1Header.MessageSize;
}
if (Version == P2PVersion.P2PV2)
{
payloadMessageSize = (uint)V2Header.MessageSize - (uint)V2Header.DataPacketHeaderLength;
}
if (payloadMessageSize <= maxSize)
return new P2PMessage[] { this };
List<P2PMessage> chunks = new List<P2PMessage>();
byte[] totalMessage = (InnerBody != null)
? InnerBody
: InnerMessage.GetBytes();
long offset = 0;
if (Version == P2PVersion.P2PV1)
{
while (offset < totalMessage.LongLength)
{
P2PMessage chunkMessage = new P2PMessage(Version);
uint messageSize = (uint)Math.Min((uint)maxSize, (totalMessage.LongLength - offset));
byte[] chunk = new byte[messageSize];
Buffer.BlockCopy(totalMessage, (int)offset, chunk, 0, (int)messageSize);
chunkMessage.V1Header.Flags = V1Header.Flags;
chunkMessage.V1Header.AckIdentifier = V1Header.AckIdentifier;
chunkMessage.V1Header.AckTotalSize = V1Header.AckTotalSize;
chunkMessage.V1Header.Identifier = V1Header.Identifier;
chunkMessage.V1Header.SessionId = V1Header.SessionId;
chunkMessage.V1Header.TotalSize = V1Header.TotalSize;
chunkMessage.V1Header.Offset = (ulong)offset;
chunkMessage.V1Header.MessageSize = messageSize;
chunkMessage.InnerBody = chunk;
chunkMessage.V1Header.AckSessionId = V1Header.AckSessionId;
chunkMessage.Footer = Footer;
chunkMessage.PrepareMessage();
chunks.Add(chunkMessage);
offset += messageSize;
}
}
if (Version == P2PVersion.P2PV2)
{
uint nextId = Header.Identifier;
long dataRemain = (long)V2Header.DataRemaining;
while (offset < totalMessage.LongLength)
{
P2PMessage chunkMessage = new P2PMessage(Version);
int maxDataSize = maxSize;
if (offset == 0 && V2Header.HeaderTLVs.Count > 0)
{
foreach (KeyValuePair<byte, byte[]> keyvalue in V2Header.HeaderTLVs)
{
chunkMessage.V2Header.HeaderTLVs[keyvalue.Key] = keyvalue.Value;
}
maxDataSize = maxSize - chunkMessage.V2Header.HeaderLength;
}
uint dataSize = (uint)Math.Min((uint)maxDataSize, (totalMessage.LongLength - offset));
byte[] chunk = new byte[dataSize];
Buffer.BlockCopy(totalMessage, (int)offset, chunk, 0, (int)dataSize);
if (offset == 0)
{
chunkMessage.V2Header.OperationCode = V2Header.OperationCode;
}
chunkMessage.V2Header.SessionId = V2Header.SessionId;
chunkMessage.V2Header.TFCombination = V2Header.TFCombination;
chunkMessage.V2Header.PackageNumber = V2Header.PackageNumber;
if (totalMessage.LongLength + dataRemain - (dataSize + offset) > 0)
{
chunkMessage.V2Header.DataRemaining = (ulong)(totalMessage.LongLength + dataRemain - (dataSize + offset));
}
if ((offset != 0) &&
TFCombination.First == (V2Header.TFCombination & TFCombination.First))
{
chunkMessage.V2Header.TFCombination = (TFCombination)(V2Header.TFCombination - TFCombination.First);
}
chunkMessage.InnerBody = chunk;
chunkMessage.Header.Identifier = nextId;
nextId += chunkMessage.Header.MessageSize;
chunks.Add(chunkMessage);
offset += dataSize;
}
}
return chunks.ToArray();
}
public P2PMessage[] CreateFromOffsets(long[] offsets, byte[] allData)
{
List<P2PMessage> messages = new List<P2PMessage>(offsets.Length);
long offset = allData.Length;
for (int i = offsets.Length - 1; i >= 0; i--)
{
P2PMessage m = new P2PMessage(Version);
long length = offset - offsets[i];
byte[] part = new byte[length];
Array.Copy(allData, offsets[i], part, 0, length);
m.ParseBytes(part);
offset -= length;
messages.Add(m);
}
messages.Reverse();
return messages.ToArray();
}
/// <summary>
/// Returns debug info
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "[P2PMessage]\r\n" +
header.ToString() +
String.Format(System.Globalization.CultureInfo.InvariantCulture, "FOOTER : {1:x} ({1})\r\n", Footer.ToString(System.Globalization.CultureInfo.InvariantCulture), Footer) +
String.Format(System.Globalization.CultureInfo.InvariantCulture, "DATA : {0}\r\n",
((InnerMessage != null) ? InnerMessage.ToString() : String.Format("Binary data: {0:D} bytes", (InnerBody == null ? 0 : InnerBody.Length))));
}
public static string DumpBytes(byte[] data, int maxBytes, bool asText)
{
if (data == null || data.Length == 0)
return string.Empty;
StringBuilder sb = new StringBuilder();
uint hexChars = 0;
for (int i = 0; i < data.Length && i < maxBytes; i++)
{
string str = string.Format("0x{0:x2} ", data[i]).ToLower();
if (asText)
{
try
{
char c = Encoding.ASCII.GetChars(new byte[] { data[i] })[0];
if (char.IsLetterOrDigit(c) || char.IsPunctuation(c) || char.IsWhiteSpace(c) ||
(c == '<') || (c == '>') || (c == '='))
{
str = c.ToString() + " ";
}
hexChars = 0;
}
catch
{
hexChars++;
}
}
else
{
hexChars++;
}
sb.Append(str);
if ((hexChars > 0) && (hexChars % 10 == 0))
sb.AppendLine();
}
return sb.ToString();
}
public override byte[] GetBytes()
{
return GetBytes(true);
}
/// <summary>
/// Creates a P2P Message. This sets the MessageSize and TotalSize properly.
/// </summary>
/// <param name="appendFooter"></param>
/// <returns></returns>
public byte[] GetBytes(bool appendFooter)
{
InnerBody = GetInnerBytes();
byte[] allData = new byte[header.HeaderLength + header.MessageSize + (appendFooter ? 4 : 0)];
MemoryStream stream = new MemoryStream(allData);
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(header.GetBytes());
writer.Write(InnerBody);
if (appendFooter)
writer.Write(BitUtility.ToBigEndian(footer));
writer.Close();
stream.Close();
return allData;
}
/// <summary>
/// Parses the given message.
/// </summary>
public override void ParseBytes(byte[] data)
{
int headerAndBodyHeaderLen = header.ParseHeader(data);
byte[] bodyAndFooter = new byte[data.Length - headerAndBodyHeaderLen];
Buffer.BlockCopy(data, headerAndBodyHeaderLen, bodyAndFooter, 0, bodyAndFooter.Length);
Stream stream = new MemoryStream(bodyAndFooter);
BinaryReader reader = new BinaryReader(stream);
int innerBodyLen = 0;
if (header.MessageSize > 0)
{
if (version == P2PVersion.P2PV1)
{
InnerBody = reader.ReadBytes((int)header.MessageSize);
innerBodyLen = InnerBody.Length;
}
else if (version == P2PVersion.P2PV2)
{
InnerBody = reader.ReadBytes((int)(header.MessageSize - V2Header.DataPacketHeaderLength));
innerBodyLen = InnerBody.Length;
}
}
else
{
InnerBody = new byte[0];
}
if ((data.Length - (headerAndBodyHeaderLen + innerBodyLen)) >= 4)
{
footer = BitUtility.ToBigEndian(reader.ReadUInt32());
}
reader.Close();
stream.Close();
}
/// <summary>
/// Returns the inner message as a byte array.
/// </summary>
/// <remarks>
/// If the inner message is set the GetBytes() method is called upon that inner message.
/// If there is no inner message set, but the InnerBody property contains data then
/// that data is returned.
/// </remarks>
/// <returns></returns>
protected virtual byte[] GetInnerBytes()
{
return (InnerBody != null)
? InnerBody
: (InnerMessage != null ? InnerMessage.GetBytes() : new byte[0]);
}
};
#endregion
#region P2PDataMessage
/// <summary>
/// Represents a single P2PDataMessage which is used for the actual data transfer. No negotiation handling.
/// </summary>
/// <remarks>
/// A p2p data message can be identified by looking at the footer in the P2P Message.
/// When this value is > 0 a data message is send. When this value is 0 a normal, and more complex, MSNSLPMessage is send.
/// This class is created to provide a fast way of sending messages.
/// </remarks>
[Serializable]
public class P2PDataMessage : P2PMessage
{
/// <summary>
/// Constructs a P2P data message.
/// </summary>
public P2PDataMessage(P2PVersion v)
: base(v)
{
}
public P2PDataMessage(P2PMessage copy)
: base(copy)
{
}
/// <summary>
/// Writes 4 nul-bytes in the inner body. This message can then be used as a data preparation message.
/// </summary>
public void WritePreparationBytes()
{
InnerBody = new byte[4] { 0, 0, 0, 0 };
}
/// <summary>
/// Reads data from the stream and writes it to the inner body. Sets offset, total size, message size
/// and data remaining properly.
/// </summary>
/// <param name="ioStream">The stream to read from</param>
/// <param name="maxLength">Maximum read length</param>
public int WriteBytes(Stream ioStream, int maxLength)
{
ulong streamLen = (ulong)ioStream.Length;
ulong streamPos = (ulong)ioStream.Position;
int minReadable = (int)Math.Min((ulong)maxLength, (ulong)(streamLen - streamPos));
if (Version == P2PVersion.P2PV1)
{
V1Header.Offset = streamPos;
V1Header.TotalSize = streamLen;
}
else if (Version == P2PVersion.P2PV2)
{
// We must calculate DataRemaining before setting InnerBody for p2pv2.
// Otherwise, MessageSize will be calculated incorrectly.
V2Header.DataRemaining = (ulong)(streamLen - (streamPos + (ulong)minReadable));
}
InnerBody = new byte[minReadable];
int read = ioStream.Read(InnerBody, 0, (int)minReadable);
Debug.Assert(read == minReadable, "Calculated incorrectly?");
return read;
}
public override string ToString()
{
return "[P2PDataMessage]\r\n" + base.ToString();
}
};
#endregion
#region P2PDCMessage
/// <summary>
/// A P2P Message which is send in a direct-connection.
/// </summary>
/// <remarks>
/// The innerbody contents are used as message contents (data).
/// The InnerMessage object and footer is ignored.
/// </remarks>
[Serializable]
public class P2PDCMessage : P2PDataMessage
{
public P2PDCMessage(P2PVersion ver)
: base(ver)
{
}
/// <summary>
/// Copy constructor. Creates a shallow copy of the properties of the P2PMessage.
/// </summary>
/// <param name="message"></param>
public P2PDCMessage(P2PMessage message)
: base(message)
{
}
/// <summary>
/// Writes no footer, but a 4 byte length size in front of the header.
/// </summary>
/// <returns></returns>
public override byte[] GetBytes()
{
byte[] dataWithoutFooter = base.GetBytes(false);
byte[] p2pMessage = new byte[4 + dataWithoutFooter.Length];
Stream memStream = new MemoryStream(p2pMessage);
BinaryWriter writer = new BinaryWriter(memStream);
writer.Write(BitUtility.ToLittleEndian((uint)dataWithoutFooter.Length));
writer.Write(dataWithoutFooter);
writer.Close();
memStream.Close();
return p2pMessage;
}
/// <summary>
/// Parses a data message without the 4-byte length header and without a 4 byte footer.
/// </summary>
/// <param name="data"></param>
public override void ParseBytes(byte[] data)
{
base.ParseBytes(data);
}
public override string ToString()
{
return "[P2PDCMessage]\r\n" + base.ToString();
}
};
#endregion
#region P2PDCHandshakeMessage
/// <summary>
/// A P2P Message which is send in a direct-connection.
/// </summary>
/// <remarks>
/// The InnerBody is 0 length byte.
/// The InnerMessage is null.
/// </remarks>
[Serializable]
public class P2PDCHandshakeMessage : P2PDCMessage
{
private Guid guid;
/// <summary>
/// The Guid to use in the handshake message.
/// </summary>
public Guid Guid
{
get
{
return guid;
}
set
{
guid = value;
if (Version == P2PVersion.P2PV1)
{
// Copy this guid to the last 16 bytes of this message.
// Affected fields: AckSessionId, AckIdentifier, AckTotalSize
byte[] guidData = guid.ToByteArray();
V1Header.AckSessionId = BitUtility.ToUInt32(guidData, 0, BitConverter.IsLittleEndian);
V1Header.AckIdentifier = BitUtility.ToUInt32(guidData, 4, BitConverter.IsLittleEndian);
V1Header.AckTotalSize = BitUtility.ToUInt64(guidData, 8, BitConverter.IsLittleEndian);
}
}
}
/// <summary>
/// Defaults the Flags property to 0x100.
/// </summary>
public P2PDCHandshakeMessage(P2PVersion ver)
: base(ver)
{
if (ver == P2PVersion.P2PV1)
V1Header.Flags = P2PFlag.DirectHandshake;
InnerBody = new byte[0];
}
/// <summary>
/// Creates an acknowledgement message to a handshake message. This will only set the flag to 0.
/// </summary>
/// <returns></returns>
public override P2PMessage CreateAcknowledgement()
{
// re-create a copy of this message, it is just the same copy!
P2PDCMessage ackMessage = new P2PDCMessage(this);
// set the identifier to 0 to set our own local identifier
ackMessage.Header.Identifier = 0;
return ackMessage;
}
public override void ParseBytes(byte[] data)
{
if (Version == P2PVersion.P2PV1)
{
base.ParseBytes(data);
P2Pv1Header head = this.V1Header;
Guid = new Guid(
(int)head.AckSessionId,
(short)(head.AckIdentifier & 0x0000FFFF),
(short)((head.AckIdentifier & 0xFFFF0000) >> 16),
(byte)((head.AckTotalSize & 0x00000000000000FF)),
(byte)((head.AckTotalSize & 0x000000000000FF00) >> 8),
(byte)((head.AckTotalSize & 0x0000000000FF0000) >> 16),
(byte)((head.AckTotalSize & 0x00000000FF000000) >> 24),
(byte)((head.AckTotalSize & 0x000000FF00000000) >> 32),
(byte)((head.AckTotalSize & 0x0000FF0000000000) >> 40),
(byte)((head.AckTotalSize & 0x00FF000000000000) >> 48),
(byte)((head.AckTotalSize & 0xFF00000000000000) >> 56)
);
}
else
{
// Don't call base.ParseBytes(); Data is 16 bytes for v2.
Guid = HashedNonceGenerator.CreateGuidFromData(Version, data);
}
InnerBody = new byte[0];
}
/// <summary>
/// Writes no footer.
/// </summary>
/// <returns></returns>
public override byte[] GetBytes()
{
InnerBody = new byte[0];
byte[] guidData = guid.ToByteArray();
if (Version == P2PVersion.P2PV1)
{
byte[] handshakeMessage = base.GetBytes(); // Calls P2PDCMessage.GetBytes();
Buffer.BlockCopy(guidData, 0, handshakeMessage, handshakeMessage.Length - guidData.Length, guidData.Length);
return handshakeMessage;
}
else
{
// UINT(LE) + GUID, Don't call base.GetBytes(); Because this is 20 bytes for v2.
byte[] totalMessage = new byte[4 + 16];
byte[] packetSize = BitUtility.GetBytes((UInt32)16, true);
Buffer.BlockCopy(packetSize, 0, totalMessage, 0, packetSize.Length);
Buffer.BlockCopy(guidData, 0, totalMessage, packetSize.Length, guidData.Length);
return totalMessage;
}
}
public override string ToString()
{
return "[P2PDCHandshakeMessage]\r\n" +
String.Format(System.Globalization.CultureInfo.InvariantCulture, "Guid : {0}\r\n", this.Guid.ToString()) +
(Version == P2PVersion.P2PV1 ? base.ToString() : String.Empty);
}
}
#endregion
};
| |
#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
using System;
using System.Collections.Generic;
using System.Diagnostics;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using System.Text;
using System.IO;
using System.Xml;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
internal enum ReadType
{
Read,
ReadAsInt32,
ReadAsBytes,
ReadAsString,
ReadAsDecimal,
ReadAsDateTime,
#if !NET20
ReadAsDateTimeOffset
#endif
}
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to JSON text data.
/// </summary>
public class JsonTextReader : JsonReader, IJsonLineInfo
{
private const char UnicodeReplacementChar = '\uFFFD';
private readonly TextReader _reader;
private char[] _chars;
private int _charsUsed;
private int _charPos;
private int _lineStartPos;
private int _lineNumber;
private bool _isEndOfFile;
private StringBuffer _buffer;
private StringReference _stringReference;
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
/// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param>
public JsonTextReader(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
_reader = reader;
_lineNumber = 1;
_chars = new char[1025];
}
#if DEBUG
internal void SetCharBuffer(char[] chars)
{
_chars = chars;
}
#endif
private StringBuffer GetBuffer()
{
if (_buffer == null)
{
_buffer = new StringBuffer(1025);
}
else
{
_buffer.Position = 0;
}
return _buffer;
}
private void OnNewLine(int pos)
{
_lineNumber++;
_lineStartPos = pos - 1;
}
private void ParseString(char quote)
{
_charPos++;
ShiftBufferIfNeeded();
ReadStringIntoBuffer(quote);
if (_readType == ReadType.ReadAsBytes)
{
byte[] data;
if (_stringReference.Length == 0)
{
data = new byte[0];
}
else
{
data = Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length);
}
SetToken(JsonToken.Bytes, data);
}
else if (_readType == ReadType.ReadAsString)
{
string text = _stringReference.ToString();
SetToken(JsonToken.String, text);
_quoteChar = quote;
}
else
{
string text = _stringReference.ToString();
if (_dateParseHandling != DateParseHandling.None)
{
DateParseHandling dateParseHandling;
if (_readType == ReadType.ReadAsDateTime)
dateParseHandling = DateParseHandling.DateTime;
#if !NET20
else if (_readType == ReadType.ReadAsDateTimeOffset)
dateParseHandling = DateParseHandling.DateTimeOffset;
#endif
else
dateParseHandling = _dateParseHandling;
object dt;
if (DateTimeUtils.TryParseDateTime(text, dateParseHandling, DateTimeZoneHandling, DateFormatString, Culture, out dt))
{
SetToken(JsonToken.Date, dt);
return;
}
}
SetToken(JsonToken.String, text);
_quoteChar = quote;
}
}
private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count)
{
const int charByteCount = 2;
Buffer.BlockCopy(src, srcOffset * charByteCount, dst, dstOffset * charByteCount, count * charByteCount);
}
private void ShiftBufferIfNeeded()
{
// once in the last 10% of the buffer shift the remainling content to the start to avoid
// unnessesarly increasing the buffer size when reading numbers/strings
int length = _chars.Length;
if (length - _charPos <= length * 0.1)
{
int count = _charsUsed - _charPos;
if (count > 0)
BlockCopyChars(_chars, _charPos, _chars, 0, count);
_lineStartPos -= _charPos;
_charPos = 0;
_charsUsed = count;
_chars[_charsUsed] = '\0';
}
}
private int ReadData(bool append)
{
return ReadData(append, 0);
}
private int ReadData(bool append, int charsRequired)
{
if (_isEndOfFile)
return 0;
// char buffer is full
if (_charsUsed + charsRequired >= _chars.Length - 1)
{
if (append)
{
// copy to new array either double the size of the current or big enough to fit required content
int newArrayLength = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1);
// increase the size of the buffer
char[] dst = new char[newArrayLength];
BlockCopyChars(_chars, 0, dst, 0, _chars.Length);
_chars = dst;
}
else
{
int remainingCharCount = _charsUsed - _charPos;
if (remainingCharCount + charsRequired + 1 >= _chars.Length)
{
// the remaining count plus the required is bigger than the current buffer size
char[] dst = new char[remainingCharCount + charsRequired + 1];
if (remainingCharCount > 0)
BlockCopyChars(_chars, _charPos, dst, 0, remainingCharCount);
_chars = dst;
}
else
{
// copy any remaining data to the beginning of the buffer if needed and reset positions
if (remainingCharCount > 0)
BlockCopyChars(_chars, _charPos, _chars, 0, remainingCharCount);
}
_lineStartPos -= _charPos;
_charPos = 0;
_charsUsed = remainingCharCount;
}
}
int attemptCharReadCount = _chars.Length - _charsUsed - 1;
int charsRead = _reader.Read(_chars, _charsUsed, attemptCharReadCount);
_charsUsed += charsRead;
if (charsRead == 0)
_isEndOfFile = true;
_chars[_charsUsed] = '\0';
return charsRead;
}
private bool EnsureChars(int relativePosition, bool append)
{
if (_charPos + relativePosition >= _charsUsed)
return ReadChars(relativePosition, append);
return true;
}
private bool ReadChars(int relativePosition, bool append)
{
if (_isEndOfFile)
return false;
int charsRequired = _charPos + relativePosition - _charsUsed + 1;
int totalCharsRead = 0;
// it is possible that the TextReader doesn't return all data at once
// repeat read until the required text is returned or the reader is out of content
do
{
int charsRead = ReadData(append, charsRequired - totalCharsRead);
// no more content
if (charsRead == 0)
break;
totalCharsRead += charsRead;
} while (totalCharsRead < charsRequired);
if (totalCharsRead < charsRequired)
return false;
return true;
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>
/// true if the next token was read successfully; false if there are no more tokens to read.
/// </returns>
[DebuggerStepThrough]
public override bool Read()
{
_readType = ReadType.Read;
if (!ReadInternal())
{
SetToken(JsonToken.None);
return false;
}
return true;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>
/// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.
/// </returns>
public override byte[] ReadAsBytes()
{
return ReadAsBytesInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override decimal? ReadAsDecimal()
{
return ReadAsDecimalInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override int? ReadAsInt32()
{
return ReadAsInt32Internal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override string ReadAsString()
{
return ReadAsStringInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override DateTime? ReadAsDateTime()
{
return ReadAsDateTimeInternal();
}
#if !NET20
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns>
public override DateTimeOffset? ReadAsDateTimeOffset()
{
return ReadAsDateTimeOffsetInternal();
}
#endif
internal override bool ReadInternal()
{
while (true)
{
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValue();
case State.Complete:
break;
case State.Object:
case State.ObjectStart:
return ParseObject();
case State.PostValue:
// returns true if it hits
// end of object or array
if (ParsePostValue())
return true;
break;
case State.Finished:
if (EnsureChars(0, false))
{
EatWhitespace(false);
if (_isEndOfFile)
{
return false;
}
if (_chars[_charPos] == '/')
{
ParseComment();
return true;
}
else
{
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
}
return false;
case State.Closed:
break;
case State.Error:
break;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
}
private void ReadStringIntoBuffer(char quote)
{
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
StringBuffer buffer = null;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
if (ReadData(true) == 0)
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
}
break;
case '\\':
_charPos = charPos;
if (!EnsureChars(0, true))
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
// start of escape sequence
int escapeStartPos = charPos - 1;
char currentChar = _chars[charPos];
char writeChar;
switch (currentChar)
{
case 'b':
charPos++;
writeChar = '\b';
break;
case 't':
charPos++;
writeChar = '\t';
break;
case 'n':
charPos++;
writeChar = '\n';
break;
case 'f':
charPos++;
writeChar = '\f';
break;
case 'r':
charPos++;
writeChar = '\r';
break;
case '\\':
charPos++;
writeChar = '\\';
break;
case '"':
case '\'':
case '/':
writeChar = currentChar;
charPos++;
break;
case 'u':
charPos++;
_charPos = charPos;
writeChar = ParseUnicode();
if (StringUtils.IsLowSurrogate(writeChar))
{
// low surrogate with no preceding high surrogate; this char is replaced
writeChar = UnicodeReplacementChar;
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
bool anotherHighSurrogate;
// loop for handling situations where there are multiple consecutive high surrogates
do
{
anotherHighSurrogate = false;
// potential start of a surrogate pair
if (EnsureChars(2, true) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u')
{
char highSurrogate = writeChar;
_charPos += 2;
writeChar = ParseUnicode();
if (StringUtils.IsLowSurrogate(writeChar))
{
// a valid surrogate pair!
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
// another high surrogate; replace current and start check over
highSurrogate = UnicodeReplacementChar;
anotherHighSurrogate = true;
}
else
{
// high surrogate not followed by low surrogate; original char is replaced
highSurrogate = UnicodeReplacementChar;
}
if (buffer == null)
buffer = GetBuffer();
WriteCharToBuffer(buffer, highSurrogate, lastWritePosition, escapeStartPos);
lastWritePosition = _charPos;
}
else
{
// there are not enough remaining chars for the low surrogate or is not follow by unicode sequence
// replace high surrogate and continue on as usual
writeChar = UnicodeReplacementChar;
}
} while (anotherHighSurrogate);
}
charPos = _charPos;
break;
default:
charPos++;
_charPos = charPos;
throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
}
if (buffer == null)
buffer = GetBuffer();
WriteCharToBuffer(buffer, writeChar, lastWritePosition, escapeStartPos);
lastWritePosition = charPos;
break;
case StringUtils.CarriageReturn:
_charPos = charPos - 1;
ProcessCarriageReturn(true);
charPos = _charPos;
break;
case StringUtils.LineFeed:
_charPos = charPos - 1;
ProcessLineFeed();
charPos = _charPos;
break;
case '"':
case '\'':
if (_chars[charPos - 1] == quote)
{
charPos--;
if (initialPosition == lastWritePosition)
{
_stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition);
}
else
{
if (buffer == null)
buffer = GetBuffer();
if (charPos > lastWritePosition)
buffer.Append(_chars, lastWritePosition, charPos - lastWritePosition);
_stringReference = new StringReference(buffer.GetInternalBuffer(), 0, buffer.Position);
}
charPos++;
_charPos = charPos;
return;
}
break;
}
}
}
private void WriteCharToBuffer(StringBuffer buffer, char writeChar, int lastWritePosition, int writeToPosition)
{
if (writeToPosition > lastWritePosition)
{
buffer.Append(_chars, lastWritePosition, writeToPosition - lastWritePosition);
}
buffer.Append(writeChar);
}
private char ParseUnicode()
{
char writeChar;
if (EnsureChars(4, true))
{
string hexValues = new string(_chars, _charPos, 4);
char hexChar = Convert.ToChar(int.Parse(hexValues, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo));
writeChar = hexChar;
_charPos += 4;
}
else
{
throw JsonReaderException.Create(this, "Unexpected end while parsing unicode character.");
}
return writeChar;
}
private void ReadNumberIntoBuffer()
{
int charPos = _charPos;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
_charPos = charPos;
if (ReadData(true) == 0)
return;
}
else
{
_charPos = charPos - 1;
return;
}
break;
case '-':
case '+':
case 'a':
case 'A':
case 'b':
case 'B':
case 'c':
case 'C':
case 'd':
case 'D':
case 'e':
case 'E':
case 'f':
case 'F':
case 'x':
case 'X':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
break;
default:
_charPos = charPos - 1;
return;
}
}
}
private void ClearRecentString()
{
if (_buffer != null)
_buffer.Position = 0;
_stringReference = new StringReference();
}
private bool ParsePostValue()
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
{
_currentState = State.Finished;
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
_charPos++;
SetToken(JsonToken.EndObject);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case '/':
ParseComment();
return true;
case ',':
_charPos++;
// finished parsing
SetStateBasedOnCurrent();
return false;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
break;
}
}
}
private bool ParseObject()
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
return false;
}
else
{
_charPos++;
}
break;
case '}':
SetToken(JsonToken.EndObject);
_charPos++;
return true;
case '/':
ParseComment();
return true;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
return ParseProperty();
}
break;
}
}
}
private bool ParseProperty()
{
char firstChar = _chars[_charPos];
char quoteChar;
if (firstChar == '"' || firstChar == '\'')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
ReadStringIntoBuffer(quoteChar);
}
else if (ValidIdentifierChar(firstChar))
{
quoteChar = '\0';
ShiftBufferIfNeeded();
ParseUnquotedProperty();
}
else
{
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
string propertyName = _stringReference.ToString();
EatWhitespace(false);
if (_chars[_charPos] != ':')
throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++;
SetToken(JsonToken.PropertyName, propertyName);
_quoteChar = quoteChar;
ClearRecentString();
return true;
}
private bool ValidIdentifierChar(char value)
{
return (char.IsLetterOrDigit(value) || value == '_' || value == '$');
}
private void ParseUnquotedProperty()
{
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
while (true)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(true) == 0)
throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
break;
}
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
default:
char currentChar = _chars[_charPos];
if (ValidIdentifierChar(currentChar))
{
_charPos++;
break;
}
else if (char.IsWhiteSpace(currentChar) || currentChar == ':')
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
}
throw JsonReaderException.Create(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
}
private bool ParseValue()
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
return false;
}
else
{
_charPos++;
}
break;
case '"':
case '\'':
ParseString(currentChar);
return true;
case 't':
ParseTrue();
return true;
case 'f':
ParseFalse();
return true;
case 'n':
if (EnsureChars(1, true))
{
char next = _chars[_charPos + 1];
if (next == 'u')
ParseNull();
else if (next == 'e')
ParseConstructor();
else
throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
else
{
throw JsonReaderException.Create(this, "Unexpected end.");
}
return true;
case 'N':
ParseNumberNaN();
return true;
case 'I':
ParseNumberPositiveInfinity();
return true;
case '-':
if (EnsureChars(1, true) && _chars[_charPos + 1] == 'I')
ParseNumberNegativeInfinity();
else
ParseNumber();
return true;
case '/':
ParseComment();
return true;
case 'u':
ParseUndefined();
return true;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
return true;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ',':
// don't increment position, the next call to read will handle comma
// this is done to handle multiple empty comma values
SetToken(JsonToken.Undefined);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
break;
}
else if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.')
{
ParseNumber();
return true;
}
else
{
throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
}
}
private void ProcessLineFeed()
{
_charPos++;
OnNewLine(_charPos);
}
private void ProcessCarriageReturn(bool append)
{
_charPos++;
if (EnsureChars(1, append) && _chars[_charPos] == StringUtils.LineFeed)
_charPos++;
OnNewLine(_charPos);
}
private bool EatWhitespace(bool oneOrMore)
{
bool finished = false;
bool ateWhitespace = false;
while (!finished)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
finished = true;
}
else
{
_charPos++;
}
break;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (currentChar == ' ' || char.IsWhiteSpace(currentChar))
{
ateWhitespace = true;
_charPos++;
}
else
{
finished = true;
}
break;
}
}
return (!oneOrMore || ateWhitespace);
}
private void ParseConstructor()
{
if (MatchValueWithTrailingSeparator("new"))
{
EatWhitespace(false);
int initialPosition = _charPos;
int endPosition;
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (ReadData(true) == 0)
throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
}
else
{
endPosition = _charPos;
_charPos++;
break;
}
}
else if (char.IsLetterOrDigit(currentChar))
{
_charPos++;
}
else if (currentChar == StringUtils.CarriageReturn)
{
endPosition = _charPos;
ProcessCarriageReturn(true);
break;
}
else if (currentChar == StringUtils.LineFeed)
{
endPosition = _charPos;
ProcessLineFeed();
break;
}
else if (char.IsWhiteSpace(currentChar))
{
endPosition = _charPos;
_charPos++;
break;
}
else if (currentChar == '(')
{
endPosition = _charPos;
break;
}
else
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
_stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition);
string constructorName = _stringReference.ToString();
EatWhitespace(false);
if (_chars[_charPos] != '(')
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++;
ClearRecentString();
SetToken(JsonToken.StartConstructor, constructorName);
}
else
{
throw JsonReaderException.Create(this, "Unexpected content while parsing JSON.");
}
}
private void ParseNumber()
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
ReadNumberIntoBuffer();
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
object numberValue;
JsonToken numberType;
bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1);
bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1
&& _stringReference.Chars[_stringReference.StartIndex + 1] != '.'
&& _stringReference.Chars[_stringReference.StartIndex + 1] != 'e'
&& _stringReference.Chars[_stringReference.StartIndex + 1] != 'E');
if (_readType == ReadType.ReadAsInt32)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
// decimal.Parse doesn't support parsing hexadecimal values
int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt32(number, 16)
: Convert.ToInt32(number, 8);
numberValue = integer;
}
else
{
int value;
ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
if (parseResult == ParseResult.Success)
numberValue = value;
else if (parseResult == ParseResult.Overflow)
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int32.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
numberType = JsonToken.Integer;
}
else if (_readType == ReadType.ReadAsDecimal)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (decimal)firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
// decimal.Parse doesn't support parsing hexadecimal values
long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
numberValue = Convert.ToDecimal(integer);
}
else
{
string number = _stringReference.ToString();
decimal value;
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value))
numberValue = value;
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
numberType = JsonToken.Float;
}
else
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (long)firstChar - 48;
numberType = JsonToken.Integer;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
numberType = JsonToken.Integer;
}
else
{
long value;
ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
if (parseResult == ParseResult.Success)
{
numberValue = value;
numberType = JsonToken.Integer;
}
else if (parseResult == ParseResult.Overflow)
{
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
string number = _stringReference.ToString();
numberValue = BigInteger.Parse(number, CultureInfo.InvariantCulture);
numberType = JsonToken.Integer;
#else
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
#endif
}
else
{
string number = _stringReference.ToString();
if (_floatParseHandling == FloatParseHandling.Decimal)
{
decimal d;
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out d))
numberValue = d;
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number));
}
else
{
double d;
if (double.TryParse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
numberValue = d;
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number));
}
numberType = JsonToken.Float;
}
}
}
ClearRecentString();
SetToken(numberType, numberValue);
}
private void ParseComment()
{
// should have already parsed / character before reaching this method
_charPos++;
if (!EnsureChars(1, false))
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
bool singlelineComment;
if (_chars[_charPos] == '*')
singlelineComment = false;
else if (_chars[_charPos] == '/')
singlelineComment = true;
else
throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++;
int initialPosition = _charPos;
bool commentFinished = false;
while (!commentFinished)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(true) == 0)
{
if (!singlelineComment)
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
commentFinished = true;
}
}
else
{
_charPos++;
}
break;
case '*':
_charPos++;
if (!singlelineComment)
{
if (EnsureChars(0, true))
{
if (_chars[_charPos] == '/')
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition - 1);
_charPos++;
commentFinished = true;
}
}
}
break;
case StringUtils.CarriageReturn:
if (singlelineComment)
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
commentFinished = true;
}
ProcessCarriageReturn(true);
break;
case StringUtils.LineFeed:
if (singlelineComment)
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
commentFinished = true;
}
ProcessLineFeed();
break;
default:
_charPos++;
break;
}
}
SetToken(JsonToken.Comment, _stringReference.ToString());
ClearRecentString();
}
private bool MatchValue(string value)
{
if (!EnsureChars(value.Length - 1, true))
return false;
for (int i = 0; i < value.Length; i++)
{
if (_chars[_charPos + i] != value[i])
{
return false;
}
}
_charPos += value.Length;
return true;
}
private bool MatchValueWithTrailingSeparator(string value)
{
// will match value and then move to the next character, checking that it is a separator character
bool match = MatchValue(value);
if (!match)
return false;
if (!EnsureChars(0, false))
return true;
return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0';
}
private bool IsSeparator(char c)
{
switch (c)
{
case '}':
case ']':
case ',':
return true;
case '/':
// check next character to see if start of a comment
if (!EnsureChars(1, false))
return false;
var nextChart = _chars[_charPos + 1];
return (nextChart == '*' || nextChart == '/');
case ')':
if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart)
return true;
break;
case ' ':
case StringUtils.Tab:
case StringUtils.LineFeed:
case StringUtils.CarriageReturn:
return true;
default:
if (char.IsWhiteSpace(c))
return true;
break;
}
return false;
}
private void ParseTrue()
{
// check characters equal 'true'
// and that it is followed by either a separator character
// or the text ends
if (MatchValueWithTrailingSeparator(JsonConvert.True))
{
SetToken(JsonToken.Boolean, true);
}
else
{
throw JsonReaderException.Create(this, "Error parsing boolean value.");
}
}
private void ParseNull()
{
if (MatchValueWithTrailingSeparator(JsonConvert.Null))
{
SetToken(JsonToken.Null);
}
else
{
throw JsonReaderException.Create(this, "Error parsing null value.");
}
}
private void ParseUndefined()
{
if (MatchValueWithTrailingSeparator(JsonConvert.Undefined))
{
SetToken(JsonToken.Undefined);
}
else
{
throw JsonReaderException.Create(this, "Error parsing undefined value.");
}
}
private void ParseFalse()
{
if (MatchValueWithTrailingSeparator(JsonConvert.False))
{
SetToken(JsonToken.Boolean, false);
}
else
{
throw JsonReaderException.Create(this, "Error parsing boolean value.");
}
}
private void ParseNumberNegativeInfinity()
{
if (MatchValueWithTrailingSeparator(JsonConvert.NegativeInfinity))
{
if (_floatParseHandling == FloatParseHandling.Decimal)
throw new JsonReaderException("Cannot read -Infinity as a decimal.");
SetToken(JsonToken.Float, double.NegativeInfinity);
}
else
{
throw JsonReaderException.Create(this, "Error parsing negative infinity value.");
}
}
private void ParseNumberPositiveInfinity()
{
if (MatchValueWithTrailingSeparator(JsonConvert.PositiveInfinity))
{
if (_floatParseHandling == FloatParseHandling.Decimal)
throw new JsonReaderException("Cannot read Infinity as a decimal.");
SetToken(JsonToken.Float, double.PositiveInfinity);
}
else
{
throw JsonReaderException.Create(this, "Error parsing positive infinity value.");
}
}
private void ParseNumberNaN()
{
if (MatchValueWithTrailingSeparator(JsonConvert.NaN))
{
if (_floatParseHandling == FloatParseHandling.Decimal)
throw new JsonReaderException("Cannot read NaN as a decimal.");
SetToken(JsonToken.Float, double.NaN);
}
else
{
throw JsonReaderException.Create(this, "Error parsing NaN value.");
}
}
/// <summary>
/// Changes the state to closed.
/// </summary>
public override void Close()
{
base.Close();
if (CloseInput && _reader != null)
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
_reader.Close();
#else
_reader.Dispose();
#endif
if (_buffer != null)
_buffer.Clear();
}
/// <summary>
/// Gets a value indicating whether the class can return line information.
/// </summary>
/// <returns>
/// <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>.
/// </returns>
public bool HasLineInfo()
{
return true;
}
/// <summary>
/// Gets the current line number.
/// </summary>
/// <value>
/// The current line number or 0 if no line information is available (for example, HasLineInfo returns false).
/// </value>
public int LineNumber
{
get
{
if (CurrentState == State.Start && LinePosition == 0)
return 0;
return _lineNumber;
}
}
/// <summary>
/// Gets the current line position.
/// </summary>
/// <value>
/// The current line position or 0 if no line information is available (for example, HasLineInfo returns false).
/// </value>
public int LinePosition
{
get { return _charPos - _lineStartPos; }
}
}
}
| |
//
// 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.
//
using NLog.LayoutRenderers;
using NLog.Targets;
using Xunit.Extensions;
namespace NLog.UnitTests.Config
{
using System;
using System.Globalization;
using System.Threading;
using Xunit;
using NLog.Config;
public class CultureInfoTests : NLogTestBase
{
[Fact]
public void WhenInvariantCultureDefinedThenDefaultCultureIsInvariantCulture()
{
var configuration = CreateConfigurationFromString("<nlog useInvariantCulture='true'></nlog>");
Assert.Equal(CultureInfo.InvariantCulture, configuration.DefaultCultureInfo);
}
[Fact]
public void DifferentConfigurations_UseDifferentDefaultCulture()
{
var currentCulture = CultureInfo.CurrentCulture;
try
{
// set the current thread culture to be definitely different from the InvariantCulture
Thread.CurrentThread.CurrentCulture = GetCultureInfo("de-DE");
var configurationTemplate = @"<nlog useInvariantCulture='{0}'>
<targets>
<target name='debug' type='Debug' layout='${{message}}' />
</targets>
<rules>
<logger name='*' writeTo='debug'/>
</rules>
</nlog>";
// configuration with current culture
var configuration1 = CreateConfigurationFromString(string.Format(configurationTemplate, false));
Assert.Null(configuration1.DefaultCultureInfo);
// configuration with invariant culture
var configuration2 = CreateConfigurationFromString(string.Format(configurationTemplate, true));
Assert.Equal(CultureInfo.InvariantCulture, configuration2.DefaultCultureInfo);
Assert.NotEqual(configuration1.DefaultCultureInfo, configuration2.DefaultCultureInfo);
var testNumber = 3.14;
var testDate = DateTime.Now;
const string formatString = "{0},{1:d}";
AssertMessageFormattedWithCulture(configuration1, CultureInfo.CurrentCulture, formatString, testNumber, testDate);
AssertMessageFormattedWithCulture(configuration2, CultureInfo.InvariantCulture, formatString, testNumber, testDate);
}
finally
{
// restore current thread culture
Thread.CurrentThread.CurrentCulture = currentCulture;
}
}
private void AssertMessageFormattedWithCulture(LoggingConfiguration configuration, CultureInfo culture, string formatString, params object[] parameters)
{
var expected = string.Format(culture, formatString, parameters);
using (var logFactory = new LogFactory(configuration))
{
var logger = logFactory.GetLogger("test");
logger.Debug(formatString, parameters);
Assert.Equal(expected, GetDebugLastMessage("debug", configuration));
}
}
[Fact]
public void EventPropRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
var renderer = new EventPropertiesLayoutRenderer();
renderer.Item = "ADouble";
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
[Fact]
public void EventContextRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
#pragma warning disable 618
var renderer = new EventContextLayoutRenderer();
#pragma warning restore 618
renderer.Item = "ADouble";
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
[Fact]
public void ProcessInfoLayoutRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "."; // dot as date separator (01.10.2008)
string output = string.Empty;
var logEventInfo = CreateLogEventInfo(cultureName);
if (IsTravis())
{
Console.WriteLine("[SKIP] CultureInfoTests.ProcessInfoLayoutRendererCultureTest because we are running in Travis");
}
else
{
var renderer = new ProcessInfoLayoutRenderer();
renderer.Property = ProcessInfoProperty.StartTime;
renderer.Format = "d";
output = renderer.Render(logEventInfo);
Assert.Contains(expected, output);
Assert.DoesNotContain("/", output);
Assert.DoesNotContain("-", output);
}
var renderer2 = new ProcessInfoLayoutRenderer();
renderer2.Property = ProcessInfoProperty.PriorityClass;
renderer2.Format = "d";
output = renderer2.Render(logEventInfo);
Assert.True(output.Length >= 1);
Assert.True("012345678".IndexOf(output[0]) > 0);
}
[Fact]
public void AllEventPropRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "ADouble=1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
var renderer = new AllEventPropertiesLayoutRenderer();
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
[Theory]
[InlineData(typeof(TimeLayoutRenderer))]
[InlineData(typeof(ProcessTimeLayoutRenderer))]
public void DateTimeCultureTest(Type rendererType)
{
string cultureName = "de-DE";
string expected = ","; // decimal comma as separator for ticks
var logEventInfo = CreateLogEventInfo(cultureName);
var renderer = Activator.CreateInstance(rendererType) as LayoutRenderer;
Assert.NotNull(renderer);
string output = renderer.Render(logEventInfo);
Assert.Contains(expected, output);
Assert.DoesNotContain(".", output);
}
private static LogEventInfo CreateLogEventInfo(string cultureName)
{
var logEventInfo = new LogEventInfo(
LogLevel.Info,
"SomeName",
CultureInfo.GetCultureInfo(cultureName),
"SomeMessage",
null);
return logEventInfo;
}
/// <summary>
/// expected: exactly the same exception message + stack trace regardless of the CurrentUICulture
/// </summary>
[Fact]
public void ExceptionTest()
{
var target = new MemoryTarget { Layout = @"${exception:format=tostring}" };
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetCurrentClassLogger();
try
{
throw new InvalidOperationException();
}
catch (Exception ex)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US", false);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
logger.Error(ex, "");
#if !NETSTANDARD
Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE", false);
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE", false);
#endif
logger.Error(ex, "");
Assert.Equal(2, target.Logs.Count);
Assert.NotNull(target.Logs[0]);
Assert.NotNull(target.Logs[1]);
Assert.Equal(target.Logs[0], target.Logs[1]);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
namespace Orleans.Serialization.Invocation
{
public abstract class UnitTestRequest : IInvokable
{
public abstract int ArgumentCount { get; }
[DebuggerHidden]
public ValueTask<Response> Invoke()
{
try
{
var resultTask = InvokeInner();
if (resultTask.IsCompleted)
{
resultTask.GetAwaiter().GetResult();
return new ValueTask<Response>(Response.FromResult<object>(null));
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
[DebuggerHidden]
private static async ValueTask<Response> CompleteInvokeAsync(ValueTask resultTask)
{
try
{
await resultTask;
return Response.FromResult<object>(null);
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
[DebuggerHidden]
protected abstract ValueTask InvokeInner();
public abstract TTarget GetTarget<TTarget>();
public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder;
public abstract TArgument GetArgument<TArgument>(int index);
public abstract void SetArgument<TArgument>(int index, in TArgument value);
public abstract void Dispose();
public abstract string MethodName { get; }
public abstract Type[] MethodTypeArguments { get; }
public abstract string InterfaceName { get; }
public abstract Type InterfaceType { get; }
public abstract Type[] InterfaceTypeArguments { get; }
public abstract Type[] ParameterTypes { get; }
public abstract MethodInfo Method { get; }
}
public abstract class UnitTestRequest<TResult> : IInvokable
{
public abstract int ArgumentCount { get; }
[DebuggerHidden]
public ValueTask<Response> Invoke()
{
try
{
var resultTask = InvokeInner();
if (resultTask.IsCompleted)
{
return new ValueTask<Response>(Response.FromResult(resultTask.Result));
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
[DebuggerHidden]
private static async ValueTask<Response> CompleteInvokeAsync(ValueTask<TResult> resultTask)
{
try
{
var result = await resultTask;
return Response.FromResult(result);
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
[DebuggerHidden]
protected abstract ValueTask<TResult> InvokeInner();
public abstract TTarget GetTarget<TTarget>();
public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder;
public abstract TArgument GetArgument<TArgument>(int index);
public abstract void SetArgument<TArgument>(int index, in TArgument value);
public abstract void Dispose();
public abstract string MethodName { get; }
public abstract Type[] MethodTypeArguments { get; }
public abstract string InterfaceName { get; }
public abstract Type InterfaceType { get; }
public abstract Type[] InterfaceTypeArguments { get; }
public abstract Type[] ParameterTypes { get; }
public abstract MethodInfo Method { get; }
}
public abstract class UnitTestTaskRequest<TResult> : IInvokable
{
public abstract int ArgumentCount { get; }
[DebuggerHidden]
public ValueTask<Response> Invoke()
{
try
{
var resultTask = InvokeInner();
var status = resultTask.Status;
if (resultTask.IsCompleted)
{
return new ValueTask<Response>(Response.FromResult(resultTask.GetAwaiter().GetResult()));
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
[DebuggerHidden]
private static async ValueTask<Response> CompleteInvokeAsync(Task<TResult> resultTask)
{
try
{
var result = await resultTask;
return Response.FromResult(result);
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
[DebuggerHidden]
protected abstract Task<TResult> InvokeInner();
public abstract TTarget GetTarget<TTarget>();
public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder;
public abstract TArgument GetArgument<TArgument>(int index);
public abstract void SetArgument<TArgument>(int index, in TArgument value);
public abstract void Dispose();
public abstract string MethodName { get; }
public abstract Type[] MethodTypeArguments { get; }
public abstract string InterfaceName { get; }
public abstract Type InterfaceType { get; }
public abstract Type[] InterfaceTypeArguments { get; }
public abstract Type[] ParameterTypes { get; }
public abstract MethodInfo Method { get; }
}
public abstract class UnitTestTaskRequest : IInvokable
{
public abstract int ArgumentCount { get; }
[DebuggerHidden]
public ValueTask<Response> Invoke()
{
try
{
var resultTask = InvokeInner();
var status = resultTask.Status;
if (resultTask.IsCompleted)
{
resultTask.GetAwaiter().GetResult();
return new ValueTask<Response>(Response.FromResult<object>(null));
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
[DebuggerHidden]
private static async ValueTask<Response> CompleteInvokeAsync(Task resultTask)
{
try
{
await resultTask;
return Response.FromResult<object>(null);
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
[DebuggerHidden]
protected abstract Task InvokeInner();
public abstract TTarget GetTarget<TTarget>();
public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder;
public abstract TArgument GetArgument<TArgument>(int index);
public abstract void SetArgument<TArgument>(int index, in TArgument value);
public abstract void Dispose();
public abstract string MethodName { get; }
public abstract Type[] MethodTypeArguments { get; }
public abstract string InterfaceName { get; }
public abstract Type InterfaceType { get; }
public abstract Type[] InterfaceTypeArguments { get; }
public abstract Type[] ParameterTypes { get; }
public abstract MethodInfo Method { get; }
}
public abstract class UnitTestVoidRequest : IInvokable
{
public abstract int ArgumentCount { get; }
[DebuggerHidden]
public ValueTask<Response> Invoke()
{
try
{
InvokeInner();
return new ValueTask<Response>(Response.FromResult<object>(null));
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
// Generated
[DebuggerHidden]
protected abstract void InvokeInner();
public abstract TTarget GetTarget<TTarget>();
public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder;
public abstract TArgument GetArgument<TArgument>(int index);
public abstract void SetArgument<TArgument>(int index, in TArgument value);
public abstract void Dispose();
public abstract string MethodName { get; }
public abstract Type[] MethodTypeArguments { get; }
public abstract string InterfaceName { get; }
public abstract Type InterfaceType { get; }
public abstract Type[] InterfaceTypeArguments { get; }
public abstract Type[] ParameterTypes { get; }
public abstract MethodInfo Method { get; }
}
}
| |
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;
namespace LumiSoft.Net.ICMP
{
/// <summary>
/// ICMP type.
/// </summary>
public enum ICMP_Type
{
/// <summary>
/// Echo rely.
/// </summary>
EchoReply = 0,
/// <summary>
/// Time to live exceeded reply.
/// </summary>
TimeExceeded = 11,
/// <summary>
/// Echo.
/// </summary>
Echo = 8,
}
/// <summary>
/// Echo reply message.
/// </summary>
public class EchoMessage
{
private string m_IP = "";
private int m_TTL = 0;
private int m_Time = 0;
/// <summary>
///
/// </summary>
/// <param name="ip"></param>
/// <param name="ttl"></param>
/// <param name="time"></param>
public EchoMessage(string ip,int ttl,int time)
{
m_IP = ip;
m_TTL = ttl;
m_Time = time;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public string ToStringEx()
{
return "TTL=" + m_TTL + "\tTime=" + m_Time + "ms" + "\tIP=" + m_IP;
}
/// <summary>
///
/// </summary>
/// <param name="messages"></param>
/// <returns></returns>
public static string ToStringEx(EchoMessage[] messages)
{
string retVal = "";
foreach(EchoMessage m in messages){
retVal += m.ToStringEx() + "\r\n";
}
return retVal;
}
}
/// <summary>
/// Icmp utils.
/// </summary>
public class Icmp
{
// public Icmp()
// {
// }
#region function Trace
/// <summary>
/// Traces specified ip.
/// </summary>
/// <param name="destIP"></param>
/// <returns></returns>
public static EchoMessage[] Trace(string destIP)
{
ArrayList retVal = new ArrayList();
//Create Raw ICMP Socket
Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Raw,ProtocolType.Icmp);
IPEndPoint ipdest = new IPEndPoint(System.Net.IPAddress.Parse(destIP),80);
EndPoint endpoint = (EndPoint)(new IPEndPoint(System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0],80));
ushort id = (ushort)DateTime.Now.Millisecond;
byte[] ByteSend= CreatePacket(id);
int continuesNoReply = 0;
//send requests with increasing number of TTL
for(int ittl=1;ittl<=30; ittl++){
byte[] ByteRecv = new byte[256];
try
{
//Socket options to set TTL and Timeouts
s.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.IpTimeToLive ,ittl);
s.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.SendTimeout ,4000);
s.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,4000);
//Get current time
DateTime startTime = DateTime.Now;
//Send Request
s.SendTo(ByteSend,ByteSend.Length,SocketFlags.None,ipdest);
//Receive
s.ReceiveFrom(ByteRecv,ByteRecv.Length,SocketFlags.None,ref endpoint);
//Calculate time required
TimeSpan ts = DateTime.Now - startTime;
retVal.Add(new EchoMessage(((IPEndPoint)endpoint).Address.ToString(),ittl,ts.Milliseconds));
// Endpoint reached
if(ByteRecv[20] == (byte)ICMP_Type.EchoReply){
break;
}
// Un wanted reply
if(ByteRecv[20] != (byte)ICMP_Type.TimeExceeded){
throw new Exception("UnKnown error !");
}
continuesNoReply = 0;
}
catch{
//ToDo: Handle recive/send timeouts
continuesNoReply++;
}
// If there is 3 continues no reply, consider that destination host won't accept ping.
if(continuesNoReply >= 3){
break;
}
}
EchoMessage[] val = new EchoMessage[retVal.Count];
retVal.CopyTo(val);
return val;
}
#endregion
// public static void Ping(string destIP)
// {
// }
#region function CreatePacket
private static byte[] CreatePacket(ushort id)
{
/*Rfc 792 Echo or Echo Reply Message
0 8 16 24
+---------------+---------------+---------------+---------------+
| Type | Code | Checksum |
+---------------+---------------+---------------+---------------+
| ID Number | Sequence Number |
+---------------+---------------+---------------+---------------+
| Data...
+---------------+---------------+---------------+---------------+
*/
byte[] packet = new byte[8 + 2];
packet[0] = (byte)ICMP_Type.Echo; // Type
packet[1] = 0; // Code
packet[2] = 0; // Checksum
packet[3] = 0; // Checksum
packet[4] = 0; // ID
packet[5] = 0; // ID
packet[6] = 0; // Sequence
packet[7] = 0; // Sequence
// Set id
Array.Copy(BitConverter.GetBytes(id), 0, packet, 4, 2);
// Fill data 2 byte data
for(int i=0;i<2;i++){
packet[i + 8] = (byte)'x'; // Data
}
//calculate checksum
int checkSum = 0;
for(int i= 0;i<packet.Length;i+= 2){
checkSum += Convert.ToInt32(BitConverter.ToUInt16(packet,i));
}
//The checksum is the 16-bit ones's complement of the one's
//complement sum of the ICMP message starting with the ICMP Type.
checkSum = (checkSum & 0xffff);
Array.Copy(BitConverter.GetBytes((ushort)~checkSum),0,packet,2,2);
return packet;
}
#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.
// This RegexFCD class is internal to the Regex package.
// It builds a bunch of FC information (RegexFC) about
// the regex for optimization purposes.
// Implementation notes:
//
// This step is as simple as walking the tree and emitting
// sequences of codes.
using System.Globalization;
namespace System.Text.RegularExpressions
{
internal sealed class RegexFCD
{
private int[] _intStack;
private int _intDepth;
private RegexFC[] _fcStack;
private int _fcDepth;
private bool _skipAllChildren; // don't process any more children at the current level
private bool _skipchild; // don't process the current child.
private bool _failed = false;
private const int BeforeChild = 64;
private const int AfterChild = 128;
// where the regex can be pegged
internal const int Beginning = 0x0001;
internal const int Bol = 0x0002;
internal const int Start = 0x0004;
internal const int Eol = 0x0008;
internal const int EndZ = 0x0010;
internal const int End = 0x0020;
internal const int Boundary = 0x0040;
internal const int ECMABoundary = 0x0080;
/*
* This is the one of the only two functions that should be called from outside.
* It takes a RegexTree and computes the set of chars that can start it.
*/
internal static RegexPrefix FirstChars(RegexTree t)
{
RegexFCD s = new RegexFCD();
RegexFC fc = s.RegexFCFromRegexTree(t);
if (fc == null || fc._nullable)
return null;
CultureInfo culture = ((t._options & RegexOptions.CultureInvariant) != 0) ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture;
return new RegexPrefix(fc.GetFirstChars(culture), fc.IsCaseInsensitive());
}
/*
* This is a related computation: it takes a RegexTree and computes the
* leading substring if it see one. It's quite trivial and gives up easily.
*/
internal static RegexPrefix Prefix(RegexTree tree)
{
RegexNode curNode;
RegexNode concatNode = null;
int nextChild = 0;
curNode = tree._root;
for (; ;)
{
switch (curNode._type)
{
case RegexNode.Concatenate:
if (curNode.ChildCount() > 0)
{
concatNode = curNode;
nextChild = 0;
}
break;
case RegexNode.Greedy:
case RegexNode.Capture:
curNode = curNode.Child(0);
concatNode = null;
continue;
case RegexNode.Oneloop:
case RegexNode.Onelazy:
if (curNode._m > 0)
{
string pref = String.Empty.PadRight(curNode._m, curNode._ch);
return new RegexPrefix(pref, 0 != (curNode._options & RegexOptions.IgnoreCase));
}
else
return RegexPrefix.Empty;
case RegexNode.One:
return new RegexPrefix(curNode._ch.ToString(), 0 != (curNode._options & RegexOptions.IgnoreCase));
case RegexNode.Multi:
return new RegexPrefix(curNode._str, 0 != (curNode._options & RegexOptions.IgnoreCase));
case RegexNode.Bol:
case RegexNode.Eol:
case RegexNode.Boundary:
case RegexNode.ECMABoundary:
case RegexNode.Beginning:
case RegexNode.Start:
case RegexNode.EndZ:
case RegexNode.End:
case RegexNode.Empty:
case RegexNode.Require:
case RegexNode.Prevent:
break;
default:
return RegexPrefix.Empty;
}
if (concatNode == null || nextChild >= concatNode.ChildCount())
return RegexPrefix.Empty;
curNode = concatNode.Child(nextChild++);
}
}
/*
* Yet another related computation: it takes a RegexTree and computes the
* leading anchors that it encounters.
*/
internal static int Anchors(RegexTree tree)
{
RegexNode curNode;
RegexNode concatNode = null;
int nextChild = 0;
int result = 0;
curNode = tree._root;
for (; ;)
{
switch (curNode._type)
{
case RegexNode.Concatenate:
if (curNode.ChildCount() > 0)
{
concatNode = curNode;
nextChild = 0;
}
break;
case RegexNode.Greedy:
case RegexNode.Capture:
curNode = curNode.Child(0);
concatNode = null;
continue;
case RegexNode.Bol:
case RegexNode.Eol:
case RegexNode.Boundary:
case RegexNode.ECMABoundary:
case RegexNode.Beginning:
case RegexNode.Start:
case RegexNode.EndZ:
case RegexNode.End:
return result | AnchorFromType(curNode._type);
case RegexNode.Empty:
case RegexNode.Require:
case RegexNode.Prevent:
break;
default:
return result;
}
if (concatNode == null || nextChild >= concatNode.ChildCount())
return result;
curNode = concatNode.Child(nextChild++);
}
}
/*
* Convert anchor type to anchor bit.
*/
private static int AnchorFromType(int type)
{
switch (type)
{
case RegexNode.Bol: return Bol;
case RegexNode.Eol: return Eol;
case RegexNode.Boundary: return Boundary;
case RegexNode.ECMABoundary: return ECMABoundary;
case RegexNode.Beginning: return Beginning;
case RegexNode.Start: return Start;
case RegexNode.EndZ: return EndZ;
case RegexNode.End: return End;
default: return 0;
}
}
#if DEBUG
internal static String AnchorDescription(int anchors)
{
StringBuilder sb = new StringBuilder();
if (0 != (anchors & Beginning)) sb.Append(", Beginning");
if (0 != (anchors & Start)) sb.Append(", Start");
if (0 != (anchors & Bol)) sb.Append(", Bol");
if (0 != (anchors & Boundary)) sb.Append(", Boundary");
if (0 != (anchors & ECMABoundary)) sb.Append(", ECMABoundary");
if (0 != (anchors & Eol)) sb.Append(", Eol");
if (0 != (anchors & End)) sb.Append(", End");
if (0 != (anchors & EndZ)) sb.Append(", EndZ");
if (sb.Length >= 2)
return (sb.ToString(2, sb.Length - 2));
return "None";
}
#endif
/*
* private constructor; can't be created outside
*/
private RegexFCD()
{
_fcStack = new RegexFC[32];
_intStack = new int[32];
}
/*
* To avoid recursion, we use a simple integer stack.
* This is the push.
*/
private void PushInt(int I)
{
if (_intDepth >= _intStack.Length)
{
int[] expanded = new int[_intDepth * 2];
System.Array.Copy(_intStack, 0, expanded, 0, _intDepth);
_intStack = expanded;
}
_intStack[_intDepth++] = I;
}
/*
* True if the stack is empty.
*/
private bool IntIsEmpty()
{
return _intDepth == 0;
}
/*
* This is the pop.
*/
private int PopInt()
{
return _intStack[--_intDepth];
}
/*
* We also use a stack of RegexFC objects.
* This is the push.
*/
private void PushFC(RegexFC fc)
{
if (_fcDepth >= _fcStack.Length)
{
RegexFC[] expanded = new RegexFC[_fcDepth * 2];
System.Array.Copy(_fcStack, 0, expanded, 0, _fcDepth);
_fcStack = expanded;
}
_fcStack[_fcDepth++] = fc;
}
/*
* True if the stack is empty.
*/
private bool FCIsEmpty()
{
return _fcDepth == 0;
}
/*
* This is the pop.
*/
private RegexFC PopFC()
{
return _fcStack[--_fcDepth];
}
/*
* This is the top.
*/
private RegexFC TopFC()
{
return _fcStack[_fcDepth - 1];
}
/*
* The main FC computation. It does a shortcutted depth-first walk
* through the tree and calls CalculateFC to emits code before
* and after each child of an interior node, and at each leaf.
*/
private RegexFC RegexFCFromRegexTree(RegexTree tree)
{
RegexNode curNode;
int curChild;
curNode = tree._root;
curChild = 0;
for (; ;)
{
if (curNode._children == null)
{
// This is a leaf node
CalculateFC(curNode._type, curNode, 0);
}
else if (curChild < curNode._children.Count && !_skipAllChildren)
{
// This is an interior node, and we have more children to analyze
CalculateFC(curNode._type | BeforeChild, curNode, curChild);
if (!_skipchild)
{
curNode = (RegexNode)curNode._children[curChild];
// this stack is how we get a depth first walk of the tree.
PushInt(curChild);
curChild = 0;
}
else
{
curChild++;
_skipchild = false;
}
continue;
}
// This is an interior node where we've finished analyzing all the children, or
// the end of a leaf node.
_skipAllChildren = false;
if (IntIsEmpty())
break;
curChild = PopInt();
curNode = curNode._next;
CalculateFC(curNode._type | AfterChild, curNode, curChild);
if (_failed)
return null;
curChild++;
}
if (FCIsEmpty())
return null;
return PopFC();
}
/*
* Called in Beforechild to prevent further processing of the current child
*/
private void SkipChild()
{
_skipchild = true;
}
/*
* FC computation and shortcut cases for each node type
*/
private void CalculateFC(int NodeType, RegexNode node, int CurIndex)
{
bool ci = false;
bool rtl = false;
if (NodeType <= RegexNode.Ref)
{
if ((node._options & RegexOptions.IgnoreCase) != 0)
ci = true;
if ((node._options & RegexOptions.RightToLeft) != 0)
rtl = true;
}
switch (NodeType)
{
case RegexNode.Concatenate | BeforeChild:
case RegexNode.Alternate | BeforeChild:
case RegexNode.Testref | BeforeChild:
case RegexNode.Loop | BeforeChild:
case RegexNode.Lazyloop | BeforeChild:
break;
case RegexNode.Testgroup | BeforeChild:
if (CurIndex == 0)
SkipChild();
break;
case RegexNode.Empty:
PushFC(new RegexFC(true));
break;
case RegexNode.Concatenate | AfterChild:
if (CurIndex != 0)
{
RegexFC child = PopFC();
RegexFC cumul = TopFC();
_failed = !cumul.AddFC(child, true);
}
if (!TopFC()._nullable)
_skipAllChildren = true;
break;
case RegexNode.Testgroup | AfterChild:
if (CurIndex > 1)
{
RegexFC child = PopFC();
RegexFC cumul = TopFC();
_failed = !cumul.AddFC(child, false);
}
break;
case RegexNode.Alternate | AfterChild:
case RegexNode.Testref | AfterChild:
if (CurIndex != 0)
{
RegexFC child = PopFC();
RegexFC cumul = TopFC();
_failed = !cumul.AddFC(child, false);
}
break;
case RegexNode.Loop | AfterChild:
case RegexNode.Lazyloop | AfterChild:
if (node._m == 0)
TopFC()._nullable = true;
break;
case RegexNode.Group | BeforeChild:
case RegexNode.Group | AfterChild:
case RegexNode.Capture | BeforeChild:
case RegexNode.Capture | AfterChild:
case RegexNode.Greedy | BeforeChild:
case RegexNode.Greedy | AfterChild:
break;
case RegexNode.Require | BeforeChild:
case RegexNode.Prevent | BeforeChild:
SkipChild();
PushFC(new RegexFC(true));
break;
case RegexNode.Require | AfterChild:
case RegexNode.Prevent | AfterChild:
break;
case RegexNode.One:
case RegexNode.Notone:
PushFC(new RegexFC(node._ch, NodeType == RegexNode.Notone, false, ci));
break;
case RegexNode.Oneloop:
case RegexNode.Onelazy:
PushFC(new RegexFC(node._ch, false, node._m == 0, ci));
break;
case RegexNode.Notoneloop:
case RegexNode.Notonelazy:
PushFC(new RegexFC(node._ch, true, node._m == 0, ci));
break;
case RegexNode.Multi:
if (node._str.Length == 0)
PushFC(new RegexFC(true));
else if (!rtl)
PushFC(new RegexFC(node._str[0], false, false, ci));
else
PushFC(new RegexFC(node._str[node._str.Length - 1], false, false, ci));
break;
case RegexNode.Set:
PushFC(new RegexFC(node._str, false, ci));
break;
case RegexNode.Setloop:
case RegexNode.Setlazy:
PushFC(new RegexFC(node._str, node._m == 0, ci));
break;
case RegexNode.Ref:
PushFC(new RegexFC(RegexCharClass.AnyClass, true, false));
break;
case RegexNode.Nothing:
case RegexNode.Bol:
case RegexNode.Eol:
case RegexNode.Boundary:
case RegexNode.Nonboundary:
case RegexNode.ECMABoundary:
case RegexNode.NonECMABoundary:
case RegexNode.Beginning:
case RegexNode.Start:
case RegexNode.EndZ:
case RegexNode.End:
PushFC(new RegexFC(true));
break;
default:
throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, NodeType.ToString(CultureInfo.CurrentCulture)));
}
}
}
internal sealed class RegexFC
{
internal RegexCharClass _cc;
internal bool _nullable;
internal bool _caseInsensitive;
internal RegexFC(bool nullable)
{
_cc = new RegexCharClass();
_nullable = nullable;
}
internal RegexFC(char ch, bool not, bool nullable, bool caseInsensitive)
{
_cc = new RegexCharClass();
if (not)
{
if (ch > 0)
_cc.AddRange('\0', (char)(ch - 1));
if (ch < 0xFFFF)
_cc.AddRange((char)(ch + 1), '\uFFFF');
}
else
{
_cc.AddRange(ch, ch);
}
_caseInsensitive = caseInsensitive;
_nullable = nullable;
}
internal RegexFC(String charClass, bool nullable, bool caseInsensitive)
{
_cc = RegexCharClass.Parse(charClass);
_nullable = nullable;
_caseInsensitive = caseInsensitive;
}
internal bool AddFC(RegexFC fc, bool concatenate)
{
if (!_cc.CanMerge || !fc._cc.CanMerge)
{
return false;
}
if (concatenate)
{
if (!_nullable)
return true;
if (!fc._nullable)
_nullable = false;
}
else
{
if (fc._nullable)
_nullable = true;
}
_caseInsensitive |= fc._caseInsensitive;
_cc.AddCharClass(fc._cc);
return true;
}
internal String GetFirstChars(CultureInfo culture)
{
if (_caseInsensitive)
_cc.AddLowercase(culture);
return _cc.ToStringClass();
}
internal bool IsCaseInsensitive()
{
return _caseInsensitive;
}
}
internal sealed class RegexPrefix
{
internal String _prefix;
internal bool _caseInsensitive;
internal static RegexPrefix _empty = new RegexPrefix(String.Empty, false);
internal RegexPrefix(String prefix, bool ci)
{
_prefix = prefix;
_caseInsensitive = ci;
}
internal String Prefix
{
get
{
return _prefix;
}
}
internal bool CaseInsensitive
{
get
{
return _caseInsensitive;
}
}
internal static RegexPrefix Empty
{
get
{
return _empty;
}
}
}
}
| |
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using MvcTemplate.Components.Security;
using MvcTemplate.Data;
using MvcTemplate.Objects;
using MvcTemplate.Tests;
using NSubstitute;
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Xunit;
namespace MvcTemplate.Services.Tests
{
public class AccountServiceTests : IDisposable
{
private HttpContext httpContext;
private AccountService service;
private DbContext context;
private Account account;
private IHasher hasher;
public AccountServiceTests()
{
context = TestingContext.Create();
hasher = Substitute.For<IHasher>();
httpContext = new DefaultHttpContext();
service = new AccountService(new UnitOfWork(TestingContext.Create()), hasher);
hasher.HashPassword(Arg.Any<String>()).Returns(info => $"{info.Arg<String>()}Hashed");
context.Drop().Add(account = ObjectsFactory.CreateAccount(0));
context.SaveChanges();
service.CurrentAccountId = account.Id;
}
public void Dispose()
{
service.Dispose();
context.Dispose();
}
[Fact]
public void Get_ReturnsViewById()
{
AccountView actual = service.Get<AccountView>(account.Id)!;
AccountView expected = Mapper.Map<AccountView>(account);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.RoleTitle, actual.RoleTitle);
Assert.Equal(expected.IsLocked, actual.IsLocked);
Assert.Equal(expected.Username, actual.Username);
Assert.Equal(expected.Email, actual.Email);
Assert.Equal(expected.Id, actual.Id);
}
[Fact]
public void GetViews_ReturnsAccountViews()
{
AccountView[] actual = service.GetViews().ToArray();
AccountView[] expected = context
.Set<Account>()
.ProjectTo<AccountView>()
.OrderByDescending(view => view.Id)
.ToArray();
for (Int32 i = 0; i < expected.Length || i < actual.Length; i++)
{
Assert.Equal(expected[i].CreationDate, actual[i].CreationDate);
Assert.Equal(expected[i].RoleTitle, actual[i].RoleTitle);
Assert.Equal(expected[i].IsLocked, actual[i].IsLocked);
Assert.Equal(expected[i].Username, actual[i].Username);
Assert.Equal(expected[i].Email, actual[i].Email);
Assert.Equal(expected[i].Id, actual[i].Id);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void IsLoggedIn_ReturnsIsAuthenticated(Boolean isAuthenticated)
{
IPrincipal user = Substitute.For<IPrincipal>();
user.Identity?.IsAuthenticated.Returns(isAuthenticated);
Boolean actual = service.IsLoggedIn(user);
Boolean expected = isAuthenticated;
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void IsActive_ReturnsAccountState(Boolean isLocked)
{
account.IsLocked = isLocked;
context.Update(account);
context.SaveChanges();
Boolean actual = service.IsActive(account.Id);
Boolean expected = !isLocked;
Assert.Equal(expected, actual);
}
[Fact]
public void IsActive_NoAccount_ReturnsFalse()
{
Assert.False(service.IsActive(0));
}
[Fact]
public void Recover_NoEmail_ReturnsNull()
{
AccountRecoveryView view = ObjectsFactory.CreateAccountRecoveryView(account.Id + 1);
view.Email = "not@existing.email";
Assert.Null(service.Recover(view));
}
[Fact]
public void Recover_Information()
{
AccountRecoveryView view = ObjectsFactory.CreateAccountRecoveryView(0);
account.RecoveryTokenExpirationDate = DateTime.Now.AddMinutes(30);
String? oldToken = account.RecoveryToken;
view.Email = view.Email.ToUpper();
account.RecoveryToken = service.Recover(view);
Account actual = Assert.Single(context.Set<Account>().AsNoTracking());
Account expected = account;
Assert.InRange(actual.RecoveryTokenExpirationDate!.Value.Ticks,
expected.RecoveryTokenExpirationDate.Value.Ticks - TimeSpan.TicksPerSecond,
expected.RecoveryTokenExpirationDate.Value.Ticks + TimeSpan.TicksPerSecond);
Assert.Equal(expected.RecoveryToken, actual.RecoveryToken);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.IsLocked, actual.IsLocked);
Assert.Equal(expected.Passhash, actual.Passhash);
Assert.Equal(expected.Username, actual.Username);
Assert.NotEqual(oldToken, actual.RecoveryToken);
Assert.Equal(expected.RoleId, actual.RoleId);
Assert.Equal(expected.Email, actual.Email);
Assert.Equal(expected.Id, actual.Id);
Assert.NotNull(actual.RecoveryToken);
}
[Fact]
public void Reset_Account()
{
AccountResetView view = ObjectsFactory.CreateAccountResetView(0);
service.Reset(view);
Account actual = Assert.Single(context.Set<Account>().AsNoTracking());
Account expected = account;
Assert.Equal(hasher.HashPassword(view.NewPassword), actual.Passhash);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.IsLocked, actual.IsLocked);
Assert.Equal(expected.Username, actual.Username);
Assert.Null(actual.RecoveryTokenExpirationDate);
Assert.Equal(expected.RoleId, actual.RoleId);
Assert.Equal(expected.Email, actual.Email);
Assert.Equal(expected.Id, actual.Id);
Assert.Null(actual.RecoveryToken);
}
[Fact]
public void Create_Account()
{
AccountCreateView view = ObjectsFactory.CreateAccountCreateView(account.Id + 1);
view.Email = view.Email.ToUpper();
view.RoleId = account.RoleId;
service.Create(view);
Account actual = Assert.Single(context.Set<Account>(), model => model.Id != account.Id);
AccountCreateView expected = view;
Assert.Equal(hasher.HashPassword(expected.Password), actual.Passhash);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.Email?.ToLower(), actual.Email);
Assert.Equal(expected.Username, actual.Username);
Assert.Null(actual.RecoveryTokenExpirationDate);
Assert.Equal(expected.RoleId, actual.RoleId);
Assert.Null(actual.RecoveryToken);
Assert.False(actual.IsLocked);
}
[Fact]
public void Edit_Account()
{
AccountEditView view = ObjectsFactory.CreateAccountEditView(account.Id);
view.IsLocked = account.IsLocked = !account.IsLocked;
view.Username = $"{account.Username}Test";
view.RoleId = account.RoleId = null;
view.Email = $"{account.Email}s";
service.Edit(view);
Account actual = Assert.Single(context.Set<Account>().AsNoTracking());
Account expected = account;
Assert.Equal(expected.RecoveryTokenExpirationDate, actual.RecoveryTokenExpirationDate);
Assert.Equal(expected.RecoveryToken, actual.RecoveryToken);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.IsLocked, actual.IsLocked);
Assert.Equal(expected.Username, actual.Username);
Assert.Equal(expected.Passhash, actual.Passhash);
Assert.Equal(expected.RoleId, actual.RoleId);
Assert.Equal(expected.Email, actual.Email);
Assert.Equal(expected.Id, actual.Id);
}
[Fact]
public void Edit_Profile()
{
ProfileEditView view = ObjectsFactory.CreateProfileEditView(account.Id + 1);
account.Passhash = hasher.HashPassword(view.NewPassword!);
view.Username = account.Username += "Test";
view.Email = account.Email += "Test";
service.Edit(httpContext.User, view);
Account actual = Assert.Single(context.Set<Account>().AsNoTracking());
Account expected = account;
Assert.Equal(expected.RecoveryTokenExpirationDate, actual.RecoveryTokenExpirationDate);
Assert.Equal(expected.RecoveryToken, actual.RecoveryToken);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.Email.ToLower(), actual.Email);
Assert.Equal(expected.IsLocked, actual.IsLocked);
Assert.Equal(expected.Username, actual.Username);
Assert.Equal(expected.Passhash, actual.Passhash);
Assert.Equal(expected.RoleId, actual.RoleId);
Assert.Equal(expected.Id, actual.Id);
}
[Theory]
[InlineData("")]
[InlineData(null)]
[InlineData(" ")]
public void Edit_NullOrEmptyNewPassword_DoesNotEditPassword(String newPassword)
{
ProfileEditView view = ObjectsFactory.CreateProfileEditView(account.Id + 1);
view.NewPassword = newPassword;
service.Edit(httpContext.User, view);
String actual = Assert.Single(context.Set<Account>().AsNoTracking()).Passhash;
String expected = account.Passhash;
Assert.Equal(expected, actual);
}
[Fact]
public void Edit_UpdatesClaims()
{
httpContext.User.AddIdentity(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Email, "test@email.com"),
new Claim(ClaimTypes.Name, "TestName")
}));
ProfileEditView view = ObjectsFactory.CreateProfileEditView(account.Id + 1);
view.Username = account.Username += "Test";
view.Email = account.Email += "Test";
service.Edit(httpContext.User, view);
Account expected = account;
ClaimsPrincipal actual = httpContext.User;
Assert.Equal(expected.Username, actual.FindFirstValue(ClaimTypes.Name));
Assert.Equal(expected.Email.ToLower(), actual.FindFirstValue(ClaimTypes.Email));
}
[Fact]
public void Delete_Account()
{
service.Delete(account.Id);
Assert.Empty(context.Set<Account>());
}
[Fact]
public async Task Login_Account()
{
httpContext = Substitute.For<HttpContext>();
IAuthenticationService authentication = Substitute.For<IAuthenticationService>();
httpContext.RequestServices.GetService(typeof(IAuthenticationService)).Returns(authentication);
await service.Login(httpContext, account.Username.ToUpper());
await authentication.Received().SignInAsync(httpContext, "Cookies", Arg.Is<ClaimsPrincipal>(principal =>
principal.FindFirstValue(ClaimTypes.NameIdentifier) == account.Id.ToString() &&
principal.FindFirstValue(ClaimTypes.Name) == account.Username &&
principal.FindFirstValue(ClaimTypes.Email) == account.Email &&
principal.Identity!.AuthenticationType == "Password"), null);
}
[Fact]
public async Task Logout_Account()
{
httpContext = Substitute.For<HttpContext>();
IAuthenticationService authentication = Substitute.For<IAuthenticationService>();
httpContext.RequestServices.GetService(typeof(IAuthenticationService)).Returns(authentication);
await service.Logout(httpContext);
await authentication.Received().SignOutAsync(httpContext, "Cookies", null);
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
using System;
using System.Collections.Generic;
using System.Linq;
using Generator.Enums;
using Generator.Tables;
namespace Generator.Encoder {
[TypeGen(TypeGenOrders.CreatedInstructions)]
sealed class EncoderTypes {
public (EnumValue value, uint size)[] ImmSizes { get; }
public (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] LegacyOpHandlers { get; }
public (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] VexOpHandlers { get; }
public (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] XopOpHandlers { get; }
public (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] EvexOpHandlers { get; }
readonly Dictionary<OpCodeOperandKindDef, uint> toLegacy;
readonly Dictionary<OpCodeOperandKindDef, uint> toVex;
readonly Dictionary<OpCodeOperandKindDef, uint> toXop;
readonly Dictionary<OpCodeOperandKindDef, uint> toEvex;
EncoderTypes(GenTypes genTypes) {
var gen = new EncoderTypesGen(genTypes);
gen.Generate();
ImmSizes = gen.ImmSizes ?? throw new InvalidOperationException();
genTypes.Add(gen.EncFlags1 ?? throw new InvalidOperationException());
var legacyOpKind = gen.LegacyOpKind ?? throw new InvalidOperationException();
var vexOpKind = gen.VexOpKind ?? throw new InvalidOperationException();
var xopOpKind = gen.XopOpKind ?? throw new InvalidOperationException();
var evexOpKind = gen.EvexOpKind ?? throw new InvalidOperationException();
LegacyOpHandlers = CreateOpHandlers(genTypes, EncodingKind.Legacy).ToArray();
VexOpHandlers = CreateOpHandlers(genTypes, EncodingKind.VEX).ToArray();
XopOpHandlers = CreateOpHandlers(genTypes, EncodingKind.XOP).ToArray();
EvexOpHandlers = CreateOpHandlers(genTypes, EncodingKind.EVEX).ToArray();
if (new HashSet<EnumValue>(LegacyOpHandlers.Select(a => a.opCodeOperandKind)).Count != legacyOpKind.Values.Length)
throw new InvalidOperationException();
if (new HashSet<EnumValue>(VexOpHandlers.Select(a => a.opCodeOperandKind)).Count != vexOpKind.Values.Length)
throw new InvalidOperationException();
if (new HashSet<EnumValue>(XopOpHandlers.Select(a => a.opCodeOperandKind)).Count != xopOpKind.Values.Length)
throw new InvalidOperationException();
if (new HashSet<EnumValue>(EvexOpHandlers.Select(a => a.opCodeOperandKind)).Count != evexOpKind.Values.Length)
throw new InvalidOperationException();
var opKindDefs = genTypes.GetObject<OpCodeOperandKindDefs>(TypeIds.OpCodeOperandKindDefs).Defs;
toLegacy = LegacyOpHandlers.ToDictionary(a => opKindDefs[(int)a.opCodeOperandKind.Value], a => legacyOpKind[a.opCodeOperandKind.RawName].Value);
toVex = VexOpHandlers.ToDictionary(a => opKindDefs[(int)a.opCodeOperandKind.Value], a => vexOpKind[a.opCodeOperandKind.RawName].Value);
toXop = XopOpHandlers.ToDictionary(a => opKindDefs[(int)a.opCodeOperandKind.Value], a => xopOpKind[a.opCodeOperandKind.RawName].Value);
toEvex = EvexOpHandlers.ToDictionary(a => opKindDefs[(int)a.opCodeOperandKind.Value], a => evexOpKind[a.opCodeOperandKind.RawName].Value);
genTypes.AddObject(TypeIds.EncoderTypes, this);
}
static IEnumerable<(EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)> CreateOpHandlers(GenTypes genTypes, EncodingKind encoding) {
var defs = EncoderTypesGen.GetDefs(genTypes, encoding);
var register = genTypes[TypeIds.Register];
var opKind = genTypes[TypeIds.OpKind];
foreach (var def in defs) {
OpHandlerKind opHandlerKind;
object[] args;
EnumValue regLo, regHi;
switch (def.OperandEncoding) {
case OperandEncoding.None:
opHandlerKind = OpHandlerKind.None;
args = Array.Empty<object>();
break;
case OperandEncoding.NearBranch:
opHandlerKind = OpHandlerKind.OpJ;
args = def.NearBranchOpSize switch {
16 => new object[] { opKind[nameof(OpKind.NearBranch16)], def.BranchOffsetSize / 8 },
32 => new object[] { opKind[nameof(OpKind.NearBranch32)], def.BranchOffsetSize / 8 },
64 => new object[] { opKind[nameof(OpKind.NearBranch64)], def.BranchOffsetSize / 8 },
_ => throw new InvalidOperationException(),
};
break;
case OperandEncoding.Xbegin:
opHandlerKind = OpHandlerKind.OpJx;
args = new object[] { def.BranchOffsetSize / 8 };
break;
case OperandEncoding.AbsNearBranch:
opHandlerKind = OpHandlerKind.OpJdisp;
args = new object[] { def.BranchOffsetSize / 8 };
break;
case OperandEncoding.FarBranch:
opHandlerKind = OpHandlerKind.OpA;
args = new object[] { def.BranchOffsetSize / 8 };
break;
case OperandEncoding.Immediate:
switch (def.ImmediateSize) {
case 4:
if (!def.M2Z)
throw new InvalidOperationException();
opHandlerKind = OpHandlerKind.OpI4;
args = Array.Empty<object>();
break;
case 8:
opHandlerKind = OpHandlerKind.OpIb;
args = def.ImmediateSignExtSize switch {
8 => new object[] { opKind[nameof(OpKind.Immediate8)] },
16 => new object[] { opKind[nameof(OpKind.Immediate8to16)] },
32 => new object[] { opKind[nameof(OpKind.Immediate8to32)] },
64 => new object[] { opKind[nameof(OpKind.Immediate8to64)] },
_ => throw new InvalidOperationException(),
};
break;
case 16:
opHandlerKind = OpHandlerKind.OpIw;
args = Array.Empty<object>();
break;
case 32:
opHandlerKind = OpHandlerKind.OpId;
args = def.ImmediateSignExtSize switch {
32 => new object[] { opKind[nameof(OpKind.Immediate32)] },
64 => new object[] { opKind[nameof(OpKind.Immediate32to64)] },
_ => throw new InvalidOperationException(),
};
break;
case 64:
opHandlerKind = OpHandlerKind.OpIq;
args = Array.Empty<object>();
break;
default:
throw new InvalidOperationException();
}
break;
case OperandEncoding.ImpliedConst:
opHandlerKind = OpHandlerKind.OpImm;
args = new object[] { def.ImpliedConst };
break;
case OperandEncoding.ImpliedRegister:
opHandlerKind = OpHandlerKind.OpReg;
args = new object[] { register[def.Register.ToString()] };
break;
case OperandEncoding.SegRBX:
opHandlerKind = OpHandlerKind.OpMRBX;
args = Array.Empty<object>();
break;
case OperandEncoding.SegRSI:
opHandlerKind = OpHandlerKind.OpX;
args = Array.Empty<object>();
break;
case OperandEncoding.SegRDI:
opHandlerKind = OpHandlerKind.OprDI;
args = Array.Empty<object>();
break;
case OperandEncoding.ESRDI:
opHandlerKind = OpHandlerKind.OpY;
args = Array.Empty<object>();
break;
case OperandEncoding.RegImm:
opHandlerKind = OpHandlerKind.OpIsX;
(regLo, regHi) = GetRegisterRange(encoding, register, def.Register);
args = new object[] { regLo, regHi };
break;
case OperandEncoding.RegOpCode:
if (def.Register == Register.ST0) {
opHandlerKind = OpHandlerKind.OpRegSTi;
args = Array.Empty<object>();
}
else {
opHandlerKind = OpHandlerKind.OpRegEmbed8;
(regLo, regHi) = GetRegisterRange(encoding, register, def.Register);
args = new object[] { regLo, regHi };
}
break;
case OperandEncoding.RegModrmReg:
if (def.LockBit)
opHandlerKind = OpHandlerKind.OpModRM_regF0;
else if (def.Memory)
opHandlerKind = OpHandlerKind.OpModRM_reg_mem;
else
opHandlerKind = OpHandlerKind.OpModRM_reg;
(regLo, regHi) = GetRegisterRange(encoding, register, def.Register);
args = new object[] { regLo, regHi };
break;
case OperandEncoding.RegModrmRm:
opHandlerKind = OpHandlerKind.OpModRM_rm_reg_only;
(regLo, regHi) = GetRegisterRange(encoding, register, def.Register);
args = new object[] { regLo, regHi };
break;
case OperandEncoding.RegMemModrmRm:
opHandlerKind = OpHandlerKind.OpModRM_rm;
(regLo, regHi) = GetRegisterRange(encoding, register, def.Register);
args = new object[] { regLo, regHi };
break;
case OperandEncoding.RegVvvvv:
opHandlerKind = OpHandlerKind.OpHx;
(regLo, regHi) = GetRegisterRange(encoding, register, def.Register);
args = new object[] { regLo, regHi };
break;
case OperandEncoding.MemModrmRm:
if (def.Vsib) {
opHandlerKind = OpHandlerKind.OpVsib;
(regLo, regHi) = GetRegisterRange(encoding, register, def.Register);
args = new object[] { regLo, regHi };
}
else {
opHandlerKind = OpHandlerKind.OpModRM_rm_mem_only;
args = new object[] { def.SibRequired };
}
break;
case OperandEncoding.MemOffset:
opHandlerKind = OpHandlerKind.OpO;
args = Array.Empty<object>();
break;
default:
throw new InvalidOperationException();
}
yield return (def.EnumValue, opHandlerKind, args);
}
}
static (EnumValue vecLo, EnumValue vecHi) GetRegisterRange(EncodingKind encoding, EnumType registerType, Register register) =>
register switch {
Register.AL => (registerType[nameof(Register.AL)], registerType[nameof(Register.R15L)]),
Register.AX => (registerType[nameof(Register.AX)], registerType[nameof(Register.R15W)]),
Register.EAX => (registerType[nameof(Register.EAX)], registerType[nameof(Register.R15D)]),
Register.RAX => (registerType[nameof(Register.RAX)], registerType[nameof(Register.R15)]),
Register.ES => (registerType[nameof(Register.ES)], registerType[nameof(Register.GS)]),
Register.K0 => (registerType[nameof(Register.K0)], registerType[nameof(Register.K7)]),
Register.BND0 => (registerType[nameof(Register.BND0)], registerType[nameof(Register.BND3)]),
Register.CR0 => (registerType[nameof(Register.CR0)], registerType[nameof(Register.CR15)]),
Register.DR0 => (registerType[nameof(Register.DR0)], registerType[nameof(Register.DR15)]),
Register.TR0 => (registerType[nameof(Register.TR0)], registerType[nameof(Register.TR7)]),
Register.ST0 => (registerType[nameof(Register.ST0)], registerType[nameof(Register.ST7)]),
Register.MM0 => (registerType[nameof(Register.MM0)], registerType[nameof(Register.MM7)]),
Register.TMM0 => (registerType[nameof(Register.TMM0)], registerType[nameof(Register.TMM7)]),
_ => encoding switch {
EncodingKind.Legacy or EncodingKind.D3NOW or EncodingKind.VEX or EncodingKind.XOP =>
register switch {
Register.XMM0 => (registerType[nameof(Register.XMM0)], registerType[nameof(Register.XMM15)]),
Register.YMM0 => (registerType[nameof(Register.YMM0)], registerType[nameof(Register.YMM15)]),
Register.ZMM0 => (registerType[nameof(Register.ZMM0)], registerType[nameof(Register.ZMM15)]),
_ => throw new InvalidOperationException(),
},
EncodingKind.EVEX =>
register switch {
Register.XMM0 => (registerType[nameof(Register.XMM0)], registerType[nameof(Register.XMM31)]),
Register.YMM0 => (registerType[nameof(Register.YMM0)], registerType[nameof(Register.YMM31)]),
Register.ZMM0 => (registerType[nameof(Register.ZMM0)], registerType[nameof(Register.ZMM31)]),
_ => throw new InvalidOperationException(),
},
_ => throw new InvalidOperationException(),
},
};
public uint ToLegacy(OpCodeOperandKindDef opKind) => toLegacy[opKind];
public uint ToVex(OpCodeOperandKindDef opKind) => toVex[opKind];
public uint ToXop(OpCodeOperandKindDef opKind) => toXop[opKind];
public uint ToEvex(OpCodeOperandKindDef opKind) => toEvex[opKind];
}
}
| |
namespace GitVersion
{
using System;
using System.IO;
using System.Linq;
using LibGit2Sharp;
public class GitPreparer
{
string targetUrl;
string dynamicRepositoryLocation;
Authentication authentication;
string targetBranch;
bool noFetch;
string targetPath;
public GitPreparer(string targetUrl, string dynamicRepositoryLocation, Authentication authentication, string targetBranch, bool noFetch, string targetPath)
{
this.targetUrl = targetUrl;
this.dynamicRepositoryLocation = dynamicRepositoryLocation;
this.authentication = authentication;
this.targetBranch = targetBranch;
this.noFetch = noFetch;
this.targetPath = targetPath;
}
public bool IsDynamicGitRepository
{
get { return !string.IsNullOrWhiteSpace(DynamicGitRepositoryPath); }
}
public string DynamicGitRepositoryPath { get; private set; }
public void Initialise(bool normaliseGitDirectory)
{
if (string.IsNullOrWhiteSpace(targetUrl))
{
if (normaliseGitDirectory)
{
GitHelper.NormalizeGitDirectory(GetDotGitDirectory(), authentication, noFetch);
}
return;
}
var targetPath = CalculateTemporaryRepositoryPath(targetUrl, dynamicRepositoryLocation);
DynamicGitRepositoryPath = CreateDynamicRepository(targetPath, authentication, targetUrl, targetBranch, noFetch);
if (normaliseGitDirectory)
{
GitHelper.NormalizeGitDirectory(GetDotGitDirectory(), authentication, noFetch);
}
}
static string CalculateTemporaryRepositoryPath(string targetUrl, string dynamicRepositoryLocation)
{
var userTemp = dynamicRepositoryLocation ?? Path.GetTempPath();
var repositoryName = targetUrl.Split('/', '\\').Last().Replace(".git", string.Empty);
var possiblePath = Path.Combine(userTemp, repositoryName);
// Verify that the existing directory is ok for us to use
if (Directory.Exists(possiblePath))
{
if (!GitRepoHasMatchingRemote(possiblePath, targetUrl))
{
var i = 1;
var originalPath = possiblePath;
bool possiblePathExists;
do
{
possiblePath = string.Concat(originalPath, "_", i++.ToString());
possiblePathExists = Directory.Exists(possiblePath);
} while (possiblePathExists && !GitRepoHasMatchingRemote(possiblePath, targetUrl));
}
}
return possiblePath;
}
static bool GitRepoHasMatchingRemote(string possiblePath, string targetUrl)
{
try
{
using (var repository = new Repository(possiblePath))
{
return repository.Network.Remotes.Any(r => r.Url == targetUrl);
}
}
catch (Exception)
{
return false;
}
}
public string GetDotGitDirectory()
{
if (IsDynamicGitRepository)
return DynamicGitRepositoryPath;
return GitDirFinder.TreeWalkForDotGitDir(targetPath);
}
public string GetProjectRootDirectory()
{
if (IsDynamicGitRepository)
return targetPath;
return Directory.GetParent(GitDirFinder.TreeWalkForDotGitDir(targetPath)).FullName;
}
static string CreateDynamicRepository(string targetPath, Authentication authentication, string repositoryUrl, string targetBranch, bool noFetch)
{
Logger.WriteInfo(string.Format("Creating dynamic repository at '{0}'", targetPath));
var gitDirectory = Path.Combine(targetPath, ".git");
if (Directory.Exists(targetPath))
{
Logger.WriteInfo("Git repository already exists");
GitHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch);
Logger.WriteInfo(string.Format("Updating branch '{0}'", targetBranch));
using (var repo = new Repository(targetPath))
{
if (string.IsNullOrWhiteSpace(targetBranch))
{
throw new Exception("Dynamic Git repositories must have a target branch (/b)");
}
var targetGitBranch = repo.Branches[targetBranch];
var trackedBranch = targetGitBranch.TrackedBranch;
if (trackedBranch == null)
throw new InvalidOperationException(string.Format("Expecting {0} to have a remote tracking branch", targetBranch));
targetGitBranch.Checkout();
repo.Reset(ResetMode.Hard, trackedBranch.Tip);
}
return gitDirectory;
}
Credentials credentials = null;
if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
{
Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username));
credentials = new UsernamePasswordCredentials
{
Username = authentication.Username,
Password = authentication.Password
};
}
Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", repositoryUrl));
CloneRepository(repositoryUrl, gitDirectory, credentials);
// Normalize (download branches) before using the branch
GitHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch);
using (var repository = new Repository(gitDirectory))
{
if (string.IsNullOrWhiteSpace(targetBranch))
{
targetBranch = repository.Head.Name;
}
Reference newHead = null;
var localReference = GetLocalReference(repository, targetBranch);
if (localReference != null)
{
newHead = localReference;
}
if (newHead == null)
{
var remoteReference = GetRemoteReference(repository, targetBranch, repositoryUrl, authentication);
if (remoteReference != null)
{
repository.Network.Fetch(repositoryUrl, new[]
{
string.Format("{0}:{1}", remoteReference.CanonicalName, targetBranch)
});
newHead = repository.Refs[string.Format("refs/heads/{0}", targetBranch)];
}
}
if (newHead != null)
{
Logger.WriteInfo(string.Format("Switching to branch '{0}'", targetBranch));
repository.Refs.UpdateTarget(repository.Refs.Head, newHead);
}
}
return gitDirectory;
}
private static void CloneRepository(string repositoryUrl, string gitDirectory, Credentials credentials)
{
try
{
Repository.Clone(repositoryUrl, gitDirectory,
new CloneOptions
{
Checkout = false,
CredentialsProvider = (url, usernameFromUrl, types) => credentials
});
}
catch (LibGit2SharpException ex)
{
var message = ex.Message;
if (message.Contains("401"))
{
throw new Exception("Unauthorised: Incorrect username/password");
}
if (message.Contains("403"))
{
throw new Exception("Forbidden: Possbily Incorrect username/password");
}
if (message.Contains("404"))
{
throw new Exception("Not found: The repository was not found");
}
throw new Exception("There was an unknown problem with the Git repository you provided");
}
}
private static Reference GetLocalReference(Repository repository, string branchName)
{
var targetBranchName = branchName.GetCanonicalBranchName();
return repository.Refs.FirstOrDefault(localRef => string.Equals(localRef.CanonicalName, targetBranchName));
}
private static DirectReference GetRemoteReference(Repository repository, string branchName, string repositoryUrl, Authentication authentication)
{
var targetBranchName = branchName.GetCanonicalBranchName();
var remoteReferences = GitHelper.GetRemoteTipsUsingUsernamePasswordCredentials(repository, repositoryUrl, authentication.Username, authentication.Password);
return remoteReferences.FirstOrDefault(remoteRef => string.Equals(remoteRef.CanonicalName, targetBranchName));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Linq;
namespace LinqToDB.Reflection
{
using Expressions;
using Extensions;
using Mapping;
public class MemberAccessor
{
public MemberAccessor(TypeAccessor typeAccessor, string memberName)
{
TypeAccessor = typeAccessor;
if (memberName.IndexOf('.') < 0)
{
SetSimple(Expression.PropertyOrField(Expression.Constant(null, typeAccessor.Type), memberName).Member);
}
else
{
IsComplex = true;
HasGetter = true;
HasSetter = true;
var members = memberName.Split('.');
var objParam = Expression.Parameter(TypeAccessor.Type, "obj");
var expr = objParam as Expression;
var infos = members.Select(m =>
{
expr = Expression.PropertyOrField(expr, m);
return new
{
member = ((MemberExpression)expr).Member,
type = expr.Type,
};
}).ToArray();
var lastInfo = infos[infos.Length - 1];
MemberInfo = lastInfo.member;
Type = lastInfo.type;
var checkNull = infos.Take(infos.Length - 1).Any(info => info.type.IsClassEx() || info.type.IsNullable());
// Build getter.
//
{
if (checkNull)
{
var ret = Expression.Variable(Type, "ret");
Func<Expression,int,Expression> makeGetter = null; makeGetter = (ex, i) =>
{
var info = infos[i];
var next = Expression.MakeMemberAccess(ex, info.member);
if (i == infos.Length - 1)
return Expression.Assign(ret, next);
if (next.Type.IsClassEx() || next.Type.IsNullable())
{
var local = Expression.Variable(next.Type);
return Expression.Block(
new[] { local },
new[]
{
Expression.Assign(local, next) as Expression,
Expression.IfThen(
Expression.NotEqual(local, Expression.Constant(null)),
makeGetter(local, i + 1))
});
}
return makeGetter(next, i + 1);
};
expr = Expression.Block(
new[] { ret },
new[]
{
Expression.Assign(ret, new DefaultValueExpression(MappingSchema.Default, Type)),
makeGetter(objParam, 0),
ret
});
}
else
{
expr = objParam;
foreach (var info in infos)
expr = Expression.MakeMemberAccess(expr, info.member);
}
GetterExpression = Expression.Lambda(expr, objParam);
}
// Build setter.
//
{
HasSetter = !infos.Any(info => info.member is PropertyInfo && ((PropertyInfo)info.member).GetSetMethodEx(true) == null);
var valueParam = Expression.Parameter(Type, "value");
if (HasSetter)
{
if (checkNull)
{
var vars = new List<ParameterExpression>();
var exprs = new List<Expression>();
Action<Expression,int> makeSetter = null; makeSetter = (ex, i) =>
{
var info = infos[i];
var next = Expression.MakeMemberAccess(ex, info.member);
if (i == infos.Length - 1)
{
exprs.Add(Expression.Assign(next, valueParam));
}
else
{
if (next.Type.IsClassEx() || next.Type.IsNullable())
{
var local = Expression.Variable(next.Type);
vars.Add(local);
exprs.Add(Expression.Assign(local, next));
exprs.Add(
Expression.IfThen(
Expression.Equal(local, Expression.Constant(null)),
Expression.Block(
Expression.Assign(local, Expression.New(local.Type)),
Expression.Assign(next, local))));
makeSetter(local, i + 1);
}
else
{
makeSetter(next, i + 1);
}
}
};
makeSetter(objParam, 0);
expr = Expression.Block(vars, exprs);
}
else
{
expr = objParam;
foreach (var info in infos)
expr = Expression.MakeMemberAccess(expr, info.member);
expr = Expression.Assign(expr, valueParam);
}
SetterExpression = Expression.Lambda(expr, objParam, valueParam);
}
else
{
var fakeParam = Expression.Parameter(typeof(int));
SetterExpression = Expression.Lambda(
Expression.Block(
new[] { fakeParam },
new Expression[] { Expression.Assign(fakeParam, Expression.Constant(0)) }),
objParam,
valueParam);
}
}
}
SetExpressions();
}
public MemberAccessor(TypeAccessor typeAccessor, MemberInfo memberInfo)
{
TypeAccessor = typeAccessor;
SetSimple(memberInfo);
SetExpressions();
}
void SetSimple(MemberInfo memberInfo)
{
MemberInfo = memberInfo;
Type = MemberInfo is PropertyInfo ? ((PropertyInfo)MemberInfo).PropertyType : ((FieldInfo)MemberInfo).FieldType;
HasGetter = true;
HasSetter = !(memberInfo is PropertyInfo) || ((PropertyInfo)memberInfo).GetSetMethodEx(true) != null;
var objParam = Expression.Parameter(TypeAccessor.Type, "obj");
var valueParam = Expression.Parameter(Type, "value");
GetterExpression = Expression.Lambda(Expression.MakeMemberAccess(objParam, memberInfo), objParam);
if (HasSetter)
{
SetterExpression = Expression.Lambda(
Expression.Assign(GetterExpression.Body, valueParam),
objParam,
valueParam);
}
else
{
var fakeParam = Expression.Parameter(typeof(int));
SetterExpression = Expression.Lambda(
Expression.Block(
new[] { fakeParam },
new Expression[] { Expression.Assign(fakeParam, Expression.Constant(0)) }),
objParam,
valueParam);
}
}
void SetExpressions()
{
var objParam = Expression.Parameter(typeof(object), "obj");
var getterExpr = GetterExpression.GetBody(Expression.Convert(objParam, TypeAccessor.Type));
var getter = Expression.Lambda<Func<object,object>>(Expression.Convert(getterExpr, typeof(object)), objParam);
Getter = getter.Compile();
var valueParam = Expression.Parameter(typeof(object), "value");
var setterExpr = SetterExpression.GetBody(
Expression.Convert(objParam, TypeAccessor.Type),
Expression.Convert(valueParam, Type));
var setter = Expression.Lambda<Action<object,object>>(setterExpr, objParam, valueParam);
Setter = setter.Compile();
}
#region Public Properties
public MemberInfo MemberInfo { get; private set; }
public TypeAccessor TypeAccessor { get; private set; }
public bool HasGetter { get; private set; }
public bool HasSetter { get; private set; }
public Type Type { get; private set; }
public bool IsComplex { get; private set; }
public LambdaExpression GetterExpression { get; private set; }
public LambdaExpression SetterExpression { get; private set; }
public Func <object,object> Getter { get; private set; }
public Action<object,object> Setter { get; private set; }
public string Name
{
get { return MemberInfo.Name; }
}
#endregion
#region Public Methods
public T GetAttribute<T>() where T : Attribute
{
var attrs = MemberInfo.GetCustomAttributesEx(typeof(T), true);
return attrs.Length > 0? (T)attrs[0]: null;
}
public T[] GetAttributes<T>() where T : Attribute
{
Array attrs = MemberInfo.GetCustomAttributesEx(typeof(T), true);
return attrs.Length > 0? (T[])attrs: null;
}
public object[] GetAttributes()
{
var attrs = MemberInfo.GetCustomAttributesEx(true);
return attrs.Length > 0? attrs: null;
}
public T[] GetTypeAttributes<T>() where T : Attribute
{
return TypeAccessor.Type.GetAttributes<T>();
}
#endregion
#region Set/Get Value
public virtual object GetValue(object o)
{
return Getter(o);
}
public virtual void SetValue(object o, object value)
{
Setter(o, value);
}
#endregion
}
}
| |
//
// Parameter.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2012 Jeffrey Stedfast
//
// 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.Text;
using MimeKit.Encodings;
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// A header parameter as found in the Content-Type and Content-Disposition headers.
/// </summary>
public sealed class Parameter
{
string text;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Parameter"/> class.
/// </summary>
/// <param name="name">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="name"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="value"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="name"/> contains illegal characters.
/// </exception>
public Parameter (string name, string value)
{
if (name == null)
throw new ArgumentNullException ("name");
if (name.Length == 0)
throw new ArgumentException ("Parameter names are not allowed to be empty.", "name");
for (int i = 0; i < name.Length; i++) {
if (name[i] > 127 || !IsAttr ((byte) name[i]))
throw new ArgumentException ("Illegal characters in parameter name.", "name");
}
if (value == null)
throw new ArgumentNullException ("value");
Name = name;
Value = value;
}
static bool IsAttr (byte c)
{
return c.IsAttr ();
}
/// <summary>
/// Gets the parameter name.
/// </summary>
/// <value>The parameter name.</value>
public string Name {
get; private set;
}
/// <summary>
/// Gets or sets the parameter value.
/// </summary>
/// <value>The parameter value.</value>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
public string Value {
get { return text; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (text == value)
return;
text = value;
OnChanged ();
}
}
enum EncodeMethod {
None,
Quote,
Rfc2184
}
static EncodeMethod GetEncodeMethod (FormatOptions options, string name, string value, out string quoted)
{
var method = EncodeMethod.None;
quoted = null;
if (name.Length + 1 + value.Length >= options.MaxLineLength)
return EncodeMethod.Rfc2184;
for (int i = 0; i < value.Length; i++) {
if (value[i] >= 127 || ((byte) value[i]).IsCtrl ())
return EncodeMethod.Rfc2184;
if (!((byte) value[i]).IsAttr ())
method = EncodeMethod.Quote;
}
if (method == EncodeMethod.Quote) {
quoted = MimeUtils.Quote (value);
if (name.Length + 1 + quoted.Length >= options.MaxLineLength)
return EncodeMethod.Rfc2184;
}
return method;
}
static EncodeMethod GetEncodeMethod (char[] value, int startIndex, int length)
{
var method = EncodeMethod.None;
for (int i = startIndex; i < startIndex + length; i++) {
if (value[i] >= 127 || ((byte) value[i]).IsCtrl ())
return EncodeMethod.Rfc2184;
if (!((byte) value[i]).IsAttr ())
method = EncodeMethod.Quote;
}
return method;
}
static EncodeMethod GetEncodeMethod (byte[] value, int length)
{
var method = EncodeMethod.None;
for (int i = 0; i < length; i++) {
if (value[i] >= 127 || value[i].IsCtrl ())
return EncodeMethod.Rfc2184;
if (!value[i].IsAttr ())
method = EncodeMethod.Quote;
}
return method;
}
static bool IsCtrl (char c)
{
return ((byte) c).IsCtrl ();
}
static Encoding GetBestEncoding (string value, Encoding defaultEncoding)
{
int encoding = 0; // us-ascii
for (int i = 0; i < value.Length; i++) {
if (value[i] < 127) {
if (IsCtrl (value[i]))
encoding = Math.Max (encoding, 1);
} else if (value[i] < 256) {
encoding = Math.Max (encoding, 1);
} else {
encoding = 2;
}
}
switch (encoding) {
case 0: return Encoding.ASCII;
case 1: return Encoding.GetEncoding (28591); // iso-8859-1
default: return defaultEncoding;
}
}
static bool GetNextValue (string charset, Encoder encoder, HexEncoder hex, char[] chars, ref int index,
ref byte[] bytes, ref byte[] encoded, int maxLength, out string value)
{
int length = chars.Length - index;
if (length < maxLength) {
switch (GetEncodeMethod (chars, index, length)) {
case EncodeMethod.Quote:
value = MimeUtils.Quote (new string (chars, index, length));
index += length;
return false;
case EncodeMethod.None:
value = new string (chars, index, length);
index += length;
return false;
}
}
length = Math.Min (maxLength, length);
int ratio, count, n;
do {
count = encoder.GetByteCount (chars, index, length, true);
if (count > maxLength && length > 1) {
ratio = (int) Math.Round ((double) count / (double) length);
length -= Math.Max ((count - maxLength) / ratio, 1);
continue;
}
if (bytes.Length < count)
Array.Resize<byte> (ref bytes, count);
count = encoder.GetBytes (chars, index, length, bytes, 0, true);
// Note: the first chunk needs to be encoded in order to declare the charset
if (index > 0 || charset == "us-ascii") {
var method = GetEncodeMethod (bytes, count);
if (method == EncodeMethod.Quote) {
value = MimeUtils.Quote (Encoding.ASCII.GetString (bytes, 0, count));
index += length;
return false;
}
if (method == EncodeMethod.None) {
value = Encoding.ASCII.GetString (bytes, 0, count);
index += length;
return false;
}
}
n = hex.EstimateOutputLength (count);
if (encoded.Length < n)
Array.Resize<byte> (ref encoded, n);
// only the first value gets a charset declaration
int charsetLength = index == 0 ? charset.Length + 2 : 0;
n = hex.Encode (bytes, 0, count, encoded);
if (n > 3 && (charsetLength + n) > maxLength) {
int x = 0;
for (int i = n - 1; i >= 0 && charsetLength + i >= maxLength; i--) {
if (encoded[i] == (byte) '%')
x--;
else
x++;
}
ratio = (int) Math.Round ((double) count / (double) length);
length -= Math.Max (x / ratio, 1);
continue;
}
if (index == 0)
value = charset + "''" + Encoding.ASCII.GetString (encoded, 0, n);
else
value = Encoding.ASCII.GetString (encoded, 0, n);
index += length;
return true;
} while (true);
}
internal void Encode (FormatOptions options, StringBuilder builder, ref int lineLength, Encoding encoding)
{
string quoted;
var method = GetEncodeMethod (options, Name, Value, out quoted);
if (method == EncodeMethod.None)
quoted = Value;
if (method != EncodeMethod.Rfc2184) {
if (lineLength + 2 + Name.Length + 1 + quoted.Length >= options.MaxLineLength) {
builder.Append (";\n\t");
lineLength = 1;
} else {
builder.Append ("; ");
lineLength += 2;
}
lineLength += Name.Length + 1 + quoted.Length;
builder.Append (Name);
builder.Append ('=');
builder.Append (quoted);
return;
}
int maxLength = options.MaxLineLength - (Name.Length + 6);
var bestEncoding = GetBestEncoding (Value, encoding);
var charset = CharsetUtils.GetMimeCharset (bestEncoding);
var bytes = new byte[Math.Max (maxLength, 6)];
var hexbuf = new byte[bytes.Length * 3 + 3];
var encoder = bestEncoding.GetEncoder ();
var chars = Value.ToCharArray ();
var hex = new HexEncoder ();
int index = 0, i = 0;
string value, id;
bool encoded;
int length;
do {
encoded = GetNextValue (charset, encoder, hex, chars, ref index, ref bytes, ref hexbuf, maxLength, out value);
length = Name.Length + (encoded ? 1 : 0) + 1 + value.Length;
if (i == 0 && index == chars.Length) {
if (lineLength + 2 + length >= options.MaxLineLength) {
builder.Append (";\n\t");
lineLength = 1;
} else {
builder.Append ("; ");
lineLength += 2;
}
builder.Append (Name);
if (encoded)
builder.Append ('*');
builder.Append ('=');
builder.Append (value);
lineLength += length;
return;
}
builder.Append (";\n\t");
lineLength = 1;
id = i.ToString ();
length += id.Length + 1;
builder.Append (Name);
builder.Append ('*');
builder.Append (id);
if (encoded)
builder.Append ('*');
builder.Append ('=');
builder.Append (value);
lineLength += length;
i++;
} while (index < chars.Length);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current
/// <see cref="MimeKit.Parameter"/>.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current
/// <see cref="MimeKit.Parameter"/>.</returns>
public override string ToString ()
{
return Name + "=" + MimeUtils.Quote (Value);
}
internal event EventHandler Changed;
void OnChanged ()
{
if (Changed != null)
Changed (this, EventArgs.Empty);
}
}
}
| |
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
namespace uPLibrary.Hardware
{
/// <summary>
/// Driver for TB6612FNG dual motor driver
/// </summary>
public class TB6612FNG : IDisposable
{
#region Constants...
private const int DEFAULT_PWM_FREQUENCY = 10000; // Hz
private const int MAX_PWM_FREQUENCY = 100000; // Hz
#endregion
#region Fields...
// output ports and PWM for motor A
private OutputPort aIn1Port;
private OutputPort aIn2Port;
private PWM aPwm;
// output ports and PWM for motor B
private OutputPort bIn1Port;
private OutputPort bIn2Port;
private PWM bPwm;
// standby pin
private OutputPort standbyPort;
// motors mode
private MotorMode motorModeA;
private MotorMode motorModeB;
// motors speed
private int motorSpeedA;
private int motorSpeedB;
private bool isDisposed = false;
#endregion
#region Properties...
/// <summary>
/// Speed for Motor A
/// </summary>
public int MotorSpeedA
{
get
{
if (this.IsMotorEnabledA)
return this.motorSpeedA;
else
throw new ApplicationException("Motor A is disabled !!");
}
set
{
if ((value >= 0) && (value <= 100))
this.motorSpeedA = value;
this.aPwm.DutyCycle = (double)this.motorSpeedA / 100;
}
}
/// <summary>
/// Speed for Motor B
/// </summary>
public int MotorSpeedB
{
get
{
if (this.IsMotorEnabledB)
return this.motorSpeedB;
else
throw new ApplicationException("Motor B is disabled !!");
}
set
{
if ((value >= 0) && (value <= 100))
this.motorSpeedB = value;
this.bPwm.DutyCycle = (double)this.motorSpeedB / 100;
}
}
/// <summary>
/// Mode for Motor A
/// </summary>
public MotorMode MotorModeA
{
get
{
if (this.IsMotorEnabledA)
return this.motorModeA;
else
throw new ApplicationException("Motor A is disabled !!");
}
set
{
switch (value)
{
case MotorMode.CCW:
this.motorModeA = MotorMode.CCW;
this.aIn1Port.Write(false);
this.aIn2Port.Write(true);
break;
case MotorMode.CW:
this.motorModeA = MotorMode.CW;
this.aIn1Port.Write(true);
this.aIn2Port.Write(false);
break;
case MotorMode.ShortBrake:
this.motorModeA = MotorMode.ShortBrake;
this.aIn1Port.Write(true);
this.aIn2Port.Write(true);
break;
case MotorMode.Stop:
this.motorModeA = MotorMode.Stop;
this.aIn1Port.Write(false);
this.aIn2Port.Write(false);
break;
default:
break;
}
}
}
/// <summary>
/// Mode for Motor B
/// </summary>
public MotorMode MotorModeB
{
get
{
if (this.IsMotorEnabledB)
return this.motorModeB;
else
throw new ApplicationException("Motor B is disabled !!");
}
set
{
switch (value)
{
case MotorMode.CCW:
this.motorModeB = MotorMode.CCW;
this.bIn1Port.Write(false);
this.bIn2Port.Write(true);
break;
case MotorMode.CW:
this.motorModeB = MotorMode.CW;
this.bIn1Port.Write(true);
this.bIn2Port.Write(false);
break;
case MotorMode.ShortBrake:
this.motorModeB = MotorMode.ShortBrake;
this.bIn1Port.Write(true);
this.bIn2Port.Write(true);
break;
case MotorMode.Stop:
this.motorModeB = MotorMode.Stop;
this.bIn1Port.Write(false);
this.bIn2Port.Write(false);
break;
default:
break;
}
}
}
/// <summary>
/// Driver motor in standby
/// </summary>
public bool IsStandBy
{
get
{
if (standbyPort != null)
// standby signal is active low
return !this.standbyPort.Read();
else
throw new ApplicationException("StandBy not managed !");
}
set
{
if (standbyPort != null)
// standby signal is active low
this.standbyPort.Write(!value);
else
throw new ApplicationException("StandBy not managed !");
}
}
/// <summary>
/// Motor A enabled status
/// </summary>
public bool IsMotorEnabledA { get; private set; }
/// <summary>
/// Motor B enabled status
/// </summary>
public bool IsMotorEnabledB { get; private set; }
#endregion
/// <summary>
/// Constructor for using only motor A
/// </summary>
/// <param name="aIn1">Pin channel A input 1</param>
/// <param name="aIn2">Pin channel A input 2</param>
/// <param name="aPwmChannel">Pwm channel A</param>
/// <param name="standby">Pin standby</param>
public TB6612FNG(Cpu.Pin aIn1, Cpu.Pin aIn2, Cpu.PWMChannel aPwmChannel, Cpu.Pin standby = Cpu.Pin.GPIO_NONE)
{
this.aIn1Port = new OutputPort(aIn1, false);
this.aIn2Port = new OutputPort(aIn2, false);
this.aPwm = new PWM(aPwmChannel, DEFAULT_PWM_FREQUENCY, 0, false);
this.IsMotorEnabledA = true;
this.MotorModeA = MotorMode.Stop;
this.MotorSpeedA = 0;
if (standby != Cpu.Pin.GPIO_NONE)
// standby pin is active low so for not standby, set true output value
this.standbyPort = new OutputPort(standby, true);
this.aPwm.Start();
}
/// <summary>
/// Constructor for using both motors A and B
/// </summary>
/// <param name="aIn1">Pin channel A input 1</param>
/// <param name="aIn2">Pin channel A input 2</param>
/// <param name="aPwmChannel">Pwm channel A</param>
/// <param name="bIn1">Pin channel B input 1</param>
/// <param name="bIn2">Pin channel B input 2</param>
/// <param name="bPwmChannel">Pwm channel B</param>
/// <param name="standby">Pin standby</param>
public TB6612FNG(Cpu.Pin aIn1, Cpu.Pin aIn2, Cpu.PWMChannel aPwmChannel,
Cpu.Pin bIn1, Cpu.Pin bIn2, Cpu.PWMChannel bPwmChannel,
Cpu.Pin standby = Cpu.Pin.GPIO_NONE)
: this(aIn1, aIn2, aPwmChannel, standby)
{
this.bIn1Port = new OutputPort(bIn1, false);
this.bIn2Port = new OutputPort(bIn2, false);
this.bPwm = new PWM(bPwmChannel, DEFAULT_PWM_FREQUENCY, 0, false);
this.IsMotorEnabledB = true;
this.MotorModeB = MotorMode.Stop;
this.bPwm.Start();
}
#region IDisposable and Dispose Pattern...
/// <summary>
/// Disponse() method from IDisposable interface
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Internal dispose method
/// </summary>
/// <param name="disposing">Disposing managed resources</param>
protected virtual void Dispose(bool disposing)
{
if (!this.isDisposed)
{
// dispose managed resources
if (disposing)
{
// dispose motor A resources
if (this.IsMotorEnabledA)
{
this.aIn1Port.Write(false);
this.aIn2Port.Write(false);
this.aPwm.DutyCycle = 0;
this.aIn1Port.Dispose();
this.aIn2Port.Dispose();
this.aPwm.Dispose();
}
// dispose motor B resources
if (this.IsMotorEnabledB)
{
this.bIn1Port.Write(false);
this.bIn2Port.Write(false);
this.bPwm.DutyCycle = 0;
this.bIn1Port.Dispose();
this.bIn2Port.Dispose();
this.bPwm.Dispose();
}
}
}
this.isDisposed = true;
}
#endregion
}
/// <summary>
/// Motor mode
/// </summary>
public enum MotorMode
{
/// <summary>
/// Counter Clock Wise
/// </summary>
CCW,
/// <summary>
/// Clock Wise
/// </summary>
CW,
/// <summary>
/// Short Brake
/// </summary>
ShortBrake,
/// <summary>
/// Stop
/// </summary>
Stop
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
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.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for ChartCtl.
/// </summary>
internal class ChartLegendCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
bool fVisible, fLayout, fPosition, fInsidePlotArea;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox cbPosition;
private System.Windows.Forms.ComboBox cbLayout;
private System.Windows.Forms.CheckBox chkVisible;
private System.Windows.Forms.CheckBox chkInsidePlotArea;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal ChartLegendCtl(DesignXmlDraw dxDraw, List<XmlNode> ris)
{
_ReportItems = ris;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
XmlNode node = _ReportItems[0];
this.cbPosition.Text = _Draw.GetElementValue(node, "Position", "RightTop");
this.cbLayout.Text = _Draw.GetElementValue(node, "Layout", "Column");
this.chkVisible.Checked = _Draw.GetElementValue(node, "Visible", "false").ToLower() == "true"? true: false;
this.chkInsidePlotArea.Checked = _Draw.GetElementValue(node, "InsidePlotArea", "false").ToLower() == "true"? true: false;
fVisible = fLayout = fPosition = fInsidePlotArea = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.cbPosition = new System.Windows.Forms.ComboBox();
this.cbLayout = new System.Windows.Forms.ComboBox();
this.chkVisible = new System.Windows.Forms.CheckBox();
this.chkInsidePlotArea = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 18);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Position in Chart";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 50);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(112, 16);
this.label2.TabIndex = 1;
this.label2.Text = "Layout within Legend";
//
// cbPosition
//
this.cbPosition.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbPosition.Items.AddRange(new object[] {
"TopLeft",
"TopCenter",
"TopRight",
"LeftTop",
"LeftCenter",
"LeftBottom",
"RightTop",
"RightCenter",
"RightBottom",
"BottomRight",
"BottomCenter",
"BottomLeft"});
this.cbPosition.Location = new System.Drawing.Point(144, 16);
this.cbPosition.Name = "cbPosition";
this.cbPosition.Size = new System.Drawing.Size(121, 21);
this.cbPosition.TabIndex = 4;
this.cbPosition.SelectedIndexChanged += new System.EventHandler(this.cbPosition_SelectedIndexChanged);
//
// cbLayout
//
this.cbLayout.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbLayout.Items.AddRange(new object[] {
"Column",
"Row",
"Table"});
this.cbLayout.Location = new System.Drawing.Point(144, 48);
this.cbLayout.Name = "cbLayout";
this.cbLayout.Size = new System.Drawing.Size(121, 21);
this.cbLayout.TabIndex = 6;
this.cbLayout.SelectedIndexChanged += new System.EventHandler(this.cbLayout_SelectedIndexChanged);
//
// chkVisible
//
this.chkVisible.Location = new System.Drawing.Point(16, 80);
this.chkVisible.Name = "chkVisible";
this.chkVisible.Size = new System.Drawing.Size(136, 24);
this.chkVisible.TabIndex = 14;
this.chkVisible.Text = "Visible";
this.chkVisible.CheckedChanged += new System.EventHandler(this.chkVisible_CheckedChanged);
//
// chkInsidePlotArea
//
this.chkInsidePlotArea.Location = new System.Drawing.Point(16, 112);
this.chkInsidePlotArea.Name = "chkInsidePlotArea";
this.chkInsidePlotArea.Size = new System.Drawing.Size(136, 24);
this.chkInsidePlotArea.TabIndex = 15;
this.chkInsidePlotArea.Text = "Draw Inside Plot Area";
this.chkInsidePlotArea.CheckedChanged += new System.EventHandler(this.chkInsidePlotArea_CheckedChanged);
//
// ChartLegendCtl
//
this.Controls.Add(this.chkInsidePlotArea);
this.Controls.Add(this.chkVisible);
this.Controls.Add(this.cbLayout);
this.Controls.Add(this.cbPosition);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "ChartLegendCtl";
this.Size = new System.Drawing.Size(440, 288);
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
// No more changes
fVisible = fLayout = fPosition = fInsidePlotArea = false;
}
public void ApplyChanges(XmlNode node)
{
if (fVisible)
{
_Draw.SetElement(node, "Visible", this.chkVisible.Checked? "true": "false");
}
if (fLayout)
{
_Draw.SetElement(node, "Layout", this.cbLayout.Text);
}
if (fPosition)
{
_Draw.SetElement(node, "Position", this.cbPosition.Text);
}
if (fInsidePlotArea)
{
_Draw.SetElement(node, "InsidePlotArea", this.chkInsidePlotArea.Checked? "true": "false");
}
}
private void cbPosition_SelectedIndexChanged(object sender, System.EventArgs e)
{
fPosition = true;
}
private void cbLayout_SelectedIndexChanged(object sender, System.EventArgs e)
{
fLayout = true;
}
private void chkVisible_CheckedChanged(object sender, System.EventArgs e)
{
fVisible = true;
}
private void chkInsidePlotArea_CheckedChanged(object sender, System.EventArgs e)
{
fInsidePlotArea = true;
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using MindTouch.Deki.Data;
using MindTouch.Deki.Script.Compiler;
using MindTouch.Deki.Script.Expr;
using MindTouch.Deki.Script.Runtime;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki.Logic {
public static class ExtensionBL {
//--- Constants ---
public static readonly XDoc TOC = new XDoc("html").Start("body").Start("span").Attr("id", "page.toc").End().End();
private static readonly XslCompiledTransform _extensionConverterXslt;
//--- Class Constructor ---
static ExtensionBL() {
// load XSLT for normalizing extensions
XDoc doc = Plug.New("resource://mindtouch.deki/MindTouch.Deki.Resources.ExtensionConverter.xslt").With(DreamOutParam.TYPE, MimeType.XML.FullType).Get().ToDocument();
_extensionConverterXslt = new XslCompiledTransform();
_extensionConverterXslt.Load(new XmlNodeReader(doc.AsXmlNode), null, null);
}
//--- Class Methods ---
public static void StartExtensionService(DekiContext context, ServiceBE service, ServiceRepository.IServiceInfo serviceInfo, bool forceRefresh) {
// retrieve document describing the extension functions
XUri uri = new XUri(service.Uri);
XDoc manifest = null;
DekiWikiService deki = context.Deki;
var extension = serviceInfo.Extension;
if(!service.ServiceLocal) {
lock(deki.RemoteExtensionLibraries) {
deki.RemoteExtensionLibraries.TryGetValue(uri, out manifest);
}
}
if(manifest == null || forceRefresh) {
manifest = Plug.New(uri).Get().ToDocument();
// normalize the extension XML
manifest = manifest.TransformAsXml(_extensionConverterXslt);
// check if document describes a valid extension: either the extension has no functions, or the functions have end-points
if(manifest.HasName("extension") && ((manifest["function"].ListLength == 0) || (manifest["function/uri"].ListLength > 0))) {
// add source uri for service
manifest.Attr("uri", uri);
// register service in extension list
lock(deki.RemoteExtensionLibraries) {
deki.RemoteExtensionLibraries[uri] = manifest;
}
} else {
throw new DreamBadRequestException(string.Format("Invalid remote service: '{0}'", uri));
}
}
extension.Manifest = manifest;
// add function prefix if one is defined
serviceInfo.Extension.SetPreference("namespace.custom", service.Preferences["namespace"]);
string serviceNamespace = service.Preferences["namespace"] ?? manifest["namespace"].AsText;
if(serviceNamespace != null) {
serviceNamespace = serviceNamespace.Trim();
if(string.IsNullOrEmpty(serviceInfo.Namespace)) {
// Note (arnec): Namespace from preferences is assigned at service creation. If we do not have one at this
// point, it came from the extension manifest and needs to be registered as our default. Otherwise the
// preference override persists as the namespace.
context.Instance.RunningServices.RegisterNamespace(serviceInfo, serviceNamespace);
}
if(serviceNamespace.Length != 0) {
if(!DekiScriptParser.IsIdentifier(serviceNamespace)) {
throw new DreamBadRequestException(string.Format("Invalid service namespace: '{0}'", service.Preferences["namespace"] ?? manifest["namespace"].AsText));
}
} else {
serviceNamespace = null;
}
}
serviceNamespace = (serviceNamespace == null) ? string.Empty : (serviceNamespace + ".");
// add custom library title
extension.SetPreference("title.custom", service.Preferences["title"]);
extension.SetPreference("description.custom", service.Preferences["description"]);
extension.SetPreference("uri.logo.custom", service.Preferences["uri.logo"]);
extension.SetPreference("functions", service.Preferences["functions"]);
extension.SetPreference("protected", service.Preferences["protected"]);
// add each extension function
bool.TryParse(service.Preferences["protected"], out extension.IsProtected);
var functions = new List<ServiceRepository.ExtensionFunctionInfo>();
foreach(XDoc function in manifest["function"]) {
XUri functionUri = function["uri"].AsUri;
if(functionUri != null) {
functions.Add(new ServiceRepository.ExtensionFunctionInfo(serviceNamespace + function["name"].Contents, functionUri));
}
}
extension.Functions = functions.ToArray();
}
public static string GetExtensionPreference(XUri uri, string key) {
// check if we have a uri to look-up
if(uri == null) {
return null;
}
// retrieve preferences for this service
string result = null;
var serviceInfo = DekiContext.Current.Instance.RunningServices[uri];
if(serviceInfo == null || !serviceInfo.IsExtensionService) {
return null;
}
return serviceInfo.Extension.GetPreference(key);
}
public static DekiScriptEnv CreateEnvironment(PageBE page) {
DekiScriptEnv commonEnv = DekiContext.Current.Deki.CreateEnvironment();
// need to strip the config value back out for Deki
commonEnv.Vars["config"] = new DekiScriptMap();
// initialize environment
DekiScriptEnv env = commonEnv;
DekiContext deki = DekiContext.Current;
DekiInstance instance = deki.Instance;
// add site variables
env.Vars.AddNativeValueAt("site.name", instance.SiteName);
env.Vars.AddNativeValueAt("site.hostname", deki.UiUri.Uri.HostPort);
env.Vars.AddNativeValueAt("site.api", deki.ApiUri.SchemeHostPortPath);
env.Vars.AddNativeValueAt("site.language", instance.SiteLanguage);
env.Vars.AddNativeValueAt("site.uri", deki.UiUri.Uri.ToString());
env.Vars.AddNativeValueAt("site.pagecount", deki.Deki.PropertyAt("$sitepagecount"));
env.Vars.AddNativeValueAt("site.usercount", deki.Deki.PropertyAt("$siteusercount"));
env.Vars.AddNativeValueAt("site.homepage", deki.Deki.PropertyAt("$page", DekiContext.Current.Instance.HomePageId, true));
env.Vars.AddNativeValueAt("site.feed", deki.ApiUri.At("site", "feed").ToString());
env.Vars.AddNativeValueAt("site.tags", deki.Deki.PropertyAt("$sitetags"));
env.Vars.AddNativeValueAt("site.users", deki.Deki.PropertyAt("$siteusers"));
env.Vars.AddNativeValueAt("site.id", DekiScriptExpression.Constant(instance.Id));
env.Vars.AddNativeValueAt("site.timezone", DekiScriptExpression.Constant(instance.SiteTimezone));
// add page variables
env.Vars.Add("page", deki.Deki.PropertyAt("$page", page.ID, true));
// add user variables
env.Vars.Add("user", deki.Deki.PropertyAt("$user", (deki.User != null) ? deki.User.ID : 0));
// add instance functions & properties
bool hasUnsafeContentPermission = DekiXmlParser.PageAuthorCanExecute();
var functions = from service in instance.RunningServices.ExtensionServices
where hasUnsafeContentPermission || !service.Extension.IsProtected
from function in service.Extension.Functions
select function;
foreach(var function in functions) {
env.Vars.AddNativeValueAt(function.Name.ToLowerInvariant(), function.Uri);
}
return env;
}
public static void InitializeCustomDekiScriptHeaders(PageBE page) {
var current = DreamContext.Current;
DekiScriptMap env = current.GetState<DekiScriptMap>("pageimplicitenv-" + page.ID);
// check if we already have an initialized environment
if(env == null) {
DekiContext deki = DekiContext.Current;
DekiInstance instance = deki.Instance;
env = new DekiScriptMap();
// add site fields
DekiScriptMap siteFields = new DekiScriptMap();
siteFields.Add("name", DekiScriptExpression.Constant(instance.SiteName));
siteFields.Add("host", DekiScriptExpression.Constant(deki.UiUri.Uri.Host));
siteFields.Add("language", DekiScriptExpression.Constant(instance.SiteLanguage));
siteFields.Add("uri", DekiScriptExpression.Constant(deki.UiUri.Uri.ToString()));
siteFields.Add("id", DekiScriptExpression.Constant(instance.Id));
env.Add("site", siteFields);
// add page fields
DekiScriptMap pageFields = new DekiScriptMap();
pageFields.Add("title", DekiScriptExpression.Constant(page.Title.AsUserFriendlyName()));
pageFields.Add("path", DekiScriptExpression.Constant(page.Title.AsPrefixedDbPath()));
pageFields.Add("namespace", DekiScriptExpression.Constant(Title.NSToString(page.Title.Namespace)));
pageFields.Add("id", DekiScriptExpression.Constant(page.ID.ToString()));
pageFields.Add("uri", DekiScriptExpression.Constant(Utils.AsPublicUiUri(page.Title)));
pageFields.Add("date", DekiScriptExpression.Constant(page.TimeStamp.ToString("R")));
pageFields.Add("language", DekiScriptExpression.Constant(string.IsNullOrEmpty(page.Language) ? null : page.Language));
env.Add("page", pageFields);
// add user fields
DekiScriptMap userFields = new DekiScriptMap();
if(deki.User != null) {
UserBE user = deki.User;
userFields.Add("id", DekiScriptExpression.Constant(user.ID.ToString()));
userFields.Add("name", DekiScriptExpression.Constant(user.Name));
userFields.Add("uri", DekiScriptExpression.Constant(Utils.AsPublicUiUri(Title.FromDbPath(NS.USER, user.Name, null))));
userFields.Add("emailhash", DekiScriptExpression.Constant(StringUtil.ComputeHashString((user.Email ?? string.Empty).Trim().ToLowerInvariant(), Encoding.UTF8)));
userFields.Add("anonymous", DekiScriptExpression.Constant(UserBL.IsAnonymous(user).ToString().ToLowerInvariant()));
userFields.Add("language", DekiScriptExpression.Constant(string.IsNullOrEmpty(user.Language) ? null : user.Language));
} else {
userFields.Add("id", DekiScriptExpression.Constant("0"));
userFields.Add("name", DekiScriptExpression.Constant(string.Empty));
userFields.Add("uri", DekiScriptExpression.Constant(string.Empty));
userFields.Add("emailhash", DekiScriptExpression.Constant(string.Empty));
userFields.Add("anonymous", DekiScriptExpression.Constant("true"));
userFields.Add("language", DekiScriptNil.Value);
}
env.Add("user", userFields);
// store env for later
current.SetState("pageimplicitenv-" + page.ID, env);
}
// set implicit environment
DreamContext.Current.SetState(env);
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Tasks;
using Cassandra.Compression;
using Cassandra.Requests;
using Cassandra.Responses;
using Microsoft.IO;
namespace Cassandra
{
/// <summary>
/// Represents a TCP connection to a Cassandra Node
/// </summary>
internal class Connection : IDisposable
{
// ReSharper disable once InconsistentNaming
private static readonly Logger _logger = new Logger(typeof(Connection));
private readonly TcpSocket _tcpSocket;
private int _disposed;
/// <summary>
/// Determines that the connection canceled pending operations.
/// It could be because its being closed or there was a socket error.
/// </summary>
private volatile bool _isCanceled;
private readonly object _cancelLock = new object();
private readonly Timer _idleTimer;
private AutoResetEvent _pendingWaitHandle;
private int _timedOutOperations;
/// <summary>
/// Stores the available stream ids.
/// </summary>
private ConcurrentStack<short> _freeOperations;
/// <summary> Contains the requests that were sent through the wire and that hasn't been received yet.</summary>
private ConcurrentDictionary<short, OperationState> _pendingOperations;
/// <summary> It contains the requests that could not be written due to streamIds not available</summary>
private ConcurrentQueue<OperationState> _writeQueue;
/// <summary>
/// Small buffer (less than 8 bytes) that is used when the next received message is smaller than 8 bytes,
/// and it is not possible to read the header.
/// </summary>
private volatile byte[] _minimalBuffer;
private readonly byte[] _decompressorBuffer = new byte[1024];
private volatile string _keyspace;
private readonly SemaphoreSlim _keyspaceSwitchSemaphore = new SemaphoreSlim(1);
private volatile Task<bool> _keyspaceSwitchTask;
private volatile byte _frameHeaderSize;
private MemoryStream _readStream;
private int _isWriteQueueRuning;
private int _inFlight;
/// <summary>
/// The event that represents a event RESPONSE from a Cassandra node
/// </summary>
public event CassandraEventHandler CassandraEventResponse;
/// <summary>
/// Event raised when there is an error when executing the request to prevent idle disconnects
/// </summary>
public event Action<Exception> OnIdleRequestException;
/// <summary>
/// Event that gets raised when a write has been completed. Testing purposes only.
/// </summary>
public event Action WriteCompleted;
private const string IdleQuery = "SELECT key from system.local";
private const long CoalescingThreshold = 8000;
public IFrameCompressor Compressor { get; set; }
public IPEndPoint Address
{
get { return _tcpSocket.IPEndPoint; }
}
/// <summary>
/// Determines the amount of operations that are not finished.
/// </summary>
public virtual int InFlight
{
get { return Thread.VolatileRead(ref _inFlight); }
}
/// <summary>
/// Gets the amount of operations that timed out and didn't get a response
/// </summary>
public virtual int TimedOutOperations
{
get { return Thread.VolatileRead(ref _timedOutOperations); }
}
/// <summary>
/// Determine if the Connection is closed
/// </summary>
public bool IsClosed
{
//if the connection attempted to cancel pending operations
get { return _isCanceled; }
}
/// <summary>
/// Determine if the Connection has been explicitly disposed
/// </summary>
public bool IsDisposed
{
get { return Thread.VolatileRead(ref _disposed) > 0; }
}
/// <summary>
/// Gets the current keyspace.
/// </summary>
public string Keyspace
{
get
{
return _keyspace;
}
}
/// <summary>
/// Gets the amount of concurrent requests depending on the protocol version
/// </summary>
public int MaxConcurrentRequests
{
get
{
if (ProtocolVersion < 3)
{
return 128;
}
//Protocol 3 supports up to 32K concurrent request without waiting a response
//Allowing larger amounts of concurrent requests will cause large memory consumption
//Limit to 2K per connection sounds reasonable.
return 2048;
}
}
public ProtocolOptions Options { get { return Configuration.ProtocolOptions; } }
public byte ProtocolVersion { get; set; }
public Configuration Configuration { get; set; }
public Connection(byte protocolVersion, IPEndPoint endpoint, Configuration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
if (configuration.BufferPool == null)
{
throw new ArgumentNullException(null, "BufferPool can not be null");
}
ProtocolVersion = protocolVersion;
Configuration = configuration;
_tcpSocket = new TcpSocket(endpoint, configuration.SocketOptions, configuration.ProtocolOptions.SslOptions);
_idleTimer = new Timer(IdleTimeoutHandler, null, Timeout.Infinite, Timeout.Infinite);
}
/// <summary>
/// Starts the authentication flow
/// </summary>
/// <exception cref="AuthenticationException" />
private Task<Response> Authenticate()
{
//Determine which authentication flow to use.
//Check if its using a C* 1.2 with authentication patched version (like DSE 3.1)
var isPatchedVersion = ProtocolVersion == 1 && !(Configuration.AuthProvider is NoneAuthProvider) && Configuration.AuthInfoProvider == null;
if (ProtocolVersion < 2 && !isPatchedVersion)
{
//Use protocol v1 authentication flow
if (Configuration.AuthInfoProvider == null)
{
throw new AuthenticationException(
String.Format("Host {0} requires authentication, but no credentials provided in Cluster configuration", Address),
Address);
}
var credentialsProvider = Configuration.AuthInfoProvider;
var credentials = credentialsProvider.GetAuthInfos(Address);
var request = new CredentialsRequest(ProtocolVersion, credentials);
return Send(request)
.ContinueSync(response =>
{
if (!(response is ReadyResponse))
{
//If Cassandra replied with a auth response error
//The task already is faulted and the exception was already thrown.
throw new ProtocolErrorException("Expected SASL response, obtained " + response.GetType().Name);
}
return response;
});
}
//Use protocol v2+ authentication flow
//NewAuthenticator will throw AuthenticationException when NoneAuthProvider
var authenticator = Configuration.AuthProvider.NewAuthenticator(Address);
var initialResponse = authenticator.InitialResponse() ?? new byte[0];
return Authenticate(initialResponse, authenticator);
}
/// <exception cref="AuthenticationException" />
private Task<Response> Authenticate(byte[] token, IAuthenticator authenticator)
{
var request = new AuthResponseRequest(ProtocolVersion, token);
return Send(request)
.Then(response =>
{
if (response is AuthSuccessResponse)
{
//It is now authenticated
return TaskHelper.ToTask(response);
}
if (response is AuthChallengeResponse)
{
token = authenticator.EvaluateChallenge(((AuthChallengeResponse)response).Token);
if (token == null)
{
// If we get a null response, then authentication has completed
//return without sending a further response back to the server.
return TaskHelper.ToTask(response);
}
return Authenticate(token, authenticator);
}
throw new ProtocolErrorException("Expected SASL response, obtained " + response.GetType().Name);
});
}
/// <summary>
/// It callbacks all operations already sent / or to be written, that do not have a response.
/// </summary>
internal void CancelPending(Exception ex, SocketError? socketError = null)
{
//Multiple IO worker threads may been notifying that the socket is closing/in error
lock (_cancelLock)
{
_isCanceled = true;
_logger.Info("Canceling pending operations {0} and write queue {1}", Thread.VolatileRead(ref _inFlight), _writeQueue.Count);
if (socketError != null)
{
_logger.Verbose("The socket status received was {0}", socketError.Value);
}
if (_pendingOperations.IsEmpty && _writeQueue.IsEmpty)
{
if (_pendingWaitHandle != null)
{
_pendingWaitHandle.Set();
}
return;
}
if (ex == null || ex is ObjectDisposedException)
{
if (socketError != null)
{
ex = new SocketException((int)socketError.Value);
}
else
{
//It is closing
ex = new SocketException((int)SocketError.NotConnected);
}
}
//Callback all the items in the write queue
OperationState state;
while (_writeQueue.TryDequeue(out state))
{
state.InvokeCallback(ex);
}
//Callback for every pending operation
foreach (var item in _pendingOperations)
{
item.Value.InvokeCallback(ex);
}
_pendingOperations.Clear();
Interlocked.Exchange(ref _inFlight, 0);
if (_pendingWaitHandle != null)
{
_pendingWaitHandle.Set();
}
}
}
public virtual void Dispose()
{
if (Interlocked.Increment(ref _disposed) != 1)
{
//Only dispose once
return;
}
_idleTimer.Dispose();
_tcpSocket.Dispose();
_keyspaceSwitchSemaphore.Dispose();
var readStream = Interlocked.Exchange(ref _readStream, null);
if (readStream != null)
{
readStream.Close();
}
}
private void EventHandler(Exception ex, Response response)
{
if (!(response is EventResponse))
{
_logger.Error("Unexpected response type for event: " + response.GetType().Name);
return;
}
if (CassandraEventResponse != null)
{
CassandraEventResponse(this, ((EventResponse) response).CassandraEventArgs);
}
}
/// <summary>
/// Gets executed once the idle timeout has passed
/// </summary>
private void IdleTimeoutHandler(object state)
{
//Ensure there are no more idle timeouts until the query finished sending
if (_isCanceled)
{
if (!IsDisposed)
{
//If it was not manually disposed
_logger.Warning("Can not issue an heartbeat request as connection is closed");
if (OnIdleRequestException != null)
{
OnIdleRequestException(new SocketException((int)SocketError.NotConnected));
}
}
return;
}
_logger.Verbose("Connection idling, issuing a Request to prevent idle disconnects");
var request = new QueryRequest(ProtocolVersion, IdleQuery, false, QueryProtocolOptions.Default);
Send(request, (ex, response) =>
{
if (ex == null)
{
//The send succeeded
//There is a valid response but we don't care about the response
return;
}
_logger.Warning("Received heartbeat request exception " + ex.ToString());
if (ex is SocketException && OnIdleRequestException != null)
{
OnIdleRequestException(ex);
}
});
}
/// <summary>
/// Initializes the connection.
/// </summary>
/// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception>
/// <exception cref="AuthenticationException" />
/// <exception cref="UnsupportedProtocolVersionException"></exception>
public Task<Response> Open()
{
_freeOperations = new ConcurrentStack<short>(Enumerable.Range(0, MaxConcurrentRequests).Select(s => (short)s).Reverse());
_pendingOperations = new ConcurrentDictionary<short, OperationState>();
_writeQueue = new ConcurrentQueue<OperationState>();
if (Options.CustomCompressor != null)
{
Compressor = Options.CustomCompressor;
}
else if (Options.Compression == CompressionType.LZ4)
{
Compressor = new LZ4Compressor();
}
else if (Options.Compression == CompressionType.Snappy)
{
Compressor = new SnappyCompressor();
}
//Init TcpSocket
_tcpSocket.Init();
_tcpSocket.Error += CancelPending;
_tcpSocket.Closing += () => CancelPending(null, null);
//Read and write event handlers are going to be invoked using IO Threads
_tcpSocket.Read += ReadHandler;
_tcpSocket.WriteCompleted += WriteCompletedHandler;
return _tcpSocket
.Connect()
.Then(_ => Startup())
.ContinueWith(t =>
{
if (t.IsFaulted && t.Exception != null)
{
//Adapt the inner exception and rethrow
var ex = t.Exception.InnerException;
if (ex is ProtocolErrorException)
{
//As we are starting up, check for protocol version errors
//There is no other way than checking the error message from Cassandra
if (ex.Message.Contains("Invalid or unsupported protocol version"))
{
throw new UnsupportedProtocolVersionException(ProtocolVersion, ex);
}
}
if (ex is ServerErrorException && ProtocolVersion >= 3 && ex.Message.Contains("ProtocolException: Invalid or unsupported protocol version"))
{
//For some versions of Cassandra, the error is wrapped into a server error
//See CASSANDRA-9451
throw new UnsupportedProtocolVersionException(ProtocolVersion, ex);
}
throw ex;
}
return t.Result;
}, TaskContinuationOptions.ExecuteSynchronously)
.Then(response =>
{
if (response is AuthenticateResponse)
{
return Authenticate();
}
if (response is ReadyResponse)
{
return TaskHelper.ToTask(response);
}
throw new DriverInternalError("Expected READY or AUTHENTICATE, obtained " + response.GetType().Name);
});
}
/// <summary>
/// Silently kill the connection, for testing purposes only
/// </summary>
internal void Kill()
{
_tcpSocket.Kill();
}
private void ReadHandler(byte[] buffer, int bytesReceived)
{
if (_isCanceled)
{
//All pending operations have been canceled, there is no point in reading from the wire.
return;
}
//We are currently using an IO Thread
//Parse the data received
var streamIdAvailable = ReadParse(buffer, bytesReceived);
if (!streamIdAvailable)
{
return;
}
if (_pendingWaitHandle != null && _pendingOperations.IsEmpty && _writeQueue.IsEmpty)
{
_pendingWaitHandle.Set();
}
//Process a next item in the queue if possible.
//Maybe there are there items in the write queue that were waiting on a fresh streamId
RunWriteQueue();
}
private volatile FrameHeader _receivingHeader;
/// <summary>
/// Parses the bytes received into a frame. Uses the internal operation state to do the callbacks.
/// Returns true if a full operation (streamId) has been processed and there is one available.
/// </summary>
/// <returns>True if a full operation (streamId) has been processed.</returns>
internal bool ReadParse(byte[] buffer, int length)
{
if (length <= 0)
{
return false;
}
if (_frameHeaderSize == 0)
{
//Read the first byte of the message to determine the version of the response
ProtocolVersion = FrameHeader.GetProtocolVersion(buffer);
_frameHeaderSize = FrameHeader.GetSize(ProtocolVersion);
}
//Use _readStream to buffer between messages, under low pressure, it should be null most of the times
var stream = Interlocked.Exchange(ref _readStream, null);
var operationCallbacks = new LinkedList<Action<MemoryStream>>();
var offset = 0;
if (_minimalBuffer != null)
{
//use a negative offset to identify that there is a previous header buffer
offset = -1 * _minimalBuffer.Length;
}
while (offset < length)
{
FrameHeader header;
//The remaining body length to read from this buffer
int remainingBodyLength;
if (_receivingHeader == null)
{
if (length - offset < _frameHeaderSize)
{
_minimalBuffer = offset >= 0 ?
Utils.SliceBuffer(buffer, offset, length - offset) :
//it should almost never be the case there isn't enough bytes to read the header more than once
// ReSharper disable once PossibleNullReferenceException
Utils.JoinBuffers(_minimalBuffer, 0, _minimalBuffer.Length, buffer, 0, length);
break;
}
if (offset >= 0)
{
header = FrameHeader.ParseResponseHeader(ProtocolVersion, buffer, offset);
}
else
{
header = FrameHeader.ParseResponseHeader(ProtocolVersion, _minimalBuffer, buffer);
_minimalBuffer = null;
}
_logger.Verbose("Received #{0} from {1}", header.StreamId, Address);
offset += _frameHeaderSize;
remainingBodyLength = header.BodyLength;
}
else
{
header = _receivingHeader;
remainingBodyLength = header.BodyLength - (int) stream.Length;
_receivingHeader = null;
}
if (remainingBodyLength > length - offset)
{
//the buffer does not contains the body for this frame, buffer for later
MemoryStream nextMessageStream;
if (operationCallbacks.Count == 0 && stream != null)
{
//There hasn't been any operations completed with this buffer
//And there is a previous stream: reuse it
nextMessageStream = stream;
}
else
{
nextMessageStream = Configuration.BufferPool.GetStream(typeof(Connection) + "/Read");
}
nextMessageStream.Write(buffer, offset, length - offset);
Interlocked.Exchange(ref _readStream, nextMessageStream);
_receivingHeader = header;
break;
}
stream = stream ?? Configuration.BufferPool.GetStream(typeof (Connection) + "/Read");
OperationState state;
if (header.Opcode != EventResponse.OpCode)
{
state = RemoveFromPending(header.StreamId);
}
else
{
//Its an event
state = new OperationState(EventHandler);
}
stream.Write(buffer, offset, remainingBodyLength);
var callback = state.SetCompleted();
operationCallbacks.AddLast(CreateResponseAction(header, callback));
offset += remainingBodyLength;
}
return InvokeReadCallbacks(stream, operationCallbacks);
}
/// <summary>
/// Returns an action that capture the parameters closure
/// </summary>
private Action<MemoryStream> CreateResponseAction(FrameHeader header, Action<Exception, Response> callback)
{
var compressor = Compressor;
var bufferPool = Configuration.BufferPool;
var decompressorBuffer = _decompressorBuffer;
return stream =>
{
Response response = null;
Exception ex = null;
var nextPosition = stream.Position + header.BodyLength;
try
{
Stream plainTextStream = stream;
if (header.Flags.HasFlag(FrameHeader.HeaderFlag.Compression))
{
var compressedBodyStream = bufferPool.GetStream(typeof (Connection) + "/Decompress", header.BodyLength);
Utils.CopyStream(stream, compressedBodyStream, header.BodyLength, decompressorBuffer);
compressedBodyStream.Position = 0;
plainTextStream = compressor.Decompress(compressedBodyStream);
plainTextStream.Position = 0;
}
response = FrameParser.Parse(new Frame(header, plainTextStream));
}
catch (Exception catchedException)
{
ex = catchedException;
}
if (response is ErrorResponse)
{
//Create an exception from the response error
ex = ((ErrorResponse)response).Output.CreateException();
response = null;
}
//We must advance the position of the stream manually in case it was not correctly parsed
stream.Position = nextPosition;
callback(ex, response);
};
}
/// <summary>
/// Invokes the callbacks using the default TaskScheduler.
/// </summary>
/// <returns>Returns true if one or more callback has been invoked.</returns>
private static bool InvokeReadCallbacks(MemoryStream stream, ICollection<Action<MemoryStream>> operationCallbacks)
{
if (operationCallbacks.Count == 0)
{
//Not enough data to read a frame
return false;
}
//Invoke all callbacks using the default TaskScheduler
Task.Factory.StartNew(() =>
{
stream.Position = 0;
foreach (var cb in operationCallbacks)
{
cb(stream);
}
stream.Dispose();
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
return true;
}
/// <summary>
/// Sends a protocol STARTUP message
/// </summary>
private Task<Response> Startup()
{
var startupOptions = new Dictionary<string, string>();
startupOptions.Add("CQL_VERSION", "3.0.0");
if (Options.Compression == CompressionType.LZ4)
{
startupOptions.Add("COMPRESSION", "lz4");
}
else if (Options.Compression == CompressionType.Snappy)
{
startupOptions.Add("COMPRESSION", "snappy");
}
return Send(new StartupRequest(ProtocolVersion, startupOptions));
}
/// <summary>
/// Sends a new request if possible. If it is not possible it queues it up.
/// </summary>
public Task<Response> Send(IRequest request)
{
var tcs = new TaskCompletionSource<Response>();
Send(request, tcs.TrySet);
return tcs.Task;
}
/// <summary>
/// Sends a new request if possible and executes the callback when the response is parsed. If it is not possible it queues it up.
/// </summary>
public OperationState Send(IRequest request, Action<Exception, Response> callback)
{
if (_isCanceled)
{
callback(new SocketException((int)SocketError.NotConnected), null);
return null;
}
var state = new OperationState(callback)
{
Request = request
};
_writeQueue.Enqueue(state);
RunWriteQueue();
return state;
}
private void RunWriteQueue()
{
var isAlreadyRunning = Interlocked.CompareExchange(ref _isWriteQueueRuning, 1, 0) == 1;
if (isAlreadyRunning)
{
//there is another thread writing to the wire
return;
}
//Start a new task using the TaskScheduler for writing
Task.Factory.StartNew(RunWriteQueueAction, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
private void RunWriteQueueAction()
{
//Dequeue all items until threshold is passed
long totalLength = 0;
RecyclableMemoryStream stream = null;
var streamIdsAvailable = true;
while (totalLength < CoalescingThreshold)
{
OperationState state;
if (!_writeQueue.TryDequeue(out state))
{
//No more items in the write queue
break;
}
short streamId;
if (!_freeOperations.TryPop(out streamId))
{
streamIdsAvailable = false;
//Queue it up for later.
_writeQueue.Enqueue(state);
//When receiving the next complete message, we can process it.
_logger.Info("Enqueued, no streamIds available. If this message is recurrent consider configuring more connections per host or lower the pressure");
break;
}
_logger.Verbose("Sending #{0} for {1} to {2}", streamId, state.Request.GetType().Name, Address);
_pendingOperations.AddOrUpdate(streamId, state, (k, oldValue) => state);
Interlocked.Increment(ref _inFlight);
int frameLength;
try
{
//lazy initialize the stream
stream = stream ?? (RecyclableMemoryStream) Configuration.BufferPool.GetStream(GetType().Name + "/SendStream");
frameLength = state.Request.WriteFrame(streamId, stream);
if (Configuration.SocketOptions.ReadTimeoutMillis > 0 && Configuration.Timer != null)
{
state.Timeout = Configuration.Timer.NewTimeout(OnTimeout, streamId, Configuration.SocketOptions.ReadTimeoutMillis);
}
}
catch (Exception ex)
{
//There was an error while serializing or begin sending
_logger.Error(ex);
//The request was not written, clear it from pending operations
RemoveFromPending(streamId);
//Callback with the Exception
state.InvokeCallback(ex);
break;
}
//We will not use the request any more, stop reference it.
state.Request = null;
totalLength += frameLength;
}
if (totalLength == 0L)
{
//nothing to write
Interlocked.Exchange(ref _isWriteQueueRuning, 0);
if (streamIdsAvailable && !_writeQueue.IsEmpty)
{
//The write queue is not empty
//An item was added to the queue but we were running: try to launch a new queue
RunWriteQueue();
}
if (stream != null)
{
//The stream instance could be created if there was an exception while generating the frame
stream.Dispose();
}
return;
}
//Write and close the stream when flushed
// ReSharper disable once PossibleNullReferenceException : if totalLength > 0 the stream is initialized
_tcpSocket.Write(stream, () => stream.Dispose());
}
/// <summary>
/// Removes an operation from pending and frees the stream id
/// </summary>
/// <param name="streamId"></param>
internal protected virtual OperationState RemoveFromPending(short streamId)
{
OperationState state;
if (_pendingOperations.TryRemove(streamId, out state))
{
Interlocked.Decrement(ref _inFlight);
}
//Set the streamId as available
_freeOperations.Push(streamId);
return state;
}
/// <summary>
/// Sets the keyspace of the connection.
/// If the keyspace is different from the current value, it sends a Query request to change it
/// </summary>
public Task<bool> SetKeyspace(string value)
{
if (String.IsNullOrEmpty(value) || _keyspace == value)
{
//No need to switch
return TaskHelper.Completed;
}
Task<bool> keyspaceSwitch;
try
{
if (!_keyspaceSwitchSemaphore.Wait(0))
{
//Could not enter semaphore
//It is very likely that the connection is already switching keyspace
keyspaceSwitch = _keyspaceSwitchTask;
if (keyspaceSwitch != null)
{
return keyspaceSwitch.Then(_ =>
{
//validate if the new keyspace is the expected
if (_keyspace != value)
{
//multiple concurrent switches to different keyspace
return SetKeyspace(value);
}
return TaskHelper.Completed;
});
}
_keyspaceSwitchSemaphore.Wait();
}
}
catch (ObjectDisposedException)
{
//The semaphore was disposed, this connection is closed
return TaskHelper.FromException<bool>(new SocketException((int) SocketError.NotConnected));
}
//Semaphore entered
if (_keyspace == value)
{
//While waiting to enter the semaphore, the connection switched keyspace
try
{
_keyspaceSwitchSemaphore.Release();
}
catch (ObjectDisposedException)
{
//this connection is now closed but the switch completed successfully
}
return TaskHelper.Completed;
}
var request = new QueryRequest(ProtocolVersion, string.Format("USE \"{0}\"", value), false, QueryProtocolOptions.Default);
_logger.Info("Connection to host {0} switching to keyspace {1}", Address, value);
keyspaceSwitch = _keyspaceSwitchTask = Send(request).ContinueSync(r =>
{
_keyspace = value;
try
{
_keyspaceSwitchSemaphore.Release();
}
catch (ObjectDisposedException)
{
//this connection is now closed but the switch completed successfully
}
_keyspaceSwitchTask = null;
return true;
});
return keyspaceSwitch;
}
private void OnTimeout(object stateObj)
{
var streamId = (short)stateObj;
OperationState state;
if (!_pendingOperations.TryGetValue(streamId, out state))
{
return;
}
var ex = new OperationTimedOutException(Address, Configuration.SocketOptions.ReadTimeoutMillis);
//Invoke if it hasn't been invoked yet
//Once the response is obtained, we decrement the timed out counter
var timedout = state.SetTimedOut(ex, () => Interlocked.Decrement(ref _timedOutOperations) );
if (!timedout)
{
//The response was obtained since the timer elapsed, move on
return;
}
//Increase timed-out counter
Interlocked.Increment(ref _timedOutOperations);
}
/// <summary>
/// Method that gets executed when a write request has been completed.
/// </summary>
protected virtual void WriteCompletedHandler()
{
//This handler is invoked by IO threads
//Make it quick
if (WriteCompleted != null)
{
WriteCompleted();
}
//There is no need for synchronization here
//Only 1 thread can be here at the same time.
//Set the idle timeout to avoid idle disconnects
var heartBeatInterval = Configuration.PoolingOptions != null ? Configuration.PoolingOptions.GetHeartBeatInterval() : null;
if (heartBeatInterval > 0 && !_isCanceled)
{
try
{
_idleTimer.Change(heartBeatInterval.Value, Timeout.Infinite);
}
catch (ObjectDisposedException)
{
//This connection is being disposed
//Don't mind
}
}
Interlocked.Exchange(ref _isWriteQueueRuning, 0);
//Send the next request, if exists
//It will use a new thread
RunWriteQueue();
}
internal WaitHandle WaitPending()
{
if (_pendingWaitHandle == null)
{
_pendingWaitHandle = new AutoResetEvent(false);
}
if (_pendingOperations.IsEmpty && _writeQueue.IsEmpty)
{
_pendingWaitHandle.Set();
}
return _pendingWaitHandle;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BackupPoliciesOperations operations.
/// </summary>
internal partial class BackupPoliciesOperations : IServiceOperations<RecoveryServicesBackupClient>, IBackupPoliciesOperations
{
/// <summary>
/// Initializes a new instance of the BackupPoliciesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BackupPoliciesOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Lists of backup policies associated with Recovery Services Vault. API
/// provides pagination parameters to fetch scoped results.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ProtectionPolicyResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, ODataQuery<ProtectionPolicyQueryObject> odataQuery = default(ODataQuery<ProtectionPolicyQueryObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupPolicies").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ProtectionPolicyResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ProtectionPolicyResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists of backup policies associated with Recovery Services Vault. API
/// provides pagination parameters to fetch scoped results.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ProtectionPolicyResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ProtectionPolicyResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ProtectionPolicyResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the 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 AddUInt16()
{
var test = new SimpleBinaryOpTest__AddUInt16();
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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 SimpleBinaryOpTest__AddUInt16
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt16);
private const int Op2ElementCount = VectorSize / sizeof(UInt16);
private const int RetElementCount = VectorSize / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector128<UInt16> _clsVar1;
private static Vector128<UInt16> _clsVar2;
private Vector128<UInt16> _fld1;
private Vector128<UInt16> _fld2;
private SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16> _dataTable;
static SimpleBinaryOpTest__AddUInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AddUInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16>(_data1, _data2, new UInt16[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Add(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Add(
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Add(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr);
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddUInt16();
var result = Sse2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt16> left, Vector128<UInt16> right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
if ((ushort)(left[0] + right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ushort)(left[i] + right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Add)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
namespace LoggingCS
{
/// <summary>
/// UI for the LoggingSession sample.
/// </summary>
public sealed partial class Scenario2
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
MainPage rootPage = MainPage.Current;
internal LoggingSessionScenario LoggingSessionScenario { get { return LoggingSessionScenario.Instance; } }
public Scenario2()
{
// This sample UI is interested in events from
// the LoggingSessionScenario class so the UI can be updated.
LoggingSessionScenario.StatusChanged += LoggingSessionScenario_StatusChanged;
this.InitializeComponent();
}
async void LoggingSessionScenario_StatusChanged(object sender, LoggingScenarioEventArgs e)
{
if (e.Type == LoggingScenarioEventType.BusyStatusChanged)
{
UpdateControls();
}
else if (e.Type == LoggingScenarioEventType.LogFileGenerated)
{
await AddLogFileMessageDispatch("LogFileGenerated", e.LogFilePath);
}
else if (e.Type == LoggingScenarioEventType.LoggingEnabledDisabled)
{
await AddMessageDispatch(string.Format("Logging has been {0}.", e.Enabled ? "enabled" : "disabled"));
}
}
ScrollViewer FindScrollViewer(DependencyObject depObject)
{
if (depObject == null)
{
return null;
}
int countThisLevel = Windows.UI.Xaml.Media.VisualTreeHelper.GetChildrenCount(depObject);
if (countThisLevel <= 0)
{
return null;
}
for (int childIndex = 0; childIndex < countThisLevel; childIndex++)
{
DependencyObject childDepObject = Windows.UI.Xaml.Media.VisualTreeHelper.GetChild(depObject, childIndex);
if (childDepObject is ScrollViewer)
{
return (ScrollViewer)childDepObject;
}
ScrollViewer svFromChild = FindScrollViewer(childDepObject);
if (svFromChild != null)
{
return svFromChild;
}
}
return null;
}
/// <summary>
/// Add a message to the UI control which displays status while the sample is running.
/// </summary>
/// <param name="message">The message to append to the UI log.</param>
public void AddMessage(string message)
{
StatusMessageList.Text += message + "\r\n";
StatusMessageList.Select(StatusMessageList.Text.Length, 0);
ScrollViewer svFind = FindScrollViewer(StatusMessageList);
if (svFind != null)
{
svFind.ChangeView(null, StatusMessageList.ActualHeight, null);
}
}
/// <summary>
/// Dispatch to the UI thread and add a message to the UI control which displays status while the sample is running.
/// </summary>
/// <param name="message">The message to append to the UI log.</param>
public async Task AddLogFileMessageDispatch(string message, string path)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
{
string finalMessage;
if (path != null && path.Length > 0)
{
var fileName = System.IO.Path.GetFileName(path);
var directoryName = System.IO.Path.GetDirectoryName(path);
finalMessage = message + ": " + fileName;
ViewLogInfo.Text =
"Log folder: \"" + directoryName + "\"\r\n" +
"- To view with tracerpt: tracerpt.exe \"" + path + "\" -of XML -o LogFile.xml\r\n" +
"- To view with Windows Performance Toolkit (WPT): wpa.exe \"" + path + "\"";
}
else
{
finalMessage = string.Format("{0}: none, nothing logged since saving the last file.", message);
}
AddMessage(finalMessage);
}).AsTask();
}
/// <summary>
/// Dispatch to the UI thread and add a message to the UI log.
/// </summary>
/// <param name="message">The message to appened to the UI log.</param>
/// <returns>The task.</returns>
public async Task AddMessageDispatch(string message)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
{
AddMessage(message);
}).AsTask();
}
/// <summary>
/// Adjust UI controls based on what the sample is doing.
/// </summary>
private void UpdateControls()
{
if (LoggingSessionScenario.Instance.IsLoggingEnabled)
{
InputTextBlock1.Text = "Logging is enabled. Click 'Disable Logging' to disable logging. With logging enabled, you can click 'Log Messages' to use the logging API to generate log files.";
EnableDisableLoggingButton.Content = "Disable Logging";
if (LoggingSessionScenario.Instance.IsBusy)
{
DoScenarioButton.IsEnabled = false;
EnableDisableLoggingButton.IsEnabled = false;
}
else
{
DoScenarioButton.IsEnabled = true;
EnableDisableLoggingButton.IsEnabled = true;
}
}
else
{
InputTextBlock1.Text = "Logging is disabled. Click 'Enable Logging' to enable logging. After you enable logging you can click 'Log Messages' to use the logging API to generate log files.";
EnableDisableLoggingButton.Content = "Enable Logging";
DoScenarioButton.IsEnabled = false;
if (LoggingSessionScenario.Instance.IsBusy)
{
EnableDisableLoggingButton.IsEnabled = false;
}
else
{
EnableDisableLoggingButton.IsEnabled = true;
}
}
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
UpdateControls();
}
/// <summary>
/// Enabled/disabled logging.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event arguments.</param>
private void EnableDisableLogging(object sender, RoutedEventArgs e)
{
LoggingSessionScenario loggingSessionScenario = LoggingSessionScenario.Instance;
if (loggingSessionScenario.IsLoggingEnabled)
{
rootPage.NotifyUser("Disabling logging...", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Enabling logging...", NotifyType.StatusMessage);
}
LoggingSessionScenario.Instance.ToggleLoggingEnabledDisabled();
if (loggingSessionScenario.IsLoggingEnabled)
{
rootPage.NotifyUser("Logging enabled.", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Logging disabled.", NotifyType.StatusMessage);
}
UpdateControls();
}
/// <summary>
/// Run a sample scenario which logs lots of messages to produce several log files.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event args.</param>
private async void DoScenario(object sender, RoutedEventArgs e)
{
DoScenarioButton.IsEnabled = false;
rootPage.NotifyUser("Scenario running...", NotifyType.StatusMessage);
await LoggingSessionScenario.DoScenarioAsync();
rootPage.NotifyUser("Scenario finished.", NotifyType.StatusMessage);
DoScenarioButton.IsEnabled = true;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.